main.rs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. use async_executor::Executor;
  2. use clap::{IntoApp, Parser};
  3. use darkfi::{
  4. cli::{CliDao, CliDaoSubCommands, Config},
  5. rpc::{jsonrpc, jsonrpc::JsonResult},
  6. util::async_util,
  7. Error, Result,
  8. };
  9. use log::{debug, error};
  10. use serde_json::{json, Value};
  11. use std::sync::Arc;
  12. pub struct Client {
  13. url: String,
  14. }
  15. impl Client {
  16. pub fn new(url: String) -> Self {
  17. Self { url }
  18. }
  19. async fn request(&self, r: jsonrpc::JsonRequest) -> Result<Value> {
  20. let reply: JsonResult = match jsonrpc::send_request(&self.url, json!(r)).await {
  21. Ok(v) => v,
  22. Err(e) => return Err(e),
  23. };
  24. match reply {
  25. JsonResult::Resp(r) => {
  26. debug!(target: "RPC", "<-- {}", serde_json::to_string(&r)?);
  27. Ok(r.result)
  28. }
  29. JsonResult::Err(e) => {
  30. debug!(target: "RPC", "<-- {}", serde_json::to_string(&e)?);
  31. Err(Error::JsonRpcError(e.error.message.to_string()))
  32. }
  33. JsonResult::Notif(n) => {
  34. debug!(target: "RPC", "<-- {}", serde_json::to_string(&n)?);
  35. Err(Error::JsonRpcError("Unexpected reply".to_string()))
  36. }
  37. }
  38. }
  39. // --> {"jsonrpc": "2.0", "method": "say_hello", "params": [], "id": 42}
  40. // <-- {"jsonrpc": "2.0", "result": "hello world", "id": 42}
  41. async fn say_hello(&self) -> Result<Value> {
  42. let req = jsonrpc::request(json!("say_hello"), json!([]));
  43. Ok(self.request(req).await?)
  44. }
  45. }
  46. async fn start(options: CliDao) -> Result<()> {
  47. let rpc_addr = "tcp://127.0.0.1:7777";
  48. let client = Client::new(rpc_addr.to_string());
  49. match options.command {
  50. Some(CliDaoSubCommands::Hello {}) => {
  51. let reply = client.say_hello().await?;
  52. println!("Server replied: {}", &reply.to_string());
  53. return Ok(())
  54. }
  55. None => {}
  56. }
  57. error!("Please run 'dao help' to see usage.");
  58. Err(Error::MissingParams)
  59. }
  60. #[async_std::main]
  61. async fn main() -> Result<()> {
  62. let args = CliDao::parse();
  63. let matches = CliDao::into_app().get_matches();
  64. //let config_path = if args.config.is_some() {
  65. // expand_path(&args.config.clone().unwrap())?
  66. //} else {
  67. // join_config_path(&PathBuf::from("drk.toml"))?
  68. //};
  69. // Spawn config file if it's not in place already.
  70. //spawn_config(&config_path, CONFIG_FILE_CONTENTS)?;
  71. //let (lvl, conf) = log_config(matches)?;
  72. //TermLogger::init(lvl, conf, TerminalMode::Mixed, ColorChoice::Auto)?;
  73. //let config = Config::<DrkConfig>::load(config_path)?;
  74. start(args).await
  75. }