Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add comments to explain RPC client code #302

Merged
merged 3 commits into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion crates/floresta-cli/src/jsonrpc_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,34 @@ use serde::Deserialize;

use crate::rpc::JsonRPCClient;

// Define a Client struct that wraps a jsonrpc::Client
#[derive(Debug)]
pub struct Client(jsonrpc::Client);

// Configuration struct for JSON-RPC client
pub struct JsonRPCConfig {
pub url: String,
pub user: Option<String>,
pub pass: Option<String>,
}

impl Client {
// Constructor to create a new Client with a URL
pub fn new(url: String) -> Self {
let client =
jsonrpc::Client::simple_http(&url, None, None).expect("Failed to create client");
Self(client)
}

// Constructor to create a new Client with a configuration
pub fn new_with_config(config: JsonRPCConfig) -> Self {
let client =
jsonrpc::Client::simple_http(&config.url, config.user.clone(), config.pass.clone())
.expect("Failed to create client");

Self(client)
}

// Method to make an RPC call
pub fn rpc_call<Response>(
&self,
method: &str,
Expand All @@ -36,17 +40,22 @@ impl Client {
where
Response: for<'a> serde::de::Deserialize<'a> + Debug,
{
// Serialize parameters to raw JSON value
let raw = serde_json::value::to_raw_value(params)?;
// Build the RPC request
let req = self.0.build_request(method, Some(&*raw));
// Send the request and handle the response
let resp = self
.0
.send_request(req)
.map_err(crate::rpc_types::Error::from);

// Deserialize and return the result
Ok(resp?.result()?)
}
}

// Implement the JsonRPCClient trait for Client
impl JsonRPCClient for Client {
fn call<T: for<'a> serde::de::Deserialize<'a> + Debug>(
&self,
Expand All @@ -57,6 +66,7 @@ impl JsonRPCClient for Client {
}
}

// Struct to represent a JSON-RPC response
#[derive(Debug, Deserialize)]
pub struct JsonRpcResponse<Res> {
pub jsonrpc: String,
Expand Down
12 changes: 12 additions & 0 deletions crates/floresta-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,32 @@ use clap::Subcommand;
use floresta_cli::jsonrpc_client::Client;
use floresta_cli::rpc::FlorestaRPC;

// Main function that runs the CLI application
fn main() -> anyhow::Result<()> {
// Parse command line arguments into a Cli struct
let cli = Cli::parse();

// Create a new JSON-RPC client using the host from the CLI arguments
let client = Client::new(get_host(&cli));

// Perform the requested RPC call and get the result
let res = do_request(&cli, client)?;

// Print the result to the console
println!("{}", res);

// Return Ok to indicate the program ran successfully
anyhow::Ok(())
}

// Function to determine the RPC host based on CLI arguments and network type
fn get_host(cmd: &Cli) -> String {
// If a specific RPC host is provided, use it
if let Some(host) = cmd.rpc_host.clone() {
return host;
}

// Otherwise, use the default host based on the network type
match cmd.network {
Network::Bitcoin => "http://127.0.0.1:8332".into(),
Network::Testnet => "http://127.0.0.1:18332".into(),
Expand All @@ -34,8 +44,10 @@ fn get_host(cmd: &Cli) -> String {
}
}

// Function to perform the requested RPC call based on CLI arguments
fn do_request(cmd: &Cli, client: Client) -> anyhow::Result<String> {
Ok(match cmd.methods.clone() {
// Handle each possible RPC method and serialize the result to a pretty JSON string
Methods::GetBlockchainInfo => serde_json::to_string_pretty(&client.get_blockchain_info()?)?,
Methods::GetBlockHash { height } => {
serde_json::to_string_pretty(&client.get_block_hash(height)?)?
Expand Down
Loading