Skip to content

Commit

Permalink
[refactor]: Refactored error handling using anyhow
Browse files Browse the repository at this point in the history
  • Loading branch information
woxjro committed Jan 15, 2024
1 parent df98ce3 commit 0cbeef2
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 27 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ simplelog = "0.12.1"
serde = "1.0.189"
url = "2.4.1"
tempfile = "3.9.0"
anyhow = "1.0.79"

[dependencies.crossterm]
version = "0.26.1"
Expand Down
19 changes: 8 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod network;
mod route;
mod ui;
mod widget;
use anyhow::Result;
use app::{event_handling::event_handling, App};
use chrono::Utc;
use clap::Parser;
Expand All @@ -12,7 +13,7 @@ use log::LevelFilter;
use network::{IoEvent, Network};
use ratatui::prelude::*;
use simplelog::{ColorChoice, CombinedLogger, Config, TermLogger, TerminalMode, WriteLogger};
use std::{error::Error, io, sync::Arc, time::Duration};
use std::{io, sync::Arc, time::Duration};
use tokio::sync::Mutex;

#[derive(Parser, Debug)]
Expand All @@ -24,7 +25,7 @@ struct Args {
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
async fn main() -> Result<()> {
let _ = std::fs::create_dir("logs");
CombinedLogger::init(vec![
TermLogger::new(
Expand All @@ -36,10 +37,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
WriteLogger::new(
LevelFilter::Debug,
Config::default(),
std::fs::File::create(format!("logs/{}.log", Utc::now().format("%Y%m%d%H%M"))).unwrap(),
std::fs::File::create(format!("logs/{}.log", Utc::now().format("%Y%m%d%H%M")))?,
),
])
.unwrap();
])?;

// setup terminal
terminal::enable_raw_mode()?;
Expand Down Expand Up @@ -84,10 +84,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
Ok(())
}

