main.rs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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. time::Instant,
  23. };
  24. use anyhow::{anyhow, Context, Result};
  25. use clap::{CommandFactory, Parser, Subcommand};
  26. use clap_complete::{generate, Shell};
  27. use darkfi::{tx::Transaction, util::parse::decode_base10, zk::halo2::Field};
  28. use darkfi_money_contract::client::Coin;
  29. use darkfi_sdk::{
  30. crypto::{PublicKey, SecretKey, TokenId},
  31. pasta::{group::ff::PrimeField, pallas},
  32. };
  33. use darkfi_serial::{deserialize, serialize};
  34. use prettytable::{format, row, Table};
  35. use rand::rngs::OsRng;
  36. use serde_json::json;
  37. use simplelog::{ColorChoice, TermLogger, TerminalMode};
  38. use url::Url;
  39. use darkfi::{
  40. cli_desc,
  41. rpc::{client::RpcClient, jsonrpc::JsonRequest},
  42. util::{
  43. cli::{get_log_config, get_log_level},
  44. parse::encode_base10,
  45. },
  46. };
  47. /// Airdrop methods
  48. mod rpc_airdrop;
  49. /// Payment methods
  50. mod rpc_transfer;
  51. /// Swap methods
  52. mod rpc_swap;
  53. use rpc_swap::PartialSwapData;
  54. /// DAO methods
  55. mod rpc_dao;
  56. /// Blockchain methods
  57. mod rpc_blockchain;
  58. /// CLI utility functions
  59. mod cli_util;
  60. use cli_util::{parse_token_pair, parse_value_pair};
  61. /// Wallet functionality related to DAO
  62. mod wallet_dao;
  63. use wallet_dao::DaoParams;
  64. /// Wallet functionality related to Money
  65. mod wallet_money;
  66. #[derive(Parser)]
  67. #[command(about = cli_desc!())]
  68. struct Args {
  69. #[arg(short, action = clap::ArgAction::Count)]
  70. /// Increase verbosity (-vvv supported)
  71. verbose: u8,
  72. #[arg(short, long, default_value = "tcp://127.0.0.1:8340")]
  73. /// darkfid JSON-RPC endpoint
  74. endpoint: Url,
  75. #[command(subcommand)]
  76. command: Subcmd,
  77. }
  78. #[derive(Subcommand)]
  79. enum Subcmd {
  80. /// Send a ping request to the darkfid RPC endpoint
  81. Ping,
  82. /// Generate a SHELL completion script and print to stdout
  83. Completions {
  84. /// The Shell you want to generate script for
  85. shell: Shell,
  86. },
  87. /// Wallet operations
  88. Wallet {
  89. #[arg(long)]
  90. /// Initialize wallet with data for Money Contract (run this first)
  91. initialize: bool,
  92. #[arg(long)]
  93. /// Generate a new keypair in the wallet
  94. keygen: bool,
  95. #[arg(long)]
  96. /// Query the wallet for known balances
  97. balance: bool,
  98. #[arg(long)]
  99. /// Get the default address in the wallet
  100. address: bool,
  101. #[arg(long)]
  102. /// Print all the secret keys from the wallet
  103. secrets: bool,
  104. #[arg(long)]
  105. /// Import secret keys from stdin into the wallet, separated by newlines
  106. import_secrets: bool,
  107. #[arg(long)]
  108. /// Print the Merkle tree in the wallet
  109. tree: bool,
  110. #[arg(long)]
  111. /// Print all the coins in the wallet
  112. coins: bool,
  113. },
  114. /// Unspend a coin
  115. Unspend {
  116. /// base58-encoded coin to mark as unspent
  117. coin: String,
  118. },
  119. /// Airdrop some tokens
  120. Airdrop {
  121. /// Faucet JSON-RPC endpoint
  122. #[arg(short, long, default_value = "tls://faucetd.testnet.dark.fi:18340")]
  123. faucet_endpoint: Url,
  124. /// Amount to request from the faucet
  125. amount: String,
  126. /// Token ID to request from the faucet
  127. token: String,
  128. /// Optional address to send tokens to (defaults to main address in wallet)
  129. address: Option<String>,
  130. },
  131. /// Create a payment transaction
  132. Transfer {
  133. /// Amount to send
  134. amount: String,
  135. /// Token ID to send
  136. token: String,
  137. /// Recipient address
  138. recipient: String,
  139. /// Mark if this is being sent to a DAO
  140. #[clap(long)]
  141. dao: bool,
  142. /// DAO bulla, if the tokens are being sent to a DAO
  143. dao_bulla: Option<String>,
  144. },
  145. /// OTC atomic swap
  146. #[command(subcommand)]
  147. Otc(OtcSubcmd),
  148. /// Inspect a transaction from stdin
  149. Inspect,
  150. /// Read a transaction from stdin and broadcast it
  151. Broadcast,
  152. /// Subscribe to incoming blocks from darkfid
  153. ///
  154. /// This subscription will listen for incoming blocks from darkfid and look
  155. /// through their transactions to see if there's any that interest us.
  156. /// With `drk` we look at transactions calling the money contract so we can
  157. /// find coins sent to us and fill our wallet with the necessary metadata.
  158. Subscribe,
  159. /// DAO functionalities
  160. #[command(subcommand)]
  161. Dao(DaoSubcmd),
  162. /// Scan the blockchain and parse relevant transactions
  163. Scan {
  164. #[arg(long)]
  165. /// Reset Merkle tree and start scanning from first slot
  166. reset: bool,
  167. #[arg(long)]
  168. /// List all available checkpoints
  169. list: bool,
  170. #[arg(short, long)]
  171. /// Reset Merkle tree to checkpoint index and start scanning
  172. checkpoint: Option<u64>,
  173. },
  174. /// Explorer related subcommands
  175. #[command(subcommand)]
  176. Explorer(ExplorerSubcmd),
  177. /// Manage Token aliases
  178. #[command(subcommand)]
  179. Alias(AliasSubcmd),
  180. }
  181. #[derive(Subcommand)]
  182. enum OtcSubcmd {
  183. /// Initialize the first half of the atomic swap
  184. Init {
  185. /// Value pair to send:recv (11.55:99.42)
  186. #[clap(short, long)]
  187. value_pair: String,
  188. /// Token pair to send:recv (f00:b4r)
  189. #[clap(short, long)]
  190. token_pair: String,
  191. },
  192. /// Build entire swap tx given the first half from stdin
  193. Join,
  194. /// Inspect a swap half or the full swap tx from stdin
  195. Inspect,
  196. /// Sign a transaction given from stdin as the first-half
  197. Sign,
  198. }
  199. #[derive(Subcommand)]
  200. enum DaoSubcmd {
  201. /// Create DAO parameters
  202. Create {
  203. /// The minimum amount of governance tokens needed to open a proposal for this DAO
  204. proposer_limit: String,
  205. /// Minimal threshold of participating total tokens needed for a proposal to pass
  206. quorum: String,
  207. /// The ratio of winning votes/total votes needed for a proposal to pass (2 decimals),
  208. approval_ratio: f64,
  209. /// DAO's governance token ID
  210. gov_token_id: String,
  211. },
  212. /// View DAO data from stdin
  213. View,
  214. /// Import DAO data from stdin
  215. Import {
  216. /// Named identifier for the DAO
  217. dao_name: String,
  218. },
  219. /// List imported DAOs (or info about a specific one)
  220. List {
  221. /// Numeric identifier for the DAO (optional)
  222. dao_id: Option<u64>,
  223. },
  224. /// Show the balance of a DAO
  225. Balance {
  226. /// Numeric identifier for the DAO
  227. dao_id: u64,
  228. },
  229. /// Mint an imported DAO on-chain
  230. Mint {
  231. /// Numeric identifier for the DAO
  232. dao_id: u64,
  233. },
  234. /// Create a proposal for a DAO
  235. Propose {
  236. /// Numeric identifier for the DAO
  237. dao_id: u64,
  238. /// Pubkey to send tokens to with proposal success
  239. recipient: String,
  240. /// Amount to send from DAO with proposal success
  241. amount: String,
  242. /// Token ID to send from DAO with proposal success
  243. token_id: String,
  244. },
  245. /// List DAO proposals
  246. Proposals {
  247. /// Numeric identifier for the DAO
  248. dao_id: u64,
  249. },
  250. /// View a DAO proposal data
  251. Proposal {
  252. /// Numeric identifier for the DAO
  253. dao_id: u64,
  254. /// Numeric identifier for the proposal
  255. proposal_id: u64,
  256. },
  257. /// Vote on a given proposal
  258. Vote {
  259. /// Numeric identifier for the DAO
  260. dao_id: u64,
  261. /// Numeric identifier for the proposal
  262. proposal_id: u64,
  263. /// Vote (0 for NO, 1 for YES)
  264. vote: u8,
  265. /// Vote weight (amount of governance tokens)
  266. vote_weight: String,
  267. },
  268. /// Execute a DAO proposal
  269. Exec {
  270. /// Numeric identifier for the DAO
  271. dao_id: u64,
  272. /// Numeric identifier for the proposal
  273. proposal_id: u64,
  274. },
  275. }
  276. #[derive(Subcommand)]
  277. enum ExplorerSubcmd {
  278. /// Fetch a blockchain transaction by hash
  279. FetchTx {
  280. /// Transaction hash
  281. tx_hash: String,
  282. },
  283. /// Read a transaction from stdin and simulate it
  284. SimulateTx,
  285. }
  286. #[derive(Subcommand)]
  287. enum AliasSubcmd {
  288. /// Create a Token alias
  289. Add {
  290. /// Token alias
  291. alias: String,
  292. /// Token to create alias for
  293. token: String,
  294. },
  295. /// Print alias info of optional arguments.
  296. /// If no argument is provided, list all the aliases in the wallet.
  297. Show {
  298. /// Token alias to search for
  299. #[clap(short, long)]
  300. alias: Option<String>,
  301. /// Token to search alias for
  302. #[clap(short, long)]
  303. token: Option<String>,
  304. },
  305. /// Remove a Token alias
  306. Remove {
  307. /// Token alias to remove
  308. alias: String,
  309. },
  310. }
  311. pub struct Drk {
  312. pub rpc_client: RpcClient,
  313. }
  314. impl Drk {
  315. async fn new(endpoint: Url) -> Result<Self> {
  316. let rpc_client = RpcClient::new(endpoint).await?;
  317. Ok(Self { rpc_client })
  318. }
  319. async fn ping(&self) -> Result<()> {
  320. let latency = Instant::now();
  321. let req = JsonRequest::new("ping", json!([]));
  322. let rep = self.rpc_client.oneshot_request(req).await?;
  323. let latency = latency.elapsed();
  324. println!("Got reply: {}", rep);
  325. println!("Latency: {:?}", latency);
  326. Ok(())
  327. }
  328. }
  329. #[async_std::main]
  330. async fn main() -> Result<()> {
  331. let args = Args::parse();
  332. if args.verbose > 0 {
  333. let log_level = get_log_level(args.verbose.into());
  334. let log_config = get_log_config();
  335. TermLogger::init(log_level, log_config, TerminalMode::Mixed, ColorChoice::Auto)?;
  336. }
  337. match args.command {
  338. Subcmd::Ping => {
  339. let drk = Drk::new(args.endpoint).await?;
  340. drk.ping().await.with_context(|| "Failed to ping darkfid RPC endpoint")?;
  341. Ok(())
  342. }
  343. Subcmd::Completions { shell } => {
  344. let mut cmd = Args::command();
  345. generate(shell, &mut cmd, "./drk", &mut std::io::stdout());
  346. Ok(())
  347. }
  348. Subcmd::Wallet {
  349. initialize,
  350. keygen,
  351. balance,
  352. address,
  353. secrets,
  354. import_secrets,
  355. tree,
  356. coins,
  357. } => {
  358. if !initialize &&
  359. !keygen &&
  360. !balance &&
  361. !address &&
  362. !secrets &&
  363. !tree &&
  364. !coins &&
  365. !import_secrets
  366. {
  367. eprintln!("Error: You must use at least one flag for this subcommand");
  368. eprintln!("Run with \"wallet -h\" to see the subcommand usage.");
  369. exit(2);
  370. }
  371. let drk = Drk::new(args.endpoint).await?;
  372. if initialize {
  373. drk.initialize_money().await?;
  374. drk.initialize_dao().await?;
  375. return Ok(())
  376. }
  377. if keygen {
  378. drk.money_keygen().await.with_context(|| "Failed to generate keypair")?;
  379. return Ok(())
  380. }
  381. if balance {
  382. let balmap =
  383. drk.money_balance().await.with_context(|| "Failed to fetch wallet balance")?;
  384. let aliases_map = drk
  385. .get_aliases_mapped_by_token()
  386. .await
  387. .with_context(|| "Failed to fetch wallet aliases")?;
  388. // Create a prettytable with the new data:
  389. let mut table = Table::new();
  390. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  391. table.set_titles(row!["Token ID", "Aliases", "Balance"]);
  392. for (token_id, balance) in balmap.iter() {
  393. let aliases = match aliases_map.get(token_id) {
  394. Some(a) => a,
  395. None => "-",
  396. };
  397. // FIXME: Don't hardcode to 8 decimals
  398. table.add_row(row![token_id, aliases, encode_base10(*balance, 8)]);
  399. }
  400. if table.is_empty() {
  401. println!("No unspent balances found");
  402. } else {
  403. println!("{}", table);
  404. }
  405. return Ok(())
  406. }
  407. if address {
  408. let address = drk
  409. .wallet_address(1) // <-- TODO: Use is_default from the sql table
  410. .await
  411. .with_context(|| "Failed to fetch default address")?;
  412. println!("{}", address);
  413. return Ok(())
  414. }
  415. if secrets {
  416. let v = drk
  417. .get_money_secrets()
  418. .await
  419. .with_context(|| "Failed to fetch wallet secrets")?;
  420. drk.rpc_client.close().await?;
  421. for i in v {
  422. println!("{}", i);
  423. }
  424. return Ok(())
  425. }
  426. if import_secrets {
  427. let mut secrets = vec![];
  428. let lines = stdin().lines();
  429. for (i, line) in lines.enumerate() {
  430. if let Ok(line) = line {
  431. let bytes = bs58::decode(&line.trim()).into_vec()?;
  432. let Ok(secret) = deserialize(&bytes) else {
  433. eprintln!("Warning: Failed to deserialize secret on line {}", i);
  434. continue
  435. };
  436. secrets.push(secret);
  437. }
  438. }
  439. let pubkeys = drk
  440. .import_money_secrets(secrets)
  441. .await
  442. .with_context(|| "Failed to import secret keys into wallet")?;
  443. drk.rpc_client.close().await?;
  444. for key in pubkeys {
  445. println!("{}", key);
  446. }
  447. return Ok(())
  448. }
  449. if tree {
  450. let v =
  451. drk.get_money_tree().await.with_context(|| "Failed to fetch Merkle tree")?;
  452. drk.rpc_client.close().await?;
  453. println!("{:#?}", v);
  454. return Ok(())
  455. }
  456. if coins {
  457. let coins = drk
  458. .get_coins(true)
  459. .await
  460. .with_context(|| "Failed to fetch coins from wallet")?;
  461. let aliases_map = drk
  462. .get_aliases_mapped_by_token()
  463. .await
  464. .with_context(|| "Failed to fetch wallet aliases")?;
  465. drk.rpc_client.close().await?;
  466. if coins.is_empty() {
  467. return Ok(())
  468. }
  469. let mut table = Table::new();
  470. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  471. table.set_titles(row!["Coin", "Spent", "Token ID", "Aliases", "Value"]);
  472. for coin in coins {
  473. let aliases = match aliases_map.get(&coin.0.note.token_id.to_string()) {
  474. Some(a) => a,
  475. None => "-",
  476. };
  477. table.add_row(row![
  478. format!("{}", bs58::encode(&serialize(&coin.0.coin.inner())).into_string()),
  479. coin.1,
  480. coin.0.note.token_id,
  481. aliases,
  482. format!("{} ({})", coin.0.note.value, encode_base10(coin.0.note.value, 8))
  483. ]);
  484. }
  485. println!("{}", table);
  486. return Ok(())
  487. }
  488. unreachable!()
  489. }
  490. Subcmd::Unspend { coin } => {
  491. let bytes: [u8; 32] = bs58::decode(&coin).into_vec()?.try_into().unwrap();
  492. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  493. Some(v) => v,
  494. None => return Err(anyhow!("Invalid coin")),
  495. };
  496. let coin = Coin::from(elem);
  497. let drk = Drk::new(args.endpoint).await?;
  498. drk.unspend_coin(&coin).await.with_context(|| "Failed to mark coin as unspent")?;
  499. Ok(())
  500. }
  501. Subcmd::Airdrop { faucet_endpoint, amount, token, address } => {
  502. let amount = f64::from_str(&amount).with_context(|| "Invalid amount")?;
  503. let drk = Drk::new(args.endpoint).await?;
  504. let token_id = drk.get_token(token).await.with_context(|| "Invalid Token ID")?;
  505. let address = match address {
  506. Some(v) => PublicKey::from_str(v.as_str()).with_context(|| "Invalid address")?,
  507. None => drk.wallet_address(1).await.with_context(|| {
  508. "Failed to fetch default address, perhaps the wallet was not initialized?"
  509. })?,
  510. };
  511. let txid = drk
  512. .request_airdrop(faucet_endpoint, amount, token_id, address)
  513. .await
  514. .with_context(|| "Failed to request airdrop")?;
  515. println!("Transaction ID: {}", txid);
  516. Ok(())
  517. }
  518. Subcmd::Transfer { amount, token, recipient, dao, dao_bulla } => {
  519. let _ = f64::from_str(&amount).with_context(|| "Invalid amount")?;
  520. let rcpt = PublicKey::from_str(&recipient).with_context(|| "Invalid recipient")?;
  521. let drk = Drk::new(args.endpoint).await?;
  522. let token_id = drk.get_token(token).await.with_context(|| "Invalid Token ID")?;
  523. let tx = drk
  524. .transfer(&amount, token_id, rcpt, dao, dao_bulla)
  525. .await
  526. .with_context(|| "Failed to create payment transaction")?;
  527. println!("{}", bs58::encode(&serialize(&tx)).into_string());
  528. Ok(())
  529. }
  530. Subcmd::Otc(cmd) => {
  531. let drk = Drk::new(args.endpoint).await?;
  532. match cmd {
  533. OtcSubcmd::Init { value_pair, token_pair } => {
  534. let (vp_send, vp_recv) = parse_value_pair(&value_pair)?;
  535. let (tp_send, tp_recv) = parse_token_pair(&token_pair)?;
  536. let half = drk
  537. .init_swap(vp_send, tp_send, vp_recv, tp_recv)
  538. .await
  539. .with_context(|| "Failed to create swap transaction half")?;
  540. println!("{}", bs58::encode(&serialize(&half)).into_string());
  541. Ok(())
  542. }
  543. OtcSubcmd::Join => {
  544. let mut buf = String::new();
  545. stdin().read_to_string(&mut buf)?;
  546. let bytes = bs58::decode(&buf.trim()).into_vec()?;
  547. let partial: PartialSwapData = deserialize(&bytes)?;
  548. let tx = drk
  549. .join_swap(partial)
  550. .await
  551. .with_context(|| "Failed to create a join swap transaction")?;
  552. println!("{}", bs58::encode(&serialize(&tx)).into_string());
  553. Ok(())
  554. }
  555. OtcSubcmd::Inspect => {
  556. let mut buf = String::new();
  557. stdin().read_to_string(&mut buf)?;
  558. let bytes = bs58::decode(&buf.trim()).into_vec()?;
  559. drk.inspect_swap(bytes).await.with_context(|| "Failed to inspect swap")?;
  560. Ok(())
  561. }
  562. OtcSubcmd::Sign => {
  563. let mut buf = String::new();
  564. stdin().read_to_string(&mut buf)?;
  565. let bytes = bs58::decode(&buf.trim()).into_vec()?;
  566. let mut tx: Transaction = deserialize(&bytes)?;
  567. drk.sign_swap(&mut tx)
  568. .await
  569. .with_context(|| "Failed to sign joined swap transaction")?;
  570. println!("{}", bs58::encode(&serialize(&tx)).into_string());
  571. Ok(())
  572. }
  573. }
  574. }
  575. Subcmd::Inspect => {
  576. let mut buf = String::new();
  577. stdin().read_to_string(&mut buf)?;
  578. let bytes = bs58::decode(&buf.trim()).into_vec()?;
  579. let tx: Transaction = deserialize(&bytes)?;
  580. println!("{:#?}", tx);
  581. Ok(())
  582. }
  583. Subcmd::Broadcast => {
  584. eprintln!("Reading transaction from stdin...");
  585. let mut buf = String::new();
  586. stdin().read_to_string(&mut buf)?;
  587. let bytes = bs58::decode(&buf.trim()).into_vec()?;
  588. let tx = deserialize(&bytes)?;
  589. let drk = Drk::new(args.endpoint).await?;
  590. let txid =
  591. drk.broadcast_tx(&tx).await.with_context(|| "Failed to broadcast transaction")?;
  592. println!("Transaction ID: {}", txid);
  593. Ok(())
  594. }
  595. Subcmd::Subscribe => {
  596. let drk = Drk::new(args.endpoint.clone()).await?;
  597. drk.subscribe_blocks(args.endpoint)
  598. .await
  599. .with_context(|| "Block subscription failed")?;
  600. Ok(())
  601. }
  602. Subcmd::Scan { reset, list, checkpoint } => {
  603. let drk = Drk::new(args.endpoint).await?;
  604. if reset {
  605. eprintln!("Reset requested.");
  606. drk.scan_blocks(true).await.with_context(|| "Failed during scanning")?;
  607. return Ok(())
  608. }
  609. if list {
  610. eprintln!("List requested.");
  611. // TODO: implement
  612. return Ok(())
  613. }
  614. if let Some(c) = checkpoint {
  615. eprintln!("Checkpoint requested: {}", c);
  616. // TODO: implement
  617. return Ok(())
  618. }
  619. drk.scan_blocks(false).await.with_context(|| "Failed during scanning")?;
  620. eprintln!("Finished scanning blockchain");
  621. Ok(())
  622. }
  623. Subcmd::Dao(cmd) => match cmd {
  624. DaoSubcmd::Create { proposer_limit, quorum, approval_ratio, gov_token_id } => {
  625. let _ = f64::from_str(&proposer_limit).with_context(|| "Invalid proposer limit")?;
  626. let _ = f64::from_str(&quorum).with_context(|| "Invalid quorum")?;
  627. let proposer_limit = decode_base10(&proposer_limit, 8, true)?;
  628. let quorum = decode_base10(&quorum, 8, true)?;
  629. if approval_ratio > 1.0 {
  630. eprintln!("Error: Approval ratio cannot be >1.0");
  631. exit(1);
  632. }
  633. let approval_ratio_base = 100_u64;
  634. let approval_ratio_quot = (approval_ratio * approval_ratio_base as f64) as u64;
  635. let drk = Drk::new(args.endpoint).await?;
  636. let gov_token_id =
  637. drk.get_token(gov_token_id).await.with_context(|| "Invalid Token ID")?;
  638. let secret_key = SecretKey::random(&mut OsRng);
  639. let bulla_blind = pallas::Base::random(&mut OsRng);
  640. let dao_params = DaoParams {
  641. proposer_limit,
  642. quorum,
  643. approval_ratio_base,
  644. approval_ratio_quot,
  645. gov_token_id,
  646. secret_key,
  647. bulla_blind,
  648. };
  649. let encoded = bs58::encode(&serialize(&dao_params)).into_string();
  650. println!("{}", encoded);
  651. Ok(())
  652. }
  653. DaoSubcmd::View => {
  654. let mut buf = String::new();
  655. stdin().read_to_string(&mut buf)?;
  656. let bytes = bs58::decode(&buf.trim()).into_vec()?;
  657. let dao_params: DaoParams = deserialize(&bytes)?;
  658. println!("{}", dao_params);
  659. Ok(())
  660. }
  661. DaoSubcmd::Import { dao_name } => {
  662. let mut buf = String::new();
  663. stdin().read_to_string(&mut buf)?;
  664. let bytes = bs58::decode(&buf.trim()).into_vec()?;
  665. let dao_params: DaoParams = deserialize(&bytes)?;
  666. let drk = Drk::new(args.endpoint).await?;
  667. drk.import_dao(dao_name, dao_params)
  668. .await
  669. .with_context(|| "Failed to import DAO")?;
  670. Ok(())
  671. }
  672. DaoSubcmd::List { dao_id } => {
  673. let drk = Drk::new(args.endpoint).await?;
  674. drk.dao_list(dao_id).await.with_context(|| "Failed to list DAO")?;
  675. Ok(())
  676. }
  677. DaoSubcmd::Balance { dao_id } => {
  678. let drk = Drk::new(args.endpoint).await?;
  679. let balmap =
  680. drk.dao_balance(dao_id).await.with_context(|| "Failed to fetch DAO balance")?;
  681. let aliases_map = drk
  682. .get_aliases_mapped_by_token()
  683. .await
  684. .with_context(|| "Failed to fetch wallet aliases")?;
  685. // Create a prettytable with the new data:
  686. let mut table = Table::new();
  687. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  688. table.set_titles(row!["Token ID", "Aliases", "Balance"]);
  689. for (token_id, balance) in balmap.iter() {
  690. let aliases = match aliases_map.get(token_id) {
  691. Some(a) => a,
  692. None => "-",
  693. };
  694. // FIXME: Don't hardcode to 8 decimals
  695. table.add_row(row![token_id, aliases, encode_base10(*balance, 8)]);
  696. }
  697. if table.is_empty() {
  698. println!("No unspent balances found");
  699. } else {
  700. println!("{}", table);
  701. }
  702. return Ok(())
  703. }
  704. DaoSubcmd::Mint { dao_id } => {
  705. let drk = Drk::new(args.endpoint).await?;
  706. let tx = drk.dao_mint(dao_id).await.with_context(|| "Failed to mint DAO")?;
  707. println!("{}", bs58::encode(&serialize(&tx)).into_string());
  708. Ok(())
  709. }
  710. DaoSubcmd::Propose { dao_id, recipient, amount, token_id } => {
  711. let _ = f64::from_str(&amount).with_context(|| "Invalid amount")?;
  712. let amount = decode_base10(&amount, 8, true)?;
  713. let rcpt = PublicKey::from_str(&recipient).with_context(|| "Invalid recipient")?;
  714. let drk = Drk::new(args.endpoint).await?;
  715. let token_id = drk.get_token(token_id).await.with_context(|| "Invalid Token ID")?;
  716. let tx = drk
  717. .dao_propose(dao_id, rcpt, amount, token_id)
  718. .await
  719. .with_context(|| "Failed to create DAO proposal")?;
  720. println!("{}", bs58::encode(&serialize(&tx)).into_string());
  721. Ok(())
  722. }
  723. DaoSubcmd::Proposals { dao_id } => {
  724. let drk = Drk::new(args.endpoint).await?;
  725. let proposals = drk.get_dao_proposals(dao_id).await?;
  726. for proposal in proposals {
  727. println!("[{}] {:?}", proposal.id, proposal.bulla());
  728. }
  729. Ok(())
  730. }
  731. DaoSubcmd::Proposal { dao_id, proposal_id } => {
  732. let drk = Drk::new(args.endpoint).await?;
  733. let proposals = drk.get_dao_proposals(dao_id).await?;
  734. let Some(proposal) = proposals.iter().find(|x| x.id == proposal_id) else {
  735. eprintln!("No such DAO proposal found");
  736. exit(1);
  737. };
  738. println!("{}", proposal);
  739. Ok(())
  740. }
  741. DaoSubcmd::Vote { dao_id, proposal_id, vote, vote_weight } => {
  742. let drk = Drk::new(args.endpoint).await?;
  743. let _ = f64::from_str(&vote_weight).with_context(|| "Invalid vote weight")?;
  744. let weight = decode_base10(&vote_weight, 8, true)?;
  745. if vote > 1 {
  746. eprintln!("Vote can be either 0 (NO) or 1 (YES)");
  747. exit(1);
  748. }
  749. let vote = vote != 0;
  750. let tx = drk
  751. .dao_vote(dao_id, proposal_id, vote, weight)
  752. .await
  753. .with_context(|| "Failed to create DAO Vote transaction")?;
  754. // TODO: Write our_vote in the proposal sql.
  755. println!("{}", bs58::encode(&serialize(&tx)).into_string());
  756. Ok(())
  757. }
  758. DaoSubcmd::Exec { dao_id, proposal_id } => {
  759. let drk = Drk::new(args.endpoint).await?;
  760. let dao = drk.get_dao_by_id(dao_id).await?;
  761. let proposal = drk.get_dao_proposal_by_id(proposal_id).await?;
  762. assert!(proposal.dao_bulla == dao.bulla());
  763. let tx = drk
  764. .dao_exec(dao, proposal)
  765. .await
  766. .with_context(|| "Failed to execute DAO proposal")?;
  767. println!("{}", bs58::encode(&serialize(&tx)).into_string());
  768. Ok(())
  769. }
  770. },
  771. Subcmd::Explorer(cmd) => match cmd {
  772. ExplorerSubcmd::FetchTx { tx_hash } => {
  773. let tx_hash = blake3::Hash::from_hex(&tx_hash)?;
  774. let drk = Drk::new(args.endpoint).await?;
  775. let tx = if let Some(tx) =
  776. drk.get_tx(&tx_hash).await.with_context(|| "Failed to fetch transaction")?
  777. {
  778. tx
  779. } else {
  780. eprintln!("Tx not found");
  781. return Ok(())
  782. };
  783. // Make sure the tx is correct
  784. assert_eq!(tx.hash(), tx_hash);
  785. println!("Transaction ID: {}", tx_hash);
  786. let is_err = drk
  787. .was_erroneous_tx(&tx_hash)
  788. .await
  789. .with_context(|| "Failed to get tx state")?;
  790. println!("State: {}", if is_err { "failed" } else { "passed" });
  791. Ok(())
  792. }
  793. ExplorerSubcmd::SimulateTx => {
  794. eprintln!("Reading transaction from stdin...");
  795. let mut buf = String::new();
  796. stdin().read_to_string(&mut buf)?;
  797. let bytes = bs58::decode(&buf.trim()).into_vec()?;
  798. let tx = deserialize(&bytes)?;
  799. let drk = Drk::new(args.endpoint).await?;
  800. let is_valid =
  801. drk.simulate_tx(&tx).await.with_context(|| "Failed to simulate tx")?;
  802. println!("Transaction ID: {}", tx.hash());
  803. println!("State: {}", if is_valid { "valid" } else { "invalid" });
  804. Ok(())
  805. }
  806. },
  807. Subcmd::Alias(cmd) => match cmd {
  808. AliasSubcmd::Add { alias, token } => {
  809. if alias.chars().count() > 5 {
  810. eprintln!("Error: Alias exceeds 5 characters");
  811. return Ok(())
  812. }
  813. let token_id =
  814. TokenId::try_from(token.as_str()).with_context(|| "Invalid Token ID")?;
  815. let drk = Drk::new(args.endpoint).await?;
  816. drk.add_alias(alias, token_id).await?;
  817. Ok(())
  818. }
  819. AliasSubcmd::Show { alias, token } => {
  820. let token_id = match token {
  821. Some(t) => {
  822. Some(TokenId::try_from(t.as_str()).with_context(|| "Invalid Token ID")?)
  823. }
  824. None => None,
  825. };
  826. let drk = Drk::new(args.endpoint).await?;
  827. let map = drk.get_aliases(alias, token_id).await?;
  828. // Create a prettytable with the new data:
  829. let mut table = Table::new();
  830. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  831. table.set_titles(row!["Alias", "Token ID"]);
  832. for (alias, token_id) in map.iter() {
  833. table.add_row(row![alias, token_id]);
  834. }
  835. if table.is_empty() {
  836. println!("No aliases found");
  837. } else {
  838. println!("{}", table);
  839. }
  840. Ok(())
  841. }
  842. AliasSubcmd::Remove { alias } => {
  843. let drk = Drk::new(args.endpoint).await?;
  844. drk.remove_alias(alias).await?;
  845. Ok(())
  846. }
  847. },
  848. }
  849. }