main.rs 27 KB

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