async fn start_ui<B: Backend>(
terminal: &mut Terminal<B>,
app: &Arc<Mutex<App>>,
) -> Result<(), Box<dyn Error>> {
async fn start_ui<B: Backend>(terminal: &mut Terminal<B>, app: &Arc<Mutex<App>>) -> Result<()> {
let mut is_first_render = true;

loop {
Expand All @@ -102,7 +99,7 @@ async fn start_ui<B: Backend>(
}

if is_first_render {
let height = terminal.size().unwrap().height as usize;
let height = terminal.size()?.height as usize;
app.dispatch(IoEvent::InitialSetup {
n: (height - 3 * 4) / 2 - 4,
});
Expand All @@ -115,6 +112,6 @@ async fn start_ui<B: Backend>(
#[tokio::main]
async fn start_tokio(io_rx: std::sync::mpsc::Receiver<IoEvent>, network: &mut Network) {
while let Ok(io_event) = io_rx.recv() {
network.handle_network_event(io_event).await;
let _ = network.handle_network_event(io_event).await;
}
}
39 changes: 23 additions & 16 deletions src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{
route::{ActiveBlock, Route, RouteId},
widget::StatefulList,
};
use anyhow::Result;
use ethers::{
core::types::{
Address, BlockId, BlockNumber, Chain, NameOrAddress, Transaction, TransactionReceipt,
Expand Down Expand Up @@ -70,7 +71,7 @@ impl<'a> Network<'a> {
Self { app, endpoint }
}

pub async fn handle_network_event(&mut self, io_event: IoEvent) {
pub async fn handle_network_event(&mut self, io_event: IoEvent) -> Result<()> {
match io_event {
IoEvent::GetStatistics => {
let res = Self::get_statistics(self.endpoint).await;
Expand All @@ -79,6 +80,7 @@ impl<'a> Network<'a> {
app.statistics = statistics;
}
app.is_loading = false;
Ok(())
}
IoEvent::GetNameOrAddressInfo {
name_or_address,
Expand All @@ -100,6 +102,7 @@ impl<'a> Network<'a> {
));

app.is_loading = false;
Ok(())
}
IoEvent::GetBlock { number } => {
let res = Self::get_block(self.endpoint, number).await;
Expand Down Expand Up @@ -127,6 +130,7 @@ impl<'a> Network<'a> {
}
let mut app = self.app.lock().await;
app.is_loading = false;
Ok(())
}
IoEvent::GetBlockByHash { hash } => {
let res = Self::get_block(self.endpoint, hash).await;
Expand Down Expand Up @@ -154,6 +158,7 @@ impl<'a> Network<'a> {
}
let mut app = self.app.lock().await;
app.is_loading = false;
Ok(())
}
IoEvent::GetDecodedInputData { transaction } => {
let res = Self::get_decoded_input_data(transaction).await;
Expand Down Expand Up @@ -186,6 +191,7 @@ impl<'a> Network<'a> {
_ => {}
}
}
Ok(())
}
IoEvent::GetTransactionWithReceipt { transaction_hash } => {
let res = Self::get_transaction_with_receipt(self.endpoint, transaction_hash).await;
Expand All @@ -194,6 +200,7 @@ impl<'a> Network<'a> {
app.set_route(Route::new(RouteId::Transaction(some), ActiveBlock::Main));
}
app.is_loading = false;
Ok(())
}
IoEvent::GetTransactionReceipts { transactions } => {
let splitted_transactions = transactions.chunks(RATE_LIMIT).collect::<Vec<_>>();
Expand All @@ -207,15 +214,15 @@ impl<'a> Network<'a> {
}
let mut app = self.app.lock().await;
app.is_loading = false;
Ok(())
}
IoEvent::InitialSetup { n } => {
let (statistics, blocks, transactions) = try_join3(
Self::get_statistics(self.endpoint),
Self::get_latest_blocks(self.endpoint, n),
Self::get_latest_transactions(self.endpoint, n),
)
.await
.unwrap();
.await?;
let mut addresses = vec![];
for transaction in &transactions {
addresses.push(transaction.transaction.from);
Expand All @@ -236,17 +243,17 @@ impl<'a> Network<'a> {

let mut app = self.app.lock().await;
app.is_loading = false;
Ok(())
}
IoEvent::GetLatestBlocks { n } => {
let blocks = Self::get_latest_blocks(self.endpoint, n).await.unwrap();
let blocks = Self::get_latest_blocks(self.endpoint, n).await?;
let mut app = self.app.lock().await;
app.latest_blocks = Some(StatefulList::with_items(blocks));
app.is_loading = false;
Ok(())
}
IoEvent::GetLatestTransactions { n } => {
let transactions = Self::get_latest_transactions(self.endpoint, n)
.await
.unwrap();
let transactions = Self::get_latest_transactions(self.endpoint, n).await?;

let mut addresses = vec![];
for transaction in &transactions {
Expand All @@ -265,11 +272,13 @@ impl<'a> Network<'a> {

let mut app = self.app.lock().await;
app.is_loading = false;
Ok(())
}
IoEvent::LookupAddresses { addresses } => {
let _ = self.update_app_with_ens_ids(&addresses).await;
let mut app = self.app.lock().await;
app.is_loading = false;
Ok(())
}
}
}
Expand Down Expand Up @@ -362,9 +371,7 @@ impl<'a> Network<'a> {
}))
}

async fn get_decoded_input_data(
transaction: Transaction,
) -> Result<Option<String>, Box<dyn Error>> {
async fn get_decoded_input_data(transaction: Transaction) -> Result<Option<String>> {
let decoded_input_data = if let Ok(client) = Client::new_from_env(Chain::Mainnet) {
if let Some(to) = transaction.to {
let abi = client.contract_abi(to).await?;
Expand Down Expand Up @@ -401,7 +408,7 @@ impl<'a> Network<'a> {
async fn get_transaction_with_receipt(
endpoint: &'a str,
transaction_hash: TxHash,
) -> Result<Option<TransactionWithReceipt>, Box<dyn Error>> {
) -> Result<Option<TransactionWithReceipt>> {
let provider = Provider::<Http>::try_from(endpoint)?;
let transaction = provider.get_transaction(transaction_hash).await?;
let transaction_receipt = provider.get_transaction_receipt(transaction_hash).await?;
Expand Down Expand Up @@ -454,7 +461,7 @@ impl<'a> Network<'a> {
async fn get_latest_blocks(
endpoint: &'a str,
n: usize,
) -> Result<Vec<BlockWithTransactionReceipts<Transaction>>, Box<dyn Error>> {
) -> Result<Vec<BlockWithTransactionReceipts<Transaction>>> {
let provider = Provider::<Http>::try_from(endpoint)?;
let block_number = provider.get_block_number().await?;

Expand All @@ -479,7 +486,7 @@ impl<'a> Network<'a> {
async fn get_transaction_receipts(
endpoint: &'a str,
transactions: &[Transaction],
) -> Result<Vec<TransactionReceipt>, Box<dyn Error>> {
) -> Result<Vec<TransactionReceipt>> {
let provider = Provider::<Http>::try_from(endpoint)?;
let query = transactions
.iter()
Expand All @@ -498,7 +505,7 @@ impl<'a> Network<'a> {
async fn get_latest_transactions(
endpoint: &'a str,
n: usize,
) -> Result<Vec<TransactionWithReceipt>, Box<dyn Error>> {
) -> Result<Vec<TransactionWithReceipt>> {
let provider = Provider::<Http>::try_from(endpoint)?;

let block = provider.get_block(BlockNumber::Latest).await?;
Expand Down Expand Up @@ -542,7 +549,7 @@ impl<'a> Network<'a> {
Ok(result)
}

async fn get_statistics(endpoint: &'a str) -> Result<Statistics, Box<dyn Error>> {
async fn get_statistics(endpoint: &'a str) -> Result<Statistics> {
let provider = Provider::<Http>::try_from(endpoint)?;

let mut ethusd = None;
Expand Down Expand Up @@ -598,7 +605,7 @@ impl<'a> Network<'a> {
async fn lookup_addresses(
endpoint: &'a str,
addresses: &[Address],
) -> Result<Vec<(Address, Option<String>)>, Box<dyn Error>> {
) -> Result<Vec<(Address, Option<String>)>> {
let provider = Provider::<Http>::try_from(endpoint)?;
let query = addresses
.iter()
Expand Down

0 comments on commit 0cbeef2

Please sign in to comment.