diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..f75d8d6 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,14 @@ +## Motivation + + + +## Solution + + diff --git a/.gitmodules b/.gitmodules index 308f142..a91f77f 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ -[submodule "ratatui-tree-widget"] - path = ratatui-tree-widget - url = https://github.com/woxjro/ratatui-tree-widget +[submodule "ethereum-consensus"] + path = ethereum-consensus + url = https://github.com/ralexstokes/ethereum-consensus.git diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..ad1e281 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,245 @@ +# Contributing to lazy-etherscan + +:balloon: Thanks for your help improving the project! We are so happy to have +you! + +There are opportunities to contribute to lazy-etherscan at any level. It doesn't matter if +you are just getting started with Rust or are the most weathered expert, we can +use your help. + +**No contribution is too small and all contributions are valued.** + +This guide will help you get started. **Do not let this guide intimidate you**. +It should be considered a map to help you navigate the process. + +## Conduct + +The lazy-etherscan project adheres to the [Rust Code of Conduct][coc]. This describes +the _minimum_ behavior expected from all contributors. + +## Contributing in Issues + +For any issue, there are fundamentally three ways an individual can contribute: + +1. By opening the issue for discussion: For instance, if you believe that you + have uncovered a bug in lazy-etherscan, creating a new issue in the lazy-etherscan + issue tracker is the way to report it. + +2. By helping to triage the issue: This can be done by providing + supporting details (a test case that demonstrates a bug), providing + suggestions on how to address the issue, or ensuring that the issue is tagged + correctly. + +3. By helping to resolve the issue: Typically this is done either in the form of + demonstrating that the issue reported is not a problem after all, or more + often, by opening a Pull Request that changes some bit of something in + lazy-etherscan in a concrete and reviewable manner. + +**Anybody can participate in any stage of contribution**. We urge you to +participate in the discussion around bugs and participate in reviewing PRs. + +### Asking for General Help + +If you have reviewed existing documentation and still have questions or are +having problems, you can open an issue asking for help. + +In exchange for receiving help, we ask that you contribute back a documentation +PR that helps others avoid the problems that you encountered. + +### Submitting a Bug Report + +When opening a new issue in the lazy-etherscan issue tracker, users will be presented +with a [basic template][template] that should be filled in. If you believe that you have +uncovered a bug, please fill out this form, following the template to the best +of your ability. Do not worry if you cannot answer every detail, just fill in +what you can. + +The two most important pieces of information we need in order to properly +evaluate the report is a description of the behavior you are seeing and a simple +test case we can use to recreate the problem on our own. If we cannot recreate +the issue, it becomes impossible for us to fix. + +In order to rule out the possibility of bugs introduced by userland code, test +cases should be limited. + +See [How to create a Minimal, Complete, and Verifiable example][mcve]. + +[mcve]: https://stackoverflow.com/help/mcve +[template]: .github/PULL_REQUEST_TEMPLATE.md + +### Triaging a Bug Report + +Once an issue has been opened, it is not uncommon for there to be discussion +around it. Some contributors may have differing opinions about the issue, +including whether the behavior being seen is a bug or a feature. This discussion +is part of the process and should be kept focused, helpful, and professional. + +Short, clipped responses—that provide neither additional context nor supporting +detail—are not helpful or professional. To many, such responses are simply +annoying and unfriendly. + +Contributors are encouraged to help one another make forward progress as much as +possible, empowering one another to solve issues collaboratively. If you choose +to comment on an issue that you feel either is not a problem that needs to be +fixed, or if you encounter information in an issue that you feel is incorrect, +explain why you feel that way with additional supporting context, and be willing +to be convinced that you may be wrong. By doing so, we can often reach the +correct outcome much faster. + +### Resolving a Bug Report + +In the majority of cases, issues are resolved by opening a Pull Request. The +process for opening and reviewing a Pull Request is similar to that of opening +and triaging issues, but carries with it a necessary review and approval +workflow that ensures that the proposed changes meet the minimal quality and +functional guidelines of the lazy-etherscan project. + +## Pull Requests + +Pull Requests are the way concrete changes are made to the code, documentation, +and dependencies in the lazy-etherscan repository. + +Even tiny pull requests (e.g., one character pull request fixing a typo in API +documentation) are greatly appreciated. Before making a large change, it is +usually a good idea to first open an issue describing the change to solicit +feedback and guidance. This will increase the likelihood of the PR getting +merged. + +### Commits + +It is a recommended best practice to keep your changes as logically grouped as +possible within individual commits. There is no limit to the number of commits +any single Pull Request may have, and many contributors find it easier to review +changes that are split across multiple commits. + +That said, if you have a number of commits that are "checkpoints" and don't +represent a single logical change, please squash those together. + +Note that multiple commits often get squashed when they are landed (see the +notes about [commit squashing](#commit-squashing)). + +#### Commit message guidelines + +Commit messages should follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) +specification. + +Here's a few examples from the master branch's commit log: + +- \[feat\](network): support empty events +- \[fix\](route): fix typo +- \[refactor\](app): Removed unused code +- \[chore\]: bump crypto deps +- \[test\]: simplify test cleanup + +### Opening the Pull Request + +From within GitHub, opening a new Pull Request will present you with a +[template] that should be filled out. Please try to do your best at filling out +the details, but feel free to skip parts if you're not sure what to put. + +[template]: .github/PULL_REQUEST_TEMPLATE.md + +### Discuss and update + +You will probably get feedback or requests for changes to your Pull Request. +This is a big part of the submission process so don't be discouraged! Some +contributors may sign off on the Pull Request right away, others may have +more detailed comments or feedback. This is a necessary part of the process +in order to evaluate whether the changes are correct and necessary. + +**Any community member can review a PR and you might get conflicting feedback**. +Keep an eye out for comments from code owners to provide guidance on conflicting +feedback. + +**Once the PR is open, do not rebase the commits**. See [Commit Squashing](#commit-squashing) for +more details. + +### Commit Squashing + +In most cases, **do not squash commits that you add to your Pull Request during +the review process**. When the commits in your Pull Request land, they may be +squashed into one commit per logical change. Metadata will be added to the +commit message (including links to the Pull Request, links to relevant issues, +and the names of the reviewers). The commit history of your Pull Request, +however, will stay intact on the Pull Request page. + +## Reviewing Pull Requests + +**Any lazy-etherscan community member is welcome to review any pull request**. + +All lazy-etherscan contributors who choose to review and provide feedback on Pull +Requests have a responsibility to both the project and the individual making the +contribution. Reviews and feedback must be helpful, insightful, and geared +towards improving the contribution as opposed to simply blocking it. If there +are reasons why you feel the PR should not land, explain what those are. Do not +expect to be able to block a Pull Request from advancing simply because you say +"No" without giving an explanation. Be open to having your mind changed. Be open +to working with the contributor to make the Pull Request better. + +Reviews that are dismissive or disrespectful of the contributor or any other +reviewers are strictly counter to the Code of Conduct. + +When reviewing a Pull Request, the primary goals are for the codebase to improve +and for the person submitting the request to succeed. **Even if a Pull Request +does not land, the submitters should come away from the experience feeling like +their effort was not wasted or unappreciated**. Every Pull Request from a new +contributor is an opportunity to grow the community. + +### Review a bit at a time. + +Do not overwhelm new contributors. + +It is tempting to micro-optimize and make everything about relative performance, +perfect grammar, or exact style matches. Do not succumb to that temptation. + +Focus first on the most significant aspects of the change: + +1. Does this change make sense for lazy-etherscan? +2. Does this change make lazy-etherscan better, even if only incrementally? +3. Are there clear bugs or larger scale issues that need attending to? +4. Is the commit message readable and correct? If it contains a breaking change + is it clear enough? + +Note that only **incremental** improvement is needed to land a PR. This means +that the PR does not need to be perfect, only better than the status quo. Follow +up PRs may be opened to continue iterating. + +When changes are necessary, _request_ them, do not _demand_ them, and **do not +assume that the submitter already knows how to add a test or run a benchmark**. + +Specific performance optimization techniques, coding styles and conventions +change over time. The first impression you give to a new contributor never does. + +Nits (requests for small changes that are not essential) are fine, but try to +avoid stalling the Pull Request. Most nits can typically be fixed by the lazy-etherscan +Collaborator landing the Pull Request but they can also be an opportunity for +the contributor to learn a bit more about the project. + +It is always good to clearly indicate nits when you comment: e.g. +`Nit: change foo() to bar(). But this is not blocking.` + +If your comments were addressed but were not folded automatically after new +commits or if they proved to be mistaken, please, [hide them][hiding-a-comment] +with the appropriate reason to keep the conversation flow concise and relevant. + +### Be aware of the person behind the code + +Be aware that _how_ you communicate requests and reviews in your feedback can +have a significant impact on the success of the Pull Request. Yes, we may land +a particular change that makes lazy-etherscan better, but the individual might just not +want to have anything to do with lazy-etherscan ever again. The goal is not just having +good code. + +### Abandoned or Stalled Pull Requests + +If a Pull Request appears to be abandoned or stalled, it is polite to first +check with the contributor to see if they intend to continue the work before +checking if they would mind if you took it over (especially if it just has nits +left). When doing so, it is courteous to give the original contributor credit +for the work they started (either by preserving their name and email address in +the commit log, or by using an `Author: ` meta-data tag in the commit. + +_Adapted from the [Tokio contributing guide](https://github.com/tokio-rs/tokio/blob/master/CONTRIBUTING.md)_. + +[hiding-a-comment]: https://help.github.com/articles/managing-disruptive-comments/#hiding-a-comment +[documentation test]: https://doc.rust-lang.org/rustdoc/documentation-tests.html diff --git a/Cargo.toml b/Cargo.toml index 12ef5a4..9b253ac 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lazy-etherscan" -version = "0.1.0" +version = "1.0.0" edition = "2021" authors = ["woxjro "] license = "MIT" @@ -21,13 +21,15 @@ futures = "0.3.28" ratatui = { version = "0.22.0", features = ["all-widgets"] } serde_json = "1.0.104" tokio = { version = "1.29.1", features = ["full"] } -#ratatui-tree-widget = { path = "./ratatui-tree-widget" } -clap = { version = "4.3.23", features = ["derive"] } +clap = { version = "4.5.3", features = ["derive"] } log = "0.4.20" simplelog = "0.12.1" -toml = "0.8.4" serde = "1.0.189" url = "2.4.1" +tempfile = "3.9.0" +anyhow = "1.0.79" +beacon-api-client = { path = "ethereum-consensus/beacon-api-client" } +ethereum-consensus = { path = "ethereum-consensus/ethereum-consensus" } [dependencies.crossterm] version = "0.26.1" diff --git a/README.md b/README.md index ee2891c..c3e5fa4 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ - [lazy-etherscan](#lazy-etherscan) - [Features](#features) + - [Prerequisites](#prerequisites) - [Build](#build) - [Configurations & Usage](#configurations--usage) - [Roadmap](#roadmap) @@ -28,6 +29,27 @@ - **No Browser Required** - Use it effortlessly even in environments where browsers are unavailable, such as within servers. - **Developer Friendly** - Operate efficiently using keyboard shortcuts. - **Easily Switch Endpoints** - Switch between endpoints, including Mainnet, Testnets, custom node connections, and even BSC endpoints. +- **Rich Search Functionality** - You can search by the following words. + - Address + - Block Number + - ENS ID + - Transaction Hash + - Ticker Name (`USDT`, `BNB`,`UNI`, ...) + +## Prerequisites +### Optional: Etherscan API Key +To see statistics information about Ethereum, you have to set an Etherscan's free API key. +You can get it from [here](https://etherscan.io/apis). +And add it to your environment variables. If you are using `zsh`, run the following command. +```sh +$ echo 'export ETHERSCAN_API_KEY=XXXXXXXXXXXX' >> ~/.zshenv +``` + +### Optional: [`ethereum-input-data-decoder`](https://github.com/miguelmota/ethereum-input-data-decoder) +To see transactions' decoded input data, you have to preinstall [`ethereum-input-data-decoder`](https://github.com/miguelmota/ethereum-input-data-decoder). Please run the following command. +```sh +$ npm install -g ethereum-input-data-decoder +``` ## Build This software has been tested and verified to work correctly on the following operating systems: @@ -35,24 +57,15 @@ This software has been tested and verified to work correctly on the following op - `macOS Ventura 13.2` ```sh -$ git clone https://github.com/woxjro/lazy-etherscan --recursive +$ git clone --recursive https://github.com/woxjro/lazy-etherscan $ cd lazy-etherscan $ cargo run -- ``` ## Configurations & Usage -### Ethereum Statistics -To see statistics information about Ethereum, you have to set an Etherscan's free API key. -You can get it from [here](https://etherscan.io/apis). -And set it to `api_key` field in `settings.toml`. You can use a setting template file (`settings.example.toml`). -```sh -$ mv ./settings.example.toml ./settings.toml -``` - -### Configurations Please check the various settings such as endpoints using the following command: ```sh -cargo run -- --help +$ cargo run -- --help ``` ### Usage @@ -70,9 +83,8 @@ The basic usage is as follows: Please see [this issue](https://github.com/woxjro/lazy-etherscan/issues/1). ## Contributing -This project is currently in the Proof of Concept (PoC) stage. -Contributions are kindly requested to be postponed until further notice. -Crash reports are welcome, please create an issue to do that. +Any contributions are welcome! +Please see [CONTRIBUTING.md](./CONTRIBUTING.md). ## Sponsors This project has been developed with a grant from the [Ethereum Foundation](https://ethereum.org/en/foundation/) and [Gitcoin](https://www.gitcoin.co/). diff --git a/docs/src/README.md b/docs/src/README.md index af0d489..dc1f085 100644 --- a/docs/src/README.md +++ b/docs/src/README.md @@ -1,10 +1,22 @@ # Introduction +`lazy-etherscan` is an Ethereum blockchain explorer that can be used from your terminal. + +![demo](../resources/screenshots/demo.gif) + +## Features +- **No Browser Required** - Use it effortlessly even in environments where browsers are unavailable, such as within servers. +- **Developer Friendly** - Operate efficiently using keyboard shortcuts. +- **Easily Switch Endpoints** - Switch between endpoints, including Mainnet, Testnets, custom node connections, and even BSC endpoints. +- **Rich Search Functionality** - You can search by the following words. + - Address + - Block Number + - ENS ID + - Transaction Hash + - Ticker Name (`USDT`, `BNB`,`UNI`, ...) + ## User Guide - [Installation](guide/installation.md) - [Configuration](guide/configuration.md) - [Usage](guide/usage.md) - - -TODO diff --git a/docs/src/guide/configuration.md b/docs/src/guide/configuration.md index e2ef709..ff37b7e 100644 --- a/docs/src/guide/configuration.md +++ b/docs/src/guide/configuration.md @@ -1,19 +1,11 @@ # Configuration -## Ethereum Statistics -To see statistics information about Ethereum, you have to set an Etherscan's free API key. -You can get it from [here](https://etherscan.io/apis). -And set it to `api_key` field in `settings.toml`. You can use a setting template file (`settings.example.toml`). -```sh -$ mv ./settings.example.toml ./settings.toml -``` - ## Endpoint -The default endpoint is https://eth.public-rpc.com, and you can also set your preferred endpoint. +The default endpoint is https://eth.llamarpc.com, and you can also set your preferred endpoint. You can find free endpoints from [ChainList](https://chainlist.org/chain/1). To set your endpoint, run with a `--endpoint` option. ```sh -cargo run -- --endpoint=https://rpc.flashbots.net +$ lazy-etherscan --endpoint=https://rpc.flashbots.net ``` In the case of the L2 blockchain networks and BSC RPC endpoints listed below, @@ -29,5 +21,5 @@ it has been confirmed that this software works to some extent. ## Other Configuration To check other configurations, run the following command. ```sh -cargo run -- --help +$ lazy-etherscan --help ``` diff --git a/docs/src/guide/installation.md b/docs/src/guide/installation.md index 0084b71..119a70b 100644 --- a/docs/src/guide/installation.md +++ b/docs/src/guide/installation.md @@ -1,10 +1,34 @@ # Installation -## Build from source This software has been tested and verified to work correctly on the following operating systems: - `Ubuntu 22.04.2 LTS` - `macOS Ventura 13.2` + + +## Prerequisites +### Optional: Etherscan API Key +To see statistics information about Ethereum, you have to set an Etherscan's free API key. +You can get it from [here](https://etherscan.io/apis). +And add it to your environment variables. If you are using `zsh`, run the following command. +```sh +$ echo 'export ETHERSCAN_API_KEY=XXXXXXXXXXXX' >> ~/.zshenv +``` + +### Optional: [`ethereum-input-data-decoder`](https://github.com/miguelmota/ethereum-input-data-decoder) +To see transactions' decoded input data, you have to preinstall [`ethereum-input-data-decoder`](https://github.com/miguelmota/ethereum-input-data-decoder). Please run the following command. +```sh +$ npm install -g ethereum-input-data-decoder +``` + + +## Installation using Cargo +```sh +$ cargo install lazy-etherscan +$ lazy-etherscan +``` + +## Build from source ```sh $ git clone https://github.com/woxjro/lazy-etherscan --recursive $ cd lazy-etherscan diff --git a/docs/src/guide/usage.md b/docs/src/guide/usage.md index e8a926e..70f880c 100644 --- a/docs/src/guide/usage.md +++ b/docs/src/guide/usage.md @@ -1,11 +1,46 @@ # Usage The basic usage is as follows: - Press `q` to exit `lazy-etherscan`. -- Press `s` to focus on the search bar, where you can perform searches for addresses, blocks, transactions, and more. - - TODO: ticker, address, blockid... +- Press `s` to focus on the search bar. You can search by the following words. + - Address + - Block Number + - ENS ID + - Transaction Hash + - Ticker Name (`USDT`, `BNB`,`UNI`, ...) - Press `1` to navigate the `Latest Blocks` panel. Use `j` to move to a block below and `k` to an above block. - Press `r` to refresh the `Latest Blocks`. - Press `2` to navigate the `Latest Transactions` panel. Use `j` to move to a transaction below and `k` to move to a transaction above. - Press `r` to refresh the `Latest Transactions`. - Press `` to toggle the sidebar. - Press `` to move to a previous screen. + +## Examples + +### Searching by Tickers + +Here is an example of searching with `USDT`. + +Press `s` to focus on the search bar. Then, press `i` to enter edit mode. Type `USDT` and press `Enter`. + +On the search results screen, the left side displays the source code of the contract, and the right side shows the contract's ABI. You can navigate between them using the left and right arrow keys. Scroll through the focused elements using the `j`/`k` keys. + +![demo](../resources/screenshots/ticker.png) + +Additionally, you can toggle the sidebar by pressing ``, allowing you to view both the source code and ABI simultaneously, as shown in the image below: + +![demo](../resources/screenshots/ticker_toggled.png) + +### Exploring a Block +Next, let's explore how to investigate blocks. + +You can input the block number in the search bar or select it from the Latest Blocks pane to navigate to the Block Details screen. + +Use `j`/`k` to navigate between selectable items such as `Transactions`, `Withdrawals`, `Fee Recipient`, and `Parent Hash`. + +For example, selecting `Transactions` and pressing `Enter` will take you to a pane displaying a list of transactions in the block. + +![demo](../resources/screenshots/block.png) + +Moreover, pressing `` toggles the sidebar, revealing more detailed information about the transaction list. + +![demo](../resources/screenshots/block_toggled.png) diff --git a/docs/src/resources/screenshots/block.png b/docs/src/resources/screenshots/block.png new file mode 100644 index 0000000..771eefc Binary files /dev/null and b/docs/src/resources/screenshots/block.png differ diff --git a/docs/src/resources/screenshots/block_toggled.png b/docs/src/resources/screenshots/block_toggled.png new file mode 100644 index 0000000..040aa3f Binary files /dev/null and b/docs/src/resources/screenshots/block_toggled.png differ diff --git a/docs/src/resources/screenshots/demo.gif b/docs/src/resources/screenshots/demo.gif new file mode 100644 index 0000000..cf653a2 Binary files /dev/null and b/docs/src/resources/screenshots/demo.gif differ diff --git a/docs/src/resources/screenshots/ticker.png b/docs/src/resources/screenshots/ticker.png new file mode 100644 index 0000000..b6b1714 Binary files /dev/null and b/docs/src/resources/screenshots/ticker.png differ diff --git a/docs/src/resources/screenshots/ticker_toggled.png b/docs/src/resources/screenshots/ticker_toggled.png new file mode 100644 index 0000000..cc778d1 Binary files /dev/null and b/docs/src/resources/screenshots/ticker_toggled.png differ diff --git a/ethereum-consensus b/ethereum-consensus new file mode 160000 index 0000000..a52eabf --- /dev/null +++ b/ethereum-consensus @@ -0,0 +1 @@ +Subproject commit a52eabfdd4d408407a4e922b57962447ca6472bf diff --git a/examples/get_beacon_block.rs b/examples/get_beacon_block.rs new file mode 100644 index 0000000..a2594b5 --- /dev/null +++ b/examples/get_beacon_block.rs @@ -0,0 +1,18 @@ +use beacon_api_client::{mainnet::Client, BlockId}; +use ethereum_consensus::primitives::Root; +use ethers::utils::hex; +use url::Url; + +#[tokio::main] +async fn main() { + let url = Url::parse("http://localhost:5052").unwrap(); + let client = Client::new(url); + + let root_hex = + hex::decode("421c16805c3416150aa04533fdfe7fc3f0880d0ed86cee33fa58011f10dd95c8").unwrap(); + let _root = Root::try_from(root_hex.as_ref()).unwrap(); + let id = BlockId::Finalized; + + let block = client.get_beacon_block(id).await.unwrap(); + dbg!(block); +} diff --git a/ratatui-tree-widget b/ratatui-tree-widget deleted file mode 160000 index 5995f04..0000000 --- a/ratatui-tree-widget +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5995f047be6f5049fcc42ab28e57b0b1dbf24eb8 diff --git a/resources/screenshots/demo.gif b/resources/screenshots/demo.gif index 695d737..cf653a2 100644 Binary files a/resources/screenshots/demo.gif and b/resources/screenshots/demo.gif differ diff --git a/settings.example.toml b/settings.example.toml deleted file mode 100644 index 5e3598d..0000000 --- a/settings.example.toml +++ /dev/null @@ -1,2 +0,0 @@ -[etherscan] -api_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXX" diff --git a/src/app.rs b/src/app.rs index ca22e93..058e0c6 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,3 +1,4 @@ +pub mod address; pub mod block; pub mod event_handling; pub mod statistics; @@ -9,7 +10,7 @@ use crate::{ widget::StatefulList, }; use ethers::core::types::{Address, NameOrAddress, Transaction, TransactionReceipt, TxHash, U64}; -use ratatui::widgets::{ListState, TableState}; +use ratatui::widgets::{ListState, ScrollbarState, TableState}; use statistics::Statistics; use std::{collections::HashMap, fs::File, io::Read, sync::mpsc::Sender}; @@ -21,8 +22,10 @@ pub enum InputMode { pub struct App { routes: Vec, io_tx: Option>, + pub endpoint: String, pub is_loading: bool, pub is_toggled: bool, + pub show_popup: bool, pub statistics: Statistics, pub latest_blocks: Option>>, pub latest_transactions: Option>, @@ -36,14 +39,25 @@ pub struct App { pub block_detail_list_state: ListState, pub transactions_table_state: TableState, pub withdrawals_table_state: TableState, + //Address Detail + pub contract_list_state: ListState, + pub source_code_scroll_state: ScrollbarState, + pub source_code_scroll: u16, + pub abi_scroll_state: ScrollbarState, + pub abi_scroll: u16, //Transaction Detail pub transaction_detail_list_state: ListState, + pub input_data_detail_list_state: ListState, + pub input_data_scroll_state: ScrollbarState, + pub input_data_scroll: u16, + pub decoded_input_data_scroll_state: ScrollbarState, + pub decoded_input_data_scroll: u16, //Token Data pub erc20_tokens: Vec, } impl App { - pub fn new(io_tx: Sender) -> App { + pub fn new(io_tx: Sender, endpoint: &str) -> App { let erc20_tokens = File::open("./data/tokens.json").map_or(vec![], |file| { let mut buffer = String::new(); let mut file = std::io::BufReader::new(file); @@ -58,8 +72,10 @@ impl App { App { routes: vec![Route::default()], + endpoint: endpoint.to_owned(), is_loading: false, is_toggled: false, + show_popup: false, io_tx: Some(io_tx), statistics: Statistics::new(), latest_blocks: None, @@ -72,8 +88,21 @@ impl App { block_detail_list_state: ListState::default(), transactions_table_state: TableState::default(), withdrawals_table_state: TableState::default(), + //Address Detail + contract_list_state: ListState::default().with_selected(Some( + address::SelectableContractDetailItem::ContractSourceCode.into(), + )), + source_code_scroll_state: ScrollbarState::default(), + abi_scroll_state: ScrollbarState::default(), + source_code_scroll: 0, + abi_scroll: 0, //Transaction Detail transaction_detail_list_state: ListState::default(), + input_data_detail_list_state: ListState::default(), + input_data_scroll_state: ScrollbarState::default(), + input_data_scroll: 0, + decoded_input_data_scroll_state: ScrollbarState::default(), + decoded_input_data_scroll: 0, //Token Data erc20_tokens, } @@ -139,9 +168,7 @@ impl App { RouteId::Block(_) => RouteId::Block(block), RouteId::TransactionsOfBlock(_) => RouteId::TransactionsOfBlock(block), RouteId::WithdrawalsOfBlock(_) => RouteId::WithdrawalsOfBlock(block), - _ => { - panic!("never occur") - } + _ => unreachable!(), }, route.get_active_block(), ) @@ -159,7 +186,6 @@ impl App { if let Err(e) = io_tx.send(action) { self.is_loading = false; println!("Error from dispatch {}", e); - // TODO: handle error }; } } diff --git a/src/app/address.rs b/src/app/address.rs new file mode 100644 index 0000000..70f133e --- /dev/null +++ b/src/app/address.rs @@ -0,0 +1,74 @@ +use crate::ethers::types::AddressInfo; + +#[derive(Copy, Clone)] +pub enum SelectableContractDetailItem { + ContractSourceCode, //0 + ContractAbi, //1 +} + +impl SelectableContractDetailItem { + pub fn next(&self, address_info: &AddressInfo) -> Self { + match self { + Self::ContractAbi => { + if address_info.contract_source_code.is_some() { + Self::ContractSourceCode + } else { + Self::ContractAbi + } + } + Self::ContractSourceCode => { + if address_info.contract_abi.is_some() { + Self::ContractAbi + } else { + Self::ContractSourceCode + } + } + } + } + + pub fn previous(&self, address_info: &AddressInfo) -> Self { + match self { + Self::ContractAbi => { + if address_info.contract_source_code.is_some() { + Self::ContractSourceCode + } else { + Self::ContractAbi + } + } + Self::ContractSourceCode => { + if address_info.contract_abi.is_some() { + Self::ContractAbi + } else { + Self::ContractSourceCode + } + } + } + } +} + +impl Default for SelectableContractDetailItem { + fn default() -> Self { + Self::ContractSourceCode + } +} + +impl From for SelectableContractDetailItem { + fn from(i: usize) -> Self { + if i == 0 { + Self::ContractSourceCode + } else if i == 1 { + Self::ContractAbi + } else { + unreachable!() + } + } +} + +impl From for usize { + fn from(val: SelectableContractDetailItem) -> Self { + match val { + SelectableContractDetailItem::ContractSourceCode => 0, + SelectableContractDetailItem::ContractAbi => 1, + } + } +} diff --git a/src/app/block.rs b/src/app/block.rs index 987c799..74fc051 100644 --- a/src/app/block.rs +++ b/src/app/block.rs @@ -62,7 +62,7 @@ impl From for SelectableBlockDetailItem { } else if i == 3 { Self::ParentHash } else { - panic!() + unreachable!() } } } diff --git a/src/app/event_handling.rs b/src/app/event_handling.rs index 7506684..6593e51 100644 --- a/src/app/event_handling.rs +++ b/src/app/event_handling.rs @@ -1,10 +1,15 @@ -use crate::app::{ - block::SelectableBlockDetailItem, statistics::Statistics, - transaction::SelectableTransactionDetailItem, App, InputMode, +use crate::{ + app::{ + address::SelectableContractDetailItem, + block::SelectableBlockDetailItem, + statistics::Statistics, + transaction::{SelectableInputDataDetailItem, SelectableTransactionDetailItem}, + App, InputMode, + }, + ethers::types::BlockWithTransactionReceipts, + network::IoEvent, + route::{ActiveBlock, Route, RouteId}, }; -use crate::ethers::types::BlockWithTransactionReceipts; -use crate::network::IoEvent; -use crate::route::{ActiveBlock, Route, RouteId}; use crossterm::event; use ethers::core::types::NameOrAddress; use log::debug; @@ -44,6 +49,12 @@ where app.pop_current_route(); } } + event::KeyCode::Char('?') => { + app.show_popup = true; + } + event::KeyCode::Esc => { + app.show_popup = false; + } _ => {} }, InputMode::Editing if key.kind == event::KeyEventKind::Press => { @@ -114,6 +125,9 @@ where )), ActiveBlock::Main, )); + app.dispatch(IoEvent::GetDecodedInputData { + transaction: transactions.items[i].transaction.to_owned(), + }); } } } @@ -203,6 +217,14 @@ where } } } + SelectableTransactionDetailItem::InputData => { + app.set_route(Route::new( + RouteId::InputDataOfTransaction( + transaction.to_owned(), + ), + ActiveBlock::Main, + )); + } } } } @@ -349,6 +371,46 @@ where } } } + RouteId::InputDataOfTransaction(_) => { + match SelectableInputDataDetailItem::from( + app.input_data_detail_list_state + .selected() + .unwrap_or(SelectableInputDataDetailItem::InputData.into()), + ) { + SelectableInputDataDetailItem::InputData => { + app.input_data_scroll = + app.input_data_scroll.saturating_add(1); + app.input_data_scroll_state = app + .input_data_scroll_state + .position(app.input_data_scroll); + } + SelectableInputDataDetailItem::DecodedInputData => { + app.decoded_input_data_scroll = + app.decoded_input_data_scroll.saturating_add(1); + app.decoded_input_data_scroll_state = app + .decoded_input_data_scroll_state + .position(app.decoded_input_data_scroll); + } + } + } + RouteId::AddressInfo(_) => match SelectableContractDetailItem::from( + app.contract_list_state.selected().unwrap_or( + SelectableContractDetailItem::ContractSourceCode.into(), + ), + ) { + SelectableContractDetailItem::ContractSourceCode => { + app.source_code_scroll = + app.source_code_scroll.saturating_add(1); + app.source_code_scroll_state = app + .source_code_scroll_state + .position(app.source_code_scroll); + } + SelectableContractDetailItem::ContractAbi => { + app.abi_scroll = app.abi_scroll.saturating_add(1); + app.abi_scroll_state = + app.abi_scroll_state.position(app.abi_scroll); + } + }, _ => {} }, _ => {} @@ -439,21 +501,58 @@ where } } } - RouteId::Transaction(transaction) => { - if let Some(transaction) = transaction.as_ref() { - if let Some(i) = app.transaction_detail_list_state.selected() { - app.transaction_detail_list_state.select(Some( - SelectableTransactionDetailItem::from(i) - .previous(transaction) - .into(), - )); - } else { - app.transaction_detail_list_state.select(Some( - SelectableTransactionDetailItem::From.into(), - )); + RouteId::Transaction(Some(transaction)) => { + if let Some(i) = app.transaction_detail_list_state.selected() { + app.transaction_detail_list_state.select(Some( + SelectableTransactionDetailItem::from(i) + .previous(&transaction) + .into(), + )); + } else { + app.transaction_detail_list_state + .select(Some(SelectableTransactionDetailItem::From.into())); + } + } + RouteId::InputDataOfTransaction(_) => { + match SelectableInputDataDetailItem::from( + app.input_data_detail_list_state + .selected() + .unwrap_or(SelectableInputDataDetailItem::InputData.into()), + ) { + SelectableInputDataDetailItem::InputData => { + app.input_data_scroll = + app.input_data_scroll.saturating_sub(1); + app.input_data_scroll_state = app + .input_data_scroll_state + .position(app.input_data_scroll); + } + SelectableInputDataDetailItem::DecodedInputData => { + app.decoded_input_data_scroll = + app.decoded_input_data_scroll.saturating_sub(1); + app.decoded_input_data_scroll_state = app + .decoded_input_data_scroll_state + .position(app.decoded_input_data_scroll); } } } + RouteId::AddressInfo(_) => match SelectableContractDetailItem::from( + app.contract_list_state.selected().unwrap_or( + SelectableContractDetailItem::ContractSourceCode.into(), + ), + ) { + SelectableContractDetailItem::ContractSourceCode => { + app.source_code_scroll = + app.source_code_scroll.saturating_sub(1); + app.source_code_scroll_state = app + .source_code_scroll_state + .position(app.source_code_scroll); + } + SelectableContractDetailItem::ContractAbi => { + app.abi_scroll = app.abi_scroll.saturating_sub(1); + app.abi_scroll_state = + app.abi_scroll_state.position(app.abi_scroll); + } + }, _ => {} }, _ => {} @@ -477,6 +576,74 @@ where } _ => {} }, + event::KeyCode::Right => { + if let ActiveBlock::Main = app.get_current_route().get_active_block() { + match app.get_current_route().get_id() { + RouteId::AddressInfo(Some(address_info)) => { + app.contract_list_state.select(Some( + SelectableContractDetailItem::from( + app.contract_list_state.selected().unwrap_or( + SelectableContractDetailItem::ContractSourceCode + .into(), + ), + ) + .next(&address_info) + .into(), + )) + } + RouteId::Transaction(Some(_)) + | RouteId::InputDataOfTransaction(Some(_)) => { + app.input_data_detail_list_state.select(Some( + SelectableInputDataDetailItem::from( + app.input_data_detail_list_state.selected().unwrap_or( + SelectableInputDataDetailItem::InputData.into(), + ), + ) + .next() + .into(), + )); + } + _ => {} + } + } + } + event::KeyCode::Left => { + if let ActiveBlock::Main = app.get_current_route().get_active_block() { + match app.get_current_route().get_id() { + RouteId::AddressInfo(Some(address_info)) => { + app.contract_list_state.select(Some( + SelectableContractDetailItem::from( + app.contract_list_state.selected().unwrap_or( + SelectableContractDetailItem::ContractSourceCode + .into(), + ), + ) + .previous(&address_info) + .into(), + )) + } + RouteId::Transaction(Some(_)) + | RouteId::InputDataOfTransaction(Some(_)) => { + app.input_data_detail_list_state.select(Some( + SelectableInputDataDetailItem::from( + app.input_data_detail_list_state.selected().unwrap_or( + SelectableInputDataDetailItem::InputData.into(), + ), + ) + .previous() + .into(), + )); + } + _ => {} + } + } + } + event::KeyCode::Char('?') => { + app.show_popup = true; + } + event::KeyCode::Esc => { + app.show_popup = false; + } _ => {} } } diff --git a/src/app/transaction.rs b/src/app/transaction.rs index fbbd7f6..57cb9aa 100644 --- a/src/app/transaction.rs +++ b/src/app/transaction.rs @@ -1,8 +1,9 @@ use crate::ethers::types::TransactionWithReceipt; pub enum SelectableTransactionDetailItem { - From, - To, + From, //0 + To, //1 + InputData, //2 } impl SelectableTransactionDetailItem { @@ -15,20 +16,22 @@ impl SelectableTransactionDetailItem { Self::From } } - Self::To => Self::From, + Self::To => Self::InputData, + Self::InputData => Self::From, } } pub fn previous(&self, transaction: &TransactionWithReceipt) -> Self { match self { - Self::From => { + Self::From => Self::InputData, + Self::To => Self::From, + Self::InputData => { if transaction.transaction.to.is_some() { Self::To } else { Self::From } } - Self::To => Self::From, } } } @@ -39,8 +42,10 @@ impl From for SelectableTransactionDetailItem { Self::From } else if i == 1 { Self::To + } else if i == 2 { + Self::InputData } else { - panic!() + unreachable!() } } } @@ -50,6 +55,49 @@ impl From for usize { match val { SelectableTransactionDetailItem::From => 0, SelectableTransactionDetailItem::To => 1, + SelectableTransactionDetailItem::InputData => 2, + } + } +} + +pub enum SelectableInputDataDetailItem { + InputData, //0 + DecodedInputData, //1 +} + +impl SelectableInputDataDetailItem { + pub fn next(&self) -> Self { + match self { + Self::InputData => Self::DecodedInputData, + Self::DecodedInputData => Self::InputData, + } + } + + pub fn previous(&self) -> Self { + match self { + Self::InputData => Self::DecodedInputData, + Self::DecodedInputData => Self::InputData, + } + } +} + +impl From for SelectableInputDataDetailItem { + fn from(i: usize) -> Self { + if i == 0 { + Self::InputData + } else if i == 1 { + Self::DecodedInputData + } else { + unreachable!() + } + } +} + +impl From for usize { + fn from(val: SelectableInputDataDetailItem) -> Self { + match val { + SelectableInputDataDetailItem::InputData => 0, + SelectableInputDataDetailItem::DecodedInputData => 1, } } } diff --git a/src/ethers.rs b/src/ethers.rs index 45fc2ac..b8cf748 100644 --- a/src/ethers.rs +++ b/src/ethers.rs @@ -1,6 +1,9 @@ pub mod types { use ethers::{ - core::types::{Address, Block, Transaction, TransactionReceipt, U256}, + core::{ + abi::Abi, + types::{Address, Block, Transaction, TransactionReceipt, U256}, + }, etherscan::contract::ContractMetadata, }; use serde::{Deserialize, Deserializer}; @@ -12,7 +15,8 @@ pub mod types { pub address: Address, pub ens_id: Option, pub avatar_url: Option, - pub contract_metadata: Option, + pub contract_abi: Option, + pub contract_source_code: Option, pub balance: U256, } @@ -20,6 +24,7 @@ pub mod types { pub struct TransactionWithReceipt { pub transaction: Transaction, pub transaction_receipt: TransactionReceipt, + pub decoded_input_data: Option, } #[derive(Clone, Debug, PartialEq)] @@ -63,6 +68,7 @@ pub mod types { } /* types */ pub mod transaction { + use anyhow::{bail, Context, Result}; use ethers::{ core::types::{Block, Transaction, TransactionReceipt}, utils::format_ether, @@ -72,23 +78,25 @@ pub mod transaction { transaction: &Transaction, transaction_receipt: &TransactionReceipt, _block: Option>, - ) -> Option { + ) -> Result { if let Some(gas_used) = transaction_receipt.gas_used { // Legacy if let Some(gas_price) = transaction.gas_price { - Some(format_ether(gas_price * gas_used)) + Ok(format_ether(gas_price * gas_used)) } else { //EIP-1559 - Some(format_ether( + Ok(format_ether( std::cmp::min( - transaction.max_fee_per_gas.unwrap(), + transaction.max_fee_per_gas.context("Fee per gas is None")?, //block.base_fee_per_gas.unwrap() + - transaction.max_priority_fee_per_gas.unwrap(), + transaction + .max_priority_fee_per_gas + .context("Max Priority Fee Per Gas is NOne")?, ) * gas_used, )) } } else { - None // the the client is running in light client mode. + bail!("The client is running in light client mode.") } } } /* transaction */ diff --git a/src/main.rs b/src/main.rs index 55faf14..939b296 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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; @@ -11,37 +12,20 @@ use crossterm::{event, execute, terminal}; use log::LevelFilter; use network::{IoEvent, Network}; use ratatui::prelude::*; -use serde::Deserialize; use simplelog::{ColorChoice, CombinedLogger, Config, TermLogger, TerminalMode, WriteLogger}; -use std::{ - error::Error, - fs, io, - io::{BufReader, Read}, - sync::Arc, - time::Duration, -}; +use std::{io, sync::Arc, time::Duration}; use tokio::sync::Mutex; -#[derive(Deserialize, Debug)] -struct Settings { - etherscan: Option, -} - -#[derive(Deserialize, Clone, Debug)] -pub struct Etherscan { - api_key: Option, -} - #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Json-RPC URL - #[arg(short, long, default_value = "https://eth.public-rpc.com")] + #[arg(short, long, default_value = "https://eth.llamarpc.com")] endpoint: String, } #[tokio::main] -async fn main() -> Result<(), Box> { +async fn main() -> Result<()> { let _ = std::fs::create_dir("logs"); CombinedLogger::init(vec![ TermLogger::new( @@ -53,15 +37,9 @@ async fn main() -> Result<(), Box> { 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(); - - let settings: Option = match read_file("./settings.toml".to_owned()) { - Ok(s) => toml::from_str(&s).unwrap_or(None), - Err(_) => None, - }; + ])?; // setup terminal terminal::enable_raw_mode()?; @@ -76,19 +54,14 @@ async fn main() -> Result<(), Box> { let (sync_io_tx, sync_io_rx) = std::sync::mpsc::channel::(); + let args = Args::parse(); + // create app and run it - let app = Arc::new(Mutex::new(App::new(sync_io_tx))); + let app = Arc::new(Mutex::new(App::new(sync_io_tx, &args.endpoint))); let cloned_app = Arc::clone(&app); - let args = Args::parse(); std::thread::spawn(move || { - let mut network = Network::new( - &app, - &args.endpoint, - settings - .as_ref() - .map_or(&None, |settings| &settings.etherscan), - ); + let mut network = Network::new(&app, &args.endpoint); start_tokio(sync_io_rx, &mut network); }); @@ -111,23 +84,7 @@ async fn main() -> Result<(), Box> { Ok(()) } -fn read_file(path: String) -> Result { - let mut file_content = String::new(); - - let mut fr = fs::File::open(path) - .map(BufReader::new) - .map_err(|e| e.to_string())?; - - fr.read_to_string(&mut file_content) - .map_err(|e| e.to_string())?; - - Ok(file_content) -} - -async fn start_ui( - terminal: &mut Terminal, - app: &Arc>, -) -> Result<(), Box> { +async fn start_ui(terminal: &mut Terminal, app: &Arc>) -> Result<()> { let mut is_first_render = true; loop { @@ -142,7 +99,7 @@ async fn start_ui( } 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, }); @@ -153,8 +110,8 @@ async fn start_ui( } #[tokio::main] -async fn start_tokio<'a>(io_rx: std::sync::mpsc::Receiver, network: &mut Network) { +async fn start_tokio(io_rx: std::sync::mpsc::Receiver, 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; } } diff --git a/src/network.rs b/src/network.rs index df5bffc..e0ab273 100644 --- a/src/network.rs +++ b/src/network.rs @@ -1,8 +1,10 @@ -use crate::app::{statistics::Statistics, App}; -use crate::ethers::types::{AddressInfo, BlockWithTransactionReceipts, TransactionWithReceipt}; -use crate::route::{ActiveBlock, Route, RouteId}; -use crate::widget::StatefulList; -use crate::Etherscan; +use crate::{ + app::{statistics::Statistics, App}, + ethers::types::{AddressInfo, BlockWithTransactionReceipts, TransactionWithReceipt}, + route::{ActiveBlock, Route, RouteId}, + widget::StatefulList, +}; +use anyhow::Result; use ethers::{ core::types::{ Address, BlockId, BlockNumber, Chain, NameOrAddress, Transaction, TransactionReceipt, @@ -12,7 +14,13 @@ use ethers::{ providers::{Http, Middleware, Provider}, }; use futures::future::{join_all, try_join, try_join3}; -use std::{error::Error, sync::Arc}; +use std::{ + fs::File, + io::Write, + process::Command, + {error::Error, sync::Arc}, +}; +use tempfile::tempdir; use tokio::sync::Mutex; const RATE_LIMIT: usize = 60; @@ -35,6 +43,9 @@ pub enum IoEvent { GetTransactionReceipts { transactions: Vec, }, + GetDecodedInputData { + transaction: Transaction, + }, GetLatestBlocks { n: usize, }, @@ -53,37 +64,23 @@ pub enum IoEvent { pub struct Network<'a> { pub app: &'a Arc>, endpoint: &'a str, - etherscan: &'a Option, } impl<'a> Network<'a> { - pub fn new( - app: &'a Arc>, - endpoint: &'a str, - etherscan: &'a Option, - ) -> Self { - Self { - app, - endpoint, - etherscan, - } + pub fn new(app: &'a Arc>, endpoint: &'a str) -> Self { + 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, - self.etherscan - .as_ref() - .and_then(|etherscan| etherscan.api_key.to_owned()), - ) - .await; + let res = Self::get_statistics(self.endpoint).await; let mut app = self.app.lock().await; if let Ok(statistics) = res { app.statistics = statistics; } app.is_loading = false; + Ok(()) } IoEvent::GetNameOrAddressInfo { name_or_address, @@ -92,14 +89,7 @@ impl<'a> Network<'a> { let res = match name_or_address { NameOrAddress::Name(name) => Self::get_name_info(self.endpoint, &name).await, NameOrAddress::Address(address) => { - Self::get_address_info( - self.endpoint, - self.etherscan - .as_ref() - .and_then(|etherscan| etherscan.api_key.to_owned()), - address, - ) - .await + Self::get_address_info(self.endpoint, address).await } }; let mut app = self.app.lock().await; @@ -112,6 +102,7 @@ impl<'a> Network<'a> { )); app.is_loading = false; + Ok(()) } IoEvent::GetBlock { number } => { let res = Self::get_block(self.endpoint, number).await; @@ -139,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; @@ -166,6 +158,40 @@ 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; + + let mut app = self.app.lock().await; + if let Ok(decoded_input_data) = res { + let current_route = app.get_current_route(); + match current_route.get_id() { + RouteId::Transaction(transaction) + | RouteId::InputDataOfTransaction(transaction) => { + app.pop_current_route(); + let new_transaction = + transaction.map(|transaction| TransactionWithReceipt { + transaction: transaction.transaction, + transaction_receipt: transaction.transaction_receipt, + decoded_input_data, + }); + let new_route_id = match current_route.get_id() { + RouteId::Transaction(_) => RouteId::Transaction(new_transaction), + RouteId::InputDataOfTransaction(_) => { + RouteId::InputDataOfTransaction(new_transaction) + } + _ => unreachable!(), + }; + app.set_route(Route::new( + new_route_id, + current_route.get_active_block(), + )); + } + _ => {} + } + } + Ok(()) } IoEvent::GetTransactionWithReceipt { transaction_hash } => { let res = Self::get_transaction_with_receipt(self.endpoint, transaction_hash).await; @@ -174,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::>(); @@ -187,20 +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.etherscan - .as_ref() - .and_then(|etherscan| etherscan.api_key.to_owned()), - ), + Self::get_statistics(self.endpoint), Self::get_latest_blocks(self.endpoint, n), Self::get_latest_transactions(self.endpoint, n), ) - .await - .unwrap(); //TODO: remove unwrap + .await?; let mut addresses = vec![]; for transaction in &transactions { addresses.push(transaction.transaction.from); @@ -221,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 { @@ -250,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(()) } } } @@ -290,7 +314,6 @@ impl<'a> Network<'a> { } } - //TODO: use `join` async fn get_name_info( endpoint: &'a str, ens_id: &str, @@ -299,21 +322,20 @@ impl<'a> Network<'a> { let address = provider.resolve_name(ens_id).await?; let avatar_url = provider.resolve_avatar(ens_id).await.ok(); - let balance = provider.get_balance(address, None /* TODO */).await?; - //TODO: Not Found (impl LazyEtherscanError) + let balance = provider.get_balance(address, None).await?; + Ok(Some(AddressInfo { address, balance, avatar_url, - contract_metadata: None, + contract_abi: None, + contract_source_code: None, ens_id: Some(ens_id.to_owned()), })) } - //TODO: use `join` async fn get_address_info( endpoint: &'a str, - etherscan_api_key: Option, address: Address, ) -> Result, Box> { let provider = Provider::::try_from(endpoint)?; @@ -325,41 +347,108 @@ impl<'a> Network<'a> { None }; - let contract_metadata = if let Some(api_key) = etherscan_api_key { - let client = Client::builder() - .with_api_key(api_key) - .chain(Chain::Mainnet)? - .build()?; - - client.contract_source_code(address).await.ok() - } else { - None - }; + let (contract_source_code, contract_abi) = + if let Ok(client) = Client::new_from_env(Chain::Mainnet) { + try_join( + client.contract_source_code(address), + client.contract_abi(address), + ) + .await + .map_or((None, None), |res| (Some(res.0), Some(res.1))) + } else { + (None, None) + }; - let balance = provider.get_balance(address, None /* TODO */).await?; + let balance = provider.get_balance(address, None).await?; - //TODO: Not Found Ok(Some(AddressInfo { address, balance, avatar_url, - contract_metadata, + contract_abi, + contract_source_code, ens_id, })) } + async fn get_decoded_input_data(transaction: Transaction) -> Result> { + 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?; + + let s = serde_json::to_string(&abi)?; + + let dir = tempdir()?; + let file_path = dir.path().join("lazy-etherscan.tmp.abi.json"); + let mut file = File::create(&file_path)?; + writeln!(file, "{}", s)?; + + let output = Command::new("ethereum-input-data-decoder") + .args([ + "--abi", + file_path.to_str().unwrap(), + &transaction.input.to_string(), + ]) + .output() + .map_or(None, |output| String::from_utf8(output.stdout).ok()); + + drop(file); + dir.close()?; + + output + } else { + None + } + } else { + None + }; + Ok(decoded_input_data) + } + async fn get_transaction_with_receipt( endpoint: &'a str, transaction_hash: TxHash, - ) -> Result, Box> { + ) -> Result> { let provider = Provider::::try_from(endpoint)?; let transaction = provider.get_transaction(transaction_hash).await?; let transaction_receipt = provider.get_transaction_receipt(transaction_hash).await?; if let Some(transaction) = transaction { if let Some(transaction_receipt) = transaction_receipt { + 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?; + + let s = serde_json::to_string(&abi)?; + + let dir = tempdir()?; + let file_path = dir.path().join("lazy-etherscan.tmp.abi.json"); + let mut file = File::create(&file_path)?; + writeln!(file, "{}", s)?; + + let output = Command::new("ethereum-input-data-decoder") + .args([ + "--abi", + file_path.to_str().unwrap(), + &transaction.input.to_string(), + ]) + .output() + .map_or(None, |output| String::from_utf8(output.stdout).ok()); + + drop(file); + dir.close()?; + + output + } else { + None + } + } else { + None + }; + Ok(Some(TransactionWithReceipt { transaction, transaction_receipt, + decoded_input_data, })) } else { Ok(None) @@ -372,7 +461,7 @@ impl<'a> Network<'a> { async fn get_latest_blocks( endpoint: &'a str, n: usize, - ) -> Result>, Box> { + ) -> Result>> { let provider = Provider::::try_from(endpoint)?; let block_number = provider.get_block_number().await?; @@ -397,7 +486,7 @@ impl<'a> Network<'a> { async fn get_transaction_receipts( endpoint: &'a str, transactions: &[Transaction], - ) -> Result, Box> { + ) -> Result> { let provider = Provider::::try_from(endpoint)?; let query = transactions .iter() @@ -416,7 +505,7 @@ impl<'a> Network<'a> { async fn get_latest_transactions( endpoint: &'a str, n: usize, - ) -> Result, Box> { + ) -> Result> { let provider = Provider::::try_from(endpoint)?; let block = provider.get_block(BlockNumber::Latest).await?; @@ -453,28 +542,21 @@ impl<'a> Network<'a> { result.push(TransactionWithReceipt { transaction: transactions[i].to_owned(), transaction_receipt: receipts[i].to_owned(), + decoded_input_data: None, }); } Ok(result) } - async fn get_statistics( - endpoint: &'a str, - etherscan_api_key: Option, - ) -> Result> { + async fn get_statistics(endpoint: &'a str) -> Result { let provider = Provider::::try_from(endpoint)?; let mut ethusd = None; let mut node_count = None; let mut suggested_base_fee = None; let mut med_gas_price = None; - if let Some(api_key) = etherscan_api_key { - let client = Client::builder() - .with_api_key(api_key) - .chain(Chain::Mainnet)? - .build()?; - + if let Ok(client) = Client::new_from_env(Chain::Mainnet) { let (eth_price, total_node_count, gas_oracle) = try_join3(client.eth_price(), client.node_count(), client.gas_oracle()).await?; @@ -523,7 +605,7 @@ impl<'a> Network<'a> { async fn lookup_addresses( endpoint: &'a str, addresses: &[Address], - ) -> Result)>, Box> { + ) -> Result)>> { let provider = Provider::::try_from(endpoint)?; let query = addresses .iter() diff --git a/src/route.rs b/src/route.rs index 92fe606..5e3e74b 100644 --- a/src/route.rs +++ b/src/route.rs @@ -10,6 +10,7 @@ pub enum RouteId { TransactionsOfBlock(Option>), WithdrawalsOfBlock(Option>), Transaction(Option), + InputDataOfTransaction(Option), } #[derive(Clone, Copy, PartialEq, Debug)] diff --git a/src/ui/home.rs b/src/ui/home.rs index 763f118..b4d6e79 100644 --- a/src/ui/home.rs +++ b/src/ui/home.rs @@ -5,8 +5,10 @@ mod searching; mod statistics; mod transaction; mod welcome; -use crate::app::{App, InputMode}; -use crate::route::{ActiveBlock, RouteId}; +use crate::{ + app::{App, InputMode}, + route::{ActiveBlock, RouteId}, +}; use ratatui::{prelude::*, widgets::*}; /// /home @@ -15,9 +17,9 @@ pub fn render_home_layout(f: &mut Frame, app: &mut App) { // Just draw the block and the group on the same area and build the group let outer = f.size(); - let [searchbar, rest] = *Layout::default() + let [searchbar, rest, navigation_bar] = *Layout::default() .direction(Direction::Vertical) - .constraints([Constraint::Max(3), Constraint::Min(0)].as_ref()) + .constraints([Constraint::Max(3), Constraint::Min(0), Constraint::Max(1)].as_ref()) .split(outer) else { return; @@ -46,6 +48,10 @@ pub fn render_home_layout(f: &mut Frame, app: &mut App) { .block(searchbar_block); f.render_widget(input, searchbar); + let message = Paragraph::new(" /: k/j, : Cancel, q: Quit, ?: Keybindings, 1-2: Jump to panel, s: Focus on the Search bar") + .style(Style::default().fg(Color::White)); + f.render_widget(message, navigation_bar); + match app.input_mode { InputMode::Normal => // Hide the cursor. `Frame` does this by default, so we don't need to do anything here @@ -77,11 +83,11 @@ pub fn render_home_layout(f: &mut Frame, app: &mut App) { RouteId::WithdrawalsOfBlock(block_with_transaction_receipts) => { block::render(f, app, block_with_transaction_receipts, rest); } - RouteId::Transaction(transaction) => { + RouteId::Transaction(transaction) | RouteId::InputDataOfTransaction(transaction) => { transaction::render(f, app, transaction, rest); } RouteId::Welcome => { - welcome::render(f, rest); + welcome::render(f, app, rest); } RouteId::Searching(message) => { searching::render(f, &message, rest); @@ -105,7 +111,7 @@ pub fn render_home_layout(f: &mut Frame, app: &mut App) { return; }; - statistics::render(f, app, statistics); + let _ = statistics::render(f, app, statistics); latest_status::render(f, app, latest_status); match app.get_current_route().get_id() { @@ -121,15 +127,69 @@ pub fn render_home_layout(f: &mut Frame, app: &mut App) { RouteId::WithdrawalsOfBlock(block) => { block::render(f, app, block, detail); } - RouteId::Transaction(transaction) => { + RouteId::Transaction(transaction) | RouteId::InputDataOfTransaction(transaction) => { transaction::render(f, app, transaction, detail); } RouteId::Welcome => { - welcome::render(f, detail); + welcome::render(f, app, detail); } RouteId::Searching(message) => { searching::render(f, &message, detail); } } } + + let size = f.size(); + if app.show_popup { + let block = Block::default() + .title("Keybindings - Press Esc to close the popup") + .borders(Borders::ALL); + + //TODO: Enter + let input = Paragraph::new(vec![ + Line::from(Span::raw(format!(" {:<4}: {}", "j", "Down")).fg(Color::White)), + Line::from(Span::raw(format!(" {:<4}: {}", "k", "Up")).fg(Color::White)), + Line::from( + Span::raw(format!(" {:<4}: {}", "s", "Move to the Search Bar")).fg(Color::White), + ), + Line::from( + Span::raw(format!(" {:<4}: {}", "1", "Move to the Latest Blocks")).fg(Color::White), + ), + Line::from( + Span::raw(format!( + " {:<4}: {}", + "2", "Move to the Latest Transactions" + )) + .fg(Color::White), + ), + ]) + .style(Style::default().fg(Color::Green)) + .block(block.to_owned()); + + let area = centered_rect(60, 20, size); + f.render_widget(Clear, area); //this clears out the background + f.render_widget(block, area); + f.render_widget(input, area); + } +} + +/// helper function to create a centered rect using up certain percentage of the available rect `r` +fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect { + let popup_layout = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Percentage((100 - percent_y) / 2), + Constraint::Percentage(percent_y), + Constraint::Percentage((100 - percent_y) / 2), + ]) + .split(r); + + Layout::default() + .direction(Direction::Horizontal) + .constraints([ + Constraint::Percentage((100 - percent_x) / 2), + Constraint::Percentage(percent_x), + Constraint::Percentage((100 - percent_x) / 2), + ]) + .split(popup_layout[1])[1] } diff --git a/src/ui/home/address_info.rs b/src/ui/home/address_info.rs index 52ac77c..e098b17 100644 --- a/src/ui/home/address_info.rs +++ b/src/ui/home/address_info.rs @@ -1,4 +1,8 @@ -use crate::{app::App, ethers::types::AddressInfo, route::ActiveBlock}; +use crate::{ + app::{address::SelectableContractDetailItem, App}, + ethers::types::AddressInfo, + route::ActiveBlock, +}; use ethers::core::utils::format_ether; use ratatui::{prelude::*, widgets::*}; @@ -22,9 +26,9 @@ pub fn render( .borders(Borders::ALL) .border_type(BorderType::Plain); - let [detail_rect] = *Layout::default() + let [detail_rect, contract_detail_rect] = *Layout::default() .direction(Direction::Vertical) - .constraints([Constraint::Ratio(1, 1)].as_ref()) + .constraints([Constraint::Max(7), Constraint::Min(3)].as_ref()) .split(rect) else { return; @@ -67,21 +71,206 @@ pub fn render( .fg(Color::White), )); - if let Some(contract_metadata) = address_info.contract_metadata { - details.push(Line::from( - Span::raw(format!("{:<17}:", "CONTRACT METADATA")).fg(Color::White), - )); + let source_code_lines = + if let Some(contract_source_code) = address_info.contract_source_code { + let mut details = vec![]; + let source_code = contract_source_code.items[0] + .source_code() + .replace("\\n", "\n"); + let source_code = source_code.split('\n').collect::>(); - let source_code = contract_metadata.items[0] - .source_code() - .replace("\\n", "\n"); - let source_code = source_code.split('\n').collect::>(); + for (idx, line) in source_code.iter().enumerate() { + details.push(Line::from(vec![ + Span::raw(format!("{:>3} ", idx + 1)).fg(Color::Gray), + Span::raw(line.to_string()).fg(Color::White), + ])); + } + details + } else { + vec![] + }; + app.source_code_scroll_state = app + .source_code_scroll_state + .content_length(source_code_lines.len() as u16); + let abi_lines = if let Some(contract_abi) = address_info.contract_abi { + let mut details = vec![]; + let contract_abi = + serde_json::to_string_pretty(&serde_json::json!(contract_abi)).unwrap(); - for line in source_code { - details.push(Line::from( - Span::raw(format!("{:<19}{}", "", line)).fg(Color::White), - )); + let contract_abi_lines = contract_abi.split('\n').collect::>(); + + for (idx, line) in contract_abi_lines.iter().enumerate() { + details.push(Line::from(vec![ + Span::raw(format!("{:>3} ", idx + 1)).fg(Color::Gray), + Span::raw(line.to_string()).fg(Color::White), + ])); } + details + } else { + vec![] + }; + app.abi_scroll_state = app.abi_scroll_state.content_length(abi_lines.len() as u16); + + if app.is_toggled { + let chunks = Layout::default() + .direction(Direction::Horizontal) + .constraints([Constraint::Ratio(2, 3), Constraint::Ratio(1, 3)]) + .split(contract_detail_rect); + + // render SOURCE CODE + let block = Block::default().padding(Padding::new(1, 0, 0, 1)); + f.render_widget( + Paragraph::new(source_code_lines.to_owned()) + .alignment(Alignment::Left) + .block( + if let SelectableContractDetailItem::ContractSourceCode = + SelectableContractDetailItem::from( + app.contract_list_state.selected().unwrap_or( + SelectableContractDetailItem::ContractSourceCode.into(), + ), + ) + { + Block::default() + .borders(Borders::ALL) + .green() + .title(Span::styled( + "SOURCE CODE", + Style::default().add_modifier(Modifier::BOLD).green(), + )) + } else { + Block::default() + .borders(Borders::ALL) + .gray() + .title(Span::styled( + "SOURCE CODE", + Style::default().add_modifier(Modifier::BOLD), + )) + }, + ) + .scroll((app.source_code_scroll, 0)) + .wrap(Wrap { trim: false }), + block.inner(chunks[0]), + ); + + f.render_stateful_widget( + Scrollbar::default() + .orientation(ScrollbarOrientation::VerticalRight) + .begin_symbol(Some("▲")) + .end_symbol(Some("▼")), + block.inner(chunks[0]), + &mut app.source_code_scroll_state, + ); + + // render ABI + let block = Block::default().padding(Padding::new(0, 1, 0, 1)); + f.render_widget( + Paragraph::new(abi_lines.to_owned()) + .alignment(Alignment::Left) + .block( + if let SelectableContractDetailItem::ContractAbi = + SelectableContractDetailItem::from( + app.contract_list_state.selected().unwrap_or( + SelectableContractDetailItem::ContractSourceCode.into(), + ), + ) + { + Block::default() + .borders(Borders::ALL) + .green() + .title(Span::styled( + "ABI", + Style::default().add_modifier(Modifier::BOLD).green(), + )) + } else { + Block::default() + .borders(Borders::ALL) + .gray() + .title(Span::styled( + "ABI", + Style::default().add_modifier(Modifier::BOLD), + )) + }, + ) + .scroll((app.abi_scroll, 0)) + .wrap(Wrap { trim: false }), + block.inner(chunks[1]), + ); + + f.render_stateful_widget( + Scrollbar::default() + .orientation(ScrollbarOrientation::VerticalRight) + .begin_symbol(Some("▲")) + .end_symbol(Some("▼")), + block.inner(chunks[1]), + &mut app.abi_scroll_state, + ); + } else { + let chunks = Layout::default() + .direction(Direction::Vertical) + .constraints([Constraint::Length(2), Constraint::Min(0)]) + .split(contract_detail_rect); + + let block = Block::default().padding(Padding::horizontal(2)); + + let titles = ["SOURCE CODE", "ABI"] + .iter() + .map(|t| Line::from(t.to_owned())) + .collect(); + + let tabs = Tabs::new(titles) + .block(Block::default().borders(Borders::RIGHT | Borders::LEFT | Borders::TOP)) + .select( + app.contract_list_state + .selected() + .unwrap_or(SelectableContractDetailItem::ContractSourceCode.into()), + ) + .style(Style::default()) + .highlight_style(Style::default().bold().green()); + f.render_widget(tabs, block.inner(chunks[0])); + + let inner = match SelectableContractDetailItem::from( + app.contract_list_state + .selected() + .unwrap_or(SelectableContractDetailItem::ContractSourceCode.into()), + ) { + SelectableContractDetailItem::ContractSourceCode => { + Paragraph::new(source_code_lines.to_owned()) + .block( + Block::default() + .borders(Borders::RIGHT | Borders::LEFT | Borders::BOTTOM), + ) + .alignment(Alignment::Left) + .scroll((app.source_code_scroll, 0)) + .wrap(Wrap { trim: false }) + } + SelectableContractDetailItem::ContractAbi => Paragraph::new(abi_lines.to_owned()) + .block( + Block::default().borders(Borders::RIGHT | Borders::LEFT | Borders::BOTTOM), + ) + .alignment(Alignment::Left) + .scroll((app.abi_scroll, 0)) + .wrap(Wrap { trim: false }), + }; + let block = Block::default().padding(Padding::new(2, 2, 0, 1)); + f.render_widget(inner, block.inner(chunks[1])); + + f.render_stateful_widget( + Scrollbar::default() + .orientation(ScrollbarOrientation::VerticalRight) + .begin_symbol(Some("▲")) + .end_symbol(Some("▼")), + block.inner(chunks[1]), + &mut match SelectableContractDetailItem::from( + app.contract_list_state + .selected() + .unwrap_or(SelectableContractDetailItem::ContractSourceCode.into()), + ) { + SelectableContractDetailItem::ContractSourceCode => { + app.source_code_scroll_state + } + SelectableContractDetailItem::ContractAbi => app.abi_scroll_state, + }, + ); } let details = Paragraph::new(details) diff --git a/src/ui/home/block.rs b/src/ui/home/block.rs index 404ab96..36293c1 100644 --- a/src/ui/home/block.rs +++ b/src/ui/home/block.rs @@ -3,9 +3,12 @@ mod fee_info; mod gas_info; mod transactions; mod withdrawals; -use crate::app::App; -use crate::ethers::types::BlockWithTransactionReceipts; -use crate::route::{ActiveBlock, RouteId}; +use crate::{ + app::App, + ethers::types::BlockWithTransactionReceipts, + route::{ActiveBlock, RouteId}, +}; + use ethers::core::types::Transaction; use ratatui::{prelude::*, widgets::*}; @@ -34,7 +37,8 @@ pub fn render( if let RouteId::WithdrawalsOfBlock(_) = app.get_current_route().get_id() { withdrawals::render(f, app, &block_with_transaction_receipts, transactions_rect); } else { - transactions::render(f, app, &block_with_transaction_receipts, transactions_rect); + let _ = + transactions::render(f, app, &block_with_transaction_receipts, transactions_rect); } let [block_info_rect, fee_info_rect, gas_info_rect] = *Layout::default() diff --git a/src/ui/home/block/block_info.rs b/src/ui/home/block/block_info.rs index 39bd4df..c40079c 100644 --- a/src/ui/home/block/block_info.rs +++ b/src/ui/home/block/block_info.rs @@ -1,5 +1,7 @@ -use crate::app::{block::SelectableBlockDetailItem, App}; -use crate::route::{ActiveBlock, RouteId}; +use crate::{ + app::{block::SelectableBlockDetailItem, App}, + route::{ActiveBlock, RouteId}, +}; use ethers::core::types::{Block as EBlock, Transaction}; use ratatui::{prelude::*, widgets::*}; diff --git a/src/ui/home/block/fee_info.rs b/src/ui/home/block/fee_info.rs index 509c5f1..0b925e9 100644 --- a/src/ui/home/block/fee_info.rs +++ b/src/ui/home/block/fee_info.rs @@ -1,5 +1,7 @@ -use crate::app::{block::SelectableBlockDetailItem, App}; -use crate::route::{ActiveBlock, RouteId}; +use crate::{ + app::{block::SelectableBlockDetailItem, App}, + route::{ActiveBlock, RouteId}, +}; use ethers::core::types::{Block as EBlock, Transaction}; use ratatui::{prelude::*, widgets::*}; @@ -38,7 +40,7 @@ pub fn render( ), ]; - let details = vec![ + let mut details = vec![ Line::from( if app.block_detail_list_state.selected() == Some(SelectableBlockDetailItem::FeeRecipient.into()) @@ -51,21 +53,17 @@ pub fn render( fee_recipient_spans }, ), - //ref: https://docs.alchemy.com/docs/how-to-calculate-ethereum-miner-rewards#calculate-a-miner-reward - //format!("Block Reward: {} ETH", /* TODO */): - Line::from( - Span::raw(format!( - "{:<20}: {}", - "Total Difficulty", - block.total_difficulty.unwrap() - )) - .fg(Color::White), - ), Line::from( Span::raw(format!("{:<20}: {} bytes", "Size", block.size.unwrap())).fg(Color::White), ), ]; + if let Some(total_difficulty) = block.total_difficulty { + details.push(Line::from( + Span::raw(format!("{:<20}: {}", "Total Difficulty", total_difficulty)).fg(Color::White), + )); + } + let paragraph = Paragraph::new(details) .block(detail_block.to_owned()) .alignment(Alignment::Left) diff --git a/src/ui/home/block/gas_info.rs b/src/ui/home/block/gas_info.rs index 53ef522..892c27f 100644 --- a/src/ui/home/block/gas_info.rs +++ b/src/ui/home/block/gas_info.rs @@ -1,5 +1,7 @@ -use crate::app::{block::SelectableBlockDetailItem, App}; -use crate::route::{ActiveBlock, RouteId}; +use crate::{ + app::{block::SelectableBlockDetailItem, App}, + route::{ActiveBlock, RouteId}, +}; use ethers::core::{ types::{Block as EBlock, Transaction}, utils::{format_ether, format_units}, diff --git a/src/ui/home/block/transactions.rs b/src/ui/home/block/transactions.rs index 340d2db..d4c8100 100644 --- a/src/ui/home/block/transactions.rs +++ b/src/ui/home/block/transactions.rs @@ -4,6 +4,7 @@ use crate::{ route::{ActiveBlock, RouteId}, widget::Spinner, }; +use anyhow::Result; use ethers::core::{ types::{Transaction, TransactionReceipt, U64}, utils::{format_ether, format_units}, @@ -15,7 +16,7 @@ pub fn render( app: &mut App, block_with_transaction_receipts: &BlockWithTransactionReceipts, rect: Rect, -) { +) -> Result<()> { let BlockWithTransactionReceipts { block, transaction_receipts, @@ -136,6 +137,7 @@ pub fn render( .widths(&widths); f.render_stateful_widget(t, rect, &mut app.transactions_table_state); + Ok(()) } fn create_row<'a>( @@ -149,7 +151,7 @@ fn create_row<'a>( Cell::from(format!("{}", tx.hash)).fg(Color::White), if tx.to.is_some() { if tx.input.len() >= 4 { - Cell::from("ContractExecution").fg(Color::LightYellow) //TODO + Cell::from("ContractExecution").fg(Color::LightYellow) } else { Cell::from("Transfer").fg(Color::LightMagenta) } diff --git a/src/ui/home/block/withdrawals.rs b/src/ui/home/block/withdrawals.rs index c5926d4..214fa75 100644 --- a/src/ui/home/block/withdrawals.rs +++ b/src/ui/home/block/withdrawals.rs @@ -1,6 +1,8 @@ -use crate::app::App; -use crate::ethers::types::BlockWithTransactionReceipts; -use crate::route::{ActiveBlock, RouteId}; +use crate::{ + app::App, + ethers::types::BlockWithTransactionReceipts, + route::{ActiveBlock, RouteId}, +}; use ethers::core::types::Transaction; use ratatui::{prelude::*, widgets::*}; diff --git a/src/ui/home/latest_status.rs b/src/ui/home/latest_status.rs index b9c3c2f..02aff21 100644 --- a/src/ui/home/latest_status.rs +++ b/src/ui/home/latest_status.rs @@ -44,7 +44,7 @@ pub fn render(f: &mut Frame, app: &mut App, rect: Rect) { let header = vec![ ListItem::new(format!( - " {:^12} | {:^11} | {:^12} | {:^13} |", //TODO: remove these magic numbers + " {:^12} | {:^11} | {:^12} | {:^13} |", "Block Height", "Hash", "Transactions", "Time" )), ListItem::new(format!( @@ -53,7 +53,7 @@ pub fn render(f: &mut Frame, app: &mut App, rect: Rect) { "-".repeat(13), "-".repeat(14), "-".repeat(15), - )), //TODO: remove these magic numbers + )), ]; let block_list = if let Some(latest_blocks) = app.latest_blocks.as_ref() { let mut res = header; @@ -65,7 +65,7 @@ pub fn render(f: &mut Frame, app: &mut App, rect: Rect) { } = block_with_transaction_receipts; res.push(ListItem::new(format!( - "{:>13} | {:>12} | {:>7} txns | {:>4} secs ago |", //TODO: remove these magic numbers + "{:>13} | {:>12} | {:>7} txns | {:>4} secs ago |", block.number.unwrap(), block.hash.unwrap(), block.transactions.len(), @@ -95,7 +95,7 @@ pub fn render(f: &mut Frame, app: &mut App, rect: Rect) { let header = vec![ ListItem::new(format!( - "{:^22} | {:^22} | {:^11} |", //TODO: remove these magic numbers + "{:^22} | {:^22} | {:^11} |", "From", "To", "Value (ETH)" )), ListItem::new(format!( diff --git a/src/ui/home/statistics.rs b/src/ui/home/statistics.rs index 708c7fa..0d2a828 100644 --- a/src/ui/home/statistics.rs +++ b/src/ui/home/statistics.rs @@ -1,16 +1,19 @@ -use crate::app::{statistics::Statistics, App}; -use crate::widget::Spinner; +use crate::{ + app::{statistics::Statistics, App}, + widget::Spinner, +}; +use anyhow::{bail, Context, Result}; use ethers::core::utils::format_units; use ratatui::{prelude::*, widgets::*}; -pub fn render(f: &mut Frame, app: &mut App, rect: Rect) { +pub fn render(f: &mut Frame, app: &mut App, rect: Rect) -> Result<()> { let [right_statistics, left_statistics] = *Layout::default() .direction(Direction::Horizontal) .margin(0) .constraints([Constraint::Ratio(1, 2), Constraint::Ratio(1, 2)].as_ref()) .split(rect) else { - return; + bail!("Failed to create statistics columns.") }; let [statistics0, statistics1, statistics2] = *Layout::default() @@ -26,7 +29,7 @@ pub fn render(f: &mut Frame, app: &mut App, rect: Rect) { ) .split(right_statistics) else { - return; + bail!("Failed to create statistics rows.") }; let [statistics3, statistics4, statistics5] = *Layout::default() @@ -42,7 +45,7 @@ pub fn render(f: &mut Frame, app: &mut App, rect: Rect) { ) .split(left_statistics) else { - return; + bail!("Failed to create statistics rows.") }; let statistic_items = [ @@ -76,18 +79,18 @@ pub fn render(f: &mut Frame, app: &mut App, rect: Rect) { .constraints([Constraint::Length(1)].as_ref()) .split(statistic_item) else { - return; + bail!("Failed to create a rect.") }; let text = if i == Statistics::ETHUSD_INDEX { if let Some(ethusd) = app.statistics.ethusd.as_ref() { - format!("{:.4} USD/ETH ", ethusd) + format!("{:.4} USD/ETH", ethusd) } else { Spinner::default().to_string() } } else if i == Statistics::SUGGESTED_BASE_FEE_INDEX { if let Some(suggested_base_fee) = app.statistics.suggested_base_fee { - format!("{} Gwei", format_units(suggested_base_fee, "gwei").unwrap()) + format!("{} Gwei", format_units(suggested_base_fee, "gwei")?) } else { Spinner::default().to_string() } @@ -99,19 +102,22 @@ pub fn render(f: &mut Frame, app: &mut App, rect: Rect) { } } else if i == Statistics::LAST_SAFE_BLOCK_INDEX { if let Some(block) = app.statistics.last_safe_block.as_ref() { - format!("#{} ", block.number.unwrap()) + format!("#{}", block.number.context("Block Number is None")?) } else { Spinner::default().to_string() } } else if i == Statistics::MED_GAS_PRICE_INDEX { if let Some(med_gas_price) = app.statistics.med_gas_price { - format!("{} Gwei", format_units(med_gas_price, "gwei").unwrap()) + format!( + "{} Gwei", + format_units(med_gas_price, "gwei").context("Failed to parse gas price")? + ) } else { Spinner::default().to_string() } } else if i == Statistics::LAST_FINALIZED_BLOCK_INDEX { if let Some(block) = app.statistics.last_finalized_block.as_ref() { - format!("#{} ", block.number.unwrap()) + format!("#{}", block.number.context("Block Number is None")?) } else { Spinner::default().to_string() } @@ -127,4 +133,5 @@ pub fn render(f: &mut Frame, app: &mut App, rect: Rect) { f.render_widget(paragraph, text_rect); f.render_widget(block, statistic_item.to_owned()); } + Ok(()) } diff --git a/src/ui/home/transaction.rs b/src/ui/home/transaction.rs index ed2bbe9..4209469 100644 --- a/src/ui/home/transaction.rs +++ b/src/ui/home/transaction.rs @@ -1,10 +1,10 @@ use crate::{ - app::transaction::SelectableTransactionDetailItem, + app::transaction::{SelectableInputDataDetailItem, SelectableTransactionDetailItem}, ethers::{ transaction::calculate_transaction_fee, types::{ERC20Token, TransactionWithReceipt}, }, - route::ActiveBlock, + route::{ActiveBlock, RouteId}, App, }; use ethers::core::{ @@ -23,6 +23,7 @@ pub fn render( let TransactionWithReceipt { transaction, transaction_receipt, + decoded_input_data, } = transaction_with_receipt; let detail_block = Block::default() @@ -38,9 +39,9 @@ pub fn render( .borders(Borders::ALL) .border_type(BorderType::Plain); - let [detail_rect] = *Layout::default() + let [detail_rect, input_data_rect] = *Layout::default() .direction(Direction::Vertical) - .constraints([Constraint::Ratio(1, 1)].as_ref()) + .constraints([Constraint::Max(15), Constraint::Min(1)].as_ref()) .split(rect) else { return; @@ -239,6 +240,35 @@ pub fn render( )); } + details.push(Line::from( + if app.transaction_detail_list_state.selected() + == Some(SelectableTransactionDetailItem::InputData.into()) + { + Span::raw(format!( + "{:<17}: {}", + "Input Data", + if let RouteId::InputDataOfTransaction(_) = app.get_current_route().get_id() { + "▼" + } else { + "▶" + } + )) + .fg(Color::White) + .add_modifier(Modifier::BOLD) + } else { + Span::raw(format!( + "{:<17}: {}", + "Input Data", + if let RouteId::InputDataOfTransaction(_) = app.get_current_route().get_id() { + "▼" + } else { + "▶" + } + )) + .fg(Color::White) + }, + )); + let input_data = transaction .input .to_string() @@ -248,18 +278,218 @@ pub fn render( .map(|window| window.iter().collect::()) .collect::>(); - for (i, row) in input_data.iter().enumerate() { - if i == 0 { - details.push(Line::from( - Span::raw(format!("{:<17}: {}", "Input Data", row)).fg(Color::White), - )); - } else { - details.push(Line::from( - Span::raw(format!("{:<19}{}", "", row)).fg(Color::White), - )); + let mut raw_input_data = vec![]; + for (idx, line) in input_data.iter().enumerate() { + raw_input_data.push(Line::from(vec![ + Span::raw(format!("{:>3} ", idx + 1)).fg(Color::Gray), + Span::raw(line.to_string()).fg(Color::White), + ])); + } + + let mut raw_decoded_input_data = vec![]; + + if let Some(decoded_input_data) = decoded_input_data { + for (idx, line) in decoded_input_data.split('\n').enumerate() { + raw_decoded_input_data.push(Line::from(vec![ + Span::raw(format!("{:>3} ", idx + 1)).fg(Color::Gray), + Span::raw(line.to_string()).fg(Color::White), + ])); } } + app.input_data_scroll_state = app + .input_data_scroll_state + .content_length(raw_input_data.len() as u16); + + app.decoded_input_data_scroll_state = app + .decoded_input_data_scroll_state + .content_length(raw_decoded_input_data.len() as u16); + + if app.is_toggled { + let chunks = Layout::default() + .direction(Direction::Horizontal) + .constraints([Constraint::Ratio(1, 2), Constraint::Ratio(1, 2)]) + .split(input_data_rect); + + // render INPUT DATA + let block = Block::default().padding(Padding::new(1, 0, 0, 1)); + f.render_widget( + Paragraph::new(raw_input_data.to_owned()) + .alignment(Alignment::Left) + .block( + if let SelectableInputDataDetailItem::InputData = + SelectableInputDataDetailItem::from( + app.input_data_detail_list_state + .selected() + .unwrap_or(SelectableInputDataDetailItem::InputData.into()), + ) + { + Block::default() + .borders(Borders::ALL) + .green() + .title(Span::styled( + "INPUT DATA", + Style::default().add_modifier(Modifier::BOLD).green(), + )) + } else { + Block::default() + .borders(Borders::ALL) + .gray() + .title(Span::styled( + "INPUT DATA", + Style::default().add_modifier(Modifier::BOLD), + )) + }, + ) + .scroll((app.input_data_scroll, 0)) + .wrap(Wrap { trim: false }), + block.inner(chunks[0]), + ); + + f.render_stateful_widget( + Scrollbar::default() + .orientation(ScrollbarOrientation::VerticalRight) + .begin_symbol(Some("▲")) + .end_symbol(Some("▼")), + block.inner(chunks[0]), + &mut app.input_data_scroll_state, + ); + + // render DECODED INPUT DATA + let block = Block::default().padding(Padding::new(0, 1, 0, 1)); + f.render_widget( + Paragraph::new(raw_decoded_input_data) + .alignment(Alignment::Left) + .block( + //FIXME + if let SelectableInputDataDetailItem::DecodedInputData = + SelectableInputDataDetailItem::from( + app.input_data_detail_list_state + .selected() + .unwrap_or(SelectableInputDataDetailItem::InputData.into()), + ) + { + Block::default() + .borders(Borders::ALL) + .green() + .title(Span::styled( + "DECODED INPUT DATA", + Style::default().add_modifier(Modifier::BOLD).green(), + )) + } else { + Block::default() + .borders(Borders::ALL) + .gray() + .title(Span::styled( + "DECODED INPUT DATA", + Style::default().add_modifier(Modifier::BOLD), + )) + }, + ) + .scroll((app.decoded_input_data_scroll, 0)) + .wrap(Wrap { trim: false }), + block.inner(chunks[1]), + ); + + f.render_stateful_widget( + Scrollbar::default() + .orientation(ScrollbarOrientation::VerticalRight) + .begin_symbol(Some("▲")) + .end_symbol(Some("▼")), + block.inner(chunks[1]), + &mut app.decoded_input_data_scroll_state, + ); + } else { + let chunks = Layout::default() + .direction(Direction::Vertical) + .constraints([Constraint::Length(2), Constraint::Min(0)]) + .split(input_data_rect); + + let titles = ["INPUT DATA", "DECODED INPUT DATA"] + .iter() + .map(|t| Line::from(t.to_owned())) + .collect(); + + let tabs = Tabs::new(titles) + .block( + Block::default() + .borders(Borders::RIGHT | Borders::LEFT | Borders::TOP) + .border_style( + if let ActiveBlock::Main = app.get_current_route().get_active_block() { + if let RouteId::InputDataOfTransaction(_) = + app.get_current_route().get_id() + { + Style::default().fg(Color::Green) + } else { + Style::default().fg(Color::White) + } + } else { + Style::default().fg(Color::White) + }, + ), + ) + .select( + app.input_data_detail_list_state + .selected() + .unwrap_or(SelectableInputDataDetailItem::InputData.into()), + ) + .style(Style::default()) + .highlight_style(Style::default().bold().green()); + f.render_widget( + tabs, + Block::default() + .padding(Padding::horizontal(1)) + .inner(chunks[0]), + ); + + let block = Block::default().padding(Padding::new(1, 1, 0, 1)); + f.render_widget( + Paragraph::new( + match app + .input_data_detail_list_state + .selected() + .map_or(SelectableInputDataDetailItem::InputData, |i| { + SelectableInputDataDetailItem::from(i) + }) { + SelectableInputDataDetailItem::InputData => raw_input_data.to_owned(), + SelectableInputDataDetailItem::DecodedInputData => { + raw_decoded_input_data.to_owned() + } + }, + ) + .alignment(Alignment::Left) + .block( + Block::default() + .borders(Borders::RIGHT | Borders::LEFT | Borders::BOTTOM) + .border_style( + if let ActiveBlock::Main = app.get_current_route().get_active_block() { + if let RouteId::InputDataOfTransaction(_) = + app.get_current_route().get_id() + { + Style::default().fg(Color::Green) + } else { + Style::default().fg(Color::White) + } + } else { + Style::default().fg(Color::White) + }, + ), + ) + .scroll((app.input_data_scroll, 0)) + .wrap(Wrap { trim: false }), + block.inner(chunks[1]), + ); + + f.render_stateful_widget( + Scrollbar::default() + .orientation(ScrollbarOrientation::VerticalRight) + .begin_symbol(Some("▲")) + .end_symbol(Some("▼")), + block.inner(chunks[1]), + &mut app.input_data_scroll_state, + ); + } + let details = Paragraph::new(details) .block(detail_block.to_owned()) .alignment(Alignment::Left) diff --git a/src/ui/home/welcome.rs b/src/ui/home/welcome.rs index 7677866..ac7076a 100644 --- a/src/ui/home/welcome.rs +++ b/src/ui/home/welcome.rs @@ -1,20 +1,24 @@ +use crate::app::App; use ratatui::{prelude::*, widgets::*}; -pub fn render(f: &mut Frame, rect: Rect) { +pub fn render(f: &mut Frame, app: &App, rect: Rect) { let welcome_block = Block::default() .title("Welcome") .border_style(Style::default().fg(Color::White)) .borders(Borders::ALL) .border_type(BorderType::Plain); - let [detail_rect] = *Layout::default() + let [logo_rect, details_rect] = *Layout::default() .direction(Direction::Vertical) - .constraints([Constraint::Ratio(1, 1)].as_ref()) + .constraints([Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)].as_ref()) + .margin(1) .split(rect) else { return; }; + let details_block = Block::default(); + let banner = Paragraph::new(Text::from( cfonts::render(cfonts::Options { text: String::from("lazy|etherscan"), @@ -23,10 +27,34 @@ pub fn render(f: &mut Frame, rect: Rect) { }) .text, )) - .block(welcome_block.to_owned()) .wrap(Wrap { trim: false }) .alignment(Alignment::Center); - f.render_widget(banner, detail_rect); + let details = Paragraph::new(vec![ + Line::from( + Span::raw(format!(" {:<13}: {}", "RPC Endpoint", app.endpoint)).fg(Color::White), + ), + Line::from(Span::raw(format!(" {:<13}: {}", "Version", "v0.1.0")).fg(Color::White)), + Line::from( + Span::raw(format!( + " {:<13}: {}", + "Document", "https://woxjro.github.io/lazy-etherscan" + )) + .fg(Color::White), + ), + Line::from( + Span::raw(format!( + " {:<13}: {}", + "Repository", "https://github.com/woxjro/lazy-etherscan" + )) + .fg(Color::White), + ), + ]) + .block(details_block.to_owned()) + .alignment(Alignment::Left); + f.render_widget(welcome_block, rect); + f.render_widget(banner, logo_rect); + f.render_widget(details, details_rect); + f.render_widget(details_block, details_rect); } diff --git a/src/widget.rs b/src/widget.rs index fba689a..c0c9ce2 100644 --- a/src/widget.rs +++ b/src/widget.rs @@ -71,10 +71,4 @@ impl StatefulList { pub fn get_selected_item_index(&self) -> Option { self.state.selected().map(|state| state - self.header_size) } - - /* - fn unselect(&mut self) { - self.state.select(None); - } - */ } diff --git a/utils/SETUP_NODE.sh b/utils/SETUP_NODE.sh new file mode 100755 index 0000000..adb91ad --- /dev/null +++ b/utils/SETUP_NODE.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +GETH_LOG_FILE="./logs/geth.log" +LIGHTHOUSE_LOG_FILE="./logs/lighthouse.log" + +echo "Starting Ethereum Execution Node (geth)..." +geth --authrpc.addr localhost \ + --authrpc.port 8551 \ + --authrpc.vhosts localhost \ + --authrpc.jwtsecret ~/.ethereum/geth/jwtsecret >> "$GETH_LOG_FILE" 2>&1 & + +echo "Starting Beacon Node (lighthouse)..." +lighthouse bn \ + --network mainnet \ + --execution-endpoint http://localhost:8551 \ + --execution-jwt ~/.ethereum/geth/jwtsecret \ + --disable-deposit-contract-sync \ + --http >> "$LIGHTHOUSE_LOG_FILE" 2>&1 & +# --http \ +# --checkpoint-sync-url https://beaconstate.info >> "$LIGHTHOUSE_LOG_FILE" 2>&1 & diff --git a/utils/SHUTDOWN_NODE.sh b/utils/SHUTDOWN_NODE.sh new file mode 100755 index 0000000..df92325 --- /dev/null +++ b/utils/SHUTDOWN_NODE.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +echo "Shutting down Ethereum Execution Node (geth)..." +pkill geth + +echo "Shutting down Beacon Node (lighthouse)..." +pkill lighthouse