From ee765118aa0bc84df7fc4d2c6855f5702e732098 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Fri, 31 May 2024 13:52:02 -0500 Subject: [PATCH 01/23] feat(composer): check chain_id against sequencer_chain_id --- crates/astria-composer/src/executor/builder.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/astria-composer/src/executor/builder.rs b/crates/astria-composer/src/executor/builder.rs index 081de7993..c513012fc 100644 --- a/crates/astria-composer/src/executor/builder.rs +++ b/crates/astria-composer/src/executor/builder.rs @@ -12,7 +12,10 @@ use astria_eyre::eyre::{ self, eyre, WrapErr as _, + Context, + WrapErr as _ }; +use tendermint_rpc::Client; use tokio::sync::watch; use tokio_util::sync::CancellationToken; @@ -44,6 +47,7 @@ impl Builder { } = self; let sequencer_client = sequencer_client::HttpClient::new(sequencer_url.as_str()) .wrap_err("failed constructing sequencer client")?; + if(sequencer_chain_id != Client::genesis(sequencer_client).chain_id) {WrapErr::wrap_err("sequencer chain id and client chain id mismatched")}; let (status, _) = watch::channel(Status::new()); let sequencer_key = read_signing_key_from_file(&private_key_file).wrap_err_with(|| { From 6259c3a5d12a7547f3a54c977987761e082d6e95 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Tue, 4 Jun 2024 14:46:36 -0500 Subject: [PATCH 02/23] feat(composer): check sequencer_chain_id against client chain_id --- crates/astria-composer/src/executor/builder.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/astria-composer/src/executor/builder.rs b/crates/astria-composer/src/executor/builder.rs index c513012fc..c3d6df001 100644 --- a/crates/astria-composer/src/executor/builder.rs +++ b/crates/astria-composer/src/executor/builder.rs @@ -11,13 +11,12 @@ use astria_core::{ use astria_eyre::eyre::{ self, eyre, - WrapErr as _, Context, - WrapErr as _ }; -use tendermint_rpc::Client; +use sequencer_client::tendermint_rpc::Client; use tokio::sync::watch; use tokio_util::sync::CancellationToken; +use tendermint::Genesis; use crate::{ executor, @@ -47,7 +46,9 @@ impl Builder { } = self; let sequencer_client = sequencer_client::HttpClient::new(sequencer_url.as_str()) .wrap_err("failed constructing sequencer client")?; - if(sequencer_chain_id != Client::genesis(sequencer_client).chain_id) {WrapErr::wrap_err("sequencer chain id and client chain id mismatched")}; + + tokio::spawn(check_chain_ids(sequencer_client.clone(), sequencer_chain_id.clone())); + let (status, _) = watch::channel(Status::new()); let sequencer_key = read_signing_key_from_file(&private_key_file).wrap_err_with(|| { @@ -84,3 +85,12 @@ fn read_signing_key_from_file>(path: P) -> eyre::Result eyre::Result<()> { + let genesis: Genesis = Client::genesis(&sequencer_client).await.expect("Failed to retrieve client genesis file"); + let client_chain_id = genesis.chain_id.to_string(); + if sequencer_chain_id != client_chain_id { + return Err(eyre!(format!("mismatch in sequencer_chain_id: {sequencer_chain_id} and client chain_id: {client_chain_id}"))) + }; + Ok(()) +} \ No newline at end of file From 451dec233fc4785384c329a81d60e87e2ab992f1 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Tue, 4 Jun 2024 14:51:10 -0500 Subject: [PATCH 03/23] Merge from upstream --- .github/workflows/test.yml | 32 +++- .gitmodules | 3 + Cargo.lock | 34 +++++ Cargo.toml | 4 + charts/evm-rollup/Chart.yaml | 2 +- crates/astria-bridge-withdrawer/Cargo.toml | 55 +++++++ crates/astria-bridge-withdrawer/build.rs | 4 + .../ethereum/.gitignore | 14 ++ .../ethereum/README.md | 38 +++++ .../ethereum/foundry.toml | 6 + crates/astria-composer/src/metrics_init.rs | 103 ------------- crates/astria-conductor/src/metrics_init.rs | 88 ----------- .../src/metrics_init.rs | 137 ----------------- crates/astria-sequencer/src/metrics_init.rs | 140 ------------------ crates/astria-sequencer/src/mint/action.rs | 58 -------- crates/astria-sequencer/src/mint/mod.rs | 1 - 16 files changed, 190 insertions(+), 529 deletions(-) create mode 100644 .gitmodules create mode 100644 crates/astria-bridge-withdrawer/Cargo.toml create mode 100644 crates/astria-bridge-withdrawer/build.rs create mode 100644 crates/astria-bridge-withdrawer/ethereum/.gitignore create mode 100644 crates/astria-bridge-withdrawer/ethereum/README.md create mode 100644 crates/astria-bridge-withdrawer/ethereum/foundry.toml delete mode 100644 crates/astria-composer/src/metrics_init.rs delete mode 100644 crates/astria-conductor/src/metrics_init.rs delete mode 100644 crates/astria-sequencer-relayer/src/metrics_init.rs delete mode 100644 crates/astria-sequencer/src/metrics_init.rs delete mode 100644 crates/astria-sequencer/src/mint/action.rs delete mode 100644 crates/astria-sequencer/src/mint/mod.rs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e1a655244..7535c0c9b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -115,7 +115,37 @@ jobs: - name: Run tests timeout-minutes: 20 run: | - cargo nextest run --archive-file=archive.tar.zst -- --include-ignored + cargo nextest run --archive-file=archive.tar.zst + + rust-ethereum: + runs-on: buildjet-8vcpu-ubuntu-2204 + needs: run_checker + if: needs.run_checker.outputs.run_tests == 'true' + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@1.76.0 + - uses: Swatinem/rust-cache@v2.7.3 + with: + cache-provider: "buildjet" + - name: Install nextest + uses: taiki-e/install-action@nextest + - uses: arduino/setup-protoc@v3 + with: + version: "24.4" + repo-token: ${{ secrets.GITHUB_TOKEN }} + - name: Install python and solc + uses: actions/setup-python@v5 + with: + python-version: '3.10' + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + - name: Run tests + timeout-minutes: 20 + run: | + pip install solc-select + solc-select install 0.8.21 + solc-select use 0.8.21 + cargo nextest run --package astria-bridge-withdrawer -- --include-ignored doctest: runs-on: buildjet-8vcpu-ubuntu-2204 diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..41c5b6b73 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "crates/astria-bridge-withdrawer/ethereum/lib/forge-std"] + path = crates/astria-bridge-withdrawer/ethereum/lib/forge-std + url = https://github.com/foundry-rs/forge-std diff --git a/Cargo.lock b/Cargo.lock index 4e7246d6d..bd7bb35d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -493,6 +493,38 @@ dependencies = [ "wait-timeout", ] +[[package]] +name = "astria-bridge-withdrawer" +version = "0.1.0" +dependencies = [ + "astria-build-info", + "astria-config", + "astria-core", + "astria-eyre", + "astria-grpc-mock", + "astria-sequencer-client", + "astria-telemetry", + "axum", + "ethers", + "futures", + "hex", + "http", + "humantime", + "hyper", + "ibc-types", + "metrics", + "pin-project-lite", + "prost", + "serde", + "serde_json", + "sha2 0.10.8", + "tendermint 0.34.1", + "tokio", + "tokio-util 0.7.10", + "tracing", + "tryhard", +] + [[package]] name = "astria-build-info" version = "0.1.0" @@ -882,6 +914,7 @@ version = "0.1.0" dependencies = [ "base64 0.21.7", "base64-serde", + "const_format", "metrics-exporter-prometheus", "opentelemetry", "opentelemetry-otlp", @@ -2929,6 +2962,7 @@ checksum = "e79e5973c26d4baf0ce55520bd732314328cabe53193286671b47144145b9649" dependencies = [ "chrono", "ethers-core", + "ethers-solc", "reqwest", "semver 1.0.22", "serde", diff --git a/Cargo.toml b/Cargo.toml index 799032891..1e46cc79c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ exclude = ["tools/protobuf-compiler"] members = [ + "crates/astria-bridge-withdrawer", "crates/astria-build-info", "crates/astria-cli", "crates/astria-composer", @@ -24,6 +25,7 @@ members = [ # Specify default members so that cargo invocations in github actions will # not act on lints default-members = [ + "crates/astria-bridge-withdrawer", "crates/astria-build-info", "crates/astria-cli", "crates/astria-composer", @@ -55,6 +57,7 @@ bytes = "1" celestia-tendermint = "0.32.1" celestia-types = "0.1.1" clap = "4.5.4" +const_format = "0.2.32" ethers = "2.0.11" futures = "0.3" hex = "0.4" @@ -67,6 +70,7 @@ itertools = "0.12.1" itoa = "1.0.10" jsonrpsee = { version = "0.20" } once_cell = "1.17.1" +pin-project-lite = "0.2.13" sha2 = "0.10" serde = "1" serde_json = "1" diff --git a/charts/evm-rollup/Chart.yaml b/charts/evm-rollup/Chart.yaml index b79b9fac5..a95d1cdb2 100644 --- a/charts/evm-rollup/Chart.yaml +++ b/charts/evm-rollup/Chart.yaml @@ -15,7 +15,7 @@ type: application # This is the chart version. This version number should be incremented each time you make changes # to the chart and its templates, including the app version. # Versions are expected to follow Semantic Versioning (https://semver.org/) -version: 0.18.4 +version: 0.18.6 # This is the version number of the application being deployed. This version number should be # incremented each time you make changes to the application. Versions are not expected to diff --git a/crates/astria-bridge-withdrawer/Cargo.toml b/crates/astria-bridge-withdrawer/Cargo.toml new file mode 100644 index 000000000..dc5ae377f --- /dev/null +++ b/crates/astria-bridge-withdrawer/Cargo.toml @@ -0,0 +1,55 @@ +[package] +name = "astria-bridge-withdrawer" +version = "0.1.0" +edition = "2021" +rust-version = "1.73" +license = "MIT OR Apache-2.0" +readme = "README.md" +repository = "https://github.com/astriaorg/astria" +homepage = "https://astria.org" + +[[bin]] +name = "astria-bridge-withdrawer" + +[dependencies] +http = "0.2.9" + +axum = { workspace = true } +futures = { workspace = true } +hex = { workspace = true } +ethers = { workspace = true, features = ["ethers-solc", "ws"] } +hyper = { workspace = true } +humantime = { workspace = true } +ibc-types = { workspace = true } +metrics = { workspace = true } +pin-project-lite = { workspace = true } +prost = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +sha2 = { workspace = true } +tendermint = { workspace = true } +tracing = { workspace = true } +tryhard = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt-multi-thread", "signal"] } +tokio-util = { workspace = true } + +astria-build-info = { path = "../astria-build-info", features = ["runtime"] } +astria-core = { path = "../astria-core", features = ["serde", "server"] } +astria-eyre = { path = "../astria-eyre" } +config = { package = "astria-config", path = "../astria-config" } +sequencer-client = { package = "astria-sequencer-client", path = "../astria-sequencer-client", features = [ + "http", +] } +telemetry = { package = "astria-telemetry", path = "../astria-telemetry", features = [ + "display", +] } + +[dev-dependencies] +astria-core = { path = "../astria-core", features = ["server", "test-utils"] } +astria-grpc-mock = { path = "../astria-grpc-mock" } +config = { package = "astria-config", path = "../astria-config", features = [ + "tests", +] } + +[build-dependencies] +astria-build-info = { path = "../astria-build-info", features = ["build"] } diff --git a/crates/astria-bridge-withdrawer/build.rs b/crates/astria-bridge-withdrawer/build.rs new file mode 100644 index 000000000..f35d2acb0 --- /dev/null +++ b/crates/astria-bridge-withdrawer/build.rs @@ -0,0 +1,4 @@ +fn main() -> Result<(), Box> { + astria_build_info::emit("bridge-withdrawer-v")?; + Ok(()) +} diff --git a/crates/astria-bridge-withdrawer/ethereum/.gitignore b/crates/astria-bridge-withdrawer/ethereum/.gitignore new file mode 100644 index 000000000..85198aaa5 --- /dev/null +++ b/crates/astria-bridge-withdrawer/ethereum/.gitignore @@ -0,0 +1,14 @@ +# Compiler files +cache/ +out/ + +# Ignores development broadcast logs +!/broadcast +/broadcast/*/31337/ +/broadcast/**/dry-run/ + +# Docs +docs/ + +# Dotenv file +.env diff --git a/crates/astria-bridge-withdrawer/ethereum/README.md b/crates/astria-bridge-withdrawer/ethereum/README.md new file mode 100644 index 000000000..6b847ae27 --- /dev/null +++ b/crates/astria-bridge-withdrawer/ethereum/README.md @@ -0,0 +1,38 @@ +# astria-bridge-withdrawer + +Forge project for the bridge withdrawer contract. + +Requirements: + +- foundry + +Build: + +```sh +forge build +``` + +Copy the example .env: `cp local.example.env .env` + +Put your private key in `.env` and `source .env`. + +Deploy `AstriaWithdrawer.sol`: + +```sh +forge script script/AstriaWithdrawer.s.sol:AstriaWithdrawerScript \ + --rpc-url $RPC_URL --broadcast --sig "deploy()" -vvvv +``` + +Call `withdrawToSequencer` in `AstriaWithdrawer.sol`: + +```sh +forge script script/AstriaWithdrawer.s.sol:AstriaWithdrawerScript \ + --rpc-url $RPC_URL --broadcast --sig "withdrawToSequencer()" -vvvv +``` + +Call `withdrawToOriginChain` in `AstriaWithdrawer.sol`: + +```sh +forge script script/AstriaWithdrawer.s.sol:AstriaWithdrawerScript \ + --rpc-url $RPC_URL --broadcast --sig "withdrawToOriginChain()" -vvvv +``` diff --git a/crates/astria-bridge-withdrawer/ethereum/foundry.toml b/crates/astria-bridge-withdrawer/ethereum/foundry.toml new file mode 100644 index 000000000..25b918f9c --- /dev/null +++ b/crates/astria-bridge-withdrawer/ethereum/foundry.toml @@ -0,0 +1,6 @@ +[profile.default] +src = "src" +out = "out" +libs = ["lib"] + +# See more config options https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options diff --git a/crates/astria-composer/src/metrics_init.rs b/crates/astria-composer/src/metrics_init.rs deleted file mode 100644 index 71d9ac57f..000000000 --- a/crates/astria-composer/src/metrics_init.rs +++ /dev/null @@ -1,103 +0,0 @@ -//! Crate-specific metrics functionality. -//! -//! Registers metrics & lists constants to be used as metric names throughout crate. - -use metrics::{ - describe_counter, - describe_gauge, - describe_histogram, - Unit, -}; - -/// Labels -pub(crate) const ROLLUP_ID_LABEL: &str = "rollup_id"; -pub(crate) const COLLECTOR_TYPE_LABEL: &str = "collector_type"; - -/// Registers all metrics used by this crate. -// allow: refactor this. being tracked in https://github.com/astriaorg/astria/issues/1027 -#[allow(clippy::too_many_lines)] -pub fn register() { - describe_counter!( - TRANSACTIONS_RECEIVED, - Unit::Count, - "The number of transactions successfully received from collectors and bundled labelled by \ - rollup" - ); - describe_counter!( - TRANSACTIONS_DROPPED, - Unit::Count, - "The number of transactions dropped by the collectors before bundling it labelled by \ - rollup and collector type" - ); - describe_counter!( - TRANSACTIONS_DROPPED_TOO_LARGE, - Unit::Count, - "The number of transactions dropped because they were too large" - ); - describe_counter!( - NONCE_FETCH_COUNT, - Unit::Count, - "The number of times we have attempted to fetch the nonce" - ); - describe_counter!( - NONCE_FETCH_FAILURE_COUNT, - Unit::Count, - "The number of times we have failed to fetch the nonce" - ); - describe_histogram!( - NONCE_FETCH_LATENCY, - Unit::Milliseconds, - "The latency of nonce fetch" - ); - describe_gauge!(CURRENT_NONCE, Unit::Count, "The current nonce"); - describe_histogram!( - SEQUENCER_SUBMISSION_LATENCY, - Unit::Milliseconds, - "The latency of submitting a transaction to the sequencer" - ); - describe_counter!( - SEQUENCER_SUBMISSION_FAILURE_COUNT, - Unit::Count, - "The number of failed transaction submissions to the sequencer" - ); - describe_histogram!( - TRANSACTIONS_PER_SUBMISSION, - Unit::Count, - "The number of rollup transactions successfully sent to the sequencer in a single \ - submission" - ); - describe_histogram!( - BYTES_PER_SUBMISSION, - Unit::Bytes, - "The total bytes successfully sent to the sequencer in a single submission" - ); -} - -pub const TRANSACTIONS_RECEIVED: &str = concat!(env!("CARGO_CRATE_NAME"), "_transactions_received"); - -pub const TRANSACTIONS_DROPPED: &str = concat!(env!("CARGO_CRATE_NAME"), "_transactions_dropped"); - -pub const TRANSACTIONS_DROPPED_TOO_LARGE: &str = - concat!(env!("CARGO_CRATE_NAME"), "_transactions_dropped_too_large"); - -pub const NONCE_FETCH_COUNT: &str = concat!(env!("CARGO_CRATE_NAME"), "_nonce_fetch_count"); - -pub const NONCE_FETCH_FAILURE_COUNT: &str = - concat!(env!("CARGO_CRATE_NAME"), "_nonce_fetch_failure_count"); - -pub const NONCE_FETCH_LATENCY: &str = concat!(env!("CARGO_CRATE_NAME"), "_nonce_fetch_latency"); - -pub const CURRENT_NONCE: &str = concat!(env!("CARGO_CRATE_NAME"), "_current_nonce"); - -pub const SEQUENCER_SUBMISSION_LATENCY: &str = - concat!(env!("CARGO_CRATE_NAME"), "_sequencer_submission_latency"); - -pub const SEQUENCER_SUBMISSION_FAILURE_COUNT: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_sequencer_submission_failure_count" -); - -pub const TRANSACTIONS_PER_SUBMISSION: &str = - concat!(env!("CARGO_CRATE_NAME"), "_transaction_per_submission"); - -pub const BYTES_PER_SUBMISSION: &str = concat!(env!("CARGO_CRATE_NAME"), "_bytes_per_submission"); diff --git a/crates/astria-conductor/src/metrics_init.rs b/crates/astria-conductor/src/metrics_init.rs deleted file mode 100644 index d5da23a23..000000000 --- a/crates/astria-conductor/src/metrics_init.rs +++ /dev/null @@ -1,88 +0,0 @@ -//! Crate-specific metrics functionality. -//! -//! Registers metrics & lists constants to be used as metric names throughout crate. - -use metrics::{ - describe_counter, - describe_histogram, - Unit, -}; - -pub(crate) const NAMESPACE_TYPE_LABEL: &str = "namespace_type"; -pub(crate) const NAMESPACE_TYPE_METADATA: &str = "metadata"; -pub(crate) const NAMESPACE_TYPE_ROLLUP_DATA: &str = "rollup_data"; - -pub fn register() { - describe_histogram!( - BLOBS_PER_CELESTIA_FETCH, - Unit::Count, - "The number of Celestia blobs received per request sent" - ); - - describe_counter!( - CELESTIA_BLOB_FETCH_ERROR_COUNT, - Unit::Count, - "The number of calls made to fetch a blob from Celestia which have failed" - ); - - describe_histogram!( - DECODED_ITEMS_PER_CELESTIA_FETCH, - Unit::Count, - "The number of items decoded from the Celestia blobs received per request sent" - ); - - describe_counter!( - EXECUTED_FIRM_BLOCK_NUMBER, - Unit::Count, - "The number/rollup height of the last executed or confirmed firm block" - ); - - describe_counter!( - EXECUTED_SOFT_BLOCK_NUMBER, - Unit::Count, - "The number/rollup height of the last executed soft block" - ); - - describe_histogram!( - SEQUENCER_BLOCK_INFORMATION_RECONSTRUCTED_PER_CELESTIA_FETCH, - Unit::Count, - "The number of sequencer blocks (or specifically, the subset pertaining to the rollup) \ - reconstructed from a single Celestia blob fetch" - ); - - describe_histogram!( - TRANSACTIONS_PER_EXECUTED_BLOCK, - Unit::Count, - "The number of transactions that were included in the latest block executed against the \ - rollup" - ); -} - -pub const BLOBS_PER_CELESTIA_FETCH: &str = - concat!(env!("CARGO_CRATE_NAME"), "_blobs_per_celestia_fetch",); - -pub const CELESTIA_BLOB_FETCH_ERROR_COUNT: &str = - concat!(env!("CARGO_CRATE_NAME"), "_celestia_blob_fetch_error_count"); - -pub const DECODED_ITEMS_PER_CELESTIA_FETCH: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_decoded_items_per_celestia_fetch", -); - -pub const SEQUENCER_BLOCKS_METADATA_VERIFIED_PER_CELESTIA_FETCH: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_sequencer_blocks_metadata_verified_per_celestia_fetch", -); - -pub const SEQUENCER_BLOCK_INFORMATION_RECONSTRUCTED_PER_CELESTIA_FETCH: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_sequencer_block_information_reconstructed_per_celestia_fetch", -); - -pub const EXECUTED_FIRM_BLOCK_NUMBER: &str = - concat!(env!("CARGO_CRATE_NAME"), "_executed_firm_block_number"); -pub const EXECUTED_SOFT_BLOCK_NUMBER: &str = - concat!(env!("CARGO_CRATE_NAME"), "_executed_soft_block_number"); - -pub const TRANSACTIONS_PER_EXECUTED_BLOCK: &str = - concat!(env!("CARGO_CRATE_NAME"), "_transactions_per_executed_block",); diff --git a/crates/astria-sequencer-relayer/src/metrics_init.rs b/crates/astria-sequencer-relayer/src/metrics_init.rs deleted file mode 100644 index 52616b3b0..000000000 --- a/crates/astria-sequencer-relayer/src/metrics_init.rs +++ /dev/null @@ -1,137 +0,0 @@ -//! Crate-specific metrics functionality. -//! -//! Registers metrics & lists constants to be used as metric names throughout crate. - -use metrics::{ - describe_counter, - describe_gauge, - describe_histogram, - Unit, -}; - -/// Registers all metrics used by this crate. -pub fn register() { - describe_counter!( - CELESTIA_SUBMISSION_COUNT, - Unit::Count, - "The number of calls made to submit to Celestia" - ); - - describe_counter!( - CELESTIA_SUBMISSION_HEIGHT, - Unit::Count, - "The height of the last blob successfully submitted to Celestia" - ); - - describe_counter!( - CELESTIA_SUBMISSION_FAILURE_COUNT, - Unit::Count, - "The number of calls made to submit to Celestia which have failed" - ); - - describe_counter!( - SEQUENCER_BLOCK_FETCH_FAILURE_COUNT, - Unit::Count, - "The number of calls made to fetch a block from sequencer which have failed" - ); - - describe_counter!( - SEQUENCER_HEIGHT_FETCH_FAILURE_COUNT, - Unit::Count, - "The number of calls made to fetch the current height from sequencer which have failed" - ); - - describe_counter!( - SEQUENCER_SUBMISSION_HEIGHT, - Unit::Count, - "The height of the highest sequencer block successfully submitted to Celestia" - ); - - describe_histogram!( - BLOCKS_PER_CELESTIA_TX, - Unit::Count, - "The number of Astria blocks per Celestia submission" - ); - - describe_histogram!( - BLOBS_PER_CELESTIA_TX, - Unit::Count, - "The number of blobs (Astria Sequencer blocks converted to Celestia blobs) per Celestia \ - submission" - ); - - describe_histogram!( - BYTES_PER_CELESTIA_TX, - Unit::Bytes, - "The total number of payload bytes (Astria Sequencer blocks converted to Celestia blobs) \ - per Celestia submission" - ); - - describe_histogram!( - CELESTIA_SUBMISSION_LATENCY, - Unit::Seconds, - "The time it takes to submit a blob to Celestia" - ); - - describe_histogram!( - CELESTIA_PAYLOAD_CREATION_LATENCY, - Unit::Microseconds, - "The time it takes to create a new payload for submitting to Celestia (encoding to \ - protobuf, compression, creating blobs)" - ); - - describe_gauge!( - COMPRESSION_RATIO_FOR_ASTRIA_BLOCK, - Unit::Count, - "Ratio of uncompressed:compressed data size for all `blob.data`s in an Astria block" - ); -} - -// We configure buckets for manually, in order to ensure Prometheus metrics are structured as a -// Histogram, rather than as a Summary. These values are loosely based on the initial Summary -// output, and may need to be updated over time. -pub const HISTOGRAM_BUCKETS: &[f64; 5] = &[0.00001, 0.0001, 0.001, 0.01, 0.1]; - -pub const CELESTIA_SUBMISSION_HEIGHT: &str = - concat!(env!("CARGO_CRATE_NAME"), "_celestia_submission_height"); - -pub const CELESTIA_SUBMISSION_COUNT: &str = - concat!(env!("CARGO_CRATE_NAME"), "_celestia_submission_count"); - -pub const CELESTIA_SUBMISSION_FAILURE_COUNT: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_celestia_submission_failure_count" -); - -pub const BLOCKS_PER_CELESTIA_TX: &str = - concat!(env!("CARGO_CRATE_NAME"), "_blocks_per_celestia_tx"); - -pub const BLOBS_PER_CELESTIA_TX: &str = concat!(env!("CARGO_CRATE_NAME"), "_blobs_per_celestia_tx"); - -pub const BYTES_PER_CELESTIA_TX: &str = concat!(env!("CARGO_CRATE_NAME"), "_bytes_per_celestia_tx"); - -pub const CELESTIA_PAYLOAD_CREATION_LATENCY: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_celestia_payload_creation_latency" -); - -pub const CELESTIA_SUBMISSION_LATENCY: &str = - concat!(env!("CARGO_CRATE_NAME"), "_celestia_submission_latency"); - -pub const SEQUENCER_BLOCK_FETCH_FAILURE_COUNT: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_sequencer_block_fetch_failure_count", -); - -pub const SEQUENCER_HEIGHT_FETCH_FAILURE_COUNT: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_sequencer_height_fetch_failure_count", -); - -pub const SEQUENCER_SUBMISSION_HEIGHT: &str = - concat!(env!("CARGO_CRATE_NAME"), "_sequencer_submission_height"); - -pub const COMPRESSION_RATIO_FOR_ASTRIA_BLOCK: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_compression_ratio_for_astria_block" -); diff --git a/crates/astria-sequencer/src/metrics_init.rs b/crates/astria-sequencer/src/metrics_init.rs deleted file mode 100644 index b2c369cba..000000000 --- a/crates/astria-sequencer/src/metrics_init.rs +++ /dev/null @@ -1,140 +0,0 @@ -//! Crate-specific metrics functionality. -//! -//! Registers metrics & lists constants to be used as metric names throughout crate. - -use metrics::{ - describe_counter, - describe_gauge, - describe_histogram, - Unit, -}; - -/// Registers all metrics used by this crate. -pub fn register() { - describe_counter!( - PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_DECODE_FAILURE, - Unit::Count, - "The number of transactions that have been excluded from blocks due to failing to decode" - ); - - describe_counter!( - PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_COMETBFT_SPACE, - Unit::Count, - "The number of transactions that have been excluded from blocks due to running out of \ - space in the cometbft block" - ); - - describe_counter!( - PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_SEQUENCER_SPACE, - Unit::Count, - "The number of transactions that have been excluded from blocks due to running out of \ - space in the sequencer block" - ); - - describe_counter!( - PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_FAILED_EXECUTION, - Unit::Count, - "The number of transactions that have been excluded from blocks due to failing to execute" - ); - - describe_gauge!( - PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS, - Unit::Count, - "The number of excluded transactions in a proposal being prepared" - ); - - describe_counter!( - PROCESS_PROPOSAL_SKIPPED_PROPOSAL, - Unit::Count, - "The number of times our submitted prepared proposal was skipped in process proposal" - ); - - describe_counter!( - CHECK_TX_REMOVED_TOO_LARGE, - Unit::Count, - "The number of transactions that have been removed from the mempool due to being too large" - ); - - describe_counter!( - CHECK_TX_REMOVED_FAILED_STATELESS, - Unit::Count, - "The number of transactions that have been removed from the mempool due to failing the \ - stateless check" - ); - - describe_counter!( - CHECK_TX_REMOVED_STALE_NONCE, - Unit::Count, - "The number of transactions that have been removed from the mempool due to having a stale \ - nonce" - ); - - describe_counter!( - CHECK_TX_REMOVED_ACCOUNT_BALANCE, - Unit::Count, - "The number of transactions that have been removed from the mempool due to having not \ - enough account balance" - ); - - describe_histogram!( - PROPOSAL_TRANSACTIONS, - Unit::Count, - "The number of transactions in a proposal" - ); - - describe_histogram!( - PROPOSAL_DEPOSITS, - Unit::Count, - "The number of deposits in a proposal" - ); -} - -pub const PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_DECODE_FAILURE: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_prepare_proposal_excluded_transactions_decode_failure" -); - -pub const PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_COMETBFT_SPACE: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_prepare_proposal_excluded_transactions_cometbft_space" -); - -pub const PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_SEQUENCER_SPACE: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_prepare_proposal_excluded_transactions_sequencer_space" -); - -pub const PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_FAILED_EXECUTION: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_prepare_proposal_excluded_transactions_failed_execution" -); - -pub const PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_prepare_proposal_excluded_transactions" -); - -pub const PROPOSAL_DEPOSITS: &str = concat!(env!("CARGO_CRATE_NAME"), "_proposal_deposits"); - -pub const PROPOSAL_TRANSACTIONS: &str = concat!(env!("CARGO_CRATE_NAME"), "_proposal_transactions"); - -pub const PROCESS_PROPOSAL_SKIPPED_PROPOSAL: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_process_proposal_skipped_proposal" -); - -pub const CHECK_TX_REMOVED_TOO_LARGE: &str = - concat!(env!("CARGO_CRATE_NAME"), "_check_tx_removed_too_large"); - -pub const CHECK_TX_REMOVED_FAILED_STATELESS: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_check_tx_removed_failed_stateless" -); - -pub const CHECK_TX_REMOVED_STALE_NONCE: &str = - concat!(env!("CARGO_CRATE_NAME"), "_check_tx_removed_stale_nonce"); - -pub const CHECK_TX_REMOVED_ACCOUNT_BALANCE: &str = concat!( - env!("CARGO_CRATE_NAME"), - "_check_tx_removed_account_balance" -); diff --git a/crates/astria-sequencer/src/mint/action.rs b/crates/astria-sequencer/src/mint/action.rs deleted file mode 100644 index 09ba618cc..000000000 --- a/crates/astria-sequencer/src/mint/action.rs +++ /dev/null @@ -1,58 +0,0 @@ -use anyhow::{ - ensure, - Context as _, - Result, -}; -use astria_core::{ - primitive::v1::Address, - protocol::transaction::v1alpha1::action::MintAction, -}; -use tracing::instrument; - -use crate::{ - accounts::state_ext::{ - StateReadExt as AccountStateReadExt, - StateWriteExt as AccountStateWriteExt, - }, - asset::get_native_asset, - authority::state_ext::StateReadExt as AuthorityStateReadExt, - transaction::action_handler::ActionHandler, -}; - -#[async_trait::async_trait] -impl ActionHandler for MintAction { - async fn check_stateful( - &self, - state: &S, - from: Address, - ) -> Result<()> { - // ensure signer is the valid `sudo` key in state - let sudo_address = state - .get_sudo_address() - .await - .context("failed to get sudo address from state")?; - ensure!(sudo_address == from, "signer is not the sudo key"); - Ok(()) - } - - #[instrument(skip_all)] - async fn execute( - &self, - state: &mut S, - _: Address, - ) -> Result<()> { - let native_asset = get_native_asset().id(); - - let to_balance = state - .get_account_balance(self.to, native_asset) - .await - .context("failed getting `to` account balance")?; - let new_balance = to_balance - .checked_add(self.amount) - .context("`to` balance would overflow")?; - state - .put_account_balance(self.to, native_asset, new_balance) - .context("failed updating `to` account balance")?; - Ok(()) - } -} diff --git a/crates/astria-sequencer/src/mint/mod.rs b/crates/astria-sequencer/src/mint/mod.rs deleted file mode 100644 index f04dbbc6c..000000000 --- a/crates/astria-sequencer/src/mint/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub(crate) mod action; From 58d47b2a41b5b6765b192de301a61a5c2ea1ff20 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Tue, 4 Jun 2024 19:43:36 -0500 Subject: [PATCH 04/23] Swapped Genesis for Sequencer Client Status Swapped sequencer client genesis get for sequencer client status get. Cleans up the code a bit --- crates/astria-bridge-withdrawer/src/api.rs | 32 +--- crates/astria-bridge-withdrawer/src/config.rs | 5 +- crates/astria-bridge-withdrawer/src/main.rs | 18 +- .../src/metrics_init.rs | 15 +- .../src/withdrawer/ethereum/convert.rs | 30 +-- .../src/withdrawer/ethereum/test_utils.rs | 16 +- .../src/withdrawer/ethereum/watcher.rs | 42 +---- .../src/withdrawer/mod.rs | 32 +--- .../src/withdrawer/state.rs | 4 +- .../src/withdrawer/submitter/builder.rs | 5 +- .../src/withdrawer/submitter/mod.rs | 45 +---- .../src/withdrawer/submitter/signer.rs | 10 +- crates/astria-cli/src/cli/mod.rs | 10 +- crates/astria-cli/src/cli/rollup.rs | 10 +- crates/astria-cli/src/cli/sequencer.rs | 10 +- crates/astria-cli/src/commands/mod.rs | 63 ++----- crates/astria-cli/src/commands/rollup.rs | 25 +-- crates/astria-cli/src/commands/sequencer.rs | 40 +--- crates/astria-cli/src/main.rs | 10 +- crates/astria-cli/src/types.rs | 15 +- crates/astria-cli/test-utils/src/lib.rs | 5 +- crates/astria-composer/src/api.rs | 24 +-- crates/astria-composer/src/collectors/geth.rs | 41 +---- crates/astria-composer/src/collectors/grpc.rs | 28 +-- crates/astria-composer/src/composer.rs | 46 +---- crates/astria-composer/src/config.rs | 5 +- .../astria-composer/src/executor/builder.rs | 22 +-- .../src/executor/bundle_factory/mod.rs | 21 +-- .../src/executor/bundle_factory/tests.rs | 23 +-- crates/astria-composer/src/executor/mod.rs | 66 ++----- crates/astria-composer/src/executor/tests.rs | 89 +++++---- crates/astria-composer/src/grpc.rs | 15 +- crates/astria-composer/src/main.rs | 12 +- crates/astria-composer/src/metrics_init.rs | 20 +- crates/astria-composer/src/rollup.rs | 10 +- .../tests/blackbox/geth_collector.rs | 12 +- .../tests/blackbox/grpc_collector.rs | 7 +- .../tests/blackbox/helper/mock_sequencer.rs | 15 +- .../tests/blackbox/helper/mod.rs | 32 +--- crates/astria-conductor/src/block_cache.rs | 20 +- .../src/celestia/block_verifier.rs | 42 +---- .../astria-conductor/src/celestia/builder.rs | 10 +- .../astria-conductor/src/celestia/convert.rs | 28 +-- crates/astria-conductor/src/celestia/fetch.rs | 32 +--- .../src/celestia/latest_height_stream.rs | 17 +- crates/astria-conductor/src/celestia/mod.rs | 76 ++------ .../src/celestia/reconstruct.rs | 15 +- .../src/celestia/reporting.rs | 11 +- .../astria-conductor/src/celestia/verify.rs | 81 ++------ crates/astria-conductor/src/conductor.rs | 45 +---- crates/astria-conductor/src/config.rs | 16 +- .../astria-conductor/src/executor/builder.rs | 12 +- .../astria-conductor/src/executor/channel.rs | 26 +-- .../astria-conductor/src/executor/client.rs | 51 +---- crates/astria-conductor/src/executor/mod.rs | 60 ++---- crates/astria-conductor/src/executor/state.rs | 29 +-- crates/astria-conductor/src/executor/tests.rs | 101 ++-------- crates/astria-conductor/src/main.rs | 18 +- crates/astria-conductor/src/metrics_init.rs | 13 +- .../src/sequencer/block_stream.rs | 21 +-- .../astria-conductor/src/sequencer/client.rs | 26 +-- crates/astria-conductor/src/sequencer/mod.rs | 40 +--- .../src/sequencer/reporting.rs | 19 +- crates/astria-conductor/src/utils.rs | 5 +- .../tests/blackbox/firm_only.rs | 17 +- .../tests/blackbox/helpers/macros.rs | 5 +- .../tests/blackbox/helpers/mock_grpc.rs | 49 +---- .../tests/blackbox/helpers/mod.rs | 108 +++-------- .../astria-conductor/tests/blackbox/main.rs | 7 +- .../tests/blackbox/soft_and_firm.rs | 21 +-- .../tests/blackbox/soft_only.rs | 14 +- crates/astria-config/src/lib.rs | 9 +- crates/astria-config/src/tests.rs | 10 +- crates/astria-core/src/brotli.rs | 6 +- crates/astria-core/src/celestia.rs | 5 +- crates/astria-core/src/crypto.rs | 42 +---- .../astria-core/src/execution/v1alpha2/mod.rs | 11 +- crates/astria-core/src/primitive/v1/asset.rs | 10 +- crates/astria-core/src/primitive/v1/mod.rs | 34 +--- crates/astria-core/src/primitive/v1/u128.rs | 25 +-- crates/astria-core/src/protocol/abci.rs | 5 +- .../src/protocol/account/v1alpha1/mod.rs | 41 +---- .../src/protocol/asset/v1alpha1/mod.rs | 10 +- crates/astria-core/src/protocol/test_utils.rs | 20 +- .../protocol/transaction/v1alpha1/action.rs | 43 +---- .../src/protocol/transaction/v1alpha1/mod.rs | 66 ++----- .../src/sequencerblock/v1alpha1/block.rs | 38 +--- .../src/sequencerblock/v1alpha1/celestia.rs | 47 ++--- .../src/sequencerblock/v1alpha1/mod.rs | 21 +-- crates/astria-eyre/src/lib.rs | 5 +- .../tests/health/main.rs | 61 ++---- crates/astria-grpc-mock/src/lib.rs | 10 +- crates/astria-grpc-mock/src/matcher.rs | 5 +- crates/astria-grpc-mock/src/mock.rs | 23 +-- crates/astria-grpc-mock/src/mock_server.rs | 19 +- crates/astria-grpc-mock/src/mock_set.rs | 24 +-- crates/astria-grpc-mock/src/mounted_mock.rs | 15 +- crates/astria-grpc-mock/src/response.rs | 5 +- crates/astria-grpc-mock/src/verification.rs | 5 +- crates/astria-merkle/src/audit.rs | 69 ++----- crates/astria-merkle/src/lib.rs | 19 +- crates/astria-merkle/src/tests.rs | 10 +- .../src/extension_trait.rs | 69 ++----- crates/astria-sequencer-client/src/lib.rs | 26 +-- .../astria-sequencer-client/src/tests/http.rs | 81 ++------ crates/astria-sequencer-relayer/src/api.rs | 32 +--- crates/astria-sequencer-relayer/src/config.rs | 21 +-- crates/astria-sequencer-relayer/src/lib.rs | 10 +- crates/astria-sequencer-relayer/src/main.rs | 18 +- .../src/metrics_init.rs | 24 +-- .../src/relayer/builder.rs | 27 +-- .../src/relayer/celestia_client/builder.rs | 16 +- .../relayer/celestia_client/celestia_keys.rs | 14 +- .../src/relayer/celestia_client/error.rs | 6 +- .../src/relayer/celestia_client/mod.rs | 87 ++------- .../src/relayer/celestia_client/tests.rs | 22 +-- .../src/relayer/mod.rs | 47 +---- .../src/relayer/read.rs | 37 +--- .../src/relayer/state.rs | 4 +- .../src/relayer/submission.rs | 37 +--- .../src/relayer/write/conversion.rs | 58 ++---- .../src/relayer/write/mod.rs | 44 +---- .../src/sequencer_relayer.rs | 25 +-- crates/astria-sequencer-relayer/src/utils.rs | 5 +- .../astria-sequencer-relayer/src/validator.rs | 5 +- .../helpers/mock_celestia_app_server.rs | 78 ++------ .../blackbox/helpers/mock_sequencer_server.rs | 35 +--- .../tests/blackbox/helpers/mod.rs | 5 +- .../helpers/test_sequencer_relayer.rs | 63 ++----- .../tests/blackbox/main.rs | 10 +- .../astria-sequencer-utils/src/blob_parser.rs | 49 +---- crates/astria-sequencer-utils/src/cli.rs | 10 +- .../src/genesis_parser.rs | 17 +- crates/astria-sequencer-utils/src/main.rs | 5 +- .../tests/parse_blob.rs | 10 +- .../astria-sequencer/src/accounts/action.rs | 19 +- .../src/accounts/component.rs | 16 +- crates/astria-sequencer/src/accounts/query.rs | 20 +- .../src/accounts/state_ext.rs | 36 +--- crates/astria-sequencer/src/api_state_ext.rs | 37 +--- crates/astria-sequencer/src/app/mod.rs | 79 ++------ crates/astria-sequencer/src/app/test_utils.rs | 32 +--- crates/astria-sequencer/src/app/tests_app.rs | 143 +++++--------- .../src/app/tests_breaking_changes.rs | 60 ++---- .../src/app/tests_execute_transaction.rs | 174 +++++++----------- crates/astria-sequencer/src/asset/query.rs | 26 +-- .../astria-sequencer/src/asset/state_ext.rs | 30 +-- .../astria-sequencer/src/authority/action.rs | 42 +---- .../src/authority/component.rs | 16 +- .../src/authority/state_ext.rs | 45 +---- .../src/bridge/bridge_lock_action.rs | 59 ++---- .../src/bridge/bridge_unlock_action.rs | 65 +++---- .../astria-sequencer/src/bridge/component.rs | 10 +- .../src/bridge/init_bridge_account_action.rs | 25 +-- .../astria-sequencer/src/bridge/state_ext.rs | 43 +---- crates/astria-sequencer/src/config.rs | 5 +- .../astria-sequencer/src/fee_asset_change.rs | 20 +- crates/astria-sequencer/src/genesis.rs | 10 +- crates/astria-sequencer/src/grpc/sequencer.rs | 50 ++--- crates/astria-sequencer/src/ibc/component.rs | 20 +- .../src/ibc/ibc_relayer_change.rs | 19 +- .../src/ibc/ics20_transfer.rs | 50 +---- .../src/ibc/ics20_withdrawal.rs | 32 +--- crates/astria-sequencer/src/ibc/state_ext.rs | 37 +--- crates/astria-sequencer/src/main.rs | 7 +- crates/astria-sequencer/src/mempool.rs | 58 ++---- crates/astria-sequencer/src/metrics_init.rs | 19 +- .../src/proposal/block_size_constraints.rs | 6 +- .../src/proposal/commitment.rs | 23 +-- .../astria-sequencer/src/sequence/action.rs | 19 +- .../src/sequence/component.rs | 10 +- .../src/sequence/state_ext.rs | 21 +-- crates/astria-sequencer/src/sequencer.rs | 40 +--- .../astria-sequencer/src/service/consensus.rs | 125 ++++--------- .../src/service/info/abci_query_router.rs | 20 +- .../astria-sequencer/src/service/info/mod.rs | 45 +---- .../astria-sequencer/src/service/mempool.rs | 36 +--- .../astria-sequencer/src/service/snapshot.rs | 20 +- crates/astria-sequencer/src/state_ext.rs | 17 +- .../src/transaction/action_handler.rs | 5 +- .../src/transaction/checks.rs | 54 ++---- .../astria-sequencer/src/transaction/mod.rs | 25 +-- crates/astria-telemetry/src/display.rs | 19 +- crates/astria-telemetry/src/lib.rs | 35 +--- crates/astria-telemetry/src/macros.rs | 4 +- crates/astria-test-utils/src/mock/geth.rs | 24 +-- lint/tracing_debug_field/src/lib.rs | 29 +-- 187 files changed, 1252 insertions(+), 4304 deletions(-) diff --git a/crates/astria-bridge-withdrawer/src/api.rs b/crates/astria-bridge-withdrawer/src/api.rs index 25e7e786f..47c3c00ee 100644 --- a/crates/astria-bridge-withdrawer/src/api.rs +++ b/crates/astria-bridge-withdrawer/src/api.rs @@ -1,20 +1,10 @@ use std::net::SocketAddr; use axum::{ - extract::{ - FromRef, - State, - }, - response::{ - IntoResponse, - Response, - }, - routing::{ - get, - IntoMakeService, - }, - Json, - Router, + extract::{FromRef, State}, + response::{IntoResponse, Response}, + routing::{get, IntoMakeService}, + Json, Router, }; use http::status::StatusCode; use hyper::server::conn::AddrIncoming; @@ -44,9 +34,7 @@ pub(crate) fn start(socket_addr: SocketAddr, withdrawer_state: WithdrawerState) .route("/healthz", get(get_healthz)) .route("/readyz", get(get_readyz)) .route("/status", get(get_status)) - .with_state(AppState { - withdrawer_state, - }); + .with_state(AppState { withdrawer_state }); axum::Server::bind(&socket_addr).serve(app.into_make_service()) } @@ -95,10 +83,7 @@ impl IntoResponse for Healthz { Self::Ok => (StatusCode::OK, "ok"), Self::Degraded => (StatusCode::INTERNAL_SERVER_ERROR, "degraded"), }; - let mut response = Json(ReadyzBody { - status: msg, - }) - .into_response(); + let mut response = Json(ReadyzBody { status: msg }).into_response(); *response.status_mut() = status; response } @@ -119,10 +104,7 @@ impl IntoResponse for Readyz { Self::Ok => (StatusCode::OK, "ok"), Self::NotReady => (StatusCode::SERVICE_UNAVAILABLE, "not ready"), }; - let mut response = Json(ReadyzBody { - status: msg, - }) - .into_response(); + let mut response = Json(ReadyzBody { status: msg }).into_response(); *response.status_mut() = status; response } diff --git a/crates/astria-bridge-withdrawer/src/config.rs b/crates/astria-bridge-withdrawer/src/config.rs index 4156525d0..985d45584 100644 --- a/crates/astria-bridge-withdrawer/src/config.rs +++ b/crates/astria-bridge-withdrawer/src/config.rs @@ -1,7 +1,4 @@ -use serde::{ - Deserialize, - Serialize, -}; +use serde::{Deserialize, Serialize}; // Allowed `struct_excessive_bools` because this is used as a container // for deserialization. Making this a builder-pattern is not actionable. diff --git a/crates/astria-bridge-withdrawer/src/main.rs b/crates/astria-bridge-withdrawer/src/main.rs index 53ef465bd..0daeaf62f 100644 --- a/crates/astria-bridge-withdrawer/src/main.rs +++ b/crates/astria-bridge-withdrawer/src/main.rs @@ -1,21 +1,9 @@ use std::process::ExitCode; -use astria_bridge_withdrawer::{ - metrics_init, - Config, - Service, - BUILD_INFO, -}; +use astria_bridge_withdrawer::{metrics_init, Config, Service, BUILD_INFO}; use astria_eyre::eyre::WrapErr as _; -use tokio::signal::unix::{ - signal, - SignalKind, -}; -use tracing::{ - error, - info, - warn, -}; +use tokio::signal::unix::{signal, SignalKind}; +use tracing::{error, info, warn}; #[tokio::main] async fn main() -> ExitCode { diff --git a/crates/astria-bridge-withdrawer/src/metrics_init.rs b/crates/astria-bridge-withdrawer/src/metrics_init.rs index bc9f455da..a16898317 100644 --- a/crates/astria-bridge-withdrawer/src/metrics_init.rs +++ b/crates/astria-bridge-withdrawer/src/metrics_init.rs @@ -2,12 +2,7 @@ //! //! Registers metrics & lists constants to be used as metric names throughout crate. -use metrics::{ - describe_counter, - describe_gauge, - describe_histogram, - Unit, -}; +use metrics::{describe_counter, describe_gauge, describe_histogram, Unit}; use telemetry::metric_name; /// Registers all metrics used by this crate. @@ -50,12 +45,8 @@ metric_name!(pub const SEQUENCER_SUBMISSION_LATENCY); #[cfg(test)] mod tests { use super::{ - CURRENT_NONCE, - NONCE_FETCH_COUNT, - NONCE_FETCH_FAILURE_COUNT, - NONCE_FETCH_LATENCY, - SEQUENCER_SUBMISSION_FAILURE_COUNT, - SEQUENCER_SUBMISSION_LATENCY, + CURRENT_NONCE, NONCE_FETCH_COUNT, NONCE_FETCH_FAILURE_COUNT, NONCE_FETCH_LATENCY, + SEQUENCER_SUBMISSION_FAILURE_COUNT, SEQUENCER_SUBMISSION_LATENCY, }; #[track_caller] diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/convert.rs b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/convert.rs index 90857f853..5808b1a64 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/convert.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/convert.rs @@ -1,37 +1,19 @@ use std::time::Duration; use astria_core::{ - primitive::v1::{ - asset, - asset::Denom, - Address, - }, + primitive::v1::{asset, asset::Denom, Address}, protocol::transaction::v1alpha1::{ - action::{ - BridgeUnlockAction, - Ics20Withdrawal, - }, + action::{BridgeUnlockAction, Ics20Withdrawal}, Action, }, }; -use astria_eyre::eyre::{ - self, - OptionExt, - WrapErr as _, -}; -use ethers::types::{ - TxHash, - U64, -}; +use astria_eyre::eyre::{self, OptionExt, WrapErr as _}; +use ethers::types::{TxHash, U64}; use ibc_types::core::client::Height as IbcHeight; -use serde::{ - Deserialize, - Serialize, -}; +use serde::{Deserialize, Serialize}; use crate::withdrawer::ethereum::astria_withdrawer::{ - Ics20WithdrawalFilter, - SequencerWithdrawalFilter, + Ics20WithdrawalFilter, SequencerWithdrawalFilter, }; #[derive(Debug, PartialEq, Eq)] diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/test_utils.rs b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/test_utils.rs index 9a91164d2..a9b8c4777 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/test_utils.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/test_utils.rs @@ -1,14 +1,6 @@ -use std::{ - path::Path, - sync::Arc, - time::Duration, -}; +use std::{path::Path, sync::Arc, time::Duration}; -use ethers::{ - core::utils::Anvil, - prelude::*, - utils::AnvilInstance, -}; +use ethers::{core::utils::Anvil, prelude::*, utils::AnvilInstance}; /// Starts a local anvil instance and deploys the `AstriaWithdrawer` contract to it. /// @@ -20,8 +12,8 @@ use ethers::{ /// - if the contract cannot be compiled /// - if the provider fails to connect to the anvil instance /// - if the contract fails to deploy -pub(crate) async fn deploy_astria_withdrawer() --> (Address, Arc>, LocalWallet, AnvilInstance) { +pub(crate) async fn deploy_astria_withdrawer( +) -> (Address, Arc>, LocalWallet, AnvilInstance) { // compile contract for testing let source = Path::new(&env!("CARGO_MANIFEST_DIR")).join("ethereum/src/AstriaWithdrawer.sol"); let input = CompilerInput::new(source.clone()) diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/watcher.rs b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/watcher.rs index c6fde2360..cbf9af310 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/watcher.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/watcher.rs @@ -1,44 +1,24 @@ use std::sync::Arc; -use astria_core::primitive::v1::{ - asset, - asset::Denom, -}; +use astria_core::primitive::v1::{asset, asset::Denom}; use astria_eyre::{ - eyre::{ - eyre, - WrapErr as _, - }, + eyre::{eyre, WrapErr as _}, Result, }; use ethers::{ contract::LogMeta, - providers::{ - Provider, - StreamExt as _, - Ws, - }, + providers::{Provider, StreamExt as _, Ws}, utils::hex, }; -use tokio::{ - select, - sync::mpsc, -}; +use tokio::{select, sync::mpsc}; use tokio_util::sync::CancellationToken; -use tracing::{ - info, - warn, -}; +use tracing::{info, warn}; use crate::withdrawer::{ batch::Batch, ethereum::{ astria_withdrawer::AstriaWithdrawer, - convert::{ - event_to_action, - EventWithMetadata, - WithdrawalEvent, - }, + convert::{event_to_action, EventWithMetadata, WithdrawalEvent}, }, state::State, }; @@ -309,19 +289,13 @@ mod tests { prelude::SignerMiddleware, providers::Middleware, signers::Signer as _, - types::{ - TransactionReceipt, - U256, - }, + types::{TransactionReceipt, U256}, utils::hex, }; use super::*; use crate::withdrawer::ethereum::{ - astria_withdrawer::{ - Ics20WithdrawalFilter, - SequencerWithdrawalFilter, - }, + astria_withdrawer::{Ics20WithdrawalFilter, SequencerWithdrawalFilter}, convert::EventWithMetadata, test_utils::deploy_astria_withdrawer, }; diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/mod.rs b/crates/astria-bridge-withdrawer/src/withdrawer/mod.rs index 5c54075b7..3508aad3c 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/mod.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/mod.rs @@ -1,39 +1,19 @@ -use std::{ - net::SocketAddr, - sync::Arc, - time::Duration, -}; +use std::{net::SocketAddr, sync::Arc, time::Duration}; use astria_core::primitive::v1::asset; -use astria_eyre::eyre::{ - self, - WrapErr as _, -}; +use astria_eyre::eyre::{self, WrapErr as _}; use tokio::{ select, sync::oneshot, - task::{ - JoinError, - JoinHandle, - }, + task::{JoinError, JoinHandle}, time::timeout, }; use tokio_util::sync::CancellationToken; -use tracing::{ - error, - info, -}; +use tracing::{error, info}; pub(crate) use self::state::StateSnapshot; -use self::{ - ethereum::Watcher, - state::State, - submitter::Submitter, -}; -use crate::{ - api, - config::Config, -}; +use self::{ethereum::Watcher, state::State, submitter::Submitter}; +use crate::{api, config::Config}; mod batch; mod ethereum; diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/state.rs b/crates/astria-bridge-withdrawer/src/withdrawer/state.rs index 647bb489b..1d8fdb406 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/state.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/state.rs @@ -7,9 +7,7 @@ pub(crate) struct State { impl State { pub(super) fn new() -> Self { let (inner, _) = watch::channel(StateSnapshot::default()); - Self { - inner, - } + Self { inner } } pub(super) fn set_watcher_ready(&self) { diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/submitter/builder.rs b/crates/astria-bridge-withdrawer/src/withdrawer/submitter/builder.rs index d58d7f0a4..253587f09 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/submitter/builder.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/submitter/builder.rs @@ -1,9 +1,6 @@ use std::sync::Arc; -use astria_eyre::eyre::{ - self, - Context as _, -}; +use astria_eyre::eyre::{self, Context as _}; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; use tracing::info; diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/submitter/mod.rs b/crates/astria-bridge-withdrawer/src/withdrawer/submitter/mod.rs index add064182..fe8d0d362 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/submitter/mod.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/submitter/mod.rs @@ -1,50 +1,21 @@ -use std::{ - sync::Arc, - time::Duration, -}; +use std::{sync::Arc, time::Duration}; use astria_core::protocol::transaction::v1alpha1::{ - Action, - TransactionParams, - UnsignedTransaction, -}; -use astria_eyre::eyre::{ - self, - ensure, - eyre, - Context, + Action, TransactionParams, UnsignedTransaction, }; +use astria_eyre::eyre::{self, ensure, eyre, Context}; pub(crate) use builder::Builder; use sequencer_client::{ - tendermint_rpc, - tendermint_rpc::endpoint::broadcast::tx_commit, - Address, - SequencerClientExt as _, - SignedTransaction, + tendermint_rpc, tendermint_rpc::endpoint::broadcast::tx_commit, Address, + SequencerClientExt as _, SignedTransaction, }; use signer::SequencerKey; use state::State; -use tokio::{ - select, - sync::mpsc, - time::Instant, -}; +use tokio::{select, sync::mpsc, time::Instant}; use tokio_util::sync::CancellationToken; -use tracing::{ - debug, - error, - info, - info_span, - instrument, - warn, - Instrument as _, - Span, -}; +use tracing::{debug, error, info, info_span, instrument, warn, Instrument as _, Span}; -use super::{ - batch::Batch, - state, -}; +use super::{batch::Batch, state}; mod builder; mod signer; diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/submitter/signer.rs b/crates/astria-bridge-withdrawer/src/withdrawer/submitter/signer.rs index 853d08ff9..a138fba3f 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/submitter/signer.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/submitter/signer.rs @@ -1,13 +1,7 @@ -use std::{ - fs, - path::Path, -}; +use std::{fs, path::Path}; use astria_core::crypto::SigningKey; -use astria_eyre::eyre::{ - self, - eyre, -}; +use astria_eyre::eyre::{self, eyre}; use sequencer_client::Address; pub(super) struct SequencerKey { diff --git a/crates/astria-cli/src/cli/mod.rs b/crates/astria-cli/src/cli/mod.rs index f2c2b2d22..8c335fc65 100644 --- a/crates/astria-cli/src/cli/mod.rs +++ b/crates/astria-cli/src/cli/mod.rs @@ -1,16 +1,10 @@ pub(crate) mod rollup; pub(crate) mod sequencer; -use clap::{ - Parser, - Subcommand, -}; +use clap::{Parser, Subcommand}; use color_eyre::eyre; -use crate::cli::{ - rollup::Command as RollupCommand, - sequencer::Command as SequencerCommand, -}; +use crate::cli::{rollup::Command as RollupCommand, sequencer::Command as SequencerCommand}; const DEFAULT_SEQUENCER_RPC: &str = "https://rpc.sequencer.dusk-7.devnet.astria.org"; const DEFAULT_SEQUENCER_CHAIN_ID: &str = "astria-dusk-7"; diff --git a/crates/astria-cli/src/cli/rollup.rs b/crates/astria-cli/src/cli/rollup.rs index 3199397e1..5338182e7 100644 --- a/crates/astria-cli/src/cli/rollup.rs +++ b/crates/astria-cli/src/cli/rollup.rs @@ -1,9 +1,6 @@ use std::str::FromStr; -use clap::{ - Args, - Subcommand, -}; +use clap::{Args, Subcommand}; use color_eyre::eyre; use serde::Serialize; @@ -193,10 +190,7 @@ impl FromStr for GenesisAccountArg { .parse::() .map_err(|e| eyre::eyre!("Invalid balance. Could not parse to u128: {}", e))?; - Ok(GenesisAccountArg { - address, - balance, - }) + Ok(GenesisAccountArg { address, balance }) } } diff --git a/crates/astria-cli/src/cli/sequencer.rs b/crates/astria-cli/src/cli/sequencer.rs index cca710530..fb7d3da67 100644 --- a/crates/astria-cli/src/cli/sequencer.rs +++ b/crates/astria-cli/src/cli/sequencer.rs @@ -1,14 +1,8 @@ use std::str::FromStr; use astria_sequencer_client::Address; -use clap::{ - Args, - Subcommand, -}; -use color_eyre::{ - eyre, - eyre::Context, -}; +use clap::{Args, Subcommand}; +use color_eyre::{eyre, eyre::Context}; /// Interact with a Sequencer node #[derive(Debug, Subcommand)] diff --git a/crates/astria-cli/src/commands/mod.rs b/crates/astria-cli/src/commands/mod.rs index cf7930c60..319815afe 100644 --- a/crates/astria-cli/src/commands/mod.rs +++ b/crates/astria-cli/src/commands/mod.rs @@ -1,29 +1,16 @@ mod rollup; mod sequencer; -use color_eyre::{ - eyre, - eyre::eyre, -}; +use color_eyre::{eyre, eyre::eyre}; use tracing::instrument; use crate::cli::{ - rollup::{ - Command as RollupCommand, - ConfigCommand, - DeploymentCommand, - }, + rollup::{Command as RollupCommand, ConfigCommand, DeploymentCommand}, sequencer::{ - AccountCommand, - BalanceCommand, - BlockHeightCommand, - Command as SequencerCommand, - FeeAssetChangeCommand, - IbcRelayerChangeCommand, - SudoCommand, + AccountCommand, BalanceCommand, BlockHeightCommand, Command as SequencerCommand, + FeeAssetChangeCommand, IbcRelayerChangeCommand, SudoCommand, }, - Cli, - Command, + Cli, Command, }; /// Checks what function needs to be run and calls it with the appropriate arguments @@ -43,45 +30,29 @@ use crate::cli::{ pub async fn run(cli: Cli) -> eyre::Result<()> { if let Some(command) = cli.command { match command { - Command::Rollup { - command, - } => match command { - RollupCommand::Config { - command, - } => match command { + Command::Rollup { command } => match command { + RollupCommand::Config { command } => match command { ConfigCommand::Create(args) => rollup::create_config(&args).await?, ConfigCommand::Edit(args) => rollup::edit_config(&args)?, ConfigCommand::Delete(args) => rollup::delete_config(&args)?, }, - RollupCommand::Deployment { - command, - } => match command { + RollupCommand::Deployment { command } => match command { DeploymentCommand::Create(args) => rollup::create_deployment(&args)?, DeploymentCommand::Delete(args) => rollup::delete_deployment(&args)?, DeploymentCommand::List => rollup::list_deployments(), }, }, - Command::Sequencer { - command, - } => match command { - SequencerCommand::Account { - command, - } => match command { + Command::Sequencer { command } => match command { + SequencerCommand::Account { command } => match command { AccountCommand::Create => sequencer::create_account(), AccountCommand::Balance(args) => sequencer::get_balance(&args).await?, AccountCommand::Nonce(args) => sequencer::get_nonce(&args).await?, }, - SequencerCommand::Balance { - command, - } => match command { + SequencerCommand::Balance { command } => match command { BalanceCommand::Get(args) => sequencer::get_balance(&args).await?, }, - SequencerCommand::Sudo { - command, - } => match command { - SudoCommand::IbcRelayer { - command, - } => match command { + SequencerCommand::Sudo { command } => match command { + SudoCommand::IbcRelayer { command } => match command { IbcRelayerChangeCommand::Add(args) => { sequencer::ibc_relayer_add(&args).await?; } @@ -89,9 +60,7 @@ pub async fn run(cli: Cli) -> eyre::Result<()> { sequencer::ibc_relayer_remove(&args).await?; } }, - SudoCommand::FeeAsset { - command, - } => match command { + SudoCommand::FeeAsset { command } => match command { FeeAssetChangeCommand::Add(args) => sequencer::fee_asset_add(&args).await?, FeeAssetChangeCommand::Remove(args) => { sequencer::fee_asset_remove(&args).await?; @@ -105,9 +74,7 @@ pub async fn run(cli: Cli) -> eyre::Result<()> { } }, SequencerCommand::Transfer(args) => sequencer::send_transfer(&args).await?, - SequencerCommand::BlockHeight { - command, - } => match command { + SequencerCommand::BlockHeight { command } => match command { BlockHeightCommand::Get(args) => sequencer::get_block_height(&args).await?, }, SequencerCommand::InitBridgeAccount(args) => { diff --git a/crates/astria-cli/src/commands/rollup.rs b/crates/astria-cli/src/commands/rollup.rs index b94771226..050b97449 100644 --- a/crates/astria-cli/src/commands/rollup.rs +++ b/crates/astria-cli/src/commands/rollup.rs @@ -1,32 +1,17 @@ use std::{ - env::{ - self, - consts::OS, - }, + env::{self, consts::OS}, fs::File, - io::{ - Read, - Write, - }, + io::{Read, Write}, path::PathBuf, process::Command, }; -use astria_sequencer_client::{ - Client, - HttpClient, -}; -use color_eyre::{ - eyre, - eyre::Context, -}; +use astria_sequencer_client::{Client, HttpClient}; +use color_eyre::{eyre, eyre::Context}; use crate::{ cli::rollup::{ - ConfigCreateArgs, - ConfigDeleteArgs, - ConfigEditArgs, - DeploymentCreateArgs, + ConfigCreateArgs, ConfigDeleteArgs, ConfigEditArgs, DeploymentCreateArgs, DeploymentDeleteArgs, }, types::Rollup, diff --git a/crates/astria-cli/src/commands/sequencer.rs b/crates/astria-cli/src/commands/sequencer.rs index 9b9460c08..20a1a4e27 100644 --- a/crates/astria-cli/src/commands/sequencer.rs +++ b/crates/astria-cli/src/commands/sequencer.rs @@ -3,45 +3,24 @@ use astria_core::{ primitive::v1::asset, protocol::transaction::v1alpha1::{ action::{ - Action, - BridgeLockAction, - FeeAssetChangeAction, - IbcRelayerChangeAction, - InitBridgeAccountAction, - SudoAddressChangeAction, - TransferAction, + Action, BridgeLockAction, FeeAssetChangeAction, IbcRelayerChangeAction, + InitBridgeAccountAction, SudoAddressChangeAction, TransferAction, }, - TransactionParams, - UnsignedTransaction, + TransactionParams, UnsignedTransaction, }, }; use astria_sequencer_client::{ - tendermint, - tendermint_rpc::endpoint, - Client, - HttpClient, - SequencerClientExt, + tendermint, tendermint_rpc::endpoint, Client, HttpClient, SequencerClientExt, }; use color_eyre::{ eyre, - eyre::{ - ensure, - eyre, - Context, - }, + eyre::{ensure, eyre, Context}, }; use rand::rngs::OsRng; use crate::cli::sequencer::{ - BasicAccountArgs, - BlockHeightGetArgs, - BridgeLockArgs, - FeeAssetChangeArgs, - IbcRelayerChangeArgs, - InitBridgeAccountArgs, - SudoAddressChangeArgs, - TransferArgs, - ValidatorUpdateArgs, + BasicAccountArgs, BlockHeightGetArgs, BridgeLockArgs, FeeAssetChangeArgs, IbcRelayerChangeArgs, + InitBridgeAccountArgs, SudoAddressChangeArgs, TransferArgs, ValidatorUpdateArgs, }; /// Generate a new signing key (this is also called a secret key by other implementations) @@ -255,10 +234,7 @@ pub(crate) async fn ibc_relayer_remove(args: &IbcRelayerChangeArgs) -> eyre::Res /// * If the http client cannot be created /// * If the transaction failed to be included pub(crate) async fn init_bridge_account(args: &InitBridgeAccountArgs) -> eyre::Result<()> { - use astria_core::primitive::v1::{ - asset::default_native_asset_id, - RollupId, - }; + use astria_core::primitive::v1::{asset::default_native_asset_id, RollupId}; let rollup_id = RollupId::from_unhashed_bytes(args.rollup_name.as_bytes()); let res = submit_transaction( diff --git a/crates/astria-cli/src/main.rs b/crates/astria-cli/src/main.rs index 81c257e2a..9ffa5f64e 100644 --- a/crates/astria-cli/src/main.rs +++ b/crates/astria-cli/src/main.rs @@ -1,13 +1,7 @@ use std::process::ExitCode; -use astria_cli::{ - cli::Cli, - commands, -}; -use color_eyre::{ - eyre, - eyre::Context, -}; +use astria_cli::{cli::Cli, commands}; +use color_eyre::{eyre, eyre::Context}; fn main() -> ExitCode { if let Err(err) = run() { diff --git a/crates/astria-cli/src/types.rs b/crates/astria-cli/src/types.rs index 773281f3c..f41b6ae11 100644 --- a/crates/astria-cli/src/types.rs +++ b/crates/astria-cli/src/types.rs @@ -1,13 +1,7 @@ use color_eyre::eyre; -use serde::{ - Deserialize, - Serialize, -}; +use serde::{Deserialize, Serialize}; -use crate::cli::rollup::{ - ConfigCreateArgs, - GenesisAccountArg, -}; +use crate::cli::rollup::{ConfigCreateArgs, GenesisAccountArg}; /// Rollup contains the deployment config for a rollup #[derive(Debug, PartialEq, Serialize, Deserialize)] @@ -333,10 +327,7 @@ impl Resource { #[cfg(test)] mod tests { use super::*; - use crate::cli::rollup::{ - ConfigCreateArgs, - GenesisAccountArg, - }; + use crate::cli::rollup::{ConfigCreateArgs, GenesisAccountArg}; #[test] fn test_from_all_cli_args() -> eyre::Result<()> { diff --git a/crates/astria-cli/test-utils/src/lib.rs b/crates/astria-cli/test-utils/src/lib.rs index a049c22b2..0317545f7 100644 --- a/crates/astria-cli/test-utils/src/lib.rs +++ b/crates/astria-cli/test-utils/src/lib.rs @@ -1,7 +1,4 @@ -use std::{ - env, - future::Future, -}; +use std::{env, future::Future}; use once_cell::sync::Lazy; use tempfile::TempDir; diff --git a/crates/astria-composer/src/api.rs b/crates/astria-composer/src/api.rs index 9866fd5e3..d638ec641 100644 --- a/crates/astria-composer/src/api.rs +++ b/crates/astria-composer/src/api.rs @@ -1,18 +1,9 @@ use std::net::SocketAddr; use axum::{ - extract::{ - FromRef, - State, - }, - response::{ - IntoResponse, - Response, - }, - routing::{ - get, - IntoMakeService, - }, + extract::{FromRef, State}, + response::{IntoResponse, Response}, + routing::{get, IntoMakeService}, Router, }; use hyper::server::conn::AddrIncoming; @@ -41,9 +32,7 @@ impl FromRef for ComposerStatus { pub(super) fn start(listen_addr: SocketAddr, composer_status: ComposerStatus) -> ApiServer { let app = Router::new() .route("/readyz", get(readyz)) - .with_state(AppState { - composer_status, - }); + .with_state(AppState { composer_status }); axum::Server::bind(&listen_addr).serve(app.into_make_service()) } @@ -62,10 +51,7 @@ impl IntoResponse for Readyz { Self::Ok => (axum::http::StatusCode::OK, "ok"), Self::NotReady => (axum::http::StatusCode::SERVICE_UNAVAILABLE, "not ready"), }; - let mut response = axum::Json(ReadyBody { - status: msg, - }) - .into_response(); + let mut response = axum::Json(ReadyBody { status: msg }).into_response(); *response.status_mut() = status; response } diff --git a/crates/astria-composer/src/collectors/geth.rs b/crates/astria-composer/src/collectors/geth.rs index 753da8ce4..552146bc4 100644 --- a/crates/astria-composer/src/collectors/geth.rs +++ b/crates/astria-composer/src/collectors/geth.rs @@ -16,49 +16,22 @@ use std::time::Duration; use astria_core::{ - primitive::v1::{ - asset::default_native_asset_id, - RollupId, - }, + primitive::v1::{asset::default_native_asset_id, RollupId}, protocol::transaction::v1alpha1::action::SequenceAction, }; -use astria_eyre::eyre::{ - self, - eyre, - Report, - WrapErr as _, -}; -use ethers::providers::{ - Provider, - ProviderError, - Ws, -}; +use astria_eyre::eyre::{self, eyre, Report, WrapErr as _}; +use ethers::providers::{Provider, ProviderError, Ws}; use tokio::{ select, - sync::{ - mpsc::error::SendTimeoutError, - watch, - }, + sync::{mpsc::error::SendTimeoutError, watch}, }; use tokio_util::sync::CancellationToken; -use tracing::{ - debug, - error, - info, - instrument, - warn, -}; +use tracing::{debug, error, info, instrument, warn}; use crate::{ - collectors::{ - EXECUTOR_SEND_TIMEOUT, - GETH, - }, + collectors::{EXECUTOR_SEND_TIMEOUT, GETH}, executor, - metrics_init::{ - COLLECTOR_TYPE_LABEL, - ROLLUP_ID_LABEL, - }, + metrics_init::{COLLECTOR_TYPE_LABEL, ROLLUP_ID_LABEL}, }; type StdError = dyn std::error::Error; diff --git a/crates/astria-composer/src/collectors/grpc.rs b/crates/astria-composer/src/collectors/grpc.rs index 49e37fc22..7c78b6f6d 100644 --- a/crates/astria-composer/src/collectors/grpc.rs +++ b/crates/astria-composer/src/collectors/grpc.rs @@ -4,33 +4,19 @@ use std::sync::Arc; use astria_core::{ generated::composer::v1alpha1::{ - grpc_collector_service_server::GrpcCollectorService, - SubmitRollupTransactionRequest, + grpc_collector_service_server::GrpcCollectorService, SubmitRollupTransactionRequest, SubmitRollupTransactionResponse, }, - primitive::v1::{ - asset::default_native_asset_id, - RollupId, - }, + primitive::v1::{asset::default_native_asset_id, RollupId}, protocol::transaction::v1alpha1::action::SequenceAction, }; use tokio::sync::mpsc::error::SendTimeoutError; -use tonic::{ - Request, - Response, - Status, -}; +use tonic::{Request, Response, Status}; use crate::{ - collectors::{ - EXECUTOR_SEND_TIMEOUT, - GRPC, - }, + collectors::{EXECUTOR_SEND_TIMEOUT, GRPC}, executor, - metrics_init::{ - COLLECTOR_TYPE_LABEL, - ROLLUP_ID_LABEL, - }, + metrics_init::{COLLECTOR_TYPE_LABEL, ROLLUP_ID_LABEL}, }; /// Implements the `GrpcCollectorService` which listens for incoming gRPC requests and @@ -42,9 +28,7 @@ pub(crate) struct Grpc { impl Grpc { pub(crate) fn new(executor: executor::Handle) -> Self { - Self { - executor, - } + Self { executor } } } diff --git a/crates/astria-composer/src/composer.rs b/crates/astria-composer/src/composer.rs index 90a01b56b..e2bae92ab 100644 --- a/crates/astria-composer/src/composer.rs +++ b/crates/astria-composer/src/composer.rs @@ -1,46 +1,22 @@ -use std::{ - collections::HashMap, - net::SocketAddr, - time::Duration, -}; +use std::{collections::HashMap, net::SocketAddr, time::Duration}; -use astria_eyre::eyre::{ - self, - WrapErr as _, -}; +use astria_eyre::eyre::{self, WrapErr as _}; use itertools::Itertools as _; use tokio::{ io, - signal::unix::{ - signal, - SignalKind, - }, + signal::unix::{signal, SignalKind}, sync::watch, - task::{ - JoinError, - JoinHandle, - }, + task::{JoinError, JoinHandle}, time::timeout, }; -use tokio_util::{ - sync::CancellationToken, - task::JoinMap, -}; -use tracing::{ - error, - info, - warn, -}; +use tokio_util::{sync::CancellationToken, task::JoinMap}; +use tracing::{error, info, warn}; use crate::{ - api::{ - self, - ApiServer, - }, + api::{self, ApiServer}, collectors, collectors::geth, - composer, - executor, + composer, executor, executor::Executor, grpc, grpc::GrpcServer, @@ -127,6 +103,7 @@ impl Composer { shutdown_token: shutdown_token.clone(), } .build() + .await .wrap_err("executor construction from config failed")?; let grpc_server = grpc::Builder { @@ -462,10 +439,7 @@ async fn wait_for_collectors( ) -> eyre::Result<()> { use futures::{ future::FutureExt as _, - stream::{ - FuturesUnordered, - StreamExt as _, - }, + stream::{FuturesUnordered, StreamExt as _}, }; let mut statuses = collector_statuses .iter() diff --git a/crates/astria-composer/src/config.rs b/crates/astria-composer/src/config.rs index 0dbc55bb8..0fd2a6aa7 100644 --- a/crates/astria-composer/src/config.rs +++ b/crates/astria-composer/src/config.rs @@ -1,9 +1,6 @@ use std::net::SocketAddr; -use serde::{ - Deserialize, - Serialize, -}; +use serde::{Deserialize, Serialize}; // this is a config, may have many boolean values #[allow(clippy::struct_excessive_bools)] diff --git a/crates/astria-composer/src/executor/builder.rs b/crates/astria-composer/src/executor/builder.rs index c3d6df001..0969e8aff 100644 --- a/crates/astria-composer/src/executor/builder.rs +++ b/crates/astria-composer/src/executor/builder.rs @@ -10,13 +10,13 @@ use astria_core::{ }; use astria_eyre::eyre::{ self, + ensure, eyre, - Context, + Context }; use sequencer_client::tendermint_rpc::Client; use tokio::sync::watch; use tokio_util::sync::CancellationToken; -use tendermint::Genesis; use crate::{ executor, @@ -34,7 +34,7 @@ pub(crate) struct Builder { } impl Builder { - pub(crate) fn build(self) -> eyre::Result<(super::Executor, executor::Handle)> { + pub(crate) async fn build(self) -> eyre::Result<(super::Executor, executor::Handle)> { let Self { sequencer_url, sequencer_chain_id, @@ -47,7 +47,12 @@ impl Builder { let sequencer_client = sequencer_client::HttpClient::new(sequencer_url.as_str()) .wrap_err("failed constructing sequencer client")?; - tokio::spawn(check_chain_ids(sequencer_client.clone(), sequencer_chain_id.clone())); + let client_response = sequencer_client.status().await.wrap_err("failed to retrieve sequencer network status")?; + let client_chain_id = client_response.node_info.network.to_string(); + ensure!( + sequencer_chain_id == client_chain_id, + "mismatch in sequencer_chain_id: {sequencer_chain_id} and client chain_id: {client_chain_id}" + ); let (status, _) = watch::channel(Status::new()); @@ -84,13 +89,4 @@ fn read_signing_key_from_file>(path: P) -> eyre::Result eyre::Result<()> { - let genesis: Genesis = Client::genesis(&sequencer_client).await.expect("Failed to retrieve client genesis file"); - let client_chain_id = genesis.chain_id.to_string(); - if sequencer_chain_id != client_chain_id { - return Err(eyre!(format!("mismatch in sequencer_chain_id: {sequencer_chain_id} and client chain_id: {client_chain_id}"))) - }; - Ok(()) } \ No newline at end of file diff --git a/crates/astria-composer/src/executor/bundle_factory/mod.rs b/crates/astria-composer/src/executor/bundle_factory/mod.rs index 8a2644b77..a05dbce3c 100644 --- a/crates/astria-composer/src/executor/bundle_factory/mod.rs +++ b/crates/astria-composer/src/executor/bundle_factory/mod.rs @@ -1,28 +1,15 @@ /// ! This module is responsible for bundling sequence actions into bundles that can be /// submitted to the sequencer. use std::{ - collections::{ - HashMap, - VecDeque, - }, + collections::{HashMap, VecDeque}, mem, }; use astria_core::{ - primitive::v1::{ - RollupId, - FEE_ASSET_ID_LEN, - ROLLUP_ID_LEN, - }, - protocol::transaction::v1alpha1::{ - action::SequenceAction, - Action, - }, -}; -use serde::ser::{ - Serialize, - SerializeStruct as _, + primitive::v1::{RollupId, FEE_ASSET_ID_LEN, ROLLUP_ID_LEN}, + protocol::transaction::v1alpha1::{action::SequenceAction, Action}, }; +use serde::ser::{Serialize, SerializeStruct as _}; use tracing::trace; mod tests; diff --git a/crates/astria-composer/src/executor/bundle_factory/tests.rs b/crates/astria-composer/src/executor/bundle_factory/tests.rs index b085ad607..1829cc4a0 100644 --- a/crates/astria-composer/src/executor/bundle_factory/tests.rs +++ b/crates/astria-composer/src/executor/bundle_factory/tests.rs @@ -2,22 +2,14 @@ mod sized_bundle_tests { use astria_core::{ primitive::v1::{ - asset::default_native_asset_id, - RollupId, - FEE_ASSET_ID_LEN, - ROLLUP_ID_LEN, + asset::default_native_asset_id, RollupId, FEE_ASSET_ID_LEN, ROLLUP_ID_LEN, }, protocol::transaction::v1alpha1::action::SequenceAction, }; - use insta::{ - assert_json_snapshot, - Settings, - }; + use insta::{assert_json_snapshot, Settings}; use crate::executor::bundle_factory::{ - estimate_size_of_sequence_action, - SizedBundle, - SizedBundleError, + estimate_size_of_sequence_action, SizedBundle, SizedBundleError, }; #[test] @@ -152,18 +144,13 @@ mod sized_bundle_tests { mod bundle_factory_tests { use astria_core::{ primitive::v1::{ - asset::default_native_asset_id, - RollupId, - FEE_ASSET_ID_LEN, - ROLLUP_ID_LEN, + asset::default_native_asset_id, RollupId, FEE_ASSET_ID_LEN, ROLLUP_ID_LEN, }, protocol::transaction::v1alpha1::action::SequenceAction, }; use crate::executor::bundle_factory::{ - estimate_size_of_sequence_action, - BundleFactory, - BundleFactoryError, + estimate_size_of_sequence_action, BundleFactory, BundleFactoryError, }; #[test] diff --git a/crates/astria-composer/src/executor/mod.rs b/crates/astria-composer/src/executor/mod.rs index 4c2dc7c23..429a31a86 100644 --- a/crates/astria-composer/src/executor/mod.rs +++ b/crates/astria-composer/src/executor/mod.rs @@ -3,78 +3,40 @@ /// - Transaction signing /// - Managing the connection to the sequencer /// - Submitting transactions to the sequencer -use std::{ - collections::VecDeque, - pin::Pin, - task::Poll, - time::Duration, -}; +use std::{collections::VecDeque, pin::Pin, task::Poll, time::Duration}; use astria_core::{ crypto::SigningKey, protocol::{ abci::AbciErrorCode, transaction::v1alpha1::{ - action::SequenceAction, - SignedTransaction, - TransactionParams, - UnsignedTransaction, + action::SequenceAction, SignedTransaction, TransactionParams, UnsignedTransaction, }, }, }; -use astria_eyre::eyre::{ - self, - eyre, - WrapErr as _, -}; +use astria_eyre::eyre::{self, eyre, WrapErr as _}; use futures::{ - future::{ - self, - Fuse, - FusedFuture as _, - FutureExt as _, - }, - ready, - Future, + future::{self, Fuse, FusedFuture as _, FutureExt as _}, + ready, Future, }; use pin_project_lite::pin_project; use prost::Message as _; use sequencer_client::{ - tendermint_rpc::endpoint::broadcast::tx_sync, - Address, - SequencerClientExt as _, + tendermint_rpc::endpoint::broadcast::tx_sync, Address, SequencerClientExt as _, }; use tendermint::crypto::Sha256; use tokio::{ select, - sync::{ - mpsc, - mpsc::error::SendTimeoutError, - watch, - }, - time::{ - self, - Instant, - }, + sync::{mpsc, mpsc::error::SendTimeoutError, watch}, + time::{self, Instant}, }; use tokio_util::sync::CancellationToken; use tracing::{ - debug, - error, - info, - info_span, - instrument, - instrument::Instrumented, - warn, - Instrument, - Span, + debug, error, info, info_span, instrument, instrument::Instrumented, warn, Instrument, Span, }; use self::bundle_factory::SizedBundle; -use crate::executor::bundle_factory::{ - BundleFactory, - SizedBundleReport, -}; +use crate::executor::bundle_factory::{BundleFactory, SizedBundleReport}; mod bundle_factory; @@ -588,9 +550,7 @@ impl Future for SubmitFut { } } - SubmitStateProj::WaitingForSend { - fut, - } => match ready!(fut.poll(cx)) { + SubmitStateProj::WaitingForSend { fut } => match ready!(fut.poll(cx)) { Ok(rsp) => { let tendermint::abci::Code::Err(code) = rsp.code else { info!("sequencer responded with ok; submission successful"); @@ -648,9 +608,7 @@ impl Future for SubmitFut { } }, - SubmitStateProj::WaitingForNonce { - fut, - } => match ready!(fut.poll(cx)) { + SubmitStateProj::WaitingForNonce { fut } => match ready!(fut.poll(cx)) { Ok(nonce) => { *this.nonce = nonce; let params = TransactionParams { diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index 3b7e8bebf..934b0c34f 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -1,15 +1,7 @@ -use std::{ - io::Write, - time::Duration, -}; +use std::{io::Write, time::Duration}; use astria_core::{ - primitive::v1::{ - asset::default_native_asset_id, - RollupId, - FEE_ASSET_ID_LEN, - ROLLUP_ID_LEN, - }, + primitive::v1::{asset::default_native_asset_id, RollupId, FEE_ASSET_ID_LEN, ROLLUP_ID_LEN}, protocol::transaction::v1alpha1::action::SequenceAction, }; use astria_eyre::eyre; @@ -18,34 +10,16 @@ use prost::Message; use sequencer_client::SignedTransaction; use serde_json::json; use tempfile::NamedTempFile; -use tendermint_rpc::{ - endpoint::broadcast::tx_sync, - request, - response, - Id, -}; -use tokio::{ - sync::watch, - time, -}; +use tendermint_rpc::{endpoint::broadcast::tx_sync, request, response, Id}; +use tokio::{sync::watch, time}; use tokio_util::sync::CancellationToken; use tracing::debug; use wiremock::{ - matchers::{ - body_partial_json, - body_string_contains, - }, - Mock, - MockGuard, - MockServer, - Request, - ResponseTemplate, + matchers::{body_partial_json, body_string_contains}, + Mock, MockGuard, MockServer, Request, ResponseTemplate, }; -use crate::{ - executor, - Config, -}; +use crate::{executor, Config}; static TELEMETRY: Lazy<()> = Lazy::new(|| { if std::env::var_os("TEST_LOG").is_some() { @@ -181,6 +155,33 @@ async fn mount_broadcast_tx_sync_seq_actions_mock(server: &MockServer) -> MockGu .await } +async fn mount_status_mock(server: &MockServer) -> MockGuard { + let matcher = move |request: &Request| { + let signed_tx = signed_tx_from_request(request); + let actions = signed_tx.actions(); + + // verify all received actions are sequence actions + actions.iter().all(|action| action.as_sequence().is_some()) + }; + let jsonrpc_rsp = response::Wrapper::new_with_id( + Id::Num(1), + Some(tx_sync::Response { + code: 0.into(), + data: vec![].into(), + log: String::new(), + hash: tendermint::Hash::Sha256([0; 32]), + }), + None, + ); + + Mock::given(matcher) + .respond_with(ResponseTemplate::new(200).set_body_json(&jsonrpc_rsp)) + .up_to_n_times(1) + .expect(1) + .mount_as_scoped(server) + .await +} + /// Helper to wait for the executor to connect to the mock sequencer async fn wait_for_startup( mut status: watch::Receiver, @@ -210,7 +211,7 @@ async fn full_bundle() { let shutdown_token = CancellationToken::new(); let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), - sequencer_chain_id: cfg.sequencer_chain_id.clone(), + sequencer_chain_id: "bad-id".to_string(), private_key_file: cfg.private_key_file.clone(), block_time_ms: cfg.block_time_ms, max_bytes_per_bundle: cfg.max_bytes_per_bundle, @@ -218,6 +219,7 @@ async fn full_bundle() { shutdown_token: shutdown_token.clone(), } .build() + .await .unwrap(); let status = executor.subscribe(); @@ -309,6 +311,7 @@ async fn bundle_triggered_by_block_timer() { shutdown_token: shutdown_token.clone(), } .build() + .await .unwrap(); let status = executor.subscribe(); @@ -393,6 +396,7 @@ async fn two_seq_actions_single_bundle() { shutdown_token: shutdown_token.clone(), } .build() + .await .unwrap(); let status = executor.subscribe(); @@ -469,3 +473,20 @@ async fn two_seq_actions_single_bundle() { ); } } + +// #[tokio::test] +// async fn should_exit_if_mismatch_sequencer_chain_id() { +// let (sequencer, nonce_guard, cfg, _keyfile) = setup().await; +// let shutdown_token = CancellationToken::new(); +// let (executor, executor_handle) = executor::Builder { +// sequencer_url: cfg.sequencer_url.clone(), +// sequencer_chain_id: "bad-id".to_string(), +// private_key_file: cfg.private_key_file.clone(), +// block_time_ms: cfg.block_time_ms, +// max_bytes_per_bundle: cfg.max_bytes_per_bundle, +// bundle_queue_capacity: cfg.bundle_queue_capacity, +// shutdown_token: shutdown_token.clone(), +// } +// .build() +// .unwrap(); +// } diff --git a/crates/astria-composer/src/grpc.rs b/crates/astria-composer/src/grpc.rs index 9f504ab72..72a07747d 100644 --- a/crates/astria-composer/src/grpc.rs +++ b/crates/astria-composer/src/grpc.rs @@ -9,20 +9,11 @@ use std::net::SocketAddr; use astria_core::generated::composer::v1alpha1::grpc_collector_service_server::GrpcCollectorServiceServer; -use astria_eyre::{ - eyre, - eyre::WrapErr as _, -}; -use tokio::{ - io, - net::TcpListener, -}; +use astria_eyre::{eyre, eyre::WrapErr as _}; +use tokio::{io, net::TcpListener}; use tokio_util::sync::CancellationToken; -use crate::{ - collectors, - executor, -}; +use crate::{collectors, executor}; /// Listens for incoming gRPC requests and sends the Rollup transactions to the /// Executor. The Executor then sends the transactions to the Astria Shared Sequencer. diff --git a/crates/astria-composer/src/main.rs b/crates/astria-composer/src/main.rs index 38f9f21d7..af8324d8f 100644 --- a/crates/astria-composer/src/main.rs +++ b/crates/astria-composer/src/main.rs @@ -1,16 +1,8 @@ use std::process::ExitCode; -use astria_composer::{ - metrics_init, - Composer, - Config, - BUILD_INFO, -}; +use astria_composer::{metrics_init, Composer, Config, BUILD_INFO}; use astria_eyre::eyre::WrapErr as _; -use tracing::{ - error, - info, -}; +use tracing::{error, info}; #[tokio::main] async fn main() -> ExitCode { diff --git a/crates/astria-composer/src/metrics_init.rs b/crates/astria-composer/src/metrics_init.rs index a71028b72..dd4720152 100644 --- a/crates/astria-composer/src/metrics_init.rs +++ b/crates/astria-composer/src/metrics_init.rs @@ -2,12 +2,7 @@ //! //! Registers metrics & lists constants to be used as metric names throughout crate. -use metrics::{ - describe_counter, - describe_gauge, - describe_histogram, - Unit, -}; +use metrics::{describe_counter, describe_gauge, describe_histogram, Unit}; use telemetry::metric_name; /// Labels @@ -89,16 +84,9 @@ metric_name!(pub const BYTES_PER_SUBMISSION); #[cfg(test)] mod tests { use super::{ - BYTES_PER_SUBMISSION, - CURRENT_NONCE, - NONCE_FETCH_COUNT, - NONCE_FETCH_FAILURE_COUNT, - NONCE_FETCH_LATENCY, - SEQUENCER_SUBMISSION_FAILURE_COUNT, - SEQUENCER_SUBMISSION_LATENCY, - TRANSACTIONS_DROPPED, - TRANSACTIONS_DROPPED_TOO_LARGE, - TRANSACTIONS_PER_SUBMISSION, + BYTES_PER_SUBMISSION, CURRENT_NONCE, NONCE_FETCH_COUNT, NONCE_FETCH_FAILURE_COUNT, + NONCE_FETCH_LATENCY, SEQUENCER_SUBMISSION_FAILURE_COUNT, SEQUENCER_SUBMISSION_LATENCY, + TRANSACTIONS_DROPPED, TRANSACTIONS_DROPPED_TOO_LARGE, TRANSACTIONS_PER_SUBMISSION, TRANSACTIONS_RECEIVED, }; diff --git a/crates/astria-composer/src/rollup.rs b/crates/astria-composer/src/rollup.rs index a5ebe9425..de70fca39 100644 --- a/crates/astria-composer/src/rollup.rs +++ b/crates/astria-composer/src/rollup.rs @@ -55,17 +55,11 @@ impl Rollup { // match when these capture groups match. let rollup_name = caps["rollup_name"].to_string().to_lowercase(); let url = caps["url"].to_string(); - Ok(Self { - rollup_name, - url, - }) + Ok(Self { rollup_name, url }) } pub(super) fn into_parts(self) -> (String, String) { - let Self { - rollup_name, - url, - } = self; + let Self { rollup_name, url } = self; (rollup_name, url) } } diff --git a/crates/astria-composer/tests/blackbox/geth_collector.rs b/crates/astria-composer/tests/blackbox/geth_collector.rs index ae87a59b0..581144165 100644 --- a/crates/astria-composer/tests/blackbox/geth_collector.rs +++ b/crates/astria-composer/tests/blackbox/geth_collector.rs @@ -1,17 +1,11 @@ use std::time::Duration; -use astria_core::{ - generated::protocol::account::v1alpha1::NonceResponse, - primitive::v1::RollupId, -}; +use astria_core::{generated::protocol::account::v1alpha1::NonceResponse, primitive::v1::RollupId}; use ethers::types::Transaction; use crate::helper::{ - mount_broadcast_tx_sync_invalid_nonce_mock, - mount_broadcast_tx_sync_mock, - mount_matcher_verifying_tx_integrity, - spawn_composer, - TEST_ETH_TX_JSON, + mount_broadcast_tx_sync_invalid_nonce_mock, mount_broadcast_tx_sync_mock, + mount_matcher_verifying_tx_integrity, spawn_composer, TEST_ETH_TX_JSON, }; #[tokio::test] diff --git a/crates/astria-composer/tests/blackbox/grpc_collector.rs b/crates/astria-composer/tests/blackbox/grpc_collector.rs index 2080c4463..1810770a9 100644 --- a/crates/astria-composer/tests/blackbox/grpc_collector.rs +++ b/crates/astria-composer/tests/blackbox/grpc_collector.rs @@ -13,11 +13,8 @@ use astria_core::{ use ethers::prelude::Transaction; use crate::helper::{ - mount_broadcast_tx_sync_invalid_nonce_mock, - mount_broadcast_tx_sync_mock, - mount_matcher_verifying_tx_integrity, - spawn_composer, - TEST_ETH_TX_JSON, + mount_broadcast_tx_sync_invalid_nonce_mock, mount_broadcast_tx_sync_mock, + mount_matcher_verifying_tx_integrity, spawn_composer, TEST_ETH_TX_JSON, }; #[tokio::test] diff --git a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs index 548633c27..9f5a8f291 100644 --- a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs +++ b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs @@ -1,18 +1,9 @@ use prost::Message; use serde_json::json; -use tendermint_rpc::{ - response, - Id, -}; +use tendermint_rpc::{response, Id}; use wiremock::{ - matchers::{ - body_partial_json, - body_string_contains, - }, - Mock, - MockGuard, - MockServer, - ResponseTemplate, + matchers::{body_partial_json, body_string_contains}, + Mock, MockGuard, MockServer, ResponseTemplate, }; pub async fn start() -> (MockServer, MockGuard) { diff --git a/crates/astria-composer/tests/blackbox/helper/mod.rs b/crates/astria-composer/tests/blackbox/helper/mod.rs index fe09219ef..242efc044 100644 --- a/crates/astria-composer/tests/blackbox/helper/mod.rs +++ b/crates/astria-composer/tests/blackbox/helper/mod.rs @@ -1,41 +1,19 @@ -use std::{ - collections::HashMap, - io::Write, - net::SocketAddr, - time::Duration, -}; +use std::{collections::HashMap, io::Write, net::SocketAddr, time::Duration}; -use astria_composer::{ - config::Config, - Composer, -}; +use astria_composer::{config::Config, Composer}; use astria_core::{ primitive::v1::RollupId, - protocol::{ - abci::AbciErrorCode, - transaction::v1alpha1::SignedTransaction, - }, + protocol::{abci::AbciErrorCode, transaction::v1alpha1::SignedTransaction}, }; use astria_eyre::eyre; use ethers::prelude::Transaction; use once_cell::sync::Lazy; use tempfile::NamedTempFile; -use tendermint_rpc::{ - endpoint::broadcast::tx_sync, - request, - response, - Id, -}; +use tendermint_rpc::{endpoint::broadcast::tx_sync, request, response, Id}; use test_utils::mock::Geth; use tokio::task::JoinHandle; use tracing::debug; -use wiremock::{ - Mock, - MockGuard, - MockServer, - Request, - ResponseTemplate, -}; +use wiremock::{Mock, MockGuard, MockServer, Request, ResponseTemplate}; pub mod mock_sequencer; diff --git a/crates/astria-conductor/src/block_cache.rs b/crates/astria-conductor/src/block_cache.rs index 3b3b3b56e..fb15702fe 100644 --- a/crates/astria-conductor/src/block_cache.rs +++ b/crates/astria-conductor/src/block_cache.rs @@ -1,13 +1,7 @@ //! A cache of sequencer blocks that are only yielded in sequential order. -use std::{ - collections::BTreeMap, - future::Future, -}; - -use astria_core::sequencerblock::v1alpha1::{ - block::FilteredSequencerBlock, - SubmittedMetadata, -}; +use std::{collections::BTreeMap, future::Future}; + +use astria_core::sequencerblock::v1alpha1::{block::FilteredSequencerBlock, SubmittedMetadata}; use pin_project_lite::pin_project; use sequencer_client::tendermint::block::Height; @@ -70,9 +64,7 @@ impl BlockCache { /// /// This method exists to make fetching the next block async cancellation safe. pub(crate) fn next_block(&mut self) -> NextBlock<'_, T> { - NextBlock { - cache: self, - } + NextBlock { cache: self } } } @@ -153,9 +145,7 @@ mod tests { impl From for DummyBlock { fn from(height: Height) -> DummyBlock { - DummyBlock { - height, - } + DummyBlock { height } } } diff --git a/crates/astria-conductor/src/celestia/block_verifier.rs b/crates/astria-conductor/src/celestia/block_verifier.rs index c45ee35fe..8d04ac0f4 100644 --- a/crates/astria-conductor/src/celestia/block_verifier.rs +++ b/crates/astria-conductor/src/celestia/block_verifier.rs @@ -1,15 +1,9 @@ use std::collections::HashMap; -use astria_core::crypto::{ - Signature, - VerificationKey, -}; +use astria_core::crypto::{Signature, VerificationKey}; use prost::Message; use sequencer_client::{ - tendermint::{ - self, - block::Height, - }, + tendermint::{self, block::Height}, tendermint_rpc, }; @@ -224,20 +218,12 @@ mod test { generated::sequencerblock::v1alpha1::SequencerBlockHeader as RawSequencerBlockHeader, primitive::v1::RollupId, sequencerblock::v1alpha1::{ - block::SequencerBlockHeader, - celestia::UncheckedSubmittedMetadata, + block::SequencerBlockHeader, celestia::UncheckedSubmittedMetadata, }, }; use prost::Message as _; use sequencer_client::{ - tendermint::{ - self, - account, - block::Commit, - validator, - validator::Info as Validator, - Hash, - }, + tendermint::{self, account, block::Commit, validator, validator::Info as Validator, Hash}, tendermint_proto, tendermint_rpc::endpoint::validators, }; @@ -255,10 +241,7 @@ mod test { I: IntoIterator, B: AsRef<[u8]>, { - use sha2::{ - Digest as _, - Sha256, - }; + use sha2::{Digest as _, Sha256}; merkle::Tree::from_leaves(iter.into_iter().map(|item| Sha256::digest(&item))) } @@ -481,10 +464,7 @@ mod test { #[test] fn ensure_commit_has_quorum_not_ok() { - use base64::engine::{ - general_purpose::STANDARD, - Engine as _, - }; + use base64::engine::{general_purpose::STANDARD, Engine as _}; let validator_set = validators::Response::new( 78u32.into(), vec![Validator { @@ -528,11 +508,9 @@ mod test { &tendermint::chain::Id::try_from("test-chain-g3ejvw").unwrap(), ); assert!(result.is_err()); - assert!( - result - .unwrap_err() - .to_string() - .contains("commit voting power is less than 2/3 of total voting power") - ); + assert!(result + .unwrap_err() + .to_string() + .contains("commit voting power is less than 2/3 of total voting power")); } } diff --git a/crates/astria-conductor/src/celestia/builder.rs b/crates/astria-conductor/src/celestia/builder.rs index 99cf090c9..94e2b54d6 100644 --- a/crates/astria-conductor/src/celestia/builder.rs +++ b/crates/astria-conductor/src/celestia/builder.rs @@ -2,10 +2,7 @@ use std::time::Duration; -use astria_eyre::eyre::{ - self, - WrapErr as _, -}; +use astria_eyre::eyre::{self, WrapErr as _}; use jsonrpsee::http_client::HttpClient as CelestiaClient; use tendermint_rpc::HttpClient as SequencerClient; use tokio_util::sync::CancellationToken; @@ -51,10 +48,7 @@ impl Builder { } fn create_celestia_client(endpoint: String, bearer_token: &str) -> eyre::Result { - use jsonrpsee::http_client::{ - HeaderMap, - HttpClientBuilder, - }; + use jsonrpsee::http_client::{HeaderMap, HttpClientBuilder}; let mut headers = HeaderMap::new(); let auth_value = format!("Bearer {bearer_token}").parse().wrap_err( "failed to construct Authorization header value from provided Celestia bearer token", diff --git a/crates/astria-conductor/src/celestia/convert.rs b/crates/astria-conductor/src/celestia/convert.rs index 6ffe387e3..75dd91a1d 100644 --- a/crates/astria-conductor/src/celestia/convert.rs +++ b/crates/astria-conductor/src/celestia/convert.rs @@ -1,31 +1,15 @@ use astria_core::{ brotli::decompress_bytes, - generated::sequencerblock::v1alpha1::{ - SubmittedMetadataList, - SubmittedRollupDataList, - }, + generated::sequencerblock::v1alpha1::{SubmittedMetadataList, SubmittedRollupDataList}, sequencerblock::v1alpha1::{ - celestia::{ - SubmittedMetadataError, - SubmittedRollupDataError, - }, - SubmittedMetadata, - SubmittedRollupData, + celestia::{SubmittedMetadataError, SubmittedRollupDataError}, + SubmittedMetadata, SubmittedRollupData, }, }; -use celestia_types::{ - nmt::Namespace, - Blob, -}; -use prost::{ - Message as _, - Name as _, -}; +use celestia_types::{nmt::Namespace, Blob}; +use prost::{Message as _, Name as _}; use telemetry::display::base64; -use tracing::{ - info, - warn, -}; +use tracing::{info, warn}; use super::fetch::RawBlobs; diff --git a/crates/astria-conductor/src/celestia/fetch.rs b/crates/astria-conductor/src/celestia/fetch.rs index 503c0eef2..7e3c9e3b4 100644 --- a/crates/astria-conductor/src/celestia/fetch.rs +++ b/crates/astria-conductor/src/celestia/fetch.rs @@ -1,30 +1,12 @@ -use std::{ - sync::atomic::AtomicU32, - time::Duration, -}; - -use astria_eyre::{ - eyre, - eyre::WrapErr as _, -}; -use celestia_types::{ - nmt::Namespace, - Blob, -}; -use jsonrpsee::{ - self, - http_client::HttpClient as CelestiaClient, -}; +use std::{sync::atomic::AtomicU32, time::Duration}; + +use astria_eyre::{eyre, eyre::WrapErr as _}; +use celestia_types::{nmt::Namespace, Blob}; +use jsonrpsee::{self, http_client::HttpClient as CelestiaClient}; use telemetry::display::base64; use tokio::try_join; -use tracing::{ - instrument, - warn, -}; -use tryhard::{ - backoff_strategies::BackoffStrategy, - RetryPolicy, -}; +use tracing::{instrument, warn}; +use tryhard::{backoff_strategies::BackoffStrategy, RetryPolicy}; use crate::metrics_init::CELESTIA_BLOB_FETCH_ERROR_COUNT; diff --git a/crates/astria-conductor/src/celestia/latest_height_stream.rs b/crates/astria-conductor/src/celestia/latest_height_stream.rs index 5fe47c98a..2b541cd07 100644 --- a/crates/astria-conductor/src/celestia/latest_height_stream.rs +++ b/crates/astria-conductor/src/celestia/latest_height_stream.rs @@ -1,19 +1,8 @@ -use std::{ - pin::Pin, - time::Duration, -}; +use std::{pin::Pin, time::Duration}; -use astria_eyre::eyre::{ - Result, - WrapErr as _, -}; +use astria_eyre::eyre::{Result, WrapErr as _}; use celestia_rpc::HeaderClient as _; -use futures::{ - Future, - FutureExt as _, - Stream, - StreamExt as _, -}; +use futures::{Future, FutureExt as _, Stream, StreamExt as _}; use jsonrpsee::http_client::HttpClient; use tokio_stream::wrappers::IntervalStream; diff --git a/crates/astria-conductor/src/celestia/mod.rs b/crates/astria-conductor/src/celestia/mod.rs index d69b87f76..a44086739 100644 --- a/crates/astria-conductor/src/celestia/mod.rs +++ b/crates/astria-conductor/src/celestia/mod.rs @@ -1,72 +1,30 @@ -use std::{ - cmp::max, - sync::Arc, - time::Duration, -}; +use std::{cmp::max, sync::Arc, time::Duration}; -use astria_core::{ - primitive::v1::RollupId, - sequencerblock::v1alpha1::block::SequencerBlockHeader, -}; -use astria_eyre::eyre::{ - self, - bail, - WrapErr as _, -}; +use astria_core::{primitive::v1::RollupId, sequencerblock::v1alpha1::block::SequencerBlockHeader}; +use astria_eyre::eyre::{self, bail, WrapErr as _}; use celestia_types::nmt::Namespace; use futures::{ - future::{ - BoxFuture, - Fuse, - FusedFuture as _, - }, + future::{BoxFuture, Fuse, FusedFuture as _}, FutureExt as _, }; use jsonrpsee::http_client::HttpClient as CelestiaClient; use metrics::histogram; use sequencer_client::{ - tendermint, - tendermint::block::Height as SequencerHeight, - tendermint_rpc, + tendermint, tendermint::block::Height as SequencerHeight, tendermint_rpc, HttpClient as SequencerClient, }; -use telemetry::display::{ - base64, - json, -}; -use tokio::{ - select, - sync::mpsc, - task::spawn_blocking, - try_join, -}; +use telemetry::display::{base64, json}; +use tokio::{select, sync::mpsc, task::spawn_blocking, try_join}; use tokio_stream::StreamExt as _; -use tokio_util::{ - sync::CancellationToken, - task::JoinMap, -}; -use tracing::{ - error, - info, - info_span, - instrument, - trace, - warn, -}; +use tokio_util::{sync::CancellationToken, task::JoinMap}; +use tracing::{error, info, info_span, instrument, trace, warn}; use crate::{ block_cache::GetSequencerHeight, - executor::{ - FirmSendError, - FirmTrySendError, - StateIsInit, - }, + executor::{FirmSendError, FirmTrySendError, StateIsInit}, metrics_init::{ - BLOBS_PER_CELESTIA_FETCH, - DECODED_ITEMS_PER_CELESTIA_FETCH, - NAMESPACE_TYPE_LABEL, - NAMESPACE_TYPE_METADATA, - NAMESPACE_TYPE_ROLLUP_DATA, + BLOBS_PER_CELESTIA_FETCH, DECODED_ITEMS_PER_CELESTIA_FETCH, NAMESPACE_TYPE_LABEL, + NAMESPACE_TYPE_METADATA, NAMESPACE_TYPE_ROLLUP_DATA, SEQUENCER_BLOCKS_METADATA_VERIFIED_PER_CELESTIA_FETCH, SEQUENCER_BLOCK_INFORMATION_RECONSTRUCTED_PER_CELESTIA_FETCH, }, @@ -92,15 +50,9 @@ use self::{ fetch::fetch_new_blobs, latest_height_stream::stream_latest_heights, reconstruct::reconstruct_blocks_from_verified_blobs, - verify::{ - verify_metadata, - BlobVerifier, - }, -}; -use crate::{ - block_cache::BlockCache, - executor, + verify::{verify_metadata, BlobVerifier}, }; +use crate::{block_cache::BlockCache, executor}; /// Sequencer Block information reconstructed from Celestia blobs. /// diff --git a/crates/astria-conductor/src/celestia/reconstruct.rs b/crates/astria-conductor/src/celestia/reconstruct.rs index 9deae218e..31421d000 100644 --- a/crates/astria-conductor/src/celestia/reconstruct.rs +++ b/crates/astria-conductor/src/celestia/reconstruct.rs @@ -2,21 +2,12 @@ use std::collections::HashMap; use astria_core::{ primitive::v1::RollupId, - sequencerblock::v1alpha1::{ - SubmittedMetadata, - SubmittedRollupData, - }, + sequencerblock::v1alpha1::{SubmittedMetadata, SubmittedRollupData}, }; use telemetry::display::base64; -use tracing::{ - info, - warn, -}; +use tracing::{info, warn}; -use super::{ - verify::VerifiedBlobs, - ReconstructedBlock, -}; +use super::{verify::VerifiedBlobs, ReconstructedBlock}; /// Reconstructs block information from verified blocks. /// diff --git a/crates/astria-conductor/src/celestia/reporting.rs b/crates/astria-conductor/src/celestia/reporting.rs index cd16454b6..13f4cae6e 100644 --- a/crates/astria-conductor/src/celestia/reporting.rs +++ b/crates/astria-conductor/src/celestia/reporting.rs @@ -1,15 +1,8 @@ //! Various newtype-wrappers to emit serde-serialized tracing event fields. -use serde::ser::{ - Serialize, - SerializeSeq, - SerializeStruct, -}; +use serde::ser::{Serialize, SerializeSeq, SerializeStruct}; use telemetry::display::base64; -use super::{ - ReconstructedBlock, - ReconstructedBlocks, -}; +use super::{ReconstructedBlock, ReconstructedBlocks}; pub(super) struct ReportReconstructedBlocks<'a>(pub(super) &'a ReconstructedBlocks); impl<'a> Serialize for ReportReconstructedBlocks<'a> { diff --git a/crates/astria-conductor/src/celestia/verify.rs b/crates/astria-conductor/src/celestia/verify.rs index 1f44662da..7b4adf4da 100644 --- a/crates/astria-conductor/src/celestia/verify.rs +++ b/crates/astria-conductor/src/celestia/verify.rs @@ -1,59 +1,23 @@ -use std::{ - collections::HashMap, - sync::Arc, - time::Duration, -}; +use std::{collections::HashMap, sync::Arc, time::Duration}; -use astria_core::sequencerblock::v1alpha1::{ - SubmittedMetadata, - SubmittedRollupData, -}; +use astria_core::sequencerblock::v1alpha1::{SubmittedMetadata, SubmittedRollupData}; use astria_eyre::{ eyre, - eyre::{ - ensure, - WrapErr as _, - }, + eyre::{ensure, WrapErr as _}, }; use moka::future::Cache; use sequencer_client::{ - tendermint::block::{ - signed_header::SignedHeader, - Height as SequencerHeight, - }, - tendermint_rpc, - Client as _, - HttpClient as SequencerClient, + tendermint::block::{signed_header::SignedHeader, Height as SequencerHeight}, + tendermint_rpc, Client as _, HttpClient as SequencerClient, }; use telemetry::display::base64; use tokio_util::task::JoinMap; -use tower::{ - util::BoxService, - BoxError, - Service as _, - ServiceExt as _, -}; -use tracing::{ - info, - instrument, - warn, - Instrument, -}; -use tryhard::{ - backoff_strategies::BackoffStrategy, - retry_fn, - RetryFutureConfig, - RetryPolicy, -}; +use tower::{util::BoxService, BoxError, Service as _, ServiceExt as _}; +use tracing::{info, instrument, warn, Instrument}; +use tryhard::{backoff_strategies::BackoffStrategy, retry_fn, RetryFutureConfig, RetryPolicy}; -use super::{ - block_verifier, - convert::ConvertedBlobs, -}; -use crate::executor::{ - self, - StateIsInit, -}; +use super::{block_verifier, convert::ConvertedBlobs}; +use crate::executor::{self, StateIsInit}; pub(super) struct VerifiedBlobs { celestia_height: u64, @@ -326,10 +290,7 @@ async fn fetch_commit_with_retry( .with_config(retry_config) .await .map(Into::into) - .map_err(|source| VerificationMetaError::FetchCommit { - height, - source, - }) + .map_err(|source| VerificationMetaError::FetchCommit { height, source }) } async fn fetch_validators_with_retry( @@ -399,11 +360,7 @@ impl<'a> BackoffStrategy<'a, tendermint_rpc::Error> for CometBftRetryStrategy { } fn should_retry(error: &tendermint_rpc::Error) -> bool { - use tendermint_rpc::error::ErrorDetail::{ - Http, - HttpRequestFailed, - Timeout, - }; + use tendermint_rpc::error::ErrorDetail::{Http, HttpRequestFailed, Timeout}; matches!( error.detail(), Http(..) | HttpRequestFailed(..) | Timeout(..) @@ -458,9 +415,7 @@ impl RateLimitedVerificationClient { .inner .ready() .await? - .call(VerificationRequest::Commit { - height, - }) + .call(VerificationRequest::Commit { height }) .await? { VerificationResponse::Commit(commit) => Ok(commit), @@ -509,9 +464,9 @@ impl RateLimitedVerificationClient { let client = client.clone(); async move { match req { - VerificationRequest::Commit { - height, - } => fetch_commit_with_retry(client, height).await, + VerificationRequest::Commit { height } => { + fetch_commit_with_retry(client, height).await + } VerificationRequest::Validators { prev_height, height, @@ -527,9 +482,7 @@ impl RateLimitedVerificationClient { .try_into() .wrap_err("failed to convert u32 requests-per-second to usize")?, ); - Ok(Self { - inner, - }) + Ok(Self { inner }) } } diff --git a/crates/astria-conductor/src/conductor.rs b/crates/astria-conductor/src/conductor.rs index 4945fae97..dd7c8fcc4 100644 --- a/crates/astria-conductor/src/conductor.rs +++ b/crates/astria-conductor/src/conductor.rs @@ -1,38 +1,14 @@ -use std::{ - future::Future, - time::Duration, -}; - -use astria_eyre::eyre::{ - self, - eyre, - WrapErr as _, -}; +use std::{future::Future, time::Duration}; + +use astria_eyre::eyre::{self, eyre, WrapErr as _}; use itertools::Itertools as _; use pin_project_lite::pin_project; use sequencer_client::HttpClient; -use tokio::{ - select, - time::timeout, -}; -use tokio_util::{ - sync::CancellationToken, - task::JoinMap, -}; -use tracing::{ - error, - info, - instrument, - warn, -}; - -use crate::{ - celestia, - executor, - sequencer, - utils::flatten, - Config, -}; +use tokio::{select, time::timeout}; +use tokio_util::{sync::CancellationToken, task::JoinMap}; +use tracing::{error, info, instrument, warn}; + +use crate::{celestia, executor, sequencer, utils::flatten, Config}; pin_project! { /// A handle returned by [`Conductor::spawn`]. @@ -150,10 +126,7 @@ impl Conductor { tasks.spawn(Self::CELESTIA, reader.run_until_stopped()); }; - Ok(Self { - shutdown, - tasks, - }) + Ok(Self { shutdown, tasks }) } /// Runs [`Conductor`] until it receives an exit signal. diff --git a/crates/astria-conductor/src/config.rs b/crates/astria-conductor/src/config.rs index 699f95f1c..863f3361f 100644 --- a/crates/astria-conductor/src/config.rs +++ b/crates/astria-conductor/src/config.rs @@ -1,9 +1,6 @@ //! The conductor configuration. -use serde::{ - Deserialize, - Serialize, -}; +use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)] pub enum CommitLevel { @@ -90,10 +87,7 @@ impl config::Config for Config { #[cfg(test)] mod tests { - use super::{ - CommitLevel, - Config, - }; + use super::{CommitLevel, Config}; const EXAMPLE_ENV: &str = include_str!("../local.env.example"); @@ -104,11 +98,7 @@ mod tests { #[test] fn do_commit_levels_correctly_report_mode() { - use CommitLevel::{ - FirmOnly, - SoftAndFirm, - SoftOnly, - }; + use CommitLevel::{FirmOnly, SoftAndFirm, SoftOnly}; assert!(FirmOnly.is_with_firm()); assert!(!FirmOnly.is_with_soft()); diff --git a/crates/astria-conductor/src/executor/builder.rs b/crates/astria-conductor/src/executor/builder.rs index 67941479a..28bee5a26 100644 --- a/crates/astria-conductor/src/executor/builder.rs +++ b/crates/astria-conductor/src/executor/builder.rs @@ -1,18 +1,10 @@ use std::collections::HashMap; -use astria_eyre::eyre::{ - self, - WrapErr as _, -}; +use astria_eyre::eyre::{self, WrapErr as _}; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; -use super::{ - state, - Executor, - Handle, - StateNotInit, -}; +use super::{state, Executor, Handle, StateNotInit}; use crate::config::CommitLevel; pub(crate) struct Builder { diff --git a/crates/astria-conductor/src/executor/channel.rs b/crates/astria-conductor/src/executor/channel.rs index c4348bd08..871dc9272 100644 --- a/crates/astria-conductor/src/executor/channel.rs +++ b/crates/astria-conductor/src/executor/channel.rs @@ -4,21 +4,13 @@ //! from a sequencer reader to the executor, the channel is generic over the values that are //! being sent to better test its functionality. -use std::sync::{ - Arc, - Weak, -}; +use std::sync::{Arc, Weak}; use tokio::sync::{ mpsc::{ - error::SendError as TokioSendError, - unbounded_channel, - UnboundedReceiver, - UnboundedSender, + error::SendError as TokioSendError, unbounded_channel, UnboundedReceiver, UnboundedSender, }, - AcquireError, - Semaphore, - TryAcquireError, + AcquireError, Semaphore, TryAcquireError, }; /// Creates an mpsc channel for sending soft blocks between asynchronous task. @@ -33,11 +25,7 @@ pub(super) fn soft_block_channel() -> (Sender, Receiver) { chan: tx, sem: Arc::downgrade(&sem), }; - let receiver = Receiver { - cap, - chan: rx, - sem, - }; + let receiver = Receiver { cap, chan: rx, sem }; (sender, receiver) } @@ -158,11 +146,7 @@ impl Receiver { #[cfg(test)] mod tests { - use super::{ - soft_block_channel, - SendError, - TrySendError, - }; + use super::{soft_block_channel, SendError, TrySendError}; #[test] fn fresh_channel_has_no_capacity() { diff --git a/crates/astria-conductor/src/executor/client.rs b/crates/astria-conductor/src/executor/client.rs index 8704ee076..0579b534c 100644 --- a/crates/astria-conductor/src/executor/client.rs +++ b/crates/astria-conductor/src/executor/client.rs @@ -1,42 +1,19 @@ use std::time::Duration; use astria_core::{ - execution::v1alpha2::{ - Block, - CommitmentState, - GenesisInfo, - }, + execution::v1alpha2::{Block, CommitmentState, GenesisInfo}, generated::{ - execution::{ - v1alpha2 as raw, - v1alpha2::execution_service_client::ExecutionServiceClient, - }, + execution::{v1alpha2 as raw, v1alpha2::execution_service_client::ExecutionServiceClient}, sequencerblock::v1alpha1::RollupData, }, Protobuf as _, }; -use astria_eyre::eyre::{ - self, - ensure, - WrapErr as _, -}; +use astria_eyre::eyre::{self, ensure, WrapErr as _}; use bytes::Bytes; use pbjson_types::Timestamp; -use tonic::transport::{ - Channel, - Endpoint, - Uri, -}; -use tracing::{ - instrument, - warn, - Instrument, - Span, -}; -use tryhard::{ - backoff_strategies::BackoffStrategy, - RetryPolicy, -}; +use tonic::transport::{Channel, Endpoint, Uri}; +use tracing::{instrument, warn, Instrument, Span}; +use tryhard::{backoff_strategies::BackoffStrategy, RetryPolicy}; /// A newtype wrapper around [`ExecutionServiceClient`] to work with /// idiomatic types. @@ -53,10 +30,7 @@ impl Client { .wrap_err("failed to parse provided string as uri")?; let endpoint = Endpoint::from(uri.clone()).connect_lazy(); let inner = ExecutionServiceClient::new(endpoint); - Ok(Self { - uri, - inner, - }) + Ok(Self { uri, inner }) } /// Calls RPC astria.execution.v1alpha2.GetBlock @@ -332,16 +306,9 @@ fn should_retry(status: &tonic::Status) -> bool { mod tests { use std::time::Duration; - use tonic::{ - Code, - Status, - }; + use tonic::{Code, Status}; - use super::{ - BackoffStrategy as _, - ExecutionApiRetryStrategy, - RetryPolicy, - }; + use super::{BackoffStrategy as _, ExecutionApiRetryStrategy, RetryPolicy}; #[track_caller] fn assert_retry_policy(code: Code) { diff --git a/crates/astria-conductor/src/executor/mod.rs b/crates/astria-conductor/src/executor/mod.rs index 56eb5abbf..ba8b3655b 100644 --- a/crates/astria-conductor/src/executor/mod.rs +++ b/crates/astria-conductor/src/executor/mod.rs @@ -1,49 +1,25 @@ use std::collections::HashMap; use astria_core::{ - execution::v1alpha2::{ - Block, - CommitmentState, - }, + execution::v1alpha2::{Block, CommitmentState}, primitive::v1::RollupId, - sequencerblock::v1alpha1::block::{ - FilteredSequencerBlock, - FilteredSequencerBlockParts, - }, -}; -use astria_eyre::eyre::{ - self, - bail, - ensure, - WrapErr as _, + sequencerblock::v1alpha1::block::{FilteredSequencerBlock, FilteredSequencerBlockParts}, }; +use astria_eyre::eyre::{self, bail, ensure, WrapErr as _}; use bytes::Bytes; -use sequencer_client::tendermint::{ - block::Height as SequencerHeight, - Time as TendermintTime, -}; +use sequencer_client::tendermint::{block::Height as SequencerHeight, Time as TendermintTime}; use tokio::{ select, - sync::{ - mpsc, - watch::error::RecvError, - }, + sync::{mpsc, watch::error::RecvError}, }; use tokio_util::sync::CancellationToken; -use tracing::{ - debug, - error, - info, - instrument, -}; +use tracing::{debug, error, info, instrument}; use crate::{ celestia::ReconstructedBlock, config::CommitLevel, metrics_init::{ - EXECUTED_FIRM_BLOCK_NUMBER, - EXECUTED_SOFT_BLOCK_NUMBER, - TRANSACTIONS_PER_EXECUTED_BLOCK, + EXECUTED_FIRM_BLOCK_NUMBER, EXECUTED_SOFT_BLOCK_NUMBER, TRANSACTIONS_PER_EXECUTED_BLOCK, }, }; @@ -616,11 +592,7 @@ impl Executor { #[instrument(skip_all)] async fn update_commitment_state(&mut self, update: Update) -> eyre::Result<()> { - use Update::{ - OnlyFirm, - OnlySoft, - ToSame, - }; + use Update::{OnlyFirm, OnlySoft, ToSame}; let (firm, soft, celestia_height) = match update { OnlyFirm(firm, celestia_height) => (firm, self.state.soft(), celestia_height), OnlySoft(soft) => ( @@ -730,14 +702,9 @@ impl ExecutableBlock { /// Converts a [`tendermint::Time`] to a [`prost_types::Timestamp`]. fn convert_tendermint_time_to_protobuf_timestamp(value: TendermintTime) -> pbjson_types::Timestamp { - let sequencer_client::tendermint_proto::google::protobuf::Timestamp { - seconds, - nanos, - } = value.into(); - pbjson_types::Timestamp { - seconds, - nanos, - } + let sequencer_client::tendermint_proto::google::protobuf::Timestamp { seconds, nanos } = + value.into(); + pbjson_types::Timestamp { seconds, nanos } } #[derive(Copy, Clone, Debug)] @@ -784,10 +751,7 @@ fn does_block_response_fulfill_contract( let actual = block.number(); let expected = current .checked_add(1) - .ok_or(ContractViolation::CurrentBlockNumberIsMax { - kind, - actual, - })?; + .ok_or(ContractViolation::CurrentBlockNumberIsMax { kind, actual })?; if actual == expected { Ok(()) } else { diff --git a/crates/astria-conductor/src/executor/state.rs b/crates/astria-conductor/src/executor/state.rs index f5d1bab6b..0ca95499c 100644 --- a/crates/astria-conductor/src/executor/state.rs +++ b/crates/astria-conductor/src/executor/state.rs @@ -3,32 +3,18 @@ //! //! The inner state must not be unset after having been set. use astria_core::{ - execution::v1alpha2::{ - Block, - CommitmentState, - GenesisInfo, - }, + execution::v1alpha2::{Block, CommitmentState, GenesisInfo}, primitive::v1::RollupId, }; -use astria_eyre::{ - eyre, - eyre::WrapErr as _, -}; +use astria_eyre::{eyre, eyre::WrapErr as _}; use bytes::Bytes; use sequencer_client::tendermint::block::Height as SequencerHeight; -use tokio::sync::watch::{ - self, - error::RecvError, -}; +use tokio::sync::watch::{self, error::RecvError}; pub(super) fn channel() -> (StateSender, StateReceiver) { let (tx, rx) = watch::channel(None); - let sender = StateSender { - inner: tx, - }; - let receiver = StateReceiver { - inner: rx, - }; + let sender = StateSender { inner: tx }; + let receiver = StateReceiver { inner: rx }; (sender, receiver) } @@ -340,10 +326,7 @@ pub(super) fn map_sequencer_height_to_rollup_height( #[cfg(test)] mod tests { - use astria_core::{ - generated::execution::v1alpha2 as raw, - Protobuf as _, - }; + use astria_core::{generated::execution::v1alpha2 as raw, Protobuf as _}; use pbjson_types::Timestamp; use super::*; diff --git a/crates/astria-conductor/src/executor/tests.rs b/crates/astria-conductor/src/executor/tests.rs index f6deb4db0..0f6960e2a 100644 --- a/crates/astria-conductor/src/executor/tests.rs +++ b/crates/astria-conductor/src/executor/tests.rs @@ -1,10 +1,6 @@ use astria_core::{ self, - execution::v1alpha2::{ - Block, - CommitmentState, - GenesisInfo, - }, + execution::v1alpha2::{Block, CommitmentState, GenesisInfo}, generated::execution::v1alpha2 as raw, Protobuf as _, }; @@ -12,10 +8,7 @@ use bytes::Bytes; use super::{ should_execute_firm_block, - state::{ - StateReceiver, - StateSender, - }, + state::{StateReceiver, StateSender}, RollupId, }; use crate::config::CommitLevel; @@ -39,12 +32,7 @@ struct MakeState { soft: u32, } -fn make_state( - MakeState { - firm, - soft, - }: MakeState, -) -> (StateSender, StateReceiver) { +fn make_state(MakeState { firm, soft }: MakeState) -> (StateSender, StateReceiver) { let genesis_info = GenesisInfo::try_from_raw(raw::GenesisInfo { rollup_id: Bytes::copy_from_slice(ROLLUP_ID.as_ref()), sequencer_genesis_block_height: 1, @@ -82,90 +70,27 @@ state", #[test] fn execute_block_contract_violation() { - use super::ExecutionKind::{ - Firm, - Soft, - }; - assert_contract_fulfilled( - Firm, - MakeState { - firm: 2, - soft: 3, - }, - 3, - ); + use super::ExecutionKind::{Firm, Soft}; + assert_contract_fulfilled(Firm, MakeState { firm: 2, soft: 3 }, 3); - assert_contract_fulfilled( - Soft, - MakeState { - firm: 2, - soft: 3, - }, - 4, - ); + assert_contract_fulfilled(Soft, MakeState { firm: 2, soft: 3 }, 4); - assert_contract_violated( - Firm, - MakeState { - firm: 2, - soft: 3, - }, - 1, - ); + assert_contract_violated(Firm, MakeState { firm: 2, soft: 3 }, 1); - assert_contract_violated( - Firm, - MakeState { - firm: 2, - soft: 3, - }, - 2, - ); + assert_contract_violated(Firm, MakeState { firm: 2, soft: 3 }, 2); - assert_contract_violated( - Firm, - MakeState { - firm: 2, - soft: 3, - }, - 4, - ); + assert_contract_violated(Firm, MakeState { firm: 2, soft: 3 }, 4); - assert_contract_violated( - Soft, - MakeState { - firm: 2, - soft: 3, - }, - 2, - ); + assert_contract_violated(Soft, MakeState { firm: 2, soft: 3 }, 2); - assert_contract_violated( - Soft, - MakeState { - firm: 2, - soft: 3, - }, - 3, - ); + assert_contract_violated(Soft, MakeState { firm: 2, soft: 3 }, 3); - assert_contract_violated( - Soft, - MakeState { - firm: 2, - soft: 3, - }, - 5, - ); + assert_contract_violated(Soft, MakeState { firm: 2, soft: 3 }, 5); } #[test] fn should_execute_firm() { - use CommitLevel::{ - FirmOnly, - SoftAndFirm, - SoftOnly, - }; + use CommitLevel::{FirmOnly, SoftAndFirm, SoftOnly}; assert!( should_execute_firm_block(1, 1, FirmOnly), diff --git a/crates/astria-conductor/src/main.rs b/crates/astria-conductor/src/main.rs index 4efb85676..c191e586b 100644 --- a/crates/astria-conductor/src/main.rs +++ b/crates/astria-conductor/src/main.rs @@ -1,24 +1,12 @@ use std::process::ExitCode; -use astria_conductor::{ - metrics_init, - Conductor, - Config, - BUILD_INFO, -}; +use astria_conductor::{metrics_init, Conductor, Config, BUILD_INFO}; use astria_eyre::eyre::WrapErr as _; use tokio::{ select, - signal::unix::{ - signal, - SignalKind, - }, -}; -use tracing::{ - error, - info, - warn, + signal::unix::{signal, SignalKind}, }; +use tracing::{error, info, warn}; // Following the BSD convention for failing to read config // See here: https://freedesktop.org/software/systemd/man/systemd.exec.html#Process%20Exit%20Codes diff --git a/crates/astria-conductor/src/metrics_init.rs b/crates/astria-conductor/src/metrics_init.rs index f0801c84a..2c8cff880 100644 --- a/crates/astria-conductor/src/metrics_init.rs +++ b/crates/astria-conductor/src/metrics_init.rs @@ -2,11 +2,7 @@ //! //! Registers metrics & lists constants to be used as metric names throughout crate. -use metrics::{ - describe_counter, - describe_histogram, - Unit, -}; +use metrics::{describe_counter, describe_histogram, Unit}; use telemetry::metric_name; pub(crate) const NAMESPACE_TYPE_LABEL: &str = "namespace_type"; @@ -73,11 +69,8 @@ metric_name!(pub const TRANSACTIONS_PER_EXECUTED_BLOCK); mod tests { use super::TRANSACTIONS_PER_EXECUTED_BLOCK; use crate::metrics_init::{ - BLOBS_PER_CELESTIA_FETCH, - CELESTIA_BLOB_FETCH_ERROR_COUNT, - DECODED_ITEMS_PER_CELESTIA_FETCH, - EXECUTED_FIRM_BLOCK_NUMBER, - EXECUTED_SOFT_BLOCK_NUMBER, + BLOBS_PER_CELESTIA_FETCH, CELESTIA_BLOB_FETCH_ERROR_COUNT, + DECODED_ITEMS_PER_CELESTIA_FETCH, EXECUTED_FIRM_BLOCK_NUMBER, EXECUTED_SOFT_BLOCK_NUMBER, SEQUENCER_BLOCKS_METADATA_VERIFIED_PER_CELESTIA_FETCH, SEQUENCER_BLOCK_INFORMATION_RECONSTRUCTED_PER_CELESTIA_FETCH, }; diff --git a/crates/astria-conductor/src/sequencer/block_stream.rs b/crates/astria-conductor/src/sequencer/block_stream.rs index 663f9d254..8202e1714 100644 --- a/crates/astria-conductor/src/sequencer/block_stream.rs +++ b/crates/astria-conductor/src/sequencer/block_stream.rs @@ -1,28 +1,15 @@ -use std::{ - error::Error as StdError, - pin::Pin, - task::Poll, -}; +use std::{error::Error as StdError, pin::Pin, task::Poll}; use astria_core::{ - primitive::v1::RollupId, - sequencerblock::v1alpha1::block::FilteredSequencerBlock, -}; -use astria_eyre::eyre::{ - self, - WrapErr as _, + primitive::v1::RollupId, sequencerblock::v1alpha1::block::FilteredSequencerBlock, }; +use astria_eyre::eyre::{self, WrapErr as _}; use futures::Stream; use futures_bounded::FuturesMap; use pin_project_lite::pin_project; use sequencer_client::tendermint::block::Height; use telemetry::display::json; -use tracing::{ - error, - info, - instrument, - warn, -}; +use tracing::{error, info, instrument, warn}; use super::SequencerGrpcClient; use crate::sequencer::reporting::ReportFilteredSequencerBlock; diff --git a/crates/astria-conductor/src/sequencer/client.rs b/crates/astria-conductor/src/sequencer/client.rs index 78c1eafc7..ef1fa50f4 100644 --- a/crates/astria-conductor/src/sequencer/client.rs +++ b/crates/astria-conductor/src/sequencer/client.rs @@ -4,27 +4,14 @@ use std::time::Duration; use astria_core::{ generated::sequencerblock::v1alpha1::{ - sequencer_service_client::SequencerServiceClient, - GetFilteredSequencerBlockRequest, + sequencer_service_client::SequencerServiceClient, GetFilteredSequencerBlockRequest, }, primitive::v1::RollupId, sequencerblock::v1alpha1::block::FilteredSequencerBlock, }; -use astria_eyre::eyre::{ - self, - WrapErr as _, -}; -use tonic::transport::{ - Channel, - Endpoint, - Uri, -}; -use tracing::{ - debug, - instrument, - warn, - Instrument, -}; +use astria_eyre::eyre::{self, WrapErr as _}; +use tonic::transport::{Channel, Endpoint, Uri}; +use tracing::{debug, instrument, warn, Instrument}; #[derive(Clone)] pub(crate) struct SequencerGrpcClient { @@ -40,10 +27,7 @@ impl SequencerGrpcClient { .wrap_err("failed parsing provided string as Uri")?; let endpoint = Endpoint::from(uri.clone()); let inner = SequencerServiceClient::new(endpoint.connect_lazy()); - Ok(Self { - inner, - uri, - }) + Ok(Self { inner, uri }) } /// Fetch a sequencer block filtered by `rollup_id`. diff --git a/crates/astria-conductor/src/sequencer/mod.rs b/crates/astria-conductor/src/sequencer/mod.rs index 535c61d4f..be1ef7632 100644 --- a/crates/astria-conductor/src/sequencer/mod.rs +++ b/crates/astria-conductor/src/sequencer/mod.rs @@ -3,45 +3,21 @@ use std::time::Duration; use astria_core::sequencerblock::v1alpha1::block::FilteredSequencerBlock; -use astria_eyre::eyre::{ - self, - bail, - Report, - WrapErr as _, -}; +use astria_eyre::eyre::{self, bail, Report, WrapErr as _}; use futures::{ - future::{ - self, - BoxFuture, - Fuse, - }, - FutureExt as _, - StreamExt as _, + future::{self, BoxFuture, Fuse}, + FutureExt as _, StreamExt as _, }; use sequencer_client::{ - tendermint::block::Height, - HttpClient, - LatestHeightStream, - StreamLatestHeight as _, + tendermint::block::Height, HttpClient, LatestHeightStream, StreamLatestHeight as _, }; use tokio::select; use tokio_util::sync::CancellationToken; -use tracing::{ - debug, - error, - info, - trace, - warn, -}; +use tracing::{debug, error, info, trace, warn}; use crate::{ block_cache::BlockCache, - executor::{ - self, - SoftSendError, - SoftTrySendError, - StateIsInit, - }, + executor::{self, SoftSendError, SoftTrySendError, StateIsInit}, sequencer::block_stream::BlocksFromHeightStream, }; @@ -250,9 +226,7 @@ impl RunningReader { fn send_to_executor(&mut self, block: FilteredSequencerBlock) -> eyre::Result<()> { if let Err(err) = self.executor.try_send_soft_block(block) { match err { - SoftTrySendError::Channel { - source, - } => match *source { + SoftTrySendError::Channel { source } => match *source { executor::channel::TrySendError::Closed(_) => { bail!("could not send block to executor because its channel was closed"); } diff --git a/crates/astria-conductor/src/sequencer/reporting.rs b/crates/astria-conductor/src/sequencer/reporting.rs index 285d109a0..610630aa3 100644 --- a/crates/astria-conductor/src/sequencer/reporting.rs +++ b/crates/astria-conductor/src/sequencer/reporting.rs @@ -1,16 +1,9 @@ use astria_core::{ primitive::v1::RollupId, - sequencerblock::v1alpha1::block::{ - FilteredSequencerBlock, - RollupTransactions, - }, + sequencerblock::v1alpha1::block::{FilteredSequencerBlock, RollupTransactions}, }; use indexmap::IndexMap; -use serde::ser::{ - Serialize, - SerializeMap as _, - SerializeStruct as _, -}; +use serde::ser::{Serialize, SerializeMap as _, SerializeStruct as _}; pub(super) struct ReportFilteredSequencerBlock<'a>(pub(super) &'a FilteredSequencerBlock); impl<'a> Serialize for ReportFilteredSequencerBlock<'a> { @@ -43,16 +36,12 @@ impl<'a> Serialize for ReportRollups<'a> { #[cfg(test)] mod tests { use astria_core::{ - primitive::v1::RollupId, - protocol::test_utils::ConfigureSequencerBlock, + primitive::v1::RollupId, protocol::test_utils::ConfigureSequencerBlock, sequencerblock::v1alpha1::block::FilteredSequencerBlock, }; use insta::assert_json_snapshot; - use crate::sequencer::reporting::{ - ReportFilteredSequencerBlock, - ReportRollups, - }; + use crate::sequencer::reporting::{ReportFilteredSequencerBlock, ReportRollups}; const ROLLUP_42: RollupId = RollupId::new([42u8; 32]); const ROLLUP_69: RollupId = RollupId::new([69u8; 32]); diff --git a/crates/astria-conductor/src/utils.rs b/crates/astria-conductor/src/utils.rs index efd49c60e..150752771 100644 --- a/crates/astria-conductor/src/utils.rs +++ b/crates/astria-conductor/src/utils.rs @@ -1,7 +1,4 @@ -use astria_eyre::eyre::{ - self, - WrapErr as _, -}; +use astria_eyre::eyre::{self, WrapErr as _}; use tokio::task::JoinError; pub(crate) fn flatten(res: Result, JoinError>) -> eyre::Result { diff --git a/crates/astria-conductor/tests/blackbox/firm_only.rs b/crates/astria-conductor/tests/blackbox/firm_only.rs index 51cf03db5..4c700a55b 100644 --- a/crates/astria-conductor/tests/blackbox/firm_only.rs +++ b/crates/astria-conductor/tests/blackbox/firm_only.rs @@ -1,22 +1,13 @@ use std::time::Duration; use astria_conductor::config::CommitLevel; -use futures::future::{ - join, - join4, -}; +use futures::future::{join, join4}; use tokio::time::timeout; use crate::{ - helpers::spawn_conductor, - mount_celestia_blobs, - mount_celestia_header_network_head, - mount_executed_block, - mount_get_commitment_state, - mount_get_genesis_info, - mount_sequencer_commit, - mount_sequencer_genesis, - mount_sequencer_validator_set, + helpers::spawn_conductor, mount_celestia_blobs, mount_celestia_header_network_head, + mount_executed_block, mount_get_commitment_state, mount_get_genesis_info, + mount_sequencer_commit, mount_sequencer_genesis, mount_sequencer_validator_set, mount_update_commitment_state, }; diff --git a/crates/astria-conductor/tests/blackbox/helpers/macros.rs b/crates/astria-conductor/tests/blackbox/helpers/macros.rs index 4f6779c7d..cd307c2bf 100644 --- a/crates/astria-conductor/tests/blackbox/helpers/macros.rs +++ b/crates/astria-conductor/tests/blackbox/helpers/macros.rs @@ -19,10 +19,7 @@ macro_rules! celestia_network_head { ::celestia_types::ExtendedHeader { header: ::celestia_tendermint::block::header::Header { height: $height.into(), - version: ::celestia_tendermint::block::header::Version { - block: 0, - app: 0, - }, + version: ::celestia_tendermint::block::header::Version { block: 0, app: 0 }, chain_id: "test_celestia-1000".try_into().unwrap(), time: ::celestia_tendermint::Time::from_unix_timestamp(1, 1).unwrap(), last_block_id: None, diff --git a/crates/astria-conductor/tests/blackbox/helpers/mock_grpc.rs b/crates/astria-conductor/tests/blackbox/helpers/mock_grpc.rs index f9f857f4b..86140973b 100644 --- a/crates/astria-conductor/tests/blackbox/helpers/mock_grpc.rs +++ b/crates/astria-conductor/tests/blackbox/helpers/mock_grpc.rs @@ -1,49 +1,22 @@ -use std::{ - net::SocketAddr, - sync::Arc, -}; +use std::{net::SocketAddr, sync::Arc}; use astria_core::generated::{ execution::v1alpha2::{ - execution_service_server::{ - ExecutionService, - ExecutionServiceServer, - }, - BatchGetBlocksRequest, - BatchGetBlocksResponse, - Block, - CommitmentState, - ExecuteBlockRequest, - GenesisInfo, - GetBlockRequest, - GetCommitmentStateRequest, - GetGenesisInfoRequest, + execution_service_server::{ExecutionService, ExecutionServiceServer}, + BatchGetBlocksRequest, BatchGetBlocksResponse, Block, CommitmentState, ExecuteBlockRequest, + GenesisInfo, GetBlockRequest, GetCommitmentStateRequest, GetGenesisInfoRequest, UpdateCommitmentStateRequest, }, sequencerblock::v1alpha1::{ - sequencer_service_server::{ - SequencerService, - SequencerServiceServer, - }, - FilteredSequencerBlock, - GetFilteredSequencerBlockRequest, - GetPendingNonceRequest, - GetPendingNonceResponse, - GetSequencerBlockRequest, - SequencerBlock, + sequencer_service_server::{SequencerService, SequencerServiceServer}, + FilteredSequencerBlock, GetFilteredSequencerBlockRequest, GetPendingNonceRequest, + GetPendingNonceResponse, GetSequencerBlockRequest, SequencerBlock, }, }; -use astria_eyre::eyre::{ - self, - WrapErr as _, -}; +use astria_eyre::eyre::{self, WrapErr as _}; use astria_grpc_mock::MockServer; use tokio::task::JoinHandle; -use tonic::{ - transport::Server, - Request, - Response, -}; +use tonic::{transport::Server, Request, Response}; pub struct MockGrpc { pub _server: JoinHandle>, @@ -86,9 +59,7 @@ struct SequencerServiceImpl { impl SequencerServiceImpl { fn new(mock_server: MockServer) -> Self { - Self { - mock_server, - } + Self { mock_server } } } diff --git a/crates/astria-conductor/tests/blackbox/helpers/mod.rs b/crates/astria-conductor/tests/blackbox/helpers/mod.rs index 66f415c2b..2e8acbc55 100644 --- a/crates/astria-conductor/tests/blackbox/helpers/mod.rs +++ b/crates/astria-conductor/tests/blackbox/helpers/mod.rs @@ -1,35 +1,19 @@ use std::time::Duration; -use astria_conductor::{ - conductor, - config::CommitLevel, - Conductor, - Config, -}; +use astria_conductor::{conductor, config::CommitLevel, Conductor, Config}; use astria_core::{ brotli::compress_bytes, generated::{ - execution::v1alpha2::{ - Block, - CommitmentState, - GenesisInfo, - }, + execution::v1alpha2::{Block, CommitmentState, GenesisInfo}, sequencerblock::v1alpha1::FilteredSequencerBlock, }, primitive::v1::RollupId, }; use bytes::Bytes; -use celestia_types::{ - nmt::Namespace, - Blob, -}; +use celestia_types::{nmt::Namespace, Blob}; use once_cell::sync::Lazy; use prost::Message; -use sequencer_client::{ - tendermint, - tendermint_proto, - tendermint_rpc, -}; +use sequencer_client::{tendermint, tendermint_proto, tendermint_rpc}; #[macro_use] mod macros; @@ -123,11 +107,7 @@ impl Drop for TestConductor { impl TestConductor { pub async fn mount_abci_info(&self, latest_block_height: u32) { - use wiremock::{ - matchers::body_partial_json, - Mock, - ResponseTemplate, - }; + use wiremock::{matchers::body_partial_json, Mock, ResponseTemplate}; Mock::given(body_partial_json( json!({"jsonrpc": "2.0", "method": "abci_info", "params": null}), )) @@ -154,9 +134,7 @@ impl TestConductor { block: astria_core::generated::execution::v1alpha2::Block, ) { use astria_grpc_mock::{ - matcher::message_partial_pbjson, - response::constant_response, - Mock, + matcher::message_partial_pbjson, response::constant_response, Mock, }; Mock::for_rpc_given("get_block", message_partial_pbjson(&expected_pbjson)) .respond_with(constant_response(block)) @@ -173,13 +151,8 @@ impl TestConductor { ) { use base64::prelude::*; use wiremock::{ - matchers::{ - body_partial_json, - header, - }, - Mock, - Request, - ResponseTemplate, + matchers::{body_partial_json, header}, + Mock, Request, ResponseTemplate, }; let namespace_params = BASE64_STANDARD.encode(namespace.as_bytes()); Mock::given(body_partial_json(json!({ @@ -210,12 +183,8 @@ impl TestConductor { extended_header: celestia_types::ExtendedHeader, ) { use wiremock::{ - matchers::{ - body_partial_json, - header, - }, - Mock, - ResponseTemplate, + matchers::{body_partial_json, header}, + Mock, ResponseTemplate, }; Mock::given(body_partial_json( json!({"jsonrpc": "2.0", "method": "header.NetworkHead"}), @@ -238,11 +207,7 @@ impl TestConductor { &self, signed_header: tendermint::block::signed_header::SignedHeader, ) { - use wiremock::{ - matchers::body_partial_json, - Mock, - ResponseTemplate, - }; + use wiremock::{matchers::body_partial_json, Mock, ResponseTemplate}; Mock::given(body_partial_json(json!({ "jsonrpc": "2.0", "method": "commit", @@ -267,20 +232,13 @@ impl TestConductor { pub async fn mount_genesis(&self) { use tendermint::{ consensus::{ - params::{ - AbciParams, - ValidatorParams, - }, + params::{AbciParams, ValidatorParams}, Params, }, genesis::Genesis, time::Time, }; - use wiremock::{ - matchers::body_partial_json, - Mock, - ResponseTemplate, - }; + use wiremock::{matchers::body_partial_json, Mock, ResponseTemplate}; Mock::given(body_partial_json( json!({"jsonrpc": "2.0", "method": "genesis", "params": null}), )) @@ -360,9 +318,7 @@ impl TestConductor { response: Block, ) -> astria_grpc_mock::MockGuard { use astria_grpc_mock::{ - matcher::message_partial_pbjson, - response::constant_response, - Mock, + matcher::message_partial_pbjson, response::constant_response, Mock, }; let mut mock = Mock::for_rpc_given("execute_block", message_partial_pbjson(&expected_pbjson)) @@ -381,9 +337,7 @@ impl TestConductor { response: FilteredSequencerBlock, ) { use astria_grpc_mock::{ - matcher::message_partial_pbjson, - response::constant_response, - Mock, + matcher::message_partial_pbjson, response::constant_response, Mock, }; Mock::for_rpc_given( "get_filtered_sequencer_block", @@ -402,9 +356,7 @@ impl TestConductor { ) -> astria_grpc_mock::MockGuard { use astria_core::generated::execution::v1alpha2::UpdateCommitmentStateRequest; use astria_grpc_mock::{ - matcher::message_partial_pbjson, - response::constant_response, - Mock, + matcher::message_partial_pbjson, response::constant_response, Mock, }; let mut mock = Mock::for_rpc_given( "update_commitment_state", @@ -425,11 +377,7 @@ impl TestConductor { &self, validator_set: tendermint_rpc::endpoint::validators::Response, ) { - use wiremock::{ - matchers::body_partial_json, - Mock, - ResponseTemplate, - }; + use wiremock::{matchers::body_partial_json, Mock, ResponseTemplate}; Mock::given(body_partial_json(json!({ "jsonrpc": "2.0", "method": "validators", @@ -504,8 +452,7 @@ pub struct Blobs { #[must_use] pub fn make_blobs(heights: &[u32]) -> Blobs { use astria_core::generated::sequencerblock::v1alpha1::{ - SubmittedMetadataList, - SubmittedRollupDataList, + SubmittedMetadataList, SubmittedRollupDataList, }; let mut metadata = Vec::new(); let mut rollup_data = Vec::new(); @@ -519,9 +466,7 @@ pub fn make_blobs(heights: &[u32]) -> Blobs { ); rollup_data.push(tail.swap_remove(0).into_raw()); } - let header_list = SubmittedMetadataList { - entries: metadata, - }; + let header_list = SubmittedMetadataList { entries: metadata }; let rollup_data_list = SubmittedRollupDataList { entries: rollup_data, }; @@ -534,17 +479,11 @@ pub fn make_blobs(heights: &[u32]) -> Blobs { let rollup_data_list_compressed = compress_bytes(&raw_rollup_data_list).unwrap(); let rollup = Blob::new(rollup_namespace(), rollup_data_list_compressed).unwrap(); - Blobs { - header, - rollup, - } + Blobs { header, rollup } } fn signing_key() -> astria_core::crypto::SigningKey { - use rand_chacha::{ - rand_core::SeedableRng as _, - ChaChaRng, - }; + use rand_chacha::{rand_core::SeedableRng as _, ChaChaRng}; astria_core::crypto::SigningKey::new(ChaChaRng::seed_from_u64(0)) } @@ -608,10 +547,7 @@ pub fn make_commit(height: u32) -> tendermint::block::Commit { pub fn make_signed_header(height: u32) -> tendermint::block::signed_header::SignedHeader { tendermint::block::signed_header::SignedHeader::new( tendermint::block::Header { - version: tendermint::block::header::Version { - block: 1, - app: 1, - }, + version: tendermint::block::header::Version { block: 1, app: 1 }, chain_id: crate::SEQUENCER_CHAIN_ID.try_into().unwrap(), height: height.into(), time: tendermint::time::Time::from_unix_timestamp(1, 1).unwrap(), diff --git a/crates/astria-conductor/tests/blackbox/main.rs b/crates/astria-conductor/tests/blackbox/main.rs index ad73c9344..3cef4d228 100644 --- a/crates/astria-conductor/tests/blackbox/main.rs +++ b/crates/astria-conductor/tests/blackbox/main.rs @@ -6,9 +6,4 @@ pub mod shutdown; pub mod soft_and_firm; pub mod soft_only; -use helpers::{ - rollup_namespace, - sequencer_namespace, - ROLLUP_ID, - SEQUENCER_CHAIN_ID, -}; +use helpers::{rollup_namespace, sequencer_namespace, ROLLUP_ID, SEQUENCER_CHAIN_ID}; diff --git a/crates/astria-conductor/tests/blackbox/soft_and_firm.rs b/crates/astria-conductor/tests/blackbox/soft_and_firm.rs index 0dacd4af5..1539676ab 100644 --- a/crates/astria-conductor/tests/blackbox/soft_and_firm.rs +++ b/crates/astria-conductor/tests/blackbox/soft_and_firm.rs @@ -1,25 +1,14 @@ use std::time::Duration; use astria_conductor::config::CommitLevel; -use futures::future::{ - join, - join3, -}; +use futures::future::{join, join3}; use tokio::time::timeout; use crate::{ - helpers::spawn_conductor, - mount_abci_info, - mount_celestia_blobs, - mount_celestia_header_network_head, - mount_executed_block, - mount_get_block, - mount_get_commitment_state, - mount_get_filtered_sequencer_block, - mount_get_genesis_info, - mount_sequencer_commit, - mount_sequencer_genesis, - mount_sequencer_validator_set, + helpers::spawn_conductor, mount_abci_info, mount_celestia_blobs, + mount_celestia_header_network_head, mount_executed_block, mount_get_block, + mount_get_commitment_state, mount_get_filtered_sequencer_block, mount_get_genesis_info, + mount_sequencer_commit, mount_sequencer_genesis, mount_sequencer_validator_set, mount_update_commitment_state, }; diff --git a/crates/astria-conductor/tests/blackbox/soft_only.rs b/crates/astria-conductor/tests/blackbox/soft_only.rs index 4795979f2..985249ae9 100644 --- a/crates/astria-conductor/tests/blackbox/soft_only.rs +++ b/crates/astria-conductor/tests/blackbox/soft_only.rs @@ -1,20 +1,12 @@ use std::time::Duration; use astria_conductor::config::CommitLevel; -use futures::future::{ - join, - join4, -}; +use futures::future::{join, join4}; use tokio::time::timeout; use crate::{ - helpers::spawn_conductor, - mount_abci_info, - mount_executed_block, - mount_get_commitment_state, - mount_get_filtered_sequencer_block, - mount_get_genesis_info, - mount_update_commitment_state, + helpers::spawn_conductor, mount_abci_info, mount_executed_block, mount_get_commitment_state, + mount_get_filtered_sequencer_block, mount_get_genesis_info, mount_update_commitment_state, }; #[tokio::test(flavor = "multi_thread", worker_threads = 1)] diff --git a/crates/astria-config/src/lib.rs b/crates/astria-config/src/lib.rs index 86b488ae8..1f6f8cfdd 100644 --- a/crates/astria-config/src/lib.rs +++ b/crates/astria-config/src/lib.rs @@ -69,9 +69,7 @@ impl std::error::Error for Error { impl From for Error { fn from(inner: figment::Error) -> Self { - Self { - inner, - } + Self { inner } } } @@ -128,10 +126,7 @@ pub trait Config: ::core::fmt::Debug + DeserializeOwned { prefix: &str, _internal: _internal::Internal, ) -> Result { - use figment::{ - providers::Env as FigmentEnv, - Figment, - }; + use figment::{providers::Env as FigmentEnv, Figment}; Figment::new() .merge(FigmentEnv::prefixed("RUST_").split("_").only(&["log"])) .merge(FigmentEnv::prefixed(prefix)) diff --git a/crates/astria-config/src/tests.rs b/crates/astria-config/src/tests.rs index 6411f4881..df3c3a1c5 100644 --- a/crates/astria-config/src/tests.rs +++ b/crates/astria-config/src/tests.rs @@ -33,16 +33,10 @@ use figment::Jail; use once_cell::sync::Lazy; use regex::Regex; -use crate::{ - Config, - _internal, -}; +use crate::{Config, _internal}; static TEST_PREFIX: Lazy = Lazy::new(|| { - use names::{ - Generator, - Name, - }; + use names::{Generator, Name}; Generator::with_naming(Name::Numbered).next().unwrap() }); diff --git a/crates/astria-core/src/brotli.rs b/crates/astria-core/src/brotli.rs index 211e75bc4..5961241c5 100644 --- a/crates/astria-core/src/brotli.rs +++ b/crates/astria-core/src/brotli.rs @@ -1,10 +1,6 @@ use std::io::Write as _; -use brotli::{ - enc::BrotliEncoderParams, - CompressorWriter, - DecompressorWriter, -}; +use brotli::{enc::BrotliEncoderParams, CompressorWriter, DecompressorWriter}; const BROTLI_BUFFER_SIZE: usize = 4096; diff --git a/crates/astria-core/src/celestia.rs b/crates/astria-core/src/celestia.rs index 9fc448c52..22f3179f3 100644 --- a/crates/astria-core/src/celestia.rs +++ b/crates/astria-core/src/celestia.rs @@ -28,9 +28,6 @@ pub const fn namespace_v0_from_rollup_id(rollup_id: crate::primitive::v1::Rollup /// `bytes`. #[must_use = "a celestia namespace must be used in order to be useful"] pub fn namespace_v0_from_sha256_of_bytes>(bytes: T) -> Namespace { - use sha2::{ - Digest as _, - Sha256, - }; + use sha2::{Digest as _, Sha256}; namespace_v0_from_first_10_bytes(&Sha256::digest(bytes)) } diff --git a/crates/astria-core/src/crypto.rs b/crates/astria-core/src/crypto.rs index 2c1b6a98e..35e8674e6 100644 --- a/crates/astria-core/src/crypto.rs +++ b/crates/astria-core/src/crypto.rs @@ -1,46 +1,20 @@ use std::{ cmp::Ordering, - fmt::{ - self, - Debug, - Display, - Formatter, - }, - hash::{ - Hash, - Hasher, - }, + fmt::{self, Debug, Display, Formatter}, + hash::{Hash, Hasher}, sync::OnceLock, }; -use base64::{ - display::Base64Display, - prelude::BASE64_STANDARD, - Engine, -}; +use base64::{display::Base64Display, prelude::BASE64_STANDARD, Engine}; use ed25519_consensus::{ - Error as Ed25519Error, - Signature as Ed25519Signature, - SigningKey as Ed25519SigningKey, + Error as Ed25519Error, Signature as Ed25519Signature, SigningKey as Ed25519SigningKey, VerificationKey as Ed25519VerificationKey, }; -use rand::{ - CryptoRng, - RngCore, -}; -use sha2::{ - Digest as _, - Sha256, -}; -use zeroize::{ - Zeroize, - ZeroizeOnDrop, -}; +use rand::{CryptoRng, RngCore}; +use sha2::{Digest as _, Sha256}; +use zeroize::{Zeroize, ZeroizeOnDrop}; -use crate::primitive::v1::{ - Address, - ADDRESS_LEN, -}; +use crate::primitive::v1::{Address, ADDRESS_LEN}; /// An Ed25519 signing key. // *Implementation note*: this is currently a refinement type around diff --git a/crates/astria-core/src/execution/v1alpha2/mod.rs b/crates/astria-core/src/execution/v1alpha2/mod.rs index 9e646cf14..ef7131a97 100644 --- a/crates/astria-core/src/execution/v1alpha2/mod.rs +++ b/crates/astria-core/src/execution/v1alpha2/mod.rs @@ -3,10 +3,7 @@ use pbjson_types::Timestamp; use crate::{ generated::execution::v1alpha2 as raw, - primitive::v1::{ - IncorrectRollupIdLength, - RollupId, - }, + primitive::v1::{IncorrectRollupIdLength, RollupId}, Protobuf, }; @@ -323,11 +320,7 @@ impl CommitmentStateBuilder CommitmentStateBuilder { - let Self { - firm, - soft, - .. - } = self; + let Self { firm, soft, .. } = self; CommitmentStateBuilder { firm, soft, diff --git a/crates/astria-core/src/primitive/v1/asset.rs b/crates/astria-core/src/primitive/v1/asset.rs index 3415d8ec8..31cdad242 100644 --- a/crates/astria-core/src/primitive/v1/asset.rs +++ b/crates/astria-core/src/primitive/v1/asset.rs @@ -1,9 +1,6 @@ use std::{ fmt, - fmt::{ - Display, - Formatter, - }, + fmt::{Display, Formatter}, }; /// The default sequencer asset base denomination. @@ -175,10 +172,7 @@ impl AsRef<[u8]> for Id { impl Display for Id { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - use base64::{ - display::Base64Display, - prelude::BASE64_STANDARD, - }; + use base64::{display::Base64Display, prelude::BASE64_STANDARD}; Base64Display::new(self.as_ref(), &BASE64_STANDARD).fmt(f) } } diff --git a/crates/astria-core/src/primitive/v1/mod.rs b/crates/astria-core/src/primitive/v1/mod.rs index 944d6e40b..1077d2f94 100644 --- a/crates/astria-core/src/primitive/v1/mod.rs +++ b/crates/astria-core/src/primitive/v1/mod.rs @@ -1,19 +1,10 @@ pub mod asset; pub mod u128; -use base64::{ - display::Base64Display, - prelude::BASE64_STANDARD, -}; -use sha2::{ - Digest as _, - Sha256, -}; - -use crate::{ - generated::primitive::v1 as raw, - Protobuf, -}; +use base64::{display::Base64Display, prelude::BASE64_STANDARD}; +use sha2::{Digest as _, Sha256}; + +use crate::{generated::primitive::v1 as raw, Protobuf}; pub const ADDRESS_LEN: usize = 20; pub const ROLLUP_ID_LEN: usize = 32; @@ -100,9 +91,7 @@ impl RollupId { /// ``` #[must_use] pub const fn new(inner: [u8; ROLLUP_ID_LEN]) -> Self { - Self { - inner, - } + Self { inner } } /// Returns the 32 bytes array representing the rollup ID. @@ -211,17 +200,13 @@ impl AsRef<[u8]> for RollupId { impl From<[u8; ROLLUP_ID_LEN]> for RollupId { fn from(inner: [u8; ROLLUP_ID_LEN]) -> Self { - Self { - inner, - } + Self { inner } } } impl From<&[u8; ROLLUP_ID_LEN]> for RollupId { fn from(inner: &[u8; ROLLUP_ID_LEN]) -> Self { - Self { - inner: *inner, - } + Self { inner: *inner } } } @@ -349,10 +334,7 @@ where mod tests { use insta::assert_json_snapshot; - use super::{ - Address, - IncorrectAddressLength, - }; + use super::{Address, IncorrectAddressLength}; #[test] fn account_of_20_bytes_is_converted_correctly() { diff --git a/crates/astria-core/src/primitive/v1/u128.rs b/crates/astria-core/src/primitive/v1/u128.rs index fbfb4208b..87439e916 100644 --- a/crates/astria-core/src/primitive/v1/u128.rs +++ b/crates/astria-core/src/primitive/v1/u128.rs @@ -3,30 +3,11 @@ use crate::generated::primitive::v1::Uint128; impl From for Uint128 { fn from(primitive: u128) -> Self { - let [ - h0, - h1, - h2, - h3, - h4, - h5, - h6, - h7, - l0, - l1, - l2, - l3, - l4, - l5, - l6, - l7, - ] = primitive.to_be_bytes(); + let [h0, h1, h2, h3, h4, h5, h6, h7, l0, l1, l2, l3, l4, l5, l6, l7] = + primitive.to_be_bytes(); let lo = u64::from_be_bytes([l0, l1, l2, l3, l4, l5, l6, l7]); let hi = u64::from_be_bytes([h0, h1, h2, h3, h4, h5, h6, h7]); - Self { - lo, - hi, - } + Self { lo, hi } } } diff --git a/crates/astria-core/src/protocol/abci.rs b/crates/astria-core/src/protocol/abci.rs index 76c7bc8c8..7e4694238 100644 --- a/crates/astria-core/src/protocol/abci.rs +++ b/crates/astria-core/src/protocol/abci.rs @@ -1,7 +1,4 @@ -use std::{ - borrow::Cow, - num::NonZeroU32, -}; +use std::{borrow::Cow, num::NonZeroU32}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[allow(clippy::module_name_repetitions)] diff --git a/crates/astria-core/src/protocol/account/v1alpha1/mod.rs b/crates/astria-core/src/protocol/account/v1alpha1/mod.rs index 90d6af3d6..1fe51975e 100644 --- a/crates/astria-core/src/protocol/account/v1alpha1/mod.rs +++ b/crates/astria-core/src/protocol/account/v1alpha1/mod.rs @@ -12,10 +12,7 @@ impl AssetBalance { /// native [`AssetBalance`]. #[must_use] pub fn from_raw(proto: &raw::AssetBalance) -> Self { - let raw::AssetBalance { - denom, - balance, - } = proto; + let raw::AssetBalance { denom, balance } = proto; Self { denom: Denom::from(denom.to_owned()), balance: balance.map_or(0, Into::into), @@ -38,10 +35,7 @@ impl raw::BalanceResponse { /// protobuf [`raw::BalanceResponse`]. #[must_use] pub fn from_native(native: BalanceResponse) -> Self { - let BalanceResponse { - height, - balances, - } = native; + let BalanceResponse { height, balances } = native; Self { height, balances: balances.into_iter().map(AssetBalance::into_raw).collect(), @@ -74,10 +68,7 @@ impl BalanceResponse { /// Converts a protobuf [`raw::BalanceResponse`] to an astria /// native [`BalanceResponse`]. pub fn from_raw(proto: &raw::BalanceResponse) -> Self { - let raw::BalanceResponse { - height, - balances, - } = proto; + let raw::BalanceResponse { height, balances } = proto; Self { height: *height, balances: balances.iter().map(AssetBalance::from_raw).collect(), @@ -97,14 +88,8 @@ impl raw::NonceResponse { /// astria `NonceResponse`. #[must_use] pub fn from_native(native: NonceResponse) -> Self { - let NonceResponse { - height, - nonce, - } = native; - Self { - height, - nonce, - } + let NonceResponse { height, nonce } = native; + Self { height, nonce } } /// Converts a protobuf [`raw::NonceResponse`] to an astria @@ -134,14 +119,8 @@ impl NonceResponse { /// native [`NonceResponse`]. #[must_use] pub fn from_raw(proto: &raw::NonceResponse) -> Self { - let raw::NonceResponse { - height, - nonce, - } = *proto; - Self { - height, - nonce, - } + let raw::NonceResponse { height, nonce } = *proto; + Self { height, nonce } } /// Converts an astria native [`NonceResponse`] to a @@ -154,11 +133,7 @@ impl NonceResponse { #[cfg(test)] mod tests { - use super::{ - AssetBalance, - BalanceResponse, - NonceResponse, - }; + use super::{AssetBalance, BalanceResponse, NonceResponse}; #[test] fn balance_roundtrip_is_correct() { diff --git a/crates/astria-core/src/protocol/asset/v1alpha1/mod.rs b/crates/astria-core/src/protocol/asset/v1alpha1/mod.rs index 9c0fb48c5..a9f6f3df3 100644 --- a/crates/astria-core/src/protocol/asset/v1alpha1/mod.rs +++ b/crates/astria-core/src/protocol/asset/v1alpha1/mod.rs @@ -13,10 +13,7 @@ impl DenomResponse { /// native [`DenomResponse`]. #[must_use] pub fn from_raw(proto: &raw::DenomResponse) -> Self { - let raw::DenomResponse { - height, - denom, - } = proto; + let raw::DenomResponse { height, denom } = proto; Self { height: *height, denom: denom.clone().into(), @@ -36,10 +33,7 @@ impl raw::DenomResponse { /// protobuf [`raw::DenomResponse`]. #[must_use] pub fn from_native(native: DenomResponse) -> Self { - let DenomResponse { - height, - denom, - } = native; + let DenomResponse { height, denom } = native; Self { height, denom: denom.to_string(), diff --git a/crates/astria-core/src/protocol/test_utils.rs b/crates/astria-core/src/protocol/test_utils.rs index 4fa099e20..5d13dcdb0 100644 --- a/crates/astria-core/src/protocol/test_utils.rs +++ b/crates/astria-core/src/protocol/test_utils.rs @@ -6,23 +6,12 @@ use prost::Message as _; use super::{ group_sequence_actions_in_signed_transaction_transactions_by_rollup_id, - transaction::v1alpha1::{ - action::SequenceAction, - TransactionParams, - UnsignedTransaction, - }, + transaction::v1alpha1::{action::SequenceAction, TransactionParams, UnsignedTransaction}, }; use crate::{ crypto::SigningKey, - primitive::v1::{ - asset::default_native_asset_id, - derive_merkle_tree_from_rollup_txs, - RollupId, - }, - sequencerblock::v1alpha1::{ - block::Deposit, - SequencerBlock, - }, + primitive::v1::{asset::default_native_asset_id, derive_merkle_tree_from_rollup_txs, RollupId}, + sequencerblock::v1alpha1::{block::Deposit, SequencerBlock}, }; #[derive(Default)] @@ -64,8 +53,7 @@ impl ConfigureSequencerBlock { use tendermint::Time; use crate::{ - protocol::transaction::v1alpha1::Action, - sequencerblock::v1alpha1::block::RollupData, + protocol::transaction::v1alpha1::Action, sequencerblock::v1alpha1::block::RollupData, }; let Self { diff --git a/crates/astria-core/src/protocol/transaction/v1alpha1/action.rs b/crates/astria-core/src/protocol/transaction/v1alpha1/action.rs index 04034202a..79c5e5737 100644 --- a/crates/astria-core/src/protocol/transaction/v1alpha1/action.rs +++ b/crates/astria-core/src/protocol/transaction/v1alpha1/action.rs @@ -1,8 +1,5 @@ use ibc_types::{ - core::{ - channel::ChannelId, - client::Height as IbcHeight, - }, + core::{channel::ChannelId, client::Height as IbcHeight}, IdentifierError, }; use penumbra_ibc::IbcRelay; @@ -11,14 +8,8 @@ use penumbra_proto::penumbra::core::component::ibc::v1::FungibleTokenPacketData; use super::raw; use crate::{ primitive::v1::{ - asset::{ - self, - Denom, - }, - Address, - IncorrectAddressLength, - IncorrectRollupIdLength, - RollupId, + asset::{self, Denom}, + Address, IncorrectAddressLength, IncorrectRollupIdLength, RollupId, }, Protobuf, }; @@ -57,9 +48,7 @@ impl Action { Action::BridgeUnlock(act) => Value::BridgeUnlockAction(act.into_raw()), Action::FeeChange(act) => Value::FeeChangeAction(act.into_raw()), }; - raw::Action { - value: Some(kind), - } + raw::Action { value: Some(kind) } } #[must_use] @@ -81,9 +70,7 @@ impl Action { Action::BridgeUnlock(act) => Value::BridgeUnlockAction(act.to_raw()), Action::FeeChange(act) => Value::FeeChangeAction(act.to_raw()), }; - raw::Action { - value: Some(kind), - } + raw::Action { value: Some(kind) } } /// Attempt to convert from a raw, unchecked protobuf [`raw::Action`]. @@ -94,9 +81,7 @@ impl Action { /// to a native action ([`SequenceAction`] or [`TransferAction`]) fails. pub fn try_from_raw(proto: raw::Action) -> Result { use raw::action::Value; - let raw::Action { - value, - } = proto; + let raw::Action { value } = proto; let Some(action) = value else { return Err(ActionError::unset()); }; @@ -526,9 +511,7 @@ pub struct SudoAddressChangeAction { impl SudoAddressChangeAction { #[must_use] pub fn into_raw(self) -> raw::SudoAddressChangeAction { - let Self { - new_address, - } = self; + let Self { new_address } = self; raw::SudoAddressChangeAction { new_address: Some(new_address.into_raw()), } @@ -536,9 +519,7 @@ impl SudoAddressChangeAction { #[must_use] pub fn to_raw(&self) -> raw::SudoAddressChangeAction { - let Self { - new_address, - } = self; + let Self { new_address } = self; raw::SudoAddressChangeAction { new_address: Some(new_address.to_raw()), } @@ -553,17 +534,13 @@ impl SudoAddressChangeAction { pub fn try_from_raw( proto: raw::SudoAddressChangeAction, ) -> Result { - let raw::SudoAddressChangeAction { - new_address, - } = proto; + let raw::SudoAddressChangeAction { new_address } = proto; let Some(new_address) = new_address else { return Err(SudoAddressChangeActionError::field_not_set("new_address")); }; let new_address = Address::try_from_raw(&new_address).map_err(SudoAddressChangeActionError::address)?; - Ok(Self { - new_address, - }) + Ok(Self { new_address }) } } diff --git a/crates/astria-core/src/protocol/transaction/v1alpha1/mod.rs b/crates/astria-core/src/protocol/transaction/v1alpha1/mod.rs index 25a0d5dcb..4c87ba8ff 100644 --- a/crates/astria-core/src/protocol/transaction/v1alpha1/mod.rs +++ b/crates/astria-core/src/protocol/transaction/v1alpha1/mod.rs @@ -1,15 +1,7 @@ -use prost::{ - Message as _, - Name as _, -}; +use prost::{Message as _, Name as _}; use super::raw; -use crate::crypto::{ - self, - Signature, - SigningKey, - VerificationKey, -}; +use crate::crypto::{self, Signature, SigningKey, VerificationKey}; pub mod action; pub use action::Action; @@ -82,10 +74,7 @@ impl SignedTransaction { /// and hashing the resulting bytes with sha256. #[must_use] pub fn sha256_of_proto_encoding(&self) -> [u8; 32] { - use sha2::{ - Digest as _, - Sha256, - }; + use sha2::{Digest as _, Sha256}; let bytes = self.to_raw().encode_to_vec(); Sha256::digest(bytes).into() } @@ -231,10 +220,7 @@ impl UnsignedTransaction { } pub fn into_raw(self) -> raw::UnsignedTransaction { - let Self { - actions, - params, - } = self; + let Self { actions, params } = self; let actions = actions.into_iter().map(Action::into_raw).collect(); raw::UnsignedTransaction { actions, @@ -252,10 +238,7 @@ impl UnsignedTransaction { } pub fn to_raw(&self) -> raw::UnsignedTransaction { - let Self { - actions, - params, - } = self; + let Self { actions, params } = self; let actions = actions.iter().map(Action::to_raw).collect(); let params = params.clone().into_raw(); raw::UnsignedTransaction { @@ -276,10 +259,7 @@ impl UnsignedTransaction { /// Returns an error if one of the inner raw actions could not be converted to a native /// [`Action`]. pub fn try_from_raw(proto: raw::UnsignedTransaction) -> Result { - let raw::UnsignedTransaction { - actions, - params, - } = proto; + let raw::UnsignedTransaction { actions, params } = proto; let Some(params) = params else { return Err(UnsignedTransactionError::unset_params()); }; @@ -290,10 +270,7 @@ impl UnsignedTransaction { .collect::>() .map_err(UnsignedTransactionError::action)?; - Ok(Self { - actions, - params, - }) + Ok(Self { actions, params }) } /// Attempt to convert from a protobuf [`pbjson_types::Any`]. @@ -327,9 +304,7 @@ impl UnsignedTransactionError { } fn invalid_type_url(got: String) -> Self { - Self(UnsignedTransactionErrorKind::InvalidTypeUrl { - got, - }) + Self(UnsignedTransactionErrorKind::InvalidTypeUrl { got }) } fn decode_any(inner: prost::DecodeError) -> Self { @@ -366,27 +341,15 @@ pub struct TransactionParams { impl TransactionParams { #[must_use] pub fn into_raw(self) -> raw::TransactionParams { - let Self { - nonce, - chain_id, - } = self; - raw::TransactionParams { - nonce, - chain_id, - } + let Self { nonce, chain_id } = self; + raw::TransactionParams { nonce, chain_id } } /// Convert from a raw protobuf [`raw::UnsignedTransaction`]. #[must_use] pub fn from_raw(proto: raw::TransactionParams) -> Self { - let raw::TransactionParams { - nonce, - chain_id, - } = proto; - Self { - nonce, - chain_id, - } + let raw::TransactionParams { nonce, chain_id } = proto; + Self { nonce, chain_id } } } @@ -394,10 +357,7 @@ impl TransactionParams { mod test { use super::*; use crate::{ - primitive::v1::{ - asset::default_native_asset_id, - Address, - }, + primitive::v1::{asset::default_native_asset_id, Address}, protocol::transaction::v1alpha1::action::TransferAction, }; diff --git a/crates/astria-core/src/sequencerblock/v1alpha1/block.rs b/crates/astria-core/src/sequencerblock/v1alpha1/block.rs index 90ef2f9bf..9b402a05e 100644 --- a/crates/astria-core/src/sequencerblock/v1alpha1/block.rs +++ b/crates/astria-core/src/sequencerblock/v1alpha1/block.rs @@ -2,35 +2,19 @@ use std::collections::HashMap; use indexmap::IndexMap; use sha2::Sha256; -use tendermint::{ - account, - Time, -}; +use tendermint::{account, Time}; use super::{ - are_rollup_ids_included, - are_rollup_txs_included, - celestia::{ - self, - SubmittedMetadata, - SubmittedRollupData, - }, + are_rollup_ids_included, are_rollup_txs_included, + celestia::{self, SubmittedMetadata, SubmittedRollupData}, raw, }; use crate::{ primitive::v1::{ - asset, - derive_merkle_tree_from_rollup_txs, - Address, - IncorrectAddressLength, - IncorrectRollupIdLength, - RollupId, - }, - protocol::transaction::v1alpha1::{ - action, - SignedTransaction, - SignedTransactionError, + asset, derive_merkle_tree_from_rollup_txs, Address, IncorrectAddressLength, + IncorrectRollupIdLength, RollupId, }, + protocol::transaction::v1alpha1::{action, SignedTransaction, SignedTransactionError}, Protobuf as _, }; @@ -1224,11 +1208,7 @@ impl FilteredSequencerBlockError { } fn rollup_transaction_for_id_not_in_sequencer_block(id: RollupId) -> Self { - Self( - FilteredSequencerBlockErrorKind::RollupTransactionForIdNotInSequencerBlock { - id, - }, - ) + Self(FilteredSequencerBlockErrorKind::RollupTransactionForIdNotInSequencerBlock { id }) } fn rollup_ids_not_in_sequencer_block() -> Self { @@ -1442,9 +1422,7 @@ impl RollupData { /// - if the `data` field is not set /// - if the variant is `Deposit` but a `Deposit` cannot be constructed from the raw proto pub fn try_from_raw(raw: raw::RollupData) -> Result { - let raw::RollupData { - value, - } = raw; + let raw::RollupData { value } = raw; match value { Some(raw::rollup_data::Value::SequencedData(data)) => Ok(Self::SequencedData(data)), Some(raw::rollup_data::Value::Deposit(deposit)) => Deposit::try_from_raw(deposit) diff --git a/crates/astria-core/src/sequencerblock/v1alpha1/celestia.rs b/crates/astria-core/src/sequencerblock/v1alpha1/celestia.rs index 512ed4df2..e880e30d2 100644 --- a/crates/astria-core/src/sequencerblock/v1alpha1/celestia.rs +++ b/crates/astria-core/src/sequencerblock/v1alpha1/celestia.rs @@ -1,18 +1,10 @@ -use sha2::{ - Digest as _, - Sha256, -}; +use sha2::{Digest as _, Sha256}; use super::{ block::{ - RollupTransactionsParts, - SequencerBlock, - SequencerBlockHeader, - SequencerBlockHeaderError, + RollupTransactionsParts, SequencerBlock, SequencerBlockHeader, SequencerBlockHeaderError, }, - raw, - IncorrectRollupIdLength, - RollupId, + raw, IncorrectRollupIdLength, RollupId, }; use crate::Protobuf; @@ -58,10 +50,7 @@ impl PreparedBlock { proof, }); } - Self { - head, - tail, - } + Self { head, tail } } /// Returns the head and the tail of the split block, consuming it. @@ -81,25 +70,19 @@ pub struct SubmittedRollupDataError { impl SubmittedRollupDataError { fn field_not_set(field: &'static str) -> Self { Self { - kind: SubmittedRollupDataErrorKind::FieldNotSet { - field, - }, + kind: SubmittedRollupDataErrorKind::FieldNotSet { field }, } } fn rollup_id(source: IncorrectRollupIdLength) -> Self { Self { - kind: SubmittedRollupDataErrorKind::RollupId { - source, - }, + kind: SubmittedRollupDataErrorKind::RollupId { source }, } } fn proof(source: ::Error) -> Self { Self { - kind: SubmittedRollupDataErrorKind::Proof { - source, - }, + kind: SubmittedRollupDataErrorKind::Proof { source }, } } @@ -293,9 +276,7 @@ impl SubmittedMetadataError { fn header(source: SequencerBlockHeaderError) -> Self { Self { - kind: SubmittedMetadataErrorKind::Header { - source, - }, + kind: SubmittedMetadataErrorKind::Header { source }, } } @@ -307,25 +288,19 @@ impl SubmittedMetadataError { fn rollup_ids(source: IncorrectRollupIdLength) -> Self { Self { - kind: SubmittedMetadataErrorKind::RollupIds { - source, - }, + kind: SubmittedMetadataErrorKind::RollupIds { source }, } } fn rollup_transactions_proof(source: ::Error) -> Self { Self { - kind: SubmittedMetadataErrorKind::RollupTransactionsProof { - source, - }, + kind: SubmittedMetadataErrorKind::RollupTransactionsProof { source }, } } fn rollup_ids_proof(source: ::Error) -> Self { Self { - kind: SubmittedMetadataErrorKind::RollupIdsProof { - source, - }, + kind: SubmittedMetadataErrorKind::RollupIdsProof { source }, } } diff --git a/crates/astria-core/src/sequencerblock/v1alpha1/mod.rs b/crates/astria-core/src/sequencerblock/v1alpha1/mod.rs index 62487151c..22de5e548 100644 --- a/crates/astria-core/src/sequencerblock/v1alpha1/mod.rs +++ b/crates/astria-core/src/sequencerblock/v1alpha1/mod.rs @@ -1,27 +1,14 @@ pub mod block; pub mod celestia; -pub use block::{ - RollupTransactions, - SequencerBlock, -}; -pub use celestia::{ - SubmittedMetadata, - SubmittedRollupData, -}; +pub use block::{RollupTransactions, SequencerBlock}; +pub use celestia::{SubmittedMetadata, SubmittedRollupData}; use indexmap::IndexMap; -use sha2::{ - Digest as _, - Sha256, -}; +use sha2::{Digest as _, Sha256}; use crate::{ generated::sequencerblock::v1alpha1 as raw, - primitive::v1::{ - derive_merkle_tree_from_rollup_txs, - IncorrectRollupIdLength, - RollupId, - }, + primitive::v1::{derive_merkle_tree_from_rollup_txs, IncorrectRollupIdLength, RollupId}, }; pub(crate) fn are_rollup_ids_included<'a, TRollupIds: 'a>( diff --git a/crates/astria-eyre/src/lib.rs b/crates/astria-eyre/src/lib.rs index a28cd48d1..ee4d14e19 100644 --- a/crates/astria-eyre/src/lib.rs +++ b/crates/astria-eyre/src/lib.rs @@ -1,9 +1,6 @@ #![doc = include_str!("../README.md")] -use std::{ - error::Error, - fmt::Write as _, -}; +use std::{error::Error, fmt::Write as _}; pub use eyre; #[doc(hidden)] diff --git a/crates/astria-grpc-mock-test/tests/health/main.rs b/crates/astria-grpc-mock-test/tests/health/main.rs index beaef29db..8bb1d43e7 100644 --- a/crates/astria-grpc-mock-test/tests/health/main.rs +++ b/crates/astria-grpc-mock-test/tests/health/main.rs @@ -1,40 +1,17 @@ // allow just make the tests work for now #![allow(clippy::should_panic_without_expect)] -use std::{ - net::SocketAddr, - pin::Pin, - sync::Arc, -}; +use std::{net::SocketAddr, pin::Pin, sync::Arc}; -use astria_grpc_mock::{ - matcher, - response, - Mock, -}; +use astria_grpc_mock::{matcher, response, Mock}; use astria_grpc_mock_test::health::{ health_client::HealthClient, - health_server::{ - Health, - HealthServer, - }, - HealthCheckRequest, - HealthCheckResponse, -}; -use tokio::{ - join, - task::JoinHandle, -}; -use tokio_stream::{ - wrappers::TcpListenerStream, - Stream, -}; -use tonic::{ - transport::Server, - Request, - Response, - Status, + health_server::{Health, HealthServer}, + HealthCheckRequest, HealthCheckResponse, }; +use tokio::{join, task::JoinHandle}; +use tokio_stream::{wrappers::TcpListenerStream, Stream}; +use tonic::{transport::Server, Request, Response, Status}; struct MockServer { _server: JoinHandle<()>, @@ -50,9 +27,7 @@ async fn start_mock_server() -> MockServer { let mock_server = mock_server.clone(); async move { let _ = Server::builder() - .add_service(HealthServer::new(HealthService { - mock_server, - })) + .add_service(HealthServer::new(HealthService { mock_server })) .serve_with_incoming(TcpListenerStream::new(listener)) .await; } @@ -112,9 +87,7 @@ async fn constant_response_works() { let mut client = HealthClient::connect(format!("http://{}", server.local_addr)) .await .unwrap(); - let expected_response = HealthCheckResponse { - status: 1, - }; + let expected_response = HealthCheckResponse { status: 1 }; let mock = Mock::for_rpc_given("check", matcher::message_type::()) .respond_with(response::constant_response(expected_response.clone())); server.mocked.register(mock).await; @@ -133,9 +106,7 @@ async fn constant_response_expect_two_works() { let mut client = HealthClient::connect(format!("http://{}", server.local_addr)) .await .unwrap(); - let expected_response = HealthCheckResponse { - status: 1, - }; + let expected_response = HealthCheckResponse { status: 1 }; let mock = Mock::for_rpc_given("check", matcher::message_type::()) .respond_with(response::constant_response(expected_response.clone())) .expect(2); @@ -168,9 +139,7 @@ async fn constant_response_guard_works() { let mut client = HealthClient::connect(format!("http://{}", server.local_addr)) .await .unwrap(); - let expected_response = HealthCheckResponse { - status: 1, - }; + let expected_response = HealthCheckResponse { status: 1 }; let mock = Mock::for_rpc_given("check", matcher::message_type::()) .respond_with(response::constant_response(expected_response.clone())) .expect(1); @@ -194,9 +163,7 @@ async fn exact_pbjson_match_works() { let expected_request = HealthCheckRequest { service: "helloworld".to_string(), }; - let expected_response = HealthCheckResponse { - status: 1, - }; + let expected_response = HealthCheckResponse { status: 1 }; let mock = Mock::for_rpc_given("check", matcher::message_exact_pbjson(&expected_request)) .respond_with(response::constant_response(expected_response.clone())); server.mocked.register(mock).await; @@ -218,9 +185,7 @@ async fn partial_pbjson_match_works() { let expected_request = HealthCheckRequest { service: "helloworld".to_string(), }; - let expected_response = HealthCheckResponse { - status: 1, - }; + let expected_response = HealthCheckResponse { status: 1 }; // FIXME: Right now this is equivalent to an exact check because the request only has one field. let mock = Mock::for_rpc_given("check", matcher::message_partial_pbjson(&expected_request)) .respond_with(response::constant_response(expected_response.clone())); diff --git a/crates/astria-grpc-mock/src/lib.rs b/crates/astria-grpc-mock/src/lib.rs index c709515f2..813c494bc 100644 --- a/crates/astria-grpc-mock/src/lib.rs +++ b/crates/astria-grpc-mock/src/lib.rs @@ -16,14 +16,8 @@ mod mounted_mock; pub mod response; mod verification; -pub use mock::{ - Match, - Mock, -}; -pub use mock_server::{ - MockGuard, - MockServer, -}; +pub use mock::{Match, Mock}; +pub use mock_server::{MockGuard, MockServer}; pub use response::Respond; pub type AnyMessage = Box; diff --git a/crates/astria-grpc-mock/src/matcher.rs b/crates/astria-grpc-mock/src/matcher.rs index e6ba265f0..9b5301128 100644 --- a/crates/astria-grpc-mock/src/matcher.rs +++ b/crates/astria-grpc-mock/src/matcher.rs @@ -1,9 +1,6 @@ use std::any::TypeId; -use assert_json_diff::{ - assert_json_matches_no_panic, - CompareMode, -}; +use assert_json_diff::{assert_json_matches_no_panic, CompareMode}; use serde_json::Value; use crate::mock::Match; diff --git a/crates/astria-grpc-mock/src/mock.rs b/crates/astria-grpc-mock/src/mock.rs index f0a7ff3e1..1053df657 100644 --- a/crates/astria-grpc-mock/src/mock.rs +++ b/crates/astria-grpc-mock/src/mock.rs @@ -1,21 +1,9 @@ use std::ops::{ - Range, - RangeBounds as _, - RangeFrom, - RangeFull, - RangeInclusive, - RangeTo, - RangeToInclusive, + Range, RangeBounds as _, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, }; -use super::{ - response::Respond, - AnyMessage, -}; -use crate::{ - mock_server::MockGuard, - MockServer, -}; +use super::{response::Respond, AnyMessage}; +use crate::{mock_server::MockGuard, MockServer}; pub trait Match: Send + Sync { fn matches(&self, req: &tonic::Request) -> bool; @@ -87,10 +75,7 @@ impl MockBuilder { } pub fn respond_with(self, rsp: impl Respond + 'static) -> Mock { - let Self { - rpc, - matchers, - } = self; + let Self { rpc, matchers } = self; Mock { rpc, matchers, diff --git a/crates/astria-grpc-mock/src/mock_server.rs b/crates/astria-grpc-mock/src/mock_server.rs index bd74a5b8b..17f1fdf6b 100644 --- a/crates/astria-grpc-mock/src/mock_server.rs +++ b/crates/astria-grpc-mock/src/mock_server.rs @@ -1,26 +1,17 @@ use std::{ fmt::Write as _, pin::pin, - sync::{ - atomic::AtomicBool, - Arc, - }, + sync::{atomic::AtomicBool, Arc}, }; -use tokio::sync::{ - Notify, - RwLock, -}; +use tokio::sync::{Notify, RwLock}; use tracing::debug; use super::clone_request; use crate::{ erase_request, mock::Mock, - mock_set::{ - MockId, - MockSet, - }, + mock_set::{MockId, MockSet}, verification::VerificationOutcome, AnyRequest, }; @@ -156,9 +147,7 @@ impl MockRequest { impl From for MockRequest { fn from(value: AnyRequest) -> Self { - Self { - inner: value, - } + Self { inner: value } } } diff --git a/crates/astria-grpc-mock/src/mock_set.rs b/crates/astria-grpc-mock/src/mock_set.rs index 341d858a4..0891ce852 100644 --- a/crates/astria-grpc-mock/src/mock_set.rs +++ b/crates/astria-grpc-mock/src/mock_set.rs @@ -1,28 +1,16 @@ use std::{ - ops::{ - Index, - IndexMut, - }, - sync::{ - atomic::AtomicBool, - Arc, - }, + ops::{Index, IndexMut}, + sync::{atomic::AtomicBool, Arc}, }; use tokio::sync::Notify; use tracing::debug; -use super::{ - mock::Mock, - mounted_mock::MountedMock, -}; +use super::{mock::Mock, mounted_mock::MountedMock}; use crate::{ erase_request, mounted_mock::MockResult, - verification::{ - VerificationOutcome, - VerificationReport, - }, + verification::{VerificationOutcome, VerificationReport}, }; #[derive(Debug, PartialEq, Eq, Copy, Clone)] @@ -43,9 +31,7 @@ pub(crate) struct MockSet { impl MockSet { pub(crate) fn new() -> Self { - Self { - mocks: Vec::new(), - } + Self { mocks: Vec::new() } } pub(crate) fn handle_request< diff --git a/crates/astria-grpc-mock/src/mounted_mock.rs b/crates/astria-grpc-mock/src/mounted_mock.rs index efd14f52a..a07c46e80 100644 --- a/crates/astria-grpc-mock/src/mounted_mock.rs +++ b/crates/astria-grpc-mock/src/mounted_mock.rs @@ -1,24 +1,15 @@ -use std::sync::{ - atomic::AtomicBool, - Arc, -}; +use std::sync::{atomic::AtomicBool, Arc}; use tokio::sync::Notify; use tonic::Request; use super::{ - mock::{ - Match as _, - Mock, - }, + mock::{Match as _, Mock}, response::MockResponse, AnyMessage, }; use crate::{ - clone_request, - clone_response, - response::ResponseResult, - verification::VerificationReport, + clone_request, clone_response, response::ResponseResult, verification::VerificationReport, }; pub(crate) enum MockResult { diff --git a/crates/astria-grpc-mock/src/response.rs b/crates/astria-grpc-mock/src/response.rs index 3e05e669d..9d54e20a8 100644 --- a/crates/astria-grpc-mock/src/response.rs +++ b/crates/astria-grpc-mock/src/response.rs @@ -1,9 +1,6 @@ use std::marker::PhantomData; -use super::{ - clone_response, - AnyMessage, -}; +use super::{clone_response, AnyMessage}; use crate::erase_response; pub fn constant_response< diff --git a/crates/astria-grpc-mock/src/verification.rs b/crates/astria-grpc-mock/src/verification.rs index 81c49f63c..51c9dfb94 100644 --- a/crates/astria-grpc-mock/src/verification.rs +++ b/crates/astria-grpc-mock/src/verification.rs @@ -1,9 +1,6 @@ use std::fmt::Write as _; -use crate::{ - mock::Times, - mounted_mock::BadResponse, -}; +use crate::{mock::Times, mounted_mock::BadResponse}; /// A report returned by an `MountedMock` detailing what the user expectations were and /// how many calls were actually received since the mock was mounted on the server. diff --git a/crates/astria-merkle/src/audit.rs b/crates/astria-merkle/src/audit.rs index 4ab383cbd..fb09be7b4 100644 --- a/crates/astria-merkle/src/audit.rs +++ b/crates/astria-merkle/src/audit.rs @@ -2,10 +2,7 @@ use std::num::NonZeroUsize; -use sha2::{ - Digest as _, - Sha256, -}; +use sha2::{Digest as _, Sha256}; /// Builder to construct a complex leaf ad-hoc without allocation. /// @@ -21,19 +18,12 @@ impl<'a, TLeaf, TRoot> LeafBuilder<'a, TLeaf, TRoot> { /// Returns the internal [`Audit`] with its `TLeaf` typestate set. pub fn finish_leaf(self) -> Audit<'a, WithLeafHash, TRoot> { let Self { - audit: - Audit { - proof, - root, - .. - }, + audit: Audit { proof, root, .. }, hasher, } = self; let leaf_hash = hasher.finalize().into(); Audit { - leaf_hash: WithLeafHash { - leaf_hash, - }, + leaf_hash: WithLeafHash { leaf_hash }, proof, root, } @@ -107,14 +97,8 @@ impl<'a, TLeaf, TRoot> Audit<'a, TLeaf, TRoot> { /// /// Returns a new `Audit` with its `TLeaf` type-state to [`WithLeafHash`]. pub fn with_leaf_hash(self, leaf_hash: [u8; 32]) -> Audit<'a, WithLeafHash, TRoot> { - let Self { - proof, - root, - .. - } = self; - let leaf_hash = WithLeafHash { - leaf_hash, - }; + let Self { proof, root, .. } = self; + let leaf_hash = WithLeafHash { leaf_hash }; Audit { leaf_hash, proof, @@ -127,16 +111,12 @@ impl<'a, TLeaf, TRoot> Audit<'a, TLeaf, TRoot> { /// Returns a new `Audit` with its `TRoot` type-state to [`WithRoot`]. pub fn with_root(self, root: [u8; 32]) -> Audit<'a, TLeaf, WithRoot> { let Self { - proof, - leaf_hash, - .. + proof, leaf_hash, .. } = self; Audit { leaf_hash, proof, - root: WithRoot { - root, - }, + root: WithRoot { root }, } } } @@ -161,9 +141,7 @@ impl<'a, TRoot> Audit<'a, WithLeafHash, TRoot> { /// ``` pub fn reconstruct_root(&self) -> [u8; 32] { let Self { - leaf_hash: WithLeafHash { - leaf_hash, - }, + leaf_hash: WithLeafHash { leaf_hash }, proof, .. } = self; @@ -203,13 +181,9 @@ impl<'a> Audit<'a, WithLeafHash, WithRoot> { #[must_use = "verify the audit result"] pub fn perform(&self) -> bool { let Self { - leaf_hash: WithLeafHash { - leaf_hash, - }, + leaf_hash: WithLeafHash { leaf_hash }, proof, - root: WithRoot { - root, - }, + root: WithRoot { root }, } = self; *root == proof.reconstruct_root_with_leaf_hash(*leaf_hash) } @@ -223,9 +197,7 @@ pub struct InvalidProof { impl InvalidProof { fn audit_path_not_multiple_of_32(len: usize) -> Self { Self { - kind: InvalidProofKind::AuditPathNotMultipleOf32 { - len, - }, + kind: InvalidProofKind::AuditPathNotMultipleOf32 { len }, } } @@ -272,9 +244,7 @@ enum InvalidProofKind { impl std::fmt::Display for InvalidProofKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - InvalidProofKind::AuditPathNotMultipleOf32 { - len, - } => f.write_fmt(format_args!( + InvalidProofKind::AuditPathNotMultipleOf32 { len } => f.write_fmt(format_args!( "audit path byte buffer length must be a multiple of 32 bytes, but was {len} bytes" )), InvalidProofKind::LeafIndexOutsideTree { @@ -334,10 +304,7 @@ impl UncheckedProof { /// from the proof. #[must_use = "an unchecked proof must be turned into a checked proof to be useful"] pub fn audit_path(self, audit_path: Vec) -> Self { - Self { - audit_path, - ..self - } + Self { audit_path, ..self } } /// Sets the index of the leaf that this proof is for. @@ -347,10 +314,7 @@ impl UncheckedProof { /// to a tree index `j = 2 * i`. #[must_use = "an unchecked proof must be turned into a checked proof to be useful"] pub fn leaf_index(self, leaf_index: usize) -> Self { - Self { - leaf_index, - ..self - } + Self { leaf_index, ..self } } /// Sets the tree size of the proof. @@ -359,10 +323,7 @@ impl UncheckedProof { /// not defined for empty trees. #[must_use = "an unchecked proof must be turned into a checked proof to be useful"] pub fn tree_size(self, tree_size: usize) -> Self { - Self { - tree_size, - ..self - } + Self { tree_size, ..self } } /// Constructs the [`Proof`] from the builder inputs. diff --git a/crates/astria-merkle/src/lib.rs b/crates/astria-merkle/src/lib.rs index a6e68a724..a08fad64e 100644 --- a/crates/astria-merkle/src/lib.rs +++ b/crates/astria-merkle/src/lib.rs @@ -132,19 +132,13 @@ use std::num::NonZeroUsize; -use sha2::{ - Digest as _, - Sha256, -}; +use sha2::{Digest as _, Sha256}; pub mod audit; #[cfg(test)] mod tests; -pub use audit::{ - Audit, - Proof, -}; +pub use audit::{Audit, Proof}; /// Calculates `SHA256(0x00 | leaf)` #[must_use] @@ -231,10 +225,7 @@ impl<'a> LeafBuilder<'a> { impl<'a> Drop for LeafBuilder<'a> { fn drop(&mut self) { - let Self { - tree, - hasher, - } = self; + let Self { tree, hasher } = self; let leaf_hash: [u8; 32] = hasher .take() .expect("hasher is set during the leaf builder's lifetime and only taken on drop") @@ -417,9 +408,7 @@ impl Tree { /// ``` #[must_use] pub fn new() -> Self { - Self { - nodes: Vec::new(), - } + Self { nodes: Vec::new() } } /// Returns the number of nodes in the merkle tree. diff --git a/crates/astria-merkle/src/tests.rs b/crates/astria-merkle/src/tests.rs index d985298bc..86263fa84 100644 --- a/crates/astria-merkle/src/tests.rs +++ b/crates/astria-merkle/src/tests.rs @@ -1,11 +1,5 @@ -use super::{ - is_perfect, - perfect_root, -}; -use crate::{ - complete_parent, - complete_parent_and_sibling, -}; +use super::{is_perfect, perfect_root}; +use crate::{complete_parent, complete_parent_and_sibling}; #[track_caller] fn assert_is_perfect(n: usize) { diff --git a/crates/astria-sequencer-client/src/extension_trait.rs b/crates/astria-sequencer-client/src/extension_trait.rs index b69da4fa9..6e3ec9806 100644 --- a/crates/astria-sequencer-client/src/extension_trait.rs +++ b/crates/astria-sequencer-client/src/extension_trait.rs @@ -20,45 +20,28 @@ //! # }); //! ``` -use std::{ - future, - pin::Pin, - sync::Arc, -}; +use std::{future, pin::Pin, sync::Arc}; pub use astria_core::{ primitive::v1::Address, protocol::{ - account::v1alpha1::{ - BalanceResponse, - NonceResponse, - }, + account::v1alpha1::{BalanceResponse, NonceResponse}, transaction::v1alpha1::SignedTransaction, }, - sequencerblock::v1alpha1::{ - block::SequencerBlockError, - SequencerBlock, - }, + sequencerblock::v1alpha1::{block::SequencerBlockError, SequencerBlock}, }; use async_trait::async_trait; use futures::Stream; -use prost::{ - DecodeError, - Message as _, -}; +use prost::{DecodeError, Message as _}; use tendermint::block::Height; #[cfg(feature = "http")] use tendermint_rpc::HttpClient; #[cfg(feature = "websocket")] use tendermint_rpc::WebSocketClient; use tendermint_rpc::{ - endpoint::broadcast::{ - tx_commit, - tx_sync, - }, + endpoint::broadcast::{tx_commit, tx_sync}, event::EventData, - Client, - SubscriptionClient, + Client, SubscriptionClient, }; #[cfg(feature = "http")] @@ -266,10 +249,7 @@ impl ErrorKind { /// Convenience method to construct a `TendermintRpc` variant. fn tendermint_rpc(rpc: &'static str, inner: tendermint_rpc::error::Error) -> Self { - Self::TendermintRpc(TendermintRpcError { - inner, - rpc, - }) + Self::TendermintRpc(TendermintRpcError { inner, rpc }) } } @@ -296,15 +276,9 @@ impl NewBlockStreamError { fn unexpected_event(event: &EventData) -> Self { fn event_to_name(event: &EventData) -> &'static str { match event { - EventData::NewBlock { - .. - } => "new-block", - EventData::LegacyNewBlock { - .. - } => "legacy-new-block", - EventData::Tx { - .. - } => "tx", + EventData::NewBlock { .. } => "new-block", + EventData::LegacyNewBlock { .. } => "legacy-new-block", + EventData::Tx { .. } => "tx", EventData::GenericJsonEvent(_) => "generic-json", } } @@ -347,14 +321,8 @@ impl Stream for LatestHeightStream { #[async_trait] pub trait SequencerSubscriptionClientExt: SubscriptionClient { async fn subscribe_latest_height(&self) -> Result { - use futures::stream::{ - StreamExt as _, - TryStreamExt as _, - }; - use tendermint_rpc::query::{ - EventType, - Query, - }; + use futures::stream::{StreamExt as _, TryStreamExt as _}; + use tendermint_rpc::query::{EventType, Query}; let stream = self .subscribe(Query::from(EventType::NewBlock)) .await? @@ -362,21 +330,18 @@ pub trait SequencerSubscriptionClientExt: SubscriptionClient { .and_then(|event| { future::ready(match event.data { EventData::LegacyNewBlock { - block: Some(block), - .. + block: Some(block), .. } => Ok(block.header.height), - EventData::LegacyNewBlock { - block: None, .. - } => Err(NewBlockStreamError::NoBlock), + EventData::LegacyNewBlock { block: None, .. } => { + Err(NewBlockStreamError::NoBlock) + } other => Err(NewBlockStreamError::unexpected_event(&other)), }) }) .boxed(); - Ok(LatestHeightStream { - inner: stream, - }) + Ok(LatestHeightStream { inner: stream }) } } diff --git a/crates/astria-sequencer-client/src/lib.rs b/crates/astria-sequencer-client/src/lib.rs index 4f8c018f0..773376913 100644 --- a/crates/astria-sequencer-client/src/lib.rs +++ b/crates/astria-sequencer-client/src/lib.rs @@ -4,30 +4,19 @@ pub mod extension_trait; #[cfg(not(any(feature = "http", feature = "websocket")))] compile_error!("at least one of the `http` or `websocket` features must be enabled"); -use std::{ - future::Future, - pin::Pin, - time::Duration, -}; +use std::{future::Future, pin::Pin, time::Duration}; #[cfg(any(feature = "http", feature = "websocket"))] pub use __feature_gated_exports::*; pub use astria_core::{ primitive::v1::Address, protocol::{ - account::v1alpha1::{ - BalanceResponse, - NonceResponse, - }, + account::v1alpha1::{BalanceResponse, NonceResponse}, transaction::v1alpha1::SignedTransaction, }, sequencerblock::v1alpha1::SequencerBlock, }; -use futures_util::{ - FutureExt, - Stream, - StreamExt, -}; +use futures_util::{FutureExt, Stream, StreamExt}; pub use tendermint; use tendermint::block::Height; pub use tendermint_proto; @@ -39,15 +28,10 @@ pub use tendermint_rpc::WebSocketClient; use tokio_stream::wrappers::IntervalStream; #[cfg(any(feature = "http", feature = "websocket"))] mod __feature_gated_exports { - pub use tendermint_rpc::{ - Client, - SubscriptionClient, - }; + pub use tendermint_rpc::{Client, SubscriptionClient}; pub use crate::extension_trait::{ - NewBlockStreamError, - SequencerClientExt, - SequencerSubscriptionClientExt, + NewBlockStreamError, SequencerClientExt, SequencerSubscriptionClientExt, }; } diff --git a/crates/astria-sequencer-client/src/tests/http.rs b/crates/astria-sequencer-client/src/tests/http.rs index 34d2b6153..615f6b082 100644 --- a/crates/astria-sequencer-client/src/tests/http.rs +++ b/crates/astria-sequencer-client/src/tests/http.rs @@ -1,43 +1,22 @@ use astria_core::{ crypto::SigningKey, - primitive::v1::{ - asset::default_native_asset_id, - Address, - }, + primitive::v1::{asset::default_native_asset_id, Address}, protocol::transaction::v1alpha1::{ - action::TransferAction, - SignedTransaction, - TransactionParams, - UnsignedTransaction, + action::TransferAction, SignedTransaction, TransactionParams, UnsignedTransaction, }, }; use hex_literal::hex; use serde_json::json; -use tendermint::{ - block::Height, - Hash, -}; +use tendermint::{block::Height, Hash}; use tendermint_rpc::{ - endpoint::broadcast::tx_commit::v0_37::DialectResponse, - response::Wrapper, - Id, + endpoint::broadcast::tx_commit::v0_37::DialectResponse, response::Wrapper, Id, }; use wiremock::{ - matchers::{ - body_partial_json, - body_string_contains, - }, - Mock, - MockGuard, - MockServer, - ResponseTemplate, + matchers::{body_partial_json, body_string_contains}, + Mock, MockGuard, MockServer, ResponseTemplate, }; -use crate::{ - tendermint_rpc::endpoint::broadcast::tx_sync, - HttpClient, - SequencerClientExt as _, -}; +use crate::{tendermint_rpc::endpoint::broadcast::tx_sync, HttpClient, SequencerClientExt as _}; const ALICE_ADDRESS: [u8; 20] = hex!("1c0c490f1b5528d8173c5de46d131160e4b2c0c3"); const BOB_ADDRESS: Address = Address::from_array(hex!("34fec43c7fcab9aef3b3cf8aba855e41ee69ca3a")); @@ -51,10 +30,7 @@ impl MockSequencer { async fn start() -> Self { let server = MockServer::start().await; let client = HttpClient::new(&*format!("http://{}", server.address())).unwrap(); - Self { - server, - client, - } + Self { server, client } } } @@ -128,15 +104,13 @@ fn create_signed_transaction() -> SignedTransaction { .unwrap(); let alice_key = SigningKey::from(alice_secret_bytes); - let actions = vec![ - TransferAction { - to: BOB_ADDRESS, - amount: 333_333, - asset_id: default_native_asset_id(), - fee_asset_id: default_native_asset_id(), - } - .into(), - ]; + let actions = vec![TransferAction { + to: BOB_ADDRESS, + amount: 333_333, + asset_id: default_native_asset_id(), + fee_asset_id: default_native_asset_id(), + } + .into()]; UnsignedTransaction { params: TransactionParams { nonce: 1, @@ -150,10 +124,7 @@ fn create_signed_transaction() -> SignedTransaction { #[tokio::test] async fn get_latest_nonce() { use astria_core::generated::protocol::account::v1alpha1::NonceResponse; - let MockSequencer { - server, - client, - } = MockSequencer::start().await; + let MockSequencer { server, client } = MockSequencer::start().await; let expected_response = NonceResponse { height: 10, @@ -172,15 +143,9 @@ async fn get_latest_nonce() { #[tokio::test] async fn get_latest_balance() { - use astria_core::generated::protocol::account::v1alpha1::{ - AssetBalance, - BalanceResponse, - }; + use astria_core::generated::protocol::account::v1alpha1::{AssetBalance, BalanceResponse}; - let MockSequencer { - server, - client, - } = MockSequencer::start().await; + let MockSequencer { server, client } = MockSequencer::start().await; let expected_response = BalanceResponse { height: 10, @@ -202,10 +167,7 @@ async fn get_latest_balance() { #[tokio::test] async fn submit_tx_sync() { - let MockSequencer { - server, - client, - } = MockSequencer::start().await; + let MockSequencer { server, client } = MockSequencer::start().await; let server_response = tx_sync::Response { code: 0.into(), @@ -227,10 +189,7 @@ async fn submit_tx_sync() { async fn submit_tx_commit() { use tendermint_rpc::dialect; - let MockSequencer { - server, - client, - } = MockSequencer::start().await; + let MockSequencer { server, client } = MockSequencer::start().await; let server_response = DialectResponse { check_tx: dialect::CheckTx::default(), diff --git a/crates/astria-sequencer-relayer/src/api.rs b/crates/astria-sequencer-relayer/src/api.rs index 382f78a20..40f4925f5 100644 --- a/crates/astria-sequencer-relayer/src/api.rs +++ b/crates/astria-sequencer-relayer/src/api.rs @@ -1,20 +1,10 @@ use std::net::SocketAddr; use axum::{ - extract::{ - FromRef, - State, - }, - response::{ - IntoResponse, - Response, - }, - routing::{ - get, - IntoMakeService, - }, - Json, - Router, + extract::{FromRef, State}, + response::{IntoResponse, Response}, + routing::{get, IntoMakeService}, + Json, Router, }; use http::status::StatusCode; use hyper::server::conn::AddrIncoming; @@ -44,9 +34,7 @@ pub(crate) fn start(socket_addr: SocketAddr, relayer_state: RelayerState) -> Api .route("/healthz", get(get_healthz)) .route("/readyz", get(get_readyz)) .route("/status", get(get_status)) - .with_state(AppState { - relayer_state, - }); + .with_state(AppState { relayer_state }); axum::Server::bind(&socket_addr).serve(app.into_make_service()) } @@ -95,10 +83,7 @@ impl IntoResponse for Healthz { Self::Ok => (StatusCode::OK, "ok"), Self::Degraded => (StatusCode::INTERNAL_SERVER_ERROR, "degraded"), }; - let mut response = Json(ReadyzBody { - status: msg, - }) - .into_response(); + let mut response = Json(ReadyzBody { status: msg }).into_response(); *response.status_mut() = status; response } @@ -119,10 +104,7 @@ impl IntoResponse for Readyz { Self::Ok => (StatusCode::OK, "ok"), Self::NotReady => (StatusCode::SERVICE_UNAVAILABLE, "not ready"), }; - let mut response = Json(ReadyzBody { - status: msg, - }) - .into_response(); + let mut response = Json(ReadyzBody { status: msg }).into_response(); *response.status_mut() = status; response } diff --git a/crates/astria-sequencer-relayer/src/config.rs b/crates/astria-sequencer-relayer/src/config.rs index a14d4f0ab..77b3d76ab 100644 --- a/crates/astria-sequencer-relayer/src/config.rs +++ b/crates/astria-sequencer-relayer/src/config.rs @@ -1,22 +1,9 @@ -use std::{ - collections::HashSet, - path::PathBuf, - sync::Arc, -}; +use std::{collections::HashSet, path::PathBuf, sync::Arc}; use astria_core::primitive::v1::RollupId; -use astria_eyre::eyre::{ - self, - WrapErr, -}; -use base64::{ - prelude::BASE64_STANDARD, - Engine as _, -}; -use serde::{ - Deserialize, - Serialize, -}; +use astria_eyre::eyre::{self, WrapErr}; +use base64::{prelude::BASE64_STANDARD, Engine as _}; +use serde::{Deserialize, Serialize}; // Allowed `struct_excessive_bools` because this is used as a container // for deserialization. Making this a builder-pattern is not actionable. diff --git a/crates/astria-sequencer-relayer/src/lib.rs b/crates/astria-sequencer-relayer/src/lib.rs index d6eb436f7..4f61739c5 100644 --- a/crates/astria-sequencer-relayer/src/lib.rs +++ b/crates/astria-sequencer-relayer/src/lib.rs @@ -8,11 +8,5 @@ pub(crate) mod utils; pub(crate) mod validator; pub use build_info::BUILD_INFO; -pub use config::{ - Config, - IncludeRollup, -}; -pub use sequencer_relayer::{ - SequencerRelayer, - ShutdownHandle, -}; +pub use config::{Config, IncludeRollup}; +pub use sequencer_relayer::{SequencerRelayer, ShutdownHandle}; diff --git a/crates/astria-sequencer-relayer/src/main.rs b/crates/astria-sequencer-relayer/src/main.rs index 1f5a7df97..cffaccb9a 100644 --- a/crates/astria-sequencer-relayer/src/main.rs +++ b/crates/astria-sequencer-relayer/src/main.rs @@ -1,21 +1,9 @@ use std::process::ExitCode; use astria_eyre::eyre::WrapErr as _; -use astria_sequencer_relayer::{ - metrics_init, - Config, - SequencerRelayer, - BUILD_INFO, -}; -use tokio::signal::unix::{ - signal, - SignalKind, -}; -use tracing::{ - error, - info, - warn, -}; +use astria_sequencer_relayer::{metrics_init, Config, SequencerRelayer, BUILD_INFO}; +use tokio::signal::unix::{signal, SignalKind}; +use tracing::{error, info, warn}; #[tokio::main] async fn main() -> ExitCode { diff --git a/crates/astria-sequencer-relayer/src/metrics_init.rs b/crates/astria-sequencer-relayer/src/metrics_init.rs index ab6ac9940..00db62f03 100644 --- a/crates/astria-sequencer-relayer/src/metrics_init.rs +++ b/crates/astria-sequencer-relayer/src/metrics_init.rs @@ -2,12 +2,7 @@ //! //! Registers metrics & lists constants to be used as metric names throughout crate. -use metrics::{ - describe_counter, - describe_gauge, - describe_histogram, - Unit, -}; +use metrics::{describe_counter, describe_gauge, describe_histogram, Unit}; use telemetry::metric_name; /// Registers all metrics used by this crate. @@ -109,18 +104,11 @@ metric_name!(pub const COMPRESSION_RATIO_FOR_ASTRIA_BLOCK); #[cfg(test)] mod tests { use super::{ - BLOBS_PER_CELESTIA_TX, - BLOCKS_PER_CELESTIA_TX, - BYTES_PER_CELESTIA_TX, - CELESTIA_PAYLOAD_CREATION_LATENCY, - CELESTIA_SUBMISSION_COUNT, - CELESTIA_SUBMISSION_FAILURE_COUNT, - CELESTIA_SUBMISSION_HEIGHT, - CELESTIA_SUBMISSION_LATENCY, - COMPRESSION_RATIO_FOR_ASTRIA_BLOCK, - SEQUENCER_BLOCK_FETCH_FAILURE_COUNT, - SEQUENCER_HEIGHT_FETCH_FAILURE_COUNT, - SEQUENCER_SUBMISSION_HEIGHT, + BLOBS_PER_CELESTIA_TX, BLOCKS_PER_CELESTIA_TX, BYTES_PER_CELESTIA_TX, + CELESTIA_PAYLOAD_CREATION_LATENCY, CELESTIA_SUBMISSION_COUNT, + CELESTIA_SUBMISSION_FAILURE_COUNT, CELESTIA_SUBMISSION_HEIGHT, CELESTIA_SUBMISSION_LATENCY, + COMPRESSION_RATIO_FOR_ASTRIA_BLOCK, SEQUENCER_BLOCK_FETCH_FAILURE_COUNT, + SEQUENCER_HEIGHT_FETCH_FAILURE_COUNT, SEQUENCER_SUBMISSION_HEIGHT, }; #[track_caller] diff --git a/crates/astria-sequencer-relayer/src/relayer/builder.rs b/crates/astria-sequencer-relayer/src/relayer/builder.rs index d62fe04e6..b36bfeb71 100644 --- a/crates/astria-sequencer-relayer/src/relayer/builder.rs +++ b/crates/astria-sequencer-relayer/src/relayer/builder.rs @@ -1,29 +1,12 @@ -use std::{ - path::PathBuf, - sync::Arc, - time::Duration, -}; +use std::{path::PathBuf, sync::Arc, time::Duration}; use astria_core::generated::sequencerblock::v1alpha1::sequencer_service_client::SequencerServiceClient; -use astria_eyre::eyre::{ - self, - WrapErr as _, -}; +use astria_eyre::eyre::{self, WrapErr as _}; use sequencer_client::HttpClient as SequencerClient; -use tonic::transport::{ - Endpoint, - Uri, -}; +use tonic::transport::{Endpoint, Uri}; -use super::{ - state::State, - CelestiaClientBuilder, - CelestiaKeys, -}; -use crate::{ - validator::Validator, - IncludeRollup, -}; +use super::{state::State, CelestiaClientBuilder, CelestiaKeys}; +use crate::{validator::Validator, IncludeRollup}; pub(crate) struct Builder { pub(crate) shutdown_token: tokio_util::sync::CancellationToken, diff --git a/crates/astria-sequencer-relayer/src/relayer/celestia_client/builder.rs b/crates/astria-sequencer-relayer/src/relayer/celestia_client/builder.rs index b945e3d11..e17c5329e 100644 --- a/crates/astria-sequencer-relayer/src/relayer/celestia_client/builder.rs +++ b/crates/astria-sequencer-relayer/src/relayer/celestia_client/builder.rs @@ -2,27 +2,17 @@ use std::sync::Arc; use astria_core::generated::cosmos::{ base::tendermint::v1beta1::{ - service_client::ServiceClient as NodeInfoClient, - GetNodeInfoRequest, + service_client::ServiceClient as NodeInfoClient, GetNodeInfoRequest, }, tx::v1beta1::service_client::ServiceClient as TxClient, }; use http::Uri; use tendermint::account::Id as AccountId; use thiserror::Error; -use tonic::transport::{ - Channel, - Endpoint, -}; +use tonic::transport::{Channel, Endpoint}; use tracing::trace; -use super::{ - super::State, - Bech32Address, - CelestiaClient, - CelestiaKeys, - GrpcResponseError, -}; +use super::{super::State, Bech32Address, CelestiaClient, CelestiaKeys, GrpcResponseError}; /// An error when building the `CelestiaClient`. #[derive(Error, Clone, Debug)] diff --git a/crates/astria-sequencer-relayer/src/relayer/celestia_client/celestia_keys.rs b/crates/astria-sequencer-relayer/src/relayer/celestia_client/celestia_keys.rs index 237c017e4..766a401dc 100644 --- a/crates/astria-sequencer-relayer/src/relayer/celestia_client/celestia_keys.rs +++ b/crates/astria-sequencer-relayer/src/relayer/celestia_client/celestia_keys.rs @@ -1,20 +1,12 @@ use std::{ - fmt::{ - self, - Debug, - Formatter, - }, + fmt::{self, Debug, Formatter}, fs, path::Path, }; -use k256::ecdsa::{ - signature::Signer, - Signature, -}; +use k256::ecdsa::{signature::Signer, Signature}; use tendermint::{ - account::Id as AccountId, - private_key::Secp256k1 as SigningKey, + account::Id as AccountId, private_key::Secp256k1 as SigningKey, public_key::Secp256k1 as VerificationKey, }; use thiserror::Error; diff --git a/crates/astria-sequencer-relayer/src/relayer/celestia_client/error.rs b/crates/astria-sequencer-relayer/src/relayer/celestia_client/error.rs index b8848d53a..50b7eb7b4 100644 --- a/crates/astria-sequencer-relayer/src/relayer/celestia_client/error.rs +++ b/crates/astria-sequencer-relayer/src/relayer/celestia_client/error.rs @@ -1,9 +1,5 @@ use std::{ - fmt::{ - self, - Display, - Formatter, - }, + fmt::{self, Display, Formatter}, num::ParseFloatError, }; diff --git a/crates/astria-sequencer-relayer/src/relayer/celestia_client/mod.rs b/crates/astria-sequencer-relayer/src/relayer/celestia_client/mod.rs index ac504dbb8..aaaabe3bd 100644 --- a/crates/astria-sequencer-relayer/src/relayer/celestia_client/mod.rs +++ b/crates/astria-sequencer-relayer/src/relayer/celestia_client/mod.rs @@ -8,92 +8,47 @@ mod tests; use std::{ convert::TryInto, sync::Arc, - time::{ - Duration, - Instant, - }, + time::{Duration, Instant}, }; use astria_core::generated::{ celestia::v1::{ - query_client::QueryClient as BlobQueryClient, - MsgPayForBlobs, - Params as BlobParams, + query_client::QueryClient as BlobQueryClient, MsgPayForBlobs, Params as BlobParams, QueryParamsRequest as QueryBlobParamsRequest, }, cosmos::{ auth::v1beta1::{ - query_client::QueryClient as AuthQueryClient, - BaseAccount, - Params as AuthParams, - QueryAccountRequest, - QueryAccountResponse, + query_client::QueryClient as AuthQueryClient, BaseAccount, Params as AuthParams, + QueryAccountRequest, QueryAccountResponse, QueryParamsRequest as QueryAuthParamsRequest, }, base::{ node::v1beta1::{ service_client::ServiceClient as MinGasPriceClient, - ConfigRequest as MinGasPriceRequest, - ConfigResponse as MinGasPriceResponse, + ConfigRequest as MinGasPriceRequest, ConfigResponse as MinGasPriceResponse, }, v1beta1::Coin, }, crypto::secp256k1, tx::v1beta1::{ - mode_info::{ - Single, - Sum, - }, + mode_info::{Single, Sum}, service_client::ServiceClient as TxClient, - AuthInfo, - BroadcastMode, - BroadcastTxRequest, - BroadcastTxResponse, - Fee, - GetTxRequest, - GetTxResponse, - ModeInfo, - SignDoc, - SignerInfo, - Tx, - TxBody, + AuthInfo, BroadcastMode, BroadcastTxRequest, BroadcastTxResponse, Fee, GetTxRequest, + GetTxResponse, ModeInfo, SignDoc, SignerInfo, Tx, TxBody, }, }, - tendermint::types::{ - Blob as PbBlob, - BlobTx, - }, + tendermint::types::{Blob as PbBlob, BlobTx}, }; use astria_eyre::eyre::Report; -pub(super) use builder::{ - Builder as CelestiaClientBuilder, - BuilderError, -}; +pub(super) use builder::{Builder as CelestiaClientBuilder, BuilderError}; use celestia_cost_params::CelestiaCostParams; pub(crate) use celestia_keys::CelestiaKeys; use celestia_types::Blob; -pub(super) use error::{ - GrpcResponseError, - ProtobufDecodeError, - TrySubmitError, -}; -use prost::{ - bytes::Bytes, - Message as _, - Name as _, -}; +pub(super) use error::{GrpcResponseError, ProtobufDecodeError, TrySubmitError}; +use prost::{bytes::Bytes, Message as _, Name as _}; use tokio::sync::watch; -use tonic::{ - transport::Channel, - Response, - Status, -}; -use tracing::{ - debug, - info, - trace, - warn, -}; +use tonic::{transport::Channel, Response, Status}; +use tracing::{debug, info, trace, warn}; // From https://github.com/celestiaorg/cosmos-sdk/blob/v1.18.3-sdk-v0.46.14/types/errors/errors.go#L75 const INSUFFICIENT_FEE_CODE: u32 = 13; @@ -548,11 +503,11 @@ fn calculate_fee( ) -> u64 { // Try to extract the required fee from the last error. let maybe_required_fee = match maybe_last_error { - Some(TrySubmitError::BroadcastTxResponseErrorCode { - code, - log, - .. - }) if code == INSUFFICIENT_FEE_CODE => extract_required_fee_from_log(&log), + Some(TrySubmitError::BroadcastTxResponseErrorCode { code, log, .. }) + if code == INSUFFICIENT_FEE_CODE => + { + extract_required_fee_from_log(&log) + } _ => None, }; @@ -648,9 +603,7 @@ fn new_signed_tx( const FEE_DENOM: &str = "utia"; // From https://github.com/celestiaorg/cosmos-sdk/blob/v1.18.3-sdk-v0.46.14/proto/cosmos/tx/signing/v1beta1/signing.proto#L24 const SIGNING_MODE_INFO: Option = Some(ModeInfo { - sum: Some(Sum::Single(Single { - mode: 1, - })), + sum: Some(Sum::Single(Single { mode: 1 })), }); let fee_coin = Coin { diff --git a/crates/astria-sequencer-relayer/src/relayer/celestia_client/tests.rs b/crates/astria-sequencer-relayer/src/relayer/celestia_client/tests.rs index 2b8500131..93fb9c6d9 100644 --- a/crates/astria-sequencer-relayer/src/relayer/celestia_client/tests.rs +++ b/crates/astria-sequencer-relayer/src/relayer/celestia_client/tests.rs @@ -1,8 +1,5 @@ use astria_core::generated::cosmos::base::abci::v1beta1::TxResponse; -use celestia_types::{ - blob::Commitment, - nmt::Namespace, -}; +use celestia_types::{blob::Commitment, nmt::Namespace}; use prost::bytes::Bytes; use super::*; @@ -94,9 +91,7 @@ fn account_from_bad_response_should_fail() { } // Should return `EmptyAccountInfo` if the inner response's `account` is `None`. - let response = Ok(Response::new(QueryAccountResponse { - account: None, - })); + let response = Ok(Response::new(QueryAccountResponse { account: None })); let error = account_from_response(response).unwrap_err(); // allow: `assert!(matches!(..))` provides poor feedback on failure. #[allow(clippy::manual_assert)] @@ -116,10 +111,7 @@ fn account_from_bad_response_should_fail() { })); let error = account_from_response(response).unwrap_err(); match error { - TrySubmitError::AccountInfoTypeMismatch { - expected, - received, - } => { + TrySubmitError::AccountInfoTypeMismatch { expected, received } => { assert_eq!(expected, BaseAccount::type_url(),); assert_eq!(received, bad_url,); } @@ -192,9 +184,7 @@ fn min_gas_price_from_bad_response_should_fail() { })); let error = min_gas_price_from_response(response).unwrap_err(); match error { - TrySubmitError::FailedToParseMinGasPrice { - min_gas_price, .. - } => { + TrySubmitError::FailedToParseMinGasPrice { min_gas_price, .. } => { assert_eq!(min_gas_price, bad_value,); } _ => panic!("expected `FailedToParseMinGasPrice` error, but got {error:?}"), @@ -282,9 +272,7 @@ fn tx_hash_from_bad_response_should_fail() { } // Should return `EmptyBroadcastTxResponse` if the inner response's `tx_response` is `None`. - let response = Ok(Response::new(BroadcastTxResponse { - tx_response: None, - })); + let response = Ok(Response::new(BroadcastTxResponse { tx_response: None })); let error = tx_hash_from_response(response).unwrap_err(); // allow: `assert!(matches!(..))` provides poor feedback on failure. #[allow(clippy::manual_assert)] diff --git a/crates/astria-sequencer-relayer/src/relayer/mod.rs b/crates/astria-sequencer-relayer/src/relayer/mod.rs index 84ce3abf3..44f2b2c50 100644 --- a/crates/astria-sequencer-relayer/src/relayer/mod.rs +++ b/crates/astria-sequencer-relayer/src/relayer/mod.rs @@ -1,8 +1,5 @@ use std::{ - path::{ - Path, - PathBuf, - }, + path::{Path, PathBuf}, sync::Arc, time::Duration, }; @@ -11,48 +8,25 @@ use astria_core::{ generated::sequencerblock::v1alpha1::sequencer_service_client::SequencerServiceClient, sequencerblock::v1alpha1::SequencerBlock, }; -use astria_eyre::eyre::{ - self, - bail, - eyre, - WrapErr as _, -}; +use astria_eyre::eyre::{self, bail, eyre, WrapErr as _}; use futures::{ - future::{ - BoxFuture, - Fuse, - FusedFuture as _, - }, + future::{BoxFuture, Fuse, FusedFuture as _}, FutureExt as _, }; use sequencer_client::{ - tendermint::block::Height as SequencerHeight, - HttpClient as SequencerClient, + tendermint::block::Height as SequencerHeight, HttpClient as SequencerClient, }; use tokio::{ select, - sync::{ - mpsc::error::TrySendError, - watch, - }, + sync::{mpsc::error::TrySendError, watch}, task::JoinHandle, }; use tokio_stream::StreamExt; use tokio_util::sync::CancellationToken; use tonic::transport::Channel; -use tracing::{ - debug, - error, - field::DisplayValue, - info, - instrument, - warn, -}; +use tracing::{debug, error, field::DisplayValue, info, instrument, warn}; -use crate::{ - validator::Validator, - IncludeRollup, -}; +use crate::{validator::Validator, IncludeRollup}; mod builder; mod celestia_client; @@ -62,12 +36,7 @@ mod submission; mod write; pub(crate) use builder::Builder; -use celestia_client::{ - BuilderError, - CelestiaClientBuilder, - CelestiaKeys, - TrySubmitError, -}; +use celestia_client::{BuilderError, CelestiaClientBuilder, CelestiaKeys, TrySubmitError}; use state::State; pub(crate) use state::StateSnapshot; diff --git a/crates/astria-sequencer-relayer/src/relayer/read.rs b/crates/astria-sequencer-relayer/src/relayer/read.rs index f2de26da0..ca58cd3b4 100644 --- a/crates/astria-sequencer-relayer/src/relayer/read.rs +++ b/crates/astria-sequencer-relayer/src/relayer/read.rs @@ -1,40 +1,18 @@ //! A stream of sequencer blocks. -use std::{ - future::Future as _, - pin::Pin, - sync::Arc, - task::Poll, - time::Duration, -}; +use std::{future::Future as _, pin::Pin, sync::Arc, task::Poll, time::Duration}; use astria_core::{ generated::sequencerblock::v1alpha1::{ - sequencer_service_client::SequencerServiceClient, - GetSequencerBlockRequest, + sequencer_service_client::SequencerServiceClient, GetSequencerBlockRequest, }, sequencerblock::v1alpha1::SequencerBlock, }; -use astria_eyre::eyre::{ - self, - ensure, - Report, - WrapErr as _, -}; -use futures::{ - future::BoxFuture, - ready, - FutureExt as _, -}; +use astria_eyre::eyre::{self, ensure, Report, WrapErr as _}; +use futures::{future::BoxFuture, ready, FutureExt as _}; use pin_project_lite::pin_project; use sequencer_client::tendermint::block::Height; use tokio_stream::Stream; -use tracing::{ - info, - instrument, - warn, - Instrument as _, - Span, -}; +use tracing::{info, instrument, warn, Instrument as _, Span}; /// Tracks the latest sequencer height and returns the next height the stream should fetch. /// @@ -390,10 +368,7 @@ impl BlockStreamBuilder { #[cfg(test)] mod tests { - use super::{ - Height, - Heights, - }; + use super::{Height, Heights}; #[track_caller] fn assert_next_height_is_expected( diff --git a/crates/astria-sequencer-relayer/src/relayer/state.rs b/crates/astria-sequencer-relayer/src/relayer/state.rs index 9083cbb3a..4404d5dd2 100644 --- a/crates/astria-sequencer-relayer/src/relayer/state.rs +++ b/crates/astria-sequencer-relayer/src/relayer/state.rs @@ -7,9 +7,7 @@ pub(super) struct State { impl State { pub(super) fn new() -> Self { let (inner, _) = watch::channel(StateSnapshot::default()); - Self { - inner, - } + Self { inner } } pub(super) fn set_ready(&self) { diff --git a/crates/astria-sequencer-relayer/src/relayer/submission.rs b/crates/astria-sequencer-relayer/src/relayer/submission.rs index 71654a850..6203bbbcf 100644 --- a/crates/astria-sequencer-relayer/src/relayer/submission.rs +++ b/crates/astria-sequencer-relayer/src/relayer/submission.rs @@ -1,25 +1,11 @@ //! Tracks the current submission state of sequencer-relayer and syncs it to disk. -use std::path::{ - Path, - PathBuf, -}; - -use astria_eyre::eyre::{ - self, - bail, - ensure, - WrapErr as _, -}; +use std::path::{Path, PathBuf}; + +use astria_eyre::eyre::{self, bail, ensure, WrapErr as _}; use sequencer_client::tendermint::block::Height as SequencerHeight; -use serde::{ - Deserialize, - Serialize, -}; -use tracing::{ - debug, - warn, -}; +use serde::{Deserialize, Serialize}; +use tracing::{debug, warn}; #[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "snake_case")] @@ -361,11 +347,7 @@ mod as_number { //! This is unfortunately necessary because the [`serde::Serialize`], [`serde::Deserialize`] //! implementations for [`sequencer_client::tendermint::block::Height`] write the integer as //! string, probably due to tendermint's/cometbft's go-legacy. - use serde::{ - Deserialize as _, - Deserializer, - Serializer, - }; + use serde::{Deserialize as _, Deserializer, Serializer}; use super::SequencerHeight; // Allow: the function signature is dictated by the serde(with) attribute. @@ -556,12 +538,7 @@ mod tests { //! These test the same scenarios as the tests of the same name in the super module, but //! whereas those are strict and should fail, the tests in this module should pass - use super::{ - create_files, - json, - write, - SubmissionState, - }; + use super::{create_files, json, write, SubmissionState}; const LENIENT_CONSISTENCY_CHECK: bool = true; diff --git a/crates/astria-sequencer-relayer/src/relayer/write/conversion.rs b/crates/astria-sequencer-relayer/src/relayer/write/conversion.rs index ba6753e45..83e8a3c5b 100644 --- a/crates/astria-sequencer-relayer/src/relayer/write/conversion.rs +++ b/crates/astria-sequencer-relayer/src/relayer/write/conversion.rs @@ -1,9 +1,5 @@ use std::{ - collections::{ - BTreeSet, - HashMap, - HashSet, - }, + collections::{BTreeSet, HashMap, HashSet}, pin::Pin, task::Poll, }; @@ -11,26 +7,16 @@ use std::{ use astria_core::{ brotli::compress_bytes, generated::sequencerblock::v1alpha1::{ - SubmittedMetadata, - SubmittedMetadataList, - SubmittedRollupData, - SubmittedRollupDataList, + SubmittedMetadata, SubmittedMetadataList, SubmittedRollupData, SubmittedRollupDataList, }, primitive::v1::RollupId, }; -use celestia_types::{ - nmt::Namespace, - Blob, -}; +use celestia_types::{nmt::Namespace, Blob}; use futures::Future; use pin_project_lite::pin_project; use sequencer_client::SequencerBlock; use tendermint::block::Height as SequencerHeight; -use tracing::{ - error, - trace, - warn, -}; +use tracing::{error, trace, warn}; use crate::IncludeRollup; @@ -284,12 +270,7 @@ impl Input { for (namespace, entries) in self.rollup_data_for_namespace { payload - .try_add( - namespace, - &SubmittedRollupDataList { - entries, - }, - ) + .try_add(namespace, &SubmittedRollupDataList { entries }) .map_err(|source| TryIntoPayloadError::AddToPayload { source, type_url: SubmittedRollupDataList::full_name(), @@ -369,9 +350,7 @@ impl NextSubmission { /// Only when the returned [`TakeNextSubmission`] future is polled is the data moved /// out, leaving behind an empty [`NextSubmission`] that can be used to accumulate more blocks. pub(super) fn take(&mut self) -> TakeSubmission<'_> { - TakeSubmission { - inner: Some(self), - } + TakeSubmission { inner: Some(self) } } } @@ -401,10 +380,7 @@ impl<'a> Future for TakeSubmission<'a> { number_of_blocks = input.num_blocks(), "returning payload" ); - Poll::Ready(Some(Submission { - input, - payload, - })) + Poll::Ready(Some(Submission { input, payload })) } } } @@ -471,28 +447,16 @@ where #[cfg(test)] mod tests { - use astria_core::{ - primitive::v1::RollupId, - protocol::test_utils::ConfigureSequencerBlock, - }; + use astria_core::{primitive::v1::RollupId, protocol::test_utils::ConfigureSequencerBlock}; use rand_chacha::{ - rand_core::{ - RngCore as _, - SeedableRng as _, - }, + rand_core::{RngCore as _, SeedableRng as _}, ChaChaRng, }; use sequencer_client::SequencerBlock; - use super::{ - Input, - NextSubmission, - }; + use super::{Input, NextSubmission}; use crate::{ - relayer::write::conversion::{ - TryAddError, - MAX_PAYLOAD_SIZE_BYTES, - }, + relayer::write::conversion::{TryAddError, MAX_PAYLOAD_SIZE_BYTES}, IncludeRollup, }; diff --git a/crates/astria-sequencer-relayer/src/relayer/write/mod.rs b/crates/astria-sequencer-relayer/src/relayer/write/mod.rs index 03eaa6501..f44f96f94 100644 --- a/crates/astria-sequencer-relayer/src/relayer/write/mod.rs +++ b/crates/astria-sequencer-relayer/src/relayer/write/mod.rs @@ -8,21 +8,12 @@ //! receives blocks and imposes no extra ordering. This means that if //! another task sends sequencer blocks ordered by their heights, then //! they will be written in that order. -use std::{ - sync::Arc, - time::Duration, -}; +use std::{sync::Arc, time::Duration}; -use astria_eyre::eyre::{ - self, - WrapErr as _, -}; +use astria_eyre::eyre::{self, WrapErr as _}; use celestia_types::Blob; use futures::{ - future::{ - Fuse, - FusedFuture as _, - }, + future::{Fuse, FusedFuture as _}, FutureExt as _, }; use sequencer_client::SequencerBlock; @@ -31,36 +22,19 @@ use tokio::{ sync::{ mpsc::{ self, - error::{ - SendError, - TrySendError, - }, + error::{SendError, TrySendError}, }, watch, }, }; use tokio_util::sync::CancellationToken; -use tracing::{ - debug, - error, - info, - instrument, - warn, - Instrument, - Span, -}; +use tracing::{debug, error, info, instrument, warn, Instrument, Span}; use super::{ - celestia_client::CelestiaClient, - BuilderError, - CelestiaClientBuilder, - SubmissionState, + celestia_client::CelestiaClient, BuilderError, CelestiaClientBuilder, SubmissionState, TrySubmitError, }; -use crate::{ - metrics_init, - IncludeRollup, -}; +use crate::{metrics_init, IncludeRollup}; mod conversion; use conversion::NextSubmission; @@ -142,9 +116,7 @@ impl BlobSubmitter { shutdown_token, pending_block: None, }; - let handle = BlobSubmitterHandle { - tx, - }; + let handle = BlobSubmitterHandle { tx }; (submitter, handle) } diff --git a/crates/astria-sequencer-relayer/src/sequencer_relayer.rs b/crates/astria-sequencer-relayer/src/sequencer_relayer.rs index a6d64da8c..b8187df4f 100644 --- a/crates/astria-sequencer-relayer/src/sequencer_relayer.rs +++ b/crates/astria-sequencer-relayer/src/sequencer_relayer.rs @@ -1,34 +1,19 @@ -use std::{ - net::SocketAddr, - time::Duration, -}; +use std::{net::SocketAddr, time::Duration}; -use astria_eyre::eyre::{ - self, - WrapErr as _, -}; +use astria_eyre::eyre::{self, WrapErr as _}; use tokio::{ select, sync::oneshot, - task::{ - JoinError, - JoinHandle, - }, + task::{JoinError, JoinHandle}, time::timeout, }; use tokio_util::sync::CancellationToken; -use tracing::{ - error, - info, -}; +use tracing::{error, info}; use crate::{ api, config::Config, - relayer::{ - self, - Relayer, - }, + relayer::{self, Relayer}, }; pub struct SequencerRelayer { diff --git a/crates/astria-sequencer-relayer/src/utils.rs b/crates/astria-sequencer-relayer/src/utils.rs index efd49c60e..150752771 100644 --- a/crates/astria-sequencer-relayer/src/utils.rs +++ b/crates/astria-sequencer-relayer/src/utils.rs @@ -1,7 +1,4 @@ -use astria_eyre::eyre::{ - self, - WrapErr as _, -}; +use astria_eyre::eyre::{self, WrapErr as _}; use tokio::task::JoinError; pub(crate) fn flatten(res: Result, JoinError>) -> eyre::Result { diff --git a/crates/astria-sequencer-relayer/src/validator.rs b/crates/astria-sequencer-relayer/src/validator.rs index dc385735a..6c3518a94 100644 --- a/crates/astria-sequencer-relayer/src/validator.rs +++ b/crates/astria-sequencer-relayer/src/validator.rs @@ -1,9 +1,6 @@ use std::path::Path; -use astria_eyre::eyre::{ - self, - WrapErr as _, -}; +use astria_eyre::eyre::{self, WrapErr as _}; use tendermint::account; use tendermint_config::PrivValidatorKey; use tracing::instrument; diff --git a/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_celestia_app_server.rs b/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_celestia_app_server.rs index 0b74ff626..a1074d5a3 100644 --- a/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_celestia_app_server.rs +++ b/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_celestia_app_server.rs @@ -1,31 +1,18 @@ use std::{ net::SocketAddr, - sync::{ - Arc, - Mutex, - }, + sync::{Arc, Mutex}, }; use astria_core::generated::{ celestia::v1::{ - query_server::{ - Query as BlobQueryService, - QueryServer as BlobQueryServer, - }, - Params as BlobParams, - QueryParamsRequest as QueryBlobParamsRequest, + query_server::{Query as BlobQueryService, QueryServer as BlobQueryServer}, + Params as BlobParams, QueryParamsRequest as QueryBlobParamsRequest, QueryParamsResponse as QueryBlobParamsResponse, }, cosmos::{ auth::v1beta1::{ - query_server::{ - Query as AuthQueryService, - QueryServer as AuthQueryServer, - }, - BaseAccount, - Params as AuthParams, - QueryAccountRequest, - QueryAccountResponse, + query_server::{Query as AuthQueryService, QueryServer as AuthQueryServer}, + BaseAccount, Params as AuthParams, QueryAccountRequest, QueryAccountResponse, QueryParamsRequest as QueryAuthParamsRequest, QueryParamsResponse as QueryAuthParamsResponse, }, @@ -33,63 +20,32 @@ use astria_core::generated::{ abci::v1beta1::TxResponse, node::v1beta1::{ service_server::{ - Service as MinGasPriceService, - ServiceServer as MinGasPriceServer, + Service as MinGasPriceService, ServiceServer as MinGasPriceServer, }, - ConfigRequest as MinGasPriceRequest, - ConfigResponse as MinGasPriceResponse, + ConfigRequest as MinGasPriceRequest, ConfigResponse as MinGasPriceResponse, }, tendermint::v1beta1::{ - service_server::{ - Service as NodeInfoService, - ServiceServer as NodeInfoServer, - }, - GetNodeInfoRequest, - GetNodeInfoResponse, + service_server::{Service as NodeInfoService, ServiceServer as NodeInfoServer}, + GetNodeInfoRequest, GetNodeInfoResponse, }, }, tx::v1beta1::{ - service_server::{ - Service as TxService, - ServiceServer as TxServer, - }, - BroadcastTxRequest, - BroadcastTxResponse, - GetTxRequest, - GetTxResponse, + service_server::{Service as TxService, ServiceServer as TxServer}, + BroadcastTxRequest, BroadcastTxResponse, GetTxRequest, GetTxResponse, }, }, - tendermint::{ - p2p::DefaultNodeInfo, - types::BlobTx, - }, -}; -use astria_eyre::eyre::{ - self, - WrapErr as _, + tendermint::{p2p::DefaultNodeInfo, types::BlobTx}, }; +use astria_eyre::eyre::{self, WrapErr as _}; use astria_grpc_mock::{ matcher::message_type, - response::{ - constant_response, - dynamic_response, - }, - Mock, - MockGuard, - MockServer, + response::{constant_response, dynamic_response}, + Mock, MockGuard, MockServer, }; use celestia_types::nmt::Namespace; -use prost::{ - Message, - Name, -}; +use prost::{Message, Name}; use tokio::task::JoinHandle; -use tonic::{ - transport::Server, - Request, - Response, - Status, -}; +use tonic::{transport::Server, Request, Response, Status}; const CELESTIA_NETWORK_NAME: &str = "test-celestia"; const GET_NODE_INFO_GRPC_NAME: &str = "get_node_info"; diff --git a/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_sequencer_server.rs b/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_sequencer_server.rs index 24401ee8b..5b2be674d 100644 --- a/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_sequencer_server.rs +++ b/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_sequencer_server.rs @@ -1,44 +1,23 @@ -use std::{ - net::SocketAddr, - sync::Arc, -}; +use std::{net::SocketAddr, sync::Arc}; use astria_core::{ generated::sequencerblock::v1alpha1::{ - sequencer_service_server::{ - SequencerService, - SequencerServiceServer, - }, - FilteredSequencerBlock as RawFilteredSequencerBlock, - GetFilteredSequencerBlockRequest, - GetPendingNonceRequest, - GetPendingNonceResponse, - GetSequencerBlockRequest, + sequencer_service_server::{SequencerService, SequencerServiceServer}, + FilteredSequencerBlock as RawFilteredSequencerBlock, GetFilteredSequencerBlockRequest, + GetPendingNonceRequest, GetPendingNonceResponse, GetSequencerBlockRequest, SequencerBlock as RawSequencerBlock, }, primitive::v1::RollupId, protocol::test_utils::ConfigureSequencerBlock, sequencerblock::v1alpha1::SequencerBlock, }; -use astria_eyre::eyre::{ - self, - WrapErr as _, -}; +use astria_eyre::eyre::{self, WrapErr as _}; use astria_grpc_mock::{ - matcher::message_type, - response::constant_response, - Mock, - MockGuard, - MockServer, + matcher::message_type, response::constant_response, Mock, MockGuard, MockServer, }; use tendermint::account::Id as AccountId; use tokio::task::JoinHandle; -use tonic::{ - transport::Server, - Request, - Response, - Status, -}; +use tonic::{transport::Server, Request, Response, Status}; const GET_SEQUENCER_BLOCK_GRPC_NAME: &str = "get_sequencer_block"; const GET_FILTERED_SEQUENCER_BLOCK_GRPC_NAME: &str = "get_filtered_sequencer_block"; diff --git a/crates/astria-sequencer-relayer/tests/blackbox/helpers/mod.rs b/crates/astria-sequencer-relayer/tests/blackbox/helpers/mod.rs index f9ea1ccd4..c6c24b9ba 100644 --- a/crates/astria-sequencer-relayer/tests/blackbox/helpers/mod.rs +++ b/crates/astria-sequencer-relayer/tests/blackbox/helpers/mod.rs @@ -4,9 +4,6 @@ mod test_sequencer_relayer; pub use self::{ mock_celestia_app_server::MockCelestiaAppServer, - mock_sequencer_server::{ - MockSequencerServer, - SequencerBlockToMount, - }, + mock_sequencer_server::{MockSequencerServer, SequencerBlockToMount}, test_sequencer_relayer::TestSequencerRelayerConfig, }; diff --git a/crates/astria-sequencer-relayer/tests/blackbox/helpers/test_sequencer_relayer.rs b/crates/astria-sequencer-relayer/tests/blackbox/helpers/test_sequencer_relayer.rs index 3f08ea2c8..6ead53d38 100644 --- a/crates/astria-sequencer-relayer/tests/blackbox/helpers/test_sequencer_relayer.rs +++ b/crates/astria-sequencer-relayer/tests/blackbox/helpers/test_sequencer_relayer.rs @@ -1,10 +1,6 @@ use std::{ collections::HashSet, - fmt::{ - self, - Display, - Formatter, - }, + fmt::{self, Display, Formatter}, future::Future, io::Write, mem, @@ -13,56 +9,26 @@ use std::{ }; use assert_json_diff::assert_json_include; -use astria_core::{ - crypto::SigningKey, - primitive::v1::RollupId, -}; +use astria_core::{crypto::SigningKey, primitive::v1::RollupId}; use astria_grpc_mock::MockGuard as GrpcMockGuard; -use astria_sequencer_relayer::{ - config::Config, - SequencerRelayer, - ShutdownHandle, -}; +use astria_sequencer_relayer::{config::Config, SequencerRelayer, ShutdownHandle}; use futures::TryFutureExt; use itertools::Itertools; use once_cell::sync::Lazy; -use reqwest::{ - Response, - StatusCode, -}; +use reqwest::{Response, StatusCode}; use serde::Deserialize; use serde_json::json; use tempfile::NamedTempFile; use tendermint_config::PrivValidatorKey; -use tendermint_rpc::{ - response::Wrapper, - Id, -}; +use tendermint_rpc::{response::Wrapper, Id}; use tokio::{ - runtime::{ - self, - RuntimeFlavor, - }, - task::{ - yield_now, - JoinHandle, - }, -}; -use tracing::{ - error, - info, -}; -use wiremock::{ - matchers::body_partial_json, - MockServer as WireMockServer, - ResponseTemplate, + runtime::{self, RuntimeFlavor}, + task::{yield_now, JoinHandle}, }; +use tracing::{error, info}; +use wiremock::{matchers::body_partial_json, MockServer as WireMockServer, ResponseTemplate}; -use super::{ - MockCelestiaAppServer, - MockSequencerServer, - SequencerBlockToMount, -}; +use super::{MockCelestiaAppServer, MockSequencerServer, SequencerBlockToMount}; /// Copied verbatim from /// [tendermint-rs](https://github.com/informalsystems/tendermint-rs/blob/main/config/tests/support/config/priv_validator_key.ed25519.json) @@ -154,10 +120,7 @@ impl Drop for TestSequencerRelayer { impl TestSequencerRelayer { /// Mounts a `CometBFT` ABCI Info response. pub async fn mount_abci_response(&self, height: u32) { - use tendermint::{ - abci, - hash::AppHash, - }; + use tendermint::{abci, hash::AppHash}; use tendermint_rpc::endpoint::abci_info; let abci_response = abci_info::Response { response: abci::response::Info { @@ -631,9 +594,7 @@ impl TestSequencerRelayerConfig { let validator_keyfile = write_file(PRIVATE_VALIDATOR_KEY.as_bytes()).await; let PrivValidatorKey { - address, - priv_key, - .. + address, priv_key, .. } = PrivValidatorKey::parse_json(PRIVATE_VALIDATOR_KEY).unwrap(); let signing_key = priv_key .ed25519_signing_key() diff --git a/crates/astria-sequencer-relayer/tests/blackbox/main.rs b/crates/astria-sequencer-relayer/tests/blackbox/main.rs index bcd165f4f..1f5a6b84c 100644 --- a/crates/astria-sequencer-relayer/tests/blackbox/main.rs +++ b/crates/astria-sequencer-relayer/tests/blackbox/main.rs @@ -4,14 +4,8 @@ pub mod helpers; use std::collections::HashSet; -use astria_core::{ - primitive::v1::RollupId, - protocol::test_utils::ConfigureSequencerBlock, -}; -use helpers::{ - SequencerBlockToMount, - TestSequencerRelayerConfig, -}; +use astria_core::{primitive::v1::RollupId, protocol::test_utils::ConfigureSequencerBlock}; +use helpers::{SequencerBlockToMount, TestSequencerRelayerConfig}; use reqwest::StatusCode; use tendermint::account::Id as AccountId; diff --git a/crates/astria-sequencer-utils/src/blob_parser.rs b/crates/astria-sequencer-utils/src/blob_parser.rs index 803f8f716..3610c342f 100644 --- a/crates/astria-sequencer-utils/src/blob_parser.rs +++ b/crates/astria-sequencer-utils/src/blob_parser.rs @@ -1,12 +1,6 @@ use std::{ - fmt::{ - self, - Display, - Formatter, - Write, - }, - fs, - io, + fmt::{self, Display, Formatter, Write}, + fs, io, num::NonZeroUsize, path::Path, }; @@ -14,50 +8,27 @@ use std::{ use astria_core::{ brotli::decompress_bytes, generated::sequencerblock::v1alpha1::{ - rollup_data::Value as RawRollupDataValue, - Deposit as RawDeposit, - RollupData as RawRollupData, - SubmittedMetadata as RawSubmittedMetadata, + rollup_data::Value as RawRollupDataValue, Deposit as RawDeposit, + RollupData as RawRollupData, SubmittedMetadata as RawSubmittedMetadata, SubmittedMetadataList as RawSubmittedMetadataList, SubmittedRollupData as RawSubmittedRollupData, SubmittedRollupDataList as RawSubmittedRollupDataList, }, primitive::v1::RollupId, sequencerblock::v1alpha1::{ - block::{ - Deposit, - DepositError, - SequencerBlockHeader, - }, - celestia::{ - SubmittedRollupData, - UncheckedSubmittedMetadata, - UncheckedSubmittedRollupData, - }, + block::{Deposit, DepositError, SequencerBlockHeader}, + celestia::{SubmittedRollupData, UncheckedSubmittedMetadata, UncheckedSubmittedRollupData}, }, }; -use astria_eyre::eyre::{ - bail, - Result, - WrapErr, -}; +use astria_eyre::eyre::{bail, Result, WrapErr}; use astria_merkle::audit::Proof; -use base64::{ - prelude::BASE64_STANDARD, - Engine, -}; +use base64::{prelude::BASE64_STANDARD, Engine}; use clap::ValueEnum; use colour::write_blue; -use ethers_core::types::{ - transaction::eip2930::AccessListItem, - Transaction, -}; +use ethers_core::types::{transaction::eip2930::AccessListItem, Transaction}; use indenter::indented; use itertools::Itertools; -use prost::{ - bytes::Bytes, - Message, -}; +use prost::{bytes::Bytes, Message}; use serde::Serialize; #[derive(clap::Args, Debug)] diff --git a/crates/astria-sequencer-utils/src/cli.rs b/crates/astria-sequencer-utils/src/cli.rs index acc11b0c2..08cabcd1f 100644 --- a/crates/astria-sequencer-utils/src/cli.rs +++ b/crates/astria-sequencer-utils/src/cli.rs @@ -1,12 +1,6 @@ -use clap::{ - Parser, - Subcommand, -}; +use clap::{Parser, Subcommand}; -use super::{ - blob_parser, - genesis_parser, -}; +use super::{blob_parser, genesis_parser}; /// Utilities for working with the Astria sequencer network #[derive(Debug, Parser)] diff --git a/crates/astria-sequencer-utils/src/genesis_parser.rs b/crates/astria-sequencer-utils/src/genesis_parser.rs index a61d67b68..66fe69c01 100644 --- a/crates/astria-sequencer-utils/src/genesis_parser.rs +++ b/crates/astria-sequencer-utils/src/genesis_parser.rs @@ -1,16 +1,7 @@ -use std::{ - fs::File, - path::PathBuf, -}; - -use astria_eyre::eyre::{ - Result, - WrapErr, -}; -use serde_json::{ - to_writer_pretty, - Value, -}; +use std::{fs::File, path::PathBuf}; + +use astria_eyre::eyre::{Result, WrapErr}; +use serde_json::{to_writer_pretty, Value}; #[derive(clap::Args, Debug)] pub struct Args { diff --git a/crates/astria-sequencer-utils/src/main.rs b/crates/astria-sequencer-utils/src/main.rs index 6bede2c3c..b876fd062 100644 --- a/crates/astria-sequencer-utils/src/main.rs +++ b/crates/astria-sequencer-utils/src/main.rs @@ -1,10 +1,7 @@ use astria_eyre::eyre::Result; use astria_sequencer_utils::{ blob_parser, - cli::{ - self, - Command, - }, + cli::{self, Command}, genesis_parser, }; diff --git a/crates/astria-sequencer-utils/tests/parse_blob.rs b/crates/astria-sequencer-utils/tests/parse_blob.rs index c6064d748..de42204e3 100644 --- a/crates/astria-sequencer-utils/tests/parse_blob.rs +++ b/crates/astria-sequencer-utils/tests/parse_blob.rs @@ -1,16 +1,10 @@ use std::{ fs, - path::{ - Path, - PathBuf, - }, + path::{Path, PathBuf}, }; use assert_cmd::Command; -use astria_eyre::{ - eyre::WrapErr, - Result, -}; +use astria_eyre::{eyre::WrapErr, Result}; use predicates::prelude::*; struct Resources { diff --git a/crates/astria-sequencer/src/accounts/action.rs b/crates/astria-sequencer/src/accounts/action.rs index 1546add77..75bbcdcc4 100644 --- a/crates/astria-sequencer/src/accounts/action.rs +++ b/crates/astria-sequencer/src/accounts/action.rs @@ -1,23 +1,12 @@ -use anyhow::{ - ensure, - Context, - Result, -}; +use anyhow::{ensure, Context, Result}; use astria_core::{ - primitive::v1::Address, - protocol::transaction::v1alpha1::action::TransferAction, + primitive::v1::Address, protocol::transaction::v1alpha1::action::TransferAction, }; use tracing::instrument; use crate::{ - accounts::state_ext::{ - StateReadExt, - StateWriteExt, - }, - state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, + accounts::state_ext::{StateReadExt, StateWriteExt}, + state_ext::{StateReadExt as _, StateWriteExt as _}, transaction::action_handler::ActionHandler, }; diff --git a/crates/astria-sequencer/src/accounts/component.rs b/crates/astria-sequencer/src/accounts/component.rs index 376b9c6ce..e090cde5d 100644 --- a/crates/astria-sequencer/src/accounts/component.rs +++ b/crates/astria-sequencer/src/accounts/component.rs @@ -1,21 +1,11 @@ use std::sync::Arc; -use anyhow::{ - Context, - Result, -}; -use tendermint::abci::request::{ - BeginBlock, - EndBlock, -}; +use anyhow::{Context, Result}; +use tendermint::abci::request::{BeginBlock, EndBlock}; use tracing::instrument; use super::state_ext::StateWriteExt; -use crate::{ - asset::get_native_asset, - component::Component, - genesis::GenesisState, -}; +use crate::{asset::get_native_asset, component::Component, genesis::GenesisState}; #[derive(Default)] pub(crate) struct AccountsComponent; diff --git a/crates/astria-sequencer/src/accounts/query.rs b/crates/astria-sequencer/src/accounts/query.rs index 2ac08081b..2850b3bf1 100644 --- a/crates/astria-sequencer/src/accounts/query.rs +++ b/crates/astria-sequencer/src/accounts/query.rs @@ -1,25 +1,13 @@ use anyhow::Context as _; -use astria_core::{ - primitive::v1::Address, - protocol::abci::AbciErrorCode, -}; -use cnidarium::{ - Snapshot, - Storage, -}; +use astria_core::{primitive::v1::Address, protocol::abci::AbciErrorCode}; +use cnidarium::{Snapshot, Storage}; use prost::Message as _; use tendermint::{ - abci::{ - request, - response, - }, + abci::{request, response}, block::Height, }; -use crate::{ - accounts::state_ext::StateReadExt as _, - state_ext::StateReadExt as _, -}; +use crate::{accounts::state_ext::StateReadExt as _, state_ext::StateReadExt as _}; pub(crate) async fn balance_request( storage: Storage, diff --git a/crates/astria-sequencer/src/accounts/state_ext.rs b/crates/astria-sequencer/src/accounts/state_ext.rs index b1053ea60..c964058f2 100644 --- a/crates/astria-sequencer/src/accounts/state_ext.rs +++ b/crates/astria-sequencer/src/accounts/state_ext.rs @@ -1,23 +1,11 @@ -use anyhow::{ - Context, - Result, -}; +use anyhow::{Context, Result}; use astria_core::{ - primitive::v1::{ - asset, - Address, - }, + primitive::v1::{asset, Address}, protocol::account::v1alpha1::AssetBalance, }; use async_trait::async_trait; -use borsh::{ - BorshDeserialize, - BorshSerialize, -}; -use cnidarium::{ - StateRead, - StateWrite, -}; +use borsh::{BorshDeserialize, BorshSerialize}; +use cnidarium::{StateRead, StateWrite}; use futures::StreamExt; use hex::ToHex as _; use tracing::instrument; @@ -101,10 +89,7 @@ pub(crate) trait StateReadExt: StateRead { .await .context("failed to get ibc asset denom")? .context("asset denom not found when user has balance of it; this is a bug")?; - balances.push(AssetBalance { - denom, - balance, - }); + balances.push(AssetBalance { denom, balance }); } Ok(balances) } @@ -233,21 +218,14 @@ impl StateWriteExt for T {} mod test { use astria_core::{ primitive::v1::{ - asset::{ - Denom, - Id, - DEFAULT_NATIVE_ASSET_DENOM, - }, + asset::{Denom, Id, DEFAULT_NATIVE_ASSET_DENOM}, Address, }, protocol::account::v1alpha1::AssetBalance, }; use cnidarium::StateDelta; - use super::{ - StateReadExt as _, - StateWriteExt as _, - }; + use super::{StateReadExt as _, StateWriteExt as _}; use crate::asset; #[tokio::test] diff --git a/crates/astria-sequencer/src/api_state_ext.rs b/crates/astria-sequencer/src/api_state_ext.rs index c7cc067f2..59870fe0e 100644 --- a/crates/astria-sequencer/src/api_state_ext.rs +++ b/crates/astria-sequencer/src/api_state_ext.rs @@ -1,32 +1,15 @@ -use anyhow::{ - anyhow, - bail, - Context as _, - Result, -}; +use anyhow::{anyhow, bail, Context as _, Result}; use astria_core::{ - generated::{ - primitive::v1 as primitiveRaw, - sequencerblock::v1alpha1 as raw, - }, + generated::{primitive::v1 as primitiveRaw, sequencerblock::v1alpha1 as raw}, primitive::v1::RollupId, sequencerblock::v1alpha1::block::{ - RollupTransactions, - SequencerBlock, - SequencerBlockHeader, - SequencerBlockParts, + RollupTransactions, SequencerBlock, SequencerBlockHeader, SequencerBlockParts, }, Protobuf as _, }; use async_trait::async_trait; -use borsh::{ - BorshDeserialize, - BorshSerialize, -}; -use cnidarium::{ - StateRead, - StateWrite, -}; +use borsh::{BorshDeserialize, BorshSerialize}; +use cnidarium::{StateRead, StateWrite}; use prost::Message; use tracing::instrument; @@ -70,10 +53,7 @@ impl From> for RollupIdSeq { } mod rollup_id_impl { - use super::{ - RollupId, - RollupIdSer, - }; + use super::{RollupId, RollupIdSer}; pub(super) fn deserialize( reader: &mut R, @@ -383,10 +363,7 @@ impl StateWriteExt for T {} #[cfg(test)] mod test { use astria_core::{ - primitive::v1::{ - asset::Id, - Address, - }, + primitive::v1::{asset::Id, Address}, protocol::test_utils::ConfigureSequencerBlock, sequencerblock::v1alpha1::block::Deposit, }; diff --git a/crates/astria-sequencer/src/app/mod.rs b/crates/astria-sequencer/src/app/mod.rs index bff3d5764..5879a9c0d 100644 --- a/crates/astria-sequencer/src/app/mod.rs +++ b/crates/astria-sequencer/src/app/mod.rs @@ -7,83 +7,43 @@ mod tests_breaking_changes; #[cfg(test)] mod tests_execute_transaction; -use std::{ - collections::VecDeque, - sync::Arc, -}; +use std::{collections::VecDeque, sync::Arc}; -use anyhow::{ - anyhow, - ensure, - Context, -}; +use anyhow::{anyhow, ensure, Context}; use astria_core::{ generated::protocol::transaction::v1alpha1 as raw, primitive::v1::Address, protocol::{ abci::AbciErrorCode, - transaction::v1alpha1::{ - Action, - SignedTransaction, - }, + transaction::v1alpha1::{Action, SignedTransaction}, }, sequencerblock::v1alpha1::block::SequencerBlock, }; -use cnidarium::{ - ArcStateDeltaExt, - Snapshot, - StagedWriteBatch, - StateDelta, - Storage, -}; +use cnidarium::{ArcStateDeltaExt, Snapshot, StagedWriteBatch, StateDelta, Storage}; use prost::Message as _; -use sha2::{ - Digest as _, - Sha256, -}; +use sha2::{Digest as _, Sha256}; use telemetry::display::json; use tendermint::{ - abci::{ - self, - types::ExecTxResult, - Event, - }, + abci::{self, types::ExecTxResult, Event}, account, block::Header, - AppHash, - Hash, -}; -use tracing::{ - debug, - info, - instrument, + AppHash, Hash, }; +use tracing::{debug, info, instrument}; use crate::{ accounts::{ component::AccountsComponent, - state_ext::{ - StateReadExt, - StateWriteExt as _, - }, + state_ext::{StateReadExt, StateWriteExt as _}, }, api_state_ext::StateWriteExt as _, authority::{ - component::{ - AuthorityComponent, - AuthorityComponentAppState, - }, - state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, + component::{AuthorityComponent, AuthorityComponentAppState}, + state_ext::{StateReadExt as _, StateWriteExt as _}, }, bridge::{ component::BridgeComponent, - state_ext::{ - StateReadExt as _, - StateWriteExt, - }, + state_ext::{StateReadExt as _, StateWriteExt}, }, component::Component as _, genesis::GenesisState, @@ -92,20 +52,11 @@ use crate::{ metrics_init, proposal::{ block_size_constraints::BlockSizeConstraints, - commitment::{ - generate_rollup_datas_commitment, - GeneratedCommitments, - }, + commitment::{generate_rollup_datas_commitment, GeneratedCommitments}, }, sequence::component::SequenceComponent, - state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, - transaction::{ - self, - InvalidNonce, - }, + state_ext::{StateReadExt as _, StateWriteExt as _}, + transaction::{self, InvalidNonce}, }; /// The inter-block state being written to by the application. diff --git a/crates/astria-sequencer/src/app/test_utils.rs b/crates/astria-sequencer/src/app/test_utils.rs index 09c42c2f0..b9a1526c2 100644 --- a/crates/astria-sequencer/src/app/test_utils.rs +++ b/crates/astria-sequencer/src/app/test_utils.rs @@ -1,16 +1,8 @@ use astria_core::{ crypto::SigningKey, - primitive::v1::{ - asset::DEFAULT_NATIVE_ASSET_DENOM, - Address, - RollupId, - ADDRESS_LEN, - }, + primitive::v1::{asset::DEFAULT_NATIVE_ASSET_DENOM, Address, RollupId, ADDRESS_LEN}, protocol::transaction::v1alpha1::{ - action::SequenceAction, - SignedTransaction, - TransactionParams, - UnsignedTransaction, + action::SequenceAction, SignedTransaction, TransactionParams, UnsignedTransaction, }, }; use cnidarium::Storage; @@ -18,11 +10,7 @@ use penumbra_ibc::params::IBCParameters; use crate::{ app::App, - genesis::{ - self, - Account, - GenesisState, - }, + genesis::{self, Account, GenesisState}, mempool::Mempool, }; @@ -140,14 +128,12 @@ pub(crate) fn get_mock_tx(nonce: u32) -> SignedTransaction { nonce, chain_id: "test".to_string(), }, - actions: vec![ - SequenceAction { - rollup_id: RollupId::from_unhashed_bytes([0; 32]), - data: vec![0x99], - fee_asset_id: astria_core::primitive::v1::asset::default_native_asset_id(), - } - .into(), - ], + actions: vec![SequenceAction { + rollup_id: RollupId::from_unhashed_bytes([0; 32]), + data: vec![0x99], + fee_asset_id: astria_core::primitive::v1::asset::default_native_asset_id(), + } + .into()], }; tx.into_signed(&alice_signing_key) diff --git a/crates/astria-sequencer/src/app/tests_app.rs b/crates/astria-sequencer/src/app/tests_app.rs index 9e718df32..0cff99128 100644 --- a/crates/astria-sequencer/src/app/tests_app.rs +++ b/crates/astria-sequencer/src/app/tests_app.rs @@ -1,40 +1,20 @@ use std::collections::HashMap; use astria_core::{ - primitive::v1::{ - asset::DEFAULT_NATIVE_ASSET_DENOM, - Address, - RollupId, - }, + primitive::v1::{asset::DEFAULT_NATIVE_ASSET_DENOM, Address, RollupId}, protocol::transaction::v1alpha1::{ - action::{ - BridgeLockAction, - SequenceAction, - TransferAction, - }, - TransactionParams, - UnsignedTransaction, + action::{BridgeLockAction, SequenceAction, TransferAction}, + TransactionParams, UnsignedTransaction, }, sequencerblock::v1alpha1::block::Deposit, }; use cnidarium::StateDelta; use prost::Message as _; use tendermint::{ - abci::{ - self, - request::PrepareProposal, - types::CommitInfo, - }, + abci::{self, request::PrepareProposal, types::CommitInfo}, account, - block::{ - header::Version, - Header, - Height, - Round, - }, - AppHash, - Hash, - Time, + block::{header::Version, Header, Height, Round}, + AppHash, Hash, Time, }; use super::*; @@ -42,15 +22,8 @@ use crate::{ accounts::state_ext::StateReadExt as _, app::test_utils::*, asset::get_native_asset, - authority::state_ext::{ - StateReadExt as _, - StateWriteExt as _, - ValidatorSet, - }, - bridge::state_ext::{ - StateReadExt as _, - StateWriteExt, - }, + authority::state_ext::{StateReadExt as _, StateWriteExt as _, ValidatorSet}, + bridge::state_ext::{StateReadExt as _, StateWriteExt}, genesis::Account, proposal::commitment::generate_rollup_datas_commitment, state_ext::StateReadExt as _, @@ -71,10 +44,7 @@ fn default_tendermint_header() -> Header { proposer_address: account::Id::try_from([0u8; 20].to_vec()).unwrap(), time: Time::now(), validators_hash: Hash::default(), - version: Version { - app: 0, - block: 0, - }, + version: Version { app: 0, block: 0 }, } } @@ -83,11 +53,7 @@ async fn app_genesis_and_init_chain() { let app = initialize_app(None, vec![]).await; assert_eq!(app.state.get_block_height().await.unwrap(), 0); - for Account { - address, - balance, - } in default_genesis_accounts() - { + for Account { address, balance } in default_genesis_accounts() { assert_eq!( balance, app.state @@ -127,10 +93,7 @@ async fn app_pre_execute_transactions() { #[tokio::test] async fn app_begin_block_remove_byzantine_validators() { - use tendermint::{ - abci::types, - validator, - }; + use tendermint::{abci::types, validator}; let pubkey_a = tendermint::public_key::PublicKey::from_raw_ed25519(&[1; 32]).unwrap(); let pubkey_b = tendermint::public_key::PublicKey::from_raw_ed25519(&[2; 32]).unwrap(); @@ -190,11 +153,7 @@ async fn app_commit() { assert_eq!(app.state.get_block_height().await.unwrap(), 0); let native_asset = get_native_asset().id(); - for Account { - address, - balance, - } in default_genesis_accounts() - { + for Account { address, balance } in default_genesis_accounts() { assert_eq!( balance, app.state @@ -211,11 +170,7 @@ async fn app_commit() { let snapshot = storage.latest_snapshot(); assert_eq!(snapshot.get_block_height().await.unwrap(), 0); - for Account { - address, - balance, - } in default_genesis_accounts() - { + for Account { address, balance } in default_genesis_accounts() { assert_eq!( snapshot .get_account_balance(address, native_asset) @@ -241,15 +196,13 @@ async fn app_transfer_block_fees_to_sudo() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![ - TransferAction { - to: bob_address, - amount, - asset_id: native_asset, - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![TransferAction { + to: bob_address, + amount, + asset_id: native_asset, + fee_asset_id: get_native_asset().id(), + } + .into()], }; let signed_tx = tx.into_signed(&alice_signing_key); @@ -545,14 +498,12 @@ async fn app_prepare_proposal_cometbft_max_bytes_overflow_ok() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![ - SequenceAction { - rollup_id: RollupId::from([1u8; 32]), - data: vec![1u8; 100_000], - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![SequenceAction { + rollup_id: RollupId::from([1u8; 32]), + data: vec![1u8; 100_000], + fee_asset_id: get_native_asset().id(), + } + .into()], } .into_signed(&alice_signing_key); let tx_overflow = UnsignedTransaction { @@ -560,14 +511,12 @@ async fn app_prepare_proposal_cometbft_max_bytes_overflow_ok() { nonce: 1, chain_id: "test".to_string(), }, - actions: vec![ - SequenceAction { - rollup_id: RollupId::from([1u8; 32]), - data: vec![1u8; 100_000], - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![SequenceAction { + rollup_id: RollupId::from([1u8; 32]), + data: vec![1u8; 100_000], + fee_asset_id: get_native_asset().id(), + } + .into()], } .into_signed(&alice_signing_key); @@ -618,14 +567,12 @@ async fn app_prepare_proposal_sequencer_max_bytes_overflow_ok() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![ - SequenceAction { - rollup_id: RollupId::from([1u8; 32]), - data: vec![1u8; 200_000], - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![SequenceAction { + rollup_id: RollupId::from([1u8; 32]), + data: vec![1u8; 200_000], + fee_asset_id: get_native_asset().id(), + } + .into()], } .into_signed(&alice_signing_key); let tx_overflow = UnsignedTransaction { @@ -633,14 +580,12 @@ async fn app_prepare_proposal_sequencer_max_bytes_overflow_ok() { nonce: 1, chain_id: "test".to_string(), }, - actions: vec![ - SequenceAction { - rollup_id: RollupId::from([1u8; 32]), - data: vec![1u8; 100_000], - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![SequenceAction { + rollup_id: RollupId::from([1u8; 32]), + data: vec![1u8; 100_000], + fee_asset_id: get_native_asset().id(), + } + .into()], } .into_signed(&alice_signing_key); diff --git a/crates/astria-sequencer/src/app/tests_breaking_changes.rs b/crates/astria-sequencer/src/app/tests_breaking_changes.rs index cccf427a2..7afc76f32 100644 --- a/crates/astria-sequencer/src/app/tests_breaking_changes.rs +++ b/crates/astria-sequencer/src/app/tests_breaking_changes.rs @@ -9,53 +9,29 @@ //! These are due to the extensive setup needed to test them. //! If changes are made to the execution results of these actions, manual testing is required. -use std::{ - collections::HashMap, - sync::Arc, -}; +use std::{collections::HashMap, sync::Arc}; use astria_core::{ - primitive::v1::{ - asset::DEFAULT_NATIVE_ASSET_DENOM, - Address, - RollupId, - }, + primitive::v1::{asset::DEFAULT_NATIVE_ASSET_DENOM, Address, RollupId}, protocol::transaction::v1alpha1::{ action::{ - BridgeLockAction, - BridgeUnlockAction, - IbcRelayerChangeAction, - SequenceAction, + BridgeLockAction, BridgeUnlockAction, IbcRelayerChangeAction, SequenceAction, TransferAction, }, - Action, - TransactionParams, - UnsignedTransaction, + Action, TransactionParams, UnsignedTransaction, }, sequencerblock::v1alpha1::block::Deposit, }; use cnidarium::StateDelta; use penumbra_ibc::params::IBCParameters; use prost::Message as _; -use tendermint::{ - abci, - abci::types::CommitInfo, - block::Round, - Hash, - Time, -}; +use tendermint::{abci, abci::types::CommitInfo, block::Round, Hash, Time}; use crate::{ app::test_utils::{ - address_from_hex_string, - default_fees, - default_genesis_accounts, - get_alice_signing_key_and_address, - get_bridge_signing_key_and_address, - initialize_app, - initialize_app_with_storage, - BOB_ADDRESS, - CAROL_ADDRESS, + address_from_hex_string, default_fees, default_genesis_accounts, + get_alice_signing_key_and_address, get_bridge_signing_key_and_address, initialize_app, + initialize_app_with_storage, BOB_ADDRESS, CAROL_ADDRESS, }, asset::get_native_asset, bridge::state_ext::StateWriteExt as _, @@ -156,9 +132,7 @@ async fn app_execute_transaction_with_every_action_snapshot() { use astria_core::{ primitive::v1::asset, protocol::transaction::v1alpha1::action::{ - FeeAssetChangeAction, - InitBridgeAccountAction, - SudoAddressChangeAction, + FeeAssetChangeAction, InitBridgeAccountAction, SudoAddressChangeAction, }, }; @@ -253,15 +227,13 @@ async fn app_execute_transaction_with_every_action_snapshot() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![ - BridgeUnlockAction { - to: bob_address, - amount: 10, - fee_asset_id: get_native_asset().id(), - memo: vec![0u8; 32], - } - .into(), - ], + actions: vec![BridgeUnlockAction { + to: bob_address, + amount: 10, + fee_asset_id: get_native_asset().id(), + memo: vec![0u8; 32], + } + .into()], }; let signed_tx = Arc::new(tx.into_signed(&bridge_signing_key)); diff --git a/crates/astria-sequencer/src/app/tests_execute_transaction.rs b/crates/astria-sequencer/src/app/tests_execute_transaction.rs index 7ea28736c..978d8fb8b 100644 --- a/crates/astria-sequencer/src/app/tests_execute_transaction.rs +++ b/crates/astria-sequencer/src/app/tests_execute_transaction.rs @@ -2,24 +2,13 @@ use std::sync::Arc; use astria_core::{ crypto::SigningKey, - primitive::v1::{ - asset, - asset::DEFAULT_NATIVE_ASSET_DENOM, - Address, - RollupId, - }, + primitive::v1::{asset, asset::DEFAULT_NATIVE_ASSET_DENOM, Address, RollupId}, protocol::transaction::v1alpha1::{ action::{ - BridgeLockAction, - BridgeUnlockAction, - IbcRelayerChangeAction, - SequenceAction, - SudoAddressChangeAction, - TransferAction, + BridgeLockAction, BridgeUnlockAction, IbcRelayerChangeAction, SequenceAction, + SudoAddressChangeAction, TransferAction, }, - Action, - TransactionParams, - UnsignedTransaction, + Action, TransactionParams, UnsignedTransaction, }, sequencerblock::v1alpha1::block::Deposit, }; @@ -31,18 +20,12 @@ use crate::{ app::test_utils::*, asset::get_native_asset, authority::state_ext::StateReadExt as _, - bridge::state_ext::{ - StateReadExt as _, - StateWriteExt, - }, + bridge::state_ext::{StateReadExt as _, StateWriteExt}, genesis::GenesisState, ibc::state_ext::StateReadExt as _, sequence::calculate_fee_from_state, state_ext::StateReadExt as _, - transaction::{ - InvalidChainId, - InvalidNonce, - }, + transaction::{InvalidChainId, InvalidNonce}, }; #[tokio::test] @@ -58,15 +41,13 @@ async fn app_execute_transaction_transfer() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![ - TransferAction { - to: bob_address, - amount: value, - asset_id: get_native_asset().id(), - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![TransferAction { + to: bob_address, + amount: value, + asset_id: get_native_asset().id(), + fee_asset_id: get_native_asset().id(), + } + .into()], }; let signed_tx = Arc::new(tx.into_signed(&alice_signing_key)); @@ -115,15 +96,13 @@ async fn app_execute_transaction_transfer_not_native_token() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![ - TransferAction { - to: bob_address, - amount: value, - asset_id: asset, - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![TransferAction { + to: bob_address, + amount: value, + asset_id: asset, + fee_asset_id: get_native_asset().id(), + } + .into()], }; let signed_tx = Arc::new(tx.into_signed(&alice_signing_key)); @@ -181,15 +160,13 @@ async fn app_execute_transaction_transfer_balance_too_low_for_fee() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![ - TransferAction { - to: bob, - amount: 0, - asset_id: get_native_asset().id(), - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![TransferAction { + to: bob, + amount: 0, + asset_id: get_native_asset().id(), + fee_asset_id: get_native_asset().id(), + } + .into()], }; let signed_tx = Arc::new(tx.into_signed(&keypair)); @@ -221,14 +198,12 @@ async fn app_execute_transaction_sequence() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![ - SequenceAction { - rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), - data, - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![SequenceAction { + rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), + data, + fee_asset_id: get_native_asset().id(), + } + .into()], }; let signed_tx = Arc::new(tx.into_signed(&alice_signing_key)); @@ -258,14 +233,12 @@ async fn app_execute_transaction_invalid_fee_asset() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![ - SequenceAction { - rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), - data, - fee_asset_id, - } - .into(), - ], + actions: vec![SequenceAction { + rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), + data, + fee_asset_id, + } + .into()], }; let signed_tx = Arc::new(tx.into_signed(&alice_signing_key)); @@ -545,12 +518,11 @@ async fn app_execute_transaction_fee_asset_change_removal() { app.execute_transaction(signed_tx).await.unwrap(); assert_eq!(app.state.get_account_nonce(alice_address).await.unwrap(), 1); - assert!( - !app.state - .is_allowed_fee_asset(test_asset.id()) - .await - .unwrap() - ); + assert!(!app + .state + .is_allowed_fee_asset(test_asset.id()) + .await + .unwrap()); } #[tokio::test] @@ -819,14 +791,12 @@ async fn app_execute_transaction_invalid_nonce() { nonce: 1, chain_id: "test".to_string(), }, - actions: vec![ - SequenceAction { - rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), - data, - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![SequenceAction { + rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), + data, + fee_asset_id: get_native_asset().id(), + } + .into()], }; let signed_tx = Arc::new(tx.into_signed(&alice_signing_key)); @@ -865,14 +835,12 @@ async fn app_execute_transaction_invalid_chain_id() { nonce: 0, chain_id: "wrong-chain".to_string(), }, - actions: vec![ - SequenceAction { - rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), - data, - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![SequenceAction { + rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), + data, + fee_asset_id: get_native_asset().id(), + } + .into()], }; let signed_tx = Arc::new(tx.into_signed(&alice_signing_key)); @@ -924,15 +892,13 @@ async fn app_stateful_check_fails_insufficient_total_balance() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![ - TransferAction { - to: keypair_address, - amount: fee, - asset_id: get_native_asset().id(), - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![TransferAction { + to: keypair_address, + amount: fee, + asset_id: get_native_asset().id(), + fee_asset_id: get_native_asset().id(), + } + .into()], } .into_signed(&alice_signing_key); @@ -976,14 +942,12 @@ async fn app_stateful_check_fails_insufficient_total_balance() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![ - SequenceAction { - rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), - data, - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![SequenceAction { + rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), + data, + fee_asset_id: get_native_asset().id(), + } + .into()], } .into_signed(&keypair); diff --git a/crates/astria-sequencer/src/asset/query.rs b/crates/astria-sequencer/src/asset/query.rs index 7b938704c..12e80f9a8 100644 --- a/crates/astria-sequencer/src/asset/query.rs +++ b/crates/astria-sequencer/src/asset/query.rs @@ -1,19 +1,10 @@ use anyhow::Context as _; -use astria_core::{ - primitive::v1::asset, - protocol::abci::AbciErrorCode, -}; +use astria_core::{primitive::v1::asset, protocol::abci::AbciErrorCode}; use cnidarium::Storage; use prost::Message as _; -use tendermint::abci::{ - request, - response, -}; +use tendermint::abci::{request, response}; -use crate::{ - asset::state_ext::StateReadExt as _, - state_ext::StateReadExt, -}; +use crate::{asset::state_ext::StateReadExt as _, state_ext::StateReadExt}; // Retrieve the full asset denomination given the asset ID. // @@ -66,13 +57,10 @@ pub(crate) async fn denom_request( }; }; - let payload = DenomResponse { - height, - denom, - } - .into_raw() - .encode_to_vec() - .into(); + let payload = DenomResponse { height, denom } + .into_raw() + .encode_to_vec() + .into(); let height = tendermint::block::Height::try_from(height).expect("height must fit into an i64"); response::Query { diff --git a/crates/astria-sequencer/src/asset/state_ext.rs b/crates/astria-sequencer/src/asset/state_ext.rs index 34161c2cf..177d2555b 100644 --- a/crates/astria-sequencer/src/asset/state_ext.rs +++ b/crates/astria-sequencer/src/asset/state_ext.rs @@ -1,20 +1,8 @@ -use anyhow::{ - Context as _, - Result, -}; -use astria_core::primitive::v1::{ - asset, - asset::Denom, -}; +use anyhow::{Context as _, Result}; +use astria_core::primitive::v1::{asset, asset::Denom}; use async_trait::async_trait; -use borsh::{ - BorshDeserialize, - BorshSerialize, -}; -use cnidarium::{ - StateRead, - StateWrite, -}; +use borsh::{BorshDeserialize, BorshSerialize}; +use cnidarium::{StateRead, StateWrite}; use hex::ToHex as _; use tracing::instrument; @@ -74,16 +62,10 @@ impl StateWriteExt for T {} #[cfg(test)] mod test { - use astria_core::primitive::v1::asset::{ - Denom, - Id, - }; + use astria_core::primitive::v1::asset::{Denom, Id}; use cnidarium::StateDelta; - use super::{ - StateReadExt as _, - StateWriteExt as _, - }; + use super::{StateReadExt as _, StateWriteExt as _}; #[tokio::test] async fn get_ibc_asset_non_existent() { diff --git a/crates/astria-sequencer/src/authority/action.rs b/crates/astria-sequencer/src/authority/action.rs index 6c5386e0b..9be23f907 100644 --- a/crates/astria-sequencer/src/authority/action.rs +++ b/crates/astria-sequencer/src/authority/action.rs @@ -1,25 +1,15 @@ -use anyhow::{ - bail, - ensure, - Context as _, - Result, -}; +use anyhow::{bail, ensure, Context as _, Result}; use astria_core::{ primitive::v1::Address, protocol::transaction::v1alpha1::action::{ - FeeChange, - FeeChangeAction, - SudoAddressChangeAction, + FeeChange, FeeChangeAction, SudoAddressChangeAction, }, }; use tendermint::account; use tracing::instrument; use crate::{ - authority::state_ext::{ - StateReadExt, - StateWriteExt, - }, + authority::state_ext::{StateReadExt, StateWriteExt}, transaction::action_handler::ActionHandler, }; @@ -120,10 +110,8 @@ impl ActionHandler for FeeChangeAction { #[instrument(skip_all)] async fn execute(&self, state: &mut S, _: Address) -> Result<()> { use crate::{ - accounts::state_ext::StateWriteExt as _, - bridge::state_ext::StateWriteExt as _, - ibc::state_ext::StateWriteExt as _, - sequence::state_ext::StateWriteExt as _, + accounts::state_ext::StateWriteExt as _, bridge::state_ext::StateWriteExt as _, + ibc::state_ext::StateWriteExt as _, sequence::state_ext::StateWriteExt as _, }; match self.fee_change { @@ -159,22 +147,10 @@ mod test { use super::*; use crate::{ - accounts::state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, - bridge::state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, - ibc::state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, - sequence::state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, + accounts::state_ext::{StateReadExt as _, StateWriteExt as _}, + bridge::state_ext::{StateReadExt as _, StateWriteExt as _}, + ibc::state_ext::{StateReadExt as _, StateWriteExt as _}, + sequence::state_ext::{StateReadExt as _, StateWriteExt as _}, }; #[tokio::test] diff --git a/crates/astria-sequencer/src/authority/component.rs b/crates/astria-sequencer/src/authority/component.rs index c73514356..0e15f5d00 100644 --- a/crates/astria-sequencer/src/authority/component.rs +++ b/crates/astria-sequencer/src/authority/component.rs @@ -1,24 +1,14 @@ use std::sync::Arc; -use anyhow::{ - Context, - Result, -}; +use anyhow::{Context, Result}; use astria_core::primitive::v1::Address; use tendermint::{ - abci::request::{ - BeginBlock, - EndBlock, - }, + abci::request::{BeginBlock, EndBlock}, validator, }; use tracing::instrument; -use super::state_ext::{ - StateReadExt, - StateWriteExt, - ValidatorSet, -}; +use super::state_ext::{StateReadExt, StateWriteExt, ValidatorSet}; use crate::component::Component; #[derive(Default)] diff --git a/crates/astria-sequencer/src/authority/state_ext.rs b/crates/astria-sequencer/src/authority/state_ext.rs index c1da43989..5e1fa256c 100644 --- a/crates/astria-sequencer/src/authority/state_ext.rs +++ b/crates/astria-sequencer/src/authority/state_ext.rs @@ -1,31 +1,12 @@ use std::collections::BTreeMap; -use anyhow::{ - bail, - Context, - Result, -}; -use astria_core::primitive::v1::{ - Address, - ADDRESS_LEN, -}; +use anyhow::{bail, Context, Result}; +use astria_core::primitive::v1::{Address, ADDRESS_LEN}; use async_trait::async_trait; -use borsh::{ - BorshDeserialize, - BorshSerialize, -}; -use cnidarium::{ - StateRead, - StateWrite, -}; -use serde::{ - Deserialize, - Serialize, -}; -use tendermint::{ - account, - validator, -}; +use borsh::{BorshDeserialize, BorshSerialize}; +use cnidarium::{StateRead, StateWrite}; +use serde::{Deserialize, Serialize}; +use tendermint::{account, validator}; use tracing::instrument; /// Newtype wrapper to read and write an address from rocksdb. @@ -181,17 +162,9 @@ impl StateWriteExt for T {} mod test { use astria_core::primitive::v1::Address; use cnidarium::StateDelta; - use tendermint::{ - validator, - vote, - PublicKey, - }; - - use super::{ - StateReadExt as _, - StateWriteExt as _, - ValidatorSet, - }; + use tendermint::{validator, vote, PublicKey}; + + use super::{StateReadExt as _, StateWriteExt as _, ValidatorSet}; #[tokio::test] async fn sudo_address() { diff --git a/crates/astria-sequencer/src/bridge/bridge_lock_action.rs b/crates/astria-sequencer/src/bridge/bridge_lock_action.rs index dd356054b..01002ac8c 100644 --- a/crates/astria-sequencer/src/bridge/bridge_lock_action.rs +++ b/crates/astria-sequencer/src/bridge/bridge_lock_action.rs @@ -1,14 +1,7 @@ -use anyhow::{ - ensure, - Context as _, - Result, -}; +use anyhow::{ensure, Context as _, Result}; use astria_core::{ primitive::v1::Address, - protocol::transaction::v1alpha1::action::{ - BridgeLockAction, - TransferAction, - }, + protocol::transaction::v1alpha1::action::{BridgeLockAction, TransferAction}, sequencerblock::v1alpha1::block::Deposit, }; use tracing::instrument; @@ -16,19 +9,10 @@ use tracing::instrument; use crate::{ accounts::{ action::transfer_check_stateful, - state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, - }, - bridge::state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, - state_ext::{ - StateReadExt, - StateWriteExt, + state_ext::{StateReadExt as _, StateWriteExt as _}, }, + bridge::state_ext::{StateReadExt as _, StateWriteExt as _}, + state_ext::{StateReadExt, StateWriteExt}, transaction::action_handler::ActionHandler, }; @@ -150,10 +134,7 @@ pub(crate) fn get_deposit_byte_len(deposit: &Deposit) -> u128 { #[cfg(test)] mod test { - use astria_core::primitive::v1::{ - asset, - RollupId, - }; + use astria_core::primitive::v1::{asset, RollupId}; use cnidarium::StateDelta; use super::*; @@ -190,14 +171,12 @@ mod test { state .put_account_balance(from_address, asset_id, 100) .unwrap(); - assert!( - bridge_lock - .check_stateful(&state, from_address) - .await - .unwrap_err() - .to_string() - .contains("insufficient funds for fee payment") - ); + assert!(bridge_lock + .check_stateful(&state, from_address) + .await + .unwrap_err() + .to_string() + .contains("insufficient funds for fee payment")); // enough balance; should pass let expected_deposit_fee = transfer_fee @@ -249,14 +228,12 @@ mod test { state .put_account_balance(from_address, asset_id, 100 + transfer_fee) .unwrap(); - assert!( - bridge_lock - .execute(&mut state, from_address) - .await - .unwrap_err() - .to_string() - .eq("failed to deduct fee from account balance") - ); + assert!(bridge_lock + .execute(&mut state, from_address) + .await + .unwrap_err() + .to_string() + .eq("failed to deduct fee from account balance")); // enough balance; should pass let expected_deposit_fee = transfer_fee diff --git a/crates/astria-sequencer/src/bridge/bridge_unlock_action.rs b/crates/astria-sequencer/src/bridge/bridge_unlock_action.rs index ba6abcdfa..e14c1eb72 100644 --- a/crates/astria-sequencer/src/bridge/bridge_unlock_action.rs +++ b/crates/astria-sequencer/src/bridge/bridge_unlock_action.rs @@ -1,23 +1,14 @@ -use anyhow::{ - Context as _, - Result, -}; +use anyhow::{Context as _, Result}; use astria_core::{ primitive::v1::Address, - protocol::transaction::v1alpha1::action::{ - BridgeUnlockAction, - TransferAction, - }, + protocol::transaction::v1alpha1::action::{BridgeUnlockAction, TransferAction}, }; use tracing::instrument; use crate::{ accounts::action::transfer_check_stateful, bridge::state_ext::StateReadExt as _, - state_ext::{ - StateReadExt, - StateWriteExt, - }, + state_ext::{StateReadExt, StateWriteExt}, transaction::action_handler::ActionHandler, }; @@ -72,16 +63,12 @@ impl ActionHandler for BridgeUnlockAction { #[cfg(test)] mod test { - use astria_core::primitive::v1::{ - asset, - RollupId, - }; + use astria_core::primitive::v1::{asset, RollupId}; use cnidarium::StateDelta; use super::*; use crate::{ - accounts::state_ext::StateWriteExt as _, - bridge::state_ext::StateWriteExt, + accounts::state_ext::StateWriteExt as _, bridge::state_ext::StateWriteExt, state_ext::StateWriteExt as _, }; @@ -105,14 +92,12 @@ mod test { }; // not a bridge account, should fail - assert!( - bridge_unlock - .check_stateful(&state, address) - .await - .unwrap_err() - .to_string() - .contains("failed to get bridge's asset id, must be a bridge account") - ); + assert!(bridge_unlock + .check_stateful(&state, address) + .await + .unwrap_err() + .to_string() + .contains("failed to get bridge's asset id, must be a bridge account")); } #[tokio::test] @@ -147,14 +132,12 @@ mod test { state .put_account_balance(bridge_address, asset_id, transfer_amount) .unwrap(); - assert!( - bridge_unlock - .check_stateful(&state, bridge_address) - .await - .unwrap_err() - .to_string() - .contains("insufficient funds for transfer and fee payment") - ); + assert!(bridge_unlock + .check_stateful(&state, bridge_address) + .await + .unwrap_err() + .to_string() + .contains("insufficient funds for transfer and fee payment")); // enough balance; should pass state @@ -198,14 +181,12 @@ mod test { state .put_account_balance(bridge_address, asset_id, transfer_amount) .unwrap(); - assert!( - bridge_unlock - .execute(&mut state, bridge_address) - .await - .unwrap_err() - .to_string() - .eq("failed to execute bridge unlock action as transfer action") - ); + assert!(bridge_unlock + .execute(&mut state, bridge_address) + .await + .unwrap_err() + .to_string() + .eq("failed to execute bridge unlock action as transfer action")); // enough balance; should pass state diff --git a/crates/astria-sequencer/src/bridge/component.rs b/crates/astria-sequencer/src/bridge/component.rs index b9e27ba32..8877ae738 100644 --- a/crates/astria-sequencer/src/bridge/component.rs +++ b/crates/astria-sequencer/src/bridge/component.rs @@ -1,17 +1,11 @@ use std::sync::Arc; use anyhow::Result; -use tendermint::abci::request::{ - BeginBlock, - EndBlock, -}; +use tendermint::abci::request::{BeginBlock, EndBlock}; use tracing::instrument; use super::state_ext::StateWriteExt; -use crate::{ - component::Component, - genesis::GenesisState, -}; +use crate::{component::Component, genesis::GenesisState}; #[derive(Default)] pub(crate) struct BridgeComponent; diff --git a/crates/astria-sequencer/src/bridge/init_bridge_account_action.rs b/crates/astria-sequencer/src/bridge/init_bridge_account_action.rs index 86cd28a56..7a232dd18 100644 --- a/crates/astria-sequencer/src/bridge/init_bridge_account_action.rs +++ b/crates/astria-sequencer/src/bridge/init_bridge_account_action.rs @@ -1,28 +1,13 @@ -use anyhow::{ - bail, - ensure, - Context as _, - Result, -}; +use anyhow::{bail, ensure, Context as _, Result}; use astria_core::{ - primitive::v1::Address, - protocol::transaction::v1alpha1::action::InitBridgeAccountAction, + primitive::v1::Address, protocol::transaction::v1alpha1::action::InitBridgeAccountAction, }; use tracing::instrument; use crate::{ - accounts::state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, - bridge::state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, - state_ext::{ - StateReadExt, - StateWriteExt, - }, + accounts::state_ext::{StateReadExt as _, StateWriteExt as _}, + bridge::state_ext::{StateReadExt as _, StateWriteExt as _}, + state_ext::{StateReadExt, StateWriteExt}, transaction::action_handler::ActionHandler, }; diff --git a/crates/astria-sequencer/src/bridge/state_ext.rs b/crates/astria-sequencer/src/bridge/state_ext.rs index b30373337..d839b0703 100644 --- a/crates/astria-sequencer/src/bridge/state_ext.rs +++ b/crates/astria-sequencer/src/bridge/state_ext.rs @@ -1,38 +1,18 @@ -use std::collections::{ - HashMap, - HashSet, -}; +use std::collections::{HashMap, HashSet}; -use anyhow::{ - anyhow, - Context, - Result, -}; +use anyhow::{anyhow, Context, Result}; use astria_core::{ generated::sequencerblock::v1alpha1::Deposit as RawDeposit, - primitive::v1::{ - asset, - Address, - RollupId, - }, + primitive::v1::{asset, Address, RollupId}, sequencerblock::v1alpha1::block::Deposit, }; use async_trait::async_trait; -use borsh::{ - BorshDeserialize, - BorshSerialize, -}; -use cnidarium::{ - StateRead, - StateWrite, -}; +use borsh::{BorshDeserialize, BorshSerialize}; +use cnidarium::{StateRead, StateWrite}; use futures::StreamExt as _; use hex::ToHex as _; use prost::Message as _; -use tracing::{ - debug, - instrument, -}; +use tracing::{debug, instrument}; /// Newtype wrapper to read and write a u128 from rocksdb. #[derive(BorshSerialize, BorshDeserialize, Debug)] @@ -299,19 +279,12 @@ impl StateWriteExt for T {} #[cfg(test)] mod test { use astria_core::{ - primitive::v1::{ - asset::Id, - Address, - RollupId, - }, + primitive::v1::{asset::Id, Address, RollupId}, sequencerblock::v1alpha1::block::Deposit, }; use cnidarium::StateDelta; - use super::{ - StateReadExt as _, - StateWriteExt as _, - }; + use super::{StateReadExt as _, StateWriteExt as _}; #[tokio::test] async fn get_bridge_account_rollup_id_uninitialized_ok() { diff --git a/crates/astria-sequencer/src/config.rs b/crates/astria-sequencer/src/config.rs index 234a67ca5..8c603abcc 100644 --- a/crates/astria-sequencer/src/config.rs +++ b/crates/astria-sequencer/src/config.rs @@ -1,9 +1,6 @@ use std::path::PathBuf; -use serde::{ - Deserialize, - Serialize, -}; +use serde::{Deserialize, Serialize}; // Allowed `struct_excessive_bools` because this is used as a container // for deserialization. Making this a builder-pattern is not actionable. diff --git a/crates/astria-sequencer/src/fee_asset_change.rs b/crates/astria-sequencer/src/fee_asset_change.rs index 0abbcf0f9..c20591883 100644 --- a/crates/astria-sequencer/src/fee_asset_change.rs +++ b/crates/astria-sequencer/src/fee_asset_change.rs @@ -1,25 +1,13 @@ -use anyhow::{ - bail, - ensure, - Context as _, - Result, -}; +use anyhow::{bail, ensure, Context as _, Result}; use astria_core::{ - primitive::v1::Address, - protocol::transaction::v1alpha1::action::FeeAssetChangeAction, + primitive::v1::Address, protocol::transaction::v1alpha1::action::FeeAssetChangeAction, }; use async_trait::async_trait; -use cnidarium::{ - StateRead, - StateWrite, -}; +use cnidarium::{StateRead, StateWrite}; use crate::{ authority::state_ext::StateReadExt as _, - state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, + state_ext::{StateReadExt as _, StateWriteExt as _}, transaction::action_handler::ActionHandler, }; diff --git a/crates/astria-sequencer/src/genesis.rs b/crates/astria-sequencer/src/genesis.rs index f6972f841..09eab2d8a 100644 --- a/crates/astria-sequencer/src/genesis.rs +++ b/crates/astria-sequencer/src/genesis.rs @@ -1,12 +1,6 @@ -use astria_core::primitive::v1::{ - asset, - Address, -}; +use astria_core::primitive::v1::{asset, Address}; use penumbra_ibc::params::IBCParameters; -use serde::{ - Deserialize, - Deserializer, -}; +use serde::{Deserialize, Deserializer}; /// The genesis state for the application. #[derive(Debug, Deserialize)] diff --git a/crates/astria-sequencer/src/grpc/sequencer.rs b/crates/astria-sequencer/src/grpc/sequencer.rs index f8fb17e0c..78433cd02 100644 --- a/crates/astria-sequencer/src/grpc/sequencer.rs +++ b/crates/astria-sequencer/src/grpc/sequencer.rs @@ -3,32 +3,17 @@ use std::sync::Arc; use astria_core::{ generated::sequencerblock::v1alpha1::{ sequencer_service_server::SequencerService, - FilteredSequencerBlock as RawFilteredSequencerBlock, - GetFilteredSequencerBlockRequest, - GetPendingNonceRequest, - GetPendingNonceResponse, - GetSequencerBlockRequest, + FilteredSequencerBlock as RawFilteredSequencerBlock, GetFilteredSequencerBlockRequest, + GetPendingNonceRequest, GetPendingNonceResponse, GetSequencerBlockRequest, SequencerBlock as RawSequencerBlock, }, primitive::v1::RollupId, }; use cnidarium::Storage; -use tonic::{ - Request, - Response, - Status, -}; -use tracing::{ - error, - info, - instrument, -}; +use tonic::{Request, Response, Status}; +use tracing::{error, info, instrument}; -use crate::{ - api_state_ext::StateReadExt as _, - mempool::Mempool, - state_ext::StateReadExt as _, -}; +use crate::{api_state_ext::StateReadExt as _, mempool::Mempool, state_ext::StateReadExt as _}; pub(crate) struct SequencerServer { storage: Storage, @@ -37,10 +22,7 @@ pub(crate) struct SequencerServer { impl SequencerServer { pub(crate) fn new(storage: Storage, mempool: Mempool) -> Self { - Self { - storage, - mempool, - } + Self { storage, mempool } } } @@ -189,9 +171,7 @@ impl SequencerService for SequencerServer { let nonce = self.mempool.pending_nonce(&address).await; if let Some(nonce) = nonce { - return Ok(Response::new(GetPendingNonceResponse { - inner: nonce, - })); + return Ok(Response::new(GetPendingNonceResponse { inner: nonce })); } // nonce wasn't in mempool, so just look it up from storage @@ -204,25 +184,19 @@ impl SequencerService for SequencerServer { Status::internal(format!("failed to get account nonce from storage: {e}")) })?; - Ok(Response::new(GetPendingNonceResponse { - inner: nonce, - })) + Ok(Response::new(GetPendingNonceResponse { inner: nonce })) } } #[cfg(test)] mod test { use astria_core::{ - protocol::test_utils::ConfigureSequencerBlock, - sequencerblock::v1alpha1::SequencerBlock, + protocol::test_utils::ConfigureSequencerBlock, sequencerblock::v1alpha1::SequencerBlock, }; use cnidarium::StateDelta; use super::*; - use crate::{ - api_state_ext::StateWriteExt as _, - state_ext::StateWriteExt, - }; + use crate::{api_state_ext::StateWriteExt as _, state_ext::StateWriteExt}; fn make_test_sequencer_block(height: u32) -> SequencerBlock { ConfigureSequencerBlock { @@ -243,9 +217,7 @@ mod test { storage.commit(state_tx).await.unwrap(); let server = Arc::new(SequencerServer::new(storage.clone(), mempool)); - let request = GetSequencerBlockRequest { - height: 1, - }; + let request = GetSequencerBlockRequest { height: 1 }; let request = Request::new(request); let response = server.get_sequencer_block(request).await.unwrap(); assert_eq!(response.into_inner().header.unwrap().height, 1); diff --git a/crates/astria-sequencer/src/ibc/component.rs b/crates/astria-sequencer/src/ibc/component.rs index 7d7a61b50..6fb7a6df5 100644 --- a/crates/astria-sequencer/src/ibc/component.rs +++ b/crates/astria-sequencer/src/ibc/component.rs @@ -1,26 +1,14 @@ use std::sync::Arc; -use anyhow::{ - Context, - Result, -}; -use penumbra_ibc::{ - component::Ibc, - genesis::Content, -}; -use tendermint::abci::request::{ - BeginBlock, - EndBlock, -}; +use anyhow::{Context, Result}; +use penumbra_ibc::{component::Ibc, genesis::Content}; +use tendermint::abci::request::{BeginBlock, EndBlock}; use tracing::instrument; use crate::{ component::Component, genesis::GenesisState, - ibc::{ - host_interface::AstriaHost, - state_ext::StateWriteExt, - }, + ibc::{host_interface::AstriaHost, state_ext::StateWriteExt}, }; #[derive(Default)] diff --git a/crates/astria-sequencer/src/ibc/ibc_relayer_change.rs b/crates/astria-sequencer/src/ibc/ibc_relayer_change.rs index b9a12b17c..73f989435 100644 --- a/crates/astria-sequencer/src/ibc/ibc_relayer_change.rs +++ b/crates/astria-sequencer/src/ibc/ibc_relayer_change.rs @@ -1,23 +1,12 @@ -use anyhow::{ - ensure, - Context as _, - Result, -}; +use anyhow::{ensure, Context as _, Result}; use astria_core::{ - primitive::v1::Address, - protocol::transaction::v1alpha1::action::IbcRelayerChangeAction, + primitive::v1::Address, protocol::transaction::v1alpha1::action::IbcRelayerChangeAction, }; use async_trait::async_trait; -use cnidarium::{ - StateRead, - StateWrite, -}; +use cnidarium::{StateRead, StateWrite}; use crate::{ - ibc::state_ext::{ - StateReadExt, - StateWriteExt, - }, + ibc::state_ext::{StateReadExt, StateWriteExt}, transaction::action_handler::ActionHandler, }; diff --git a/crates/astria-sequencer/src/ibc/ics20_transfer.rs b/crates/astria-sequencer/src/ibc/ics20_transfer.rs index a477a8e23..fe2bef3b1 100644 --- a/crates/astria-sequencer/src/ibc/ics20_transfer.rs +++ b/crates/astria-sequencer/src/ibc/ics20_transfer.rs @@ -11,62 +11,32 @@ //! [`AppHandlerExecute`] is used for execution. use std::borrow::Cow; -use anyhow::{ - ensure, - Context as _, - Result, -}; +use anyhow::{ensure, Context as _, Result}; use astria_core::{ - primitive::v1::{ - asset::Denom, - Address, - }, + primitive::v1::{asset::Denom, Address}, sequencerblock::v1alpha1::block::Deposit, }; -use cnidarium::{ - StateRead, - StateWrite, -}; +use cnidarium::{StateRead, StateWrite}; use ibc_types::{ core::channel::{ channel, msgs::{ - MsgAcknowledgement, - MsgChannelCloseConfirm, - MsgChannelCloseInit, - MsgChannelOpenAck, - MsgChannelOpenConfirm, - MsgChannelOpenInit, - MsgChannelOpenTry, - MsgRecvPacket, + MsgAcknowledgement, MsgChannelCloseConfirm, MsgChannelCloseInit, MsgChannelOpenAck, + MsgChannelOpenConfirm, MsgChannelOpenInit, MsgChannelOpenTry, MsgRecvPacket, MsgTimeout, }, - ChannelId, - PortId, + ChannelId, PortId, }, transfer::acknowledgement::TokenTransferAcknowledgement, }; -use penumbra_ibc::component::app_handler::{ - AppHandler, - AppHandlerCheck, - AppHandlerExecute, -}; +use penumbra_ibc::component::app_handler::{AppHandler, AppHandlerCheck, AppHandlerExecute}; use penumbra_proto::penumbra::core::component::ibc::v1::FungibleTokenPacketData; use crate::{ accounts::state_ext::StateWriteExt as _, - asset::state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, - bridge::state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, - ibc::state_ext::{ - StateReadExt, - StateWriteExt, - }, + asset::state_ext::{StateReadExt as _, StateWriteExt as _}, + bridge::state_ext::{StateReadExt as _, StateWriteExt as _}, + ibc::state_ext::{StateReadExt, StateWriteExt}, }; /// The ICS20 transfer handler. diff --git a/crates/astria-sequencer/src/ibc/ics20_withdrawal.rs b/crates/astria-sequencer/src/ibc/ics20_withdrawal.rs index 55377de80..30011fc46 100644 --- a/crates/astria-sequencer/src/ibc/ics20_withdrawal.rs +++ b/crates/astria-sequencer/src/ibc/ics20_withdrawal.rs @@ -1,37 +1,17 @@ -use anyhow::{ - anyhow, - ensure, - Context as _, - Result, -}; +use anyhow::{anyhow, ensure, Context as _, Result}; use astria_core::{ - primitive::v1::{ - asset::Denom, - Address, - }, + primitive::v1::{asset::Denom, Address}, protocol::transaction::v1alpha1::action, }; -use ibc_types::core::channel::{ - ChannelId, - PortId, -}; +use ibc_types::core::channel::{ChannelId, PortId}; use penumbra_ibc::component::packet::{ - IBCPacket, - SendPacketRead as _, - SendPacketWrite as _, - Unchecked, + IBCPacket, SendPacketRead as _, SendPacketWrite as _, Unchecked, }; use tracing::instrument; use crate::{ - accounts::state_ext::{ - StateReadExt, - StateWriteExt, - }, - ibc::state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, + accounts::state_ext::{StateReadExt, StateWriteExt}, + ibc::state_ext::{StateReadExt as _, StateWriteExt as _}, transaction::action_handler::ActionHandler, }; diff --git a/crates/astria-sequencer/src/ibc/state_ext.rs b/crates/astria-sequencer/src/ibc/state_ext.rs index 5e02e0193..f88ecfb54 100644 --- a/crates/astria-sequencer/src/ibc/state_ext.rs +++ b/crates/astria-sequencer/src/ibc/state_ext.rs @@ -1,28 +1,11 @@ -use anyhow::{ - bail, - Context, - Result, -}; -use astria_core::primitive::v1::{ - asset, - Address, - ADDRESS_LEN, -}; +use anyhow::{bail, Context, Result}; +use astria_core::primitive::v1::{asset, Address, ADDRESS_LEN}; use async_trait::async_trait; -use borsh::{ - BorshDeserialize, - BorshSerialize, -}; -use cnidarium::{ - StateRead, - StateWrite, -}; +use borsh::{BorshDeserialize, BorshSerialize}; +use cnidarium::{StateRead, StateWrite}; use hex::ToHex as _; use ibc_types::core::channel::ChannelId; -use tracing::{ - debug, - instrument, -}; +use tracing::{debug, instrument}; /// Newtype wrapper to read and write a u128 from rocksdb. #[derive(BorshSerialize, BorshDeserialize, Debug)] @@ -154,17 +137,11 @@ impl StateWriteExt for T {} #[cfg(test)] mod test { - use astria_core::primitive::v1::{ - asset::Id, - Address, - }; + use astria_core::primitive::v1::{asset::Id, Address}; use cnidarium::StateDelta; use ibc_types::core::channel::ChannelId; - use super::{ - StateReadExt as _, - StateWriteExt as _, - }; + use super::{StateReadExt as _, StateWriteExt as _}; #[tokio::test] async fn get_ibc_sudo_address_fails_if_not_set() { diff --git a/crates/astria-sequencer/src/main.rs b/crates/astria-sequencer/src/main.rs index 1adb08e16..3689ac1a5 100644 --- a/crates/astria-sequencer/src/main.rs +++ b/crates/astria-sequencer/src/main.rs @@ -1,12 +1,7 @@ use std::process::ExitCode; use anyhow::Context as _; -use astria_sequencer::{ - metrics_init, - Config, - Sequencer, - BUILD_INFO, -}; +use astria_sequencer::{metrics_init, Config, Sequencer, BUILD_INFO}; use tracing::info; // Following the BSD convention for failing to read config diff --git a/crates/astria-sequencer/src/mempool.rs b/crates/astria-sequencer/src/mempool.rs index 5cd5addc6..a0decd426 100644 --- a/crates/astria-sequencer/src/mempool.rs +++ b/crates/astria-sequencer/src/mempool.rs @@ -1,25 +1,15 @@ use std::{ - cmp::{ - self, - Ordering, - }, + cmp::{self, Ordering}, collections::HashMap, future::Future, - sync::{ - Arc, - OnceLock, - }, + sync::{Arc, OnceLock}, }; use anyhow::Context; use astria_core::{ crypto::SigningKey, primitive::v1::Address, - protocol::transaction::v1alpha1::{ - SignedTransaction, - TransactionParams, - UnsignedTransaction, - }, + protocol::transaction::v1alpha1::{SignedTransaction, TransactionParams, UnsignedTransaction}, }; use priority_queue::PriorityQueue; use tokio::sync::RwLock; @@ -80,9 +70,7 @@ impl EnqueuedTransaction { )); }; - Ok(TransactionPriority { - nonce_diff, - }) + Ok(TransactionPriority { nonce_diff }) } pub(crate) fn tx_hash(&self) -> [u8; 32] { @@ -262,20 +250,14 @@ fn dummy_signed_tx() -> &'static Arc { chain_id: String::new(), }; let signing_key = SigningKey::from([0; 32]); - let unsigned_tx = UnsignedTransaction { - actions, - params, - }; + let unsigned_tx = UnsignedTransaction { actions, params }; Arc::new(unsigned_tx.into_signed(&signing_key)) }) } #[cfg(test)] mod test { - use std::hash::{ - Hash, - Hasher, - }; + use std::hash::{Hash, Hasher}; use super::*; use crate::app::test_utils::get_mock_tx; @@ -284,12 +266,10 @@ mod test { fn transaction_priority_should_error_if_invalid() { let enqueued_tx = EnqueuedTransaction::new(get_mock_tx(0)); let priority = enqueued_tx.priority(1); - assert!( - priority - .unwrap_err() - .to_string() - .contains("less than current account nonce") - ); + assert!(priority + .unwrap_err() + .to_string() + .contains("less than current account nonce")); } // From https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html @@ -297,12 +277,8 @@ mod test { // allow: we want explicit assertions here to match the documented expected behavior. #[allow(clippy::nonminimal_bool)] fn transaction_priority_comparisons_should_be_consistent() { - let high = TransactionPriority { - nonce_diff: 0, - }; - let low = TransactionPriority { - nonce_diff: 1, - }; + let high = TransactionPriority { nonce_diff: 0 }; + let low = TransactionPriority { nonce_diff: 1 }; assert!(high.partial_cmp(&high) == Some(Ordering::Equal)); assert!(high.partial_cmp(&low) == Some(Ordering::Greater)); @@ -542,11 +518,9 @@ mod test { assert_eq!(mempool.pending_nonce(&other_address).await.unwrap(), 101); // Check the pending nonce for an address with no enqueued txs is `None`. - assert!( - mempool - .pending_nonce(&Address::from([1; 20])) - .await - .is_none() - ); + assert!(mempool + .pending_nonce(&Address::from([1; 20])) + .await + .is_none()); } } diff --git a/crates/astria-sequencer/src/metrics_init.rs b/crates/astria-sequencer/src/metrics_init.rs index 777ce1833..f961651be 100644 --- a/crates/astria-sequencer/src/metrics_init.rs +++ b/crates/astria-sequencer/src/metrics_init.rs @@ -2,12 +2,7 @@ //! //! Registers metrics & lists constants to be used as metric names throughout crate. -use metrics::{ - describe_counter, - describe_gauge, - describe_histogram, - Unit, -}; +use metrics::{describe_counter, describe_gauge, describe_histogram, Unit}; use telemetry::metric_name; /// Registers all metrics used by this crate. @@ -106,18 +101,14 @@ metric_name!(pub const CHECK_TX_REMOVED_ACCOUNT_BALANCE); #[cfg(test)] mod tests { use super::{ - CHECK_TX_REMOVED_ACCOUNT_BALANCE, - CHECK_TX_REMOVED_FAILED_STATELESS, - CHECK_TX_REMOVED_STALE_NONCE, - CHECK_TX_REMOVED_TOO_LARGE, + CHECK_TX_REMOVED_ACCOUNT_BALANCE, CHECK_TX_REMOVED_FAILED_STATELESS, + CHECK_TX_REMOVED_STALE_NONCE, CHECK_TX_REMOVED_TOO_LARGE, PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS, PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_COMETBFT_SPACE, PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_DECODE_FAILURE, PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_FAILED_EXECUTION, - PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_SEQUENCER_SPACE, - PROCESS_PROPOSAL_SKIPPED_PROPOSAL, - PROPOSAL_DEPOSITS, - PROPOSAL_TRANSACTIONS, + PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_SEQUENCER_SPACE, PROCESS_PROPOSAL_SKIPPED_PROPOSAL, + PROPOSAL_DEPOSITS, PROPOSAL_TRANSACTIONS, }; #[track_caller] diff --git a/crates/astria-sequencer/src/proposal/block_size_constraints.rs b/crates/astria-sequencer/src/proposal/block_size_constraints.rs index e20d3be64..090101378 100644 --- a/crates/astria-sequencer/src/proposal/block_size_constraints.rs +++ b/crates/astria-sequencer/src/proposal/block_size_constraints.rs @@ -1,8 +1,4 @@ -use anyhow::{ - anyhow, - ensure, - Context, -}; +use anyhow::{anyhow, ensure, Context}; use super::commitment::GeneratedCommitments; diff --git a/crates/astria-sequencer/src/proposal/commitment.rs b/crates/astria-sequencer/src/proposal/commitment.rs index 65914b849..efc8bb42e 100644 --- a/crates/astria-sequencer/src/proposal/commitment.rs +++ b/crates/astria-sequencer/src/proposal/commitment.rs @@ -6,10 +6,7 @@ use astria_core::{ group_sequence_actions_in_signed_transaction_transactions_by_rollup_id, transaction::v1alpha1::SignedTransaction, }, - sequencerblock::v1alpha1::block::{ - Deposit, - RollupData, - }, + sequencerblock::v1alpha1::block::{Deposit, RollupData}, }; use bytes::Bytes; @@ -90,28 +87,18 @@ mod test { use astria_core::{ crypto::SigningKey, primitive::v1::{ - asset::{ - Denom, - DEFAULT_NATIVE_ASSET_DENOM, - }, + asset::{Denom, DEFAULT_NATIVE_ASSET_DENOM}, Address, }, protocol::transaction::v1alpha1::{ - action::{ - SequenceAction, - TransferAction, - }, - TransactionParams, - UnsignedTransaction, + action::{SequenceAction, TransferAction}, + TransactionParams, UnsignedTransaction, }, }; use rand::rngs::OsRng; use super::*; - use crate::asset::{ - get_native_asset, - NATIVE_ASSET, - }; + use crate::asset::{get_native_asset, NATIVE_ASSET}; #[test] fn generate_rollup_datas_commitment_should_ignore_transfers() { diff --git a/crates/astria-sequencer/src/sequence/action.rs b/crates/astria-sequencer/src/sequence/action.rs index d646c5f1b..84c4afc81 100644 --- a/crates/astria-sequencer/src/sequence/action.rs +++ b/crates/astria-sequencer/src/sequence/action.rs @@ -1,24 +1,13 @@ -use anyhow::{ - ensure, - Context, - Result, -}; +use anyhow::{ensure, Context, Result}; use astria_core::{ - primitive::v1::Address, - protocol::transaction::v1alpha1::action::SequenceAction, + primitive::v1::Address, protocol::transaction::v1alpha1::action::SequenceAction, }; use tracing::instrument; use crate::{ - accounts::state_ext::{ - StateReadExt, - StateWriteExt, - }, + accounts::state_ext::{StateReadExt, StateWriteExt}, sequence::state_ext::StateReadExt as SequenceStateReadExt, - state_ext::{ - StateReadExt as _, - StateWriteExt as _, - }, + state_ext::{StateReadExt as _, StateWriteExt as _}, transaction::action_handler::ActionHandler, }; diff --git a/crates/astria-sequencer/src/sequence/component.rs b/crates/astria-sequencer/src/sequence/component.rs index 28b733f2d..17d50ec4e 100644 --- a/crates/astria-sequencer/src/sequence/component.rs +++ b/crates/astria-sequencer/src/sequence/component.rs @@ -1,17 +1,11 @@ use std::sync::Arc; use anyhow::Result; -use tendermint::abci::request::{ - BeginBlock, - EndBlock, -}; +use tendermint::abci::request::{BeginBlock, EndBlock}; use tracing::instrument; use super::state_ext::StateWriteExt; -use crate::{ - component::Component, - genesis::GenesisState, -}; +use crate::{component::Component, genesis::GenesisState}; #[derive(Default)] pub(crate) struct SequenceComponent; diff --git a/crates/astria-sequencer/src/sequence/state_ext.rs b/crates/astria-sequencer/src/sequence/state_ext.rs index 50345e42e..66f3d2f10 100644 --- a/crates/astria-sequencer/src/sequence/state_ext.rs +++ b/crates/astria-sequencer/src/sequence/state_ext.rs @@ -1,17 +1,7 @@ -use anyhow::{ - anyhow, - Context, - Result, -}; +use anyhow::{anyhow, Context, Result}; use async_trait::async_trait; -use borsh::{ - BorshDeserialize, - BorshSerialize, -}; -use cnidarium::{ - StateRead, - StateWrite, -}; +use borsh::{BorshDeserialize, BorshSerialize}; +use cnidarium::{StateRead, StateWrite}; use tracing::instrument; const SEQUENCE_ACTION_BASE_FEE_STORAGE_KEY: &str = "seqbasefee"; @@ -73,10 +63,7 @@ impl StateWriteExt for T {} mod test { use cnidarium::StateDelta; - use super::{ - StateReadExt as _, - StateWriteExt as _, - }; + use super::{StateReadExt as _, StateWriteExt as _}; #[tokio::test] async fn sequence_action_base_fee() { diff --git a/crates/astria-sequencer/src/sequencer.rs b/crates/astria-sequencer/src/sequencer.rs index ed60debb4..0b6a3585a 100644 --- a/crates/astria-sequencer/src/sequencer.rs +++ b/crates/astria-sequencer/src/sequencer.rs @@ -1,41 +1,19 @@ -use anyhow::{ - anyhow, - Context as _, - Result, -}; +use anyhow::{anyhow, Context as _, Result}; use astria_core::generated::sequencerblock::v1alpha1::sequencer_service_server::SequencerServiceServer; -use penumbra_tower_trace::{ - trace::request_span, - v038::RequestExt as _, -}; +use penumbra_tower_trace::{trace::request_span, v038::RequestExt as _}; use tendermint::v0_38::abci::ConsensusRequest; use tokio::{ select, - signal::unix::{ - signal, - SignalKind, - }, - sync::{ - oneshot, - watch, - }, + signal::unix::{signal, SignalKind}, + sync::{oneshot, watch}, task::JoinHandle, }; use tower_abci::v038::Server; -use tracing::{ - error, - info, - instrument, -}; +use tracing::{error, info, instrument}; use crate::{ - app::App, - config::Config, - grpc::sequencer::SequencerServer, - ibc::host_interface::AstriaHost, - mempool::Mempool, - service, - state_ext::StateReadExt as _, + app::App, config::Config, grpc::sequencer::SequencerServer, ibc::host_interface::AstriaHost, + mempool::Mempool, service, state_ext::StateReadExt as _, }; pub struct Sequencer; @@ -233,7 +211,5 @@ fn spawn_signal_handler() -> SignalReceiver { } }); - SignalReceiver { - stop_rx, - } + SignalReceiver { stop_rx } } diff --git a/crates/astria-sequencer/src/service/consensus.rs b/crates/astria-sequencer/src/service/consensus.rs index 993cf74d9..5c34ee31a 100644 --- a/crates/astria-sequencer/src/service/consensus.rs +++ b/crates/astria-sequencer/src/service/consensus.rs @@ -1,27 +1,12 @@ -use anyhow::{ - bail, - Context, -}; +use anyhow::{bail, Context}; use cnidarium::Storage; -use tendermint::v0_38::abci::{ - request, - response, - ConsensusRequest, - ConsensusResponse, -}; +use tendermint::v0_38::abci::{request, response, ConsensusRequest, ConsensusResponse}; use tokio::sync::mpsc; use tower_abci::BoxError; use tower_actor::Message; -use tracing::{ - instrument, - warn, - Instrument, -}; +use tracing::{instrument, warn, Instrument}; -use crate::{ - app::App, - genesis::GenesisState, -}; +use crate::{app::App, genesis::GenesisState}; pub(crate) struct Consensus { queue: mpsc::Receiver>, @@ -213,41 +198,23 @@ impl Consensus { #[cfg(test)] mod test { - use std::{ - collections::HashMap, - str::FromStr, - }; + use std::{collections::HashMap, str::FromStr}; use astria_core::{ - crypto::{ - SigningKey, - VerificationKey, - }, - primitive::v1::{ - asset::DEFAULT_NATIVE_ASSET_DENOM, - Address, - RollupId, - }, + crypto::{SigningKey, VerificationKey}, + primitive::v1::{asset::DEFAULT_NATIVE_ASSET_DENOM, Address, RollupId}, protocol::transaction::v1alpha1::{ - action::SequenceAction, - TransactionParams, - UnsignedTransaction, + action::SequenceAction, TransactionParams, UnsignedTransaction, }, }; use bytes::Bytes; use prost::Message as _; use rand::rngs::OsRng; - use tendermint::{ - account::Id, - Hash, - Time, - }; + use tendermint::{account::Id, Hash, Time}; use super::*; use crate::{ - app::test_utils::default_fees, - asset::get_native_asset, - mempool::Mempool, + app::test_utils::default_fees, asset::get_native_asset, mempool::Mempool, proposal::commitment::generate_rollup_datas_commitment, }; @@ -257,14 +224,12 @@ mod test { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![ - SequenceAction { - rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), - data: b"helloworld".to_vec(), - fee_asset_id: get_native_asset().id(), - } - .into(), - ], + actions: vec![SequenceAction { + rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), + data: b"helloworld".to_vec(), + fee_asset_id: get_native_asset().id(), + } + .into()], } } @@ -349,30 +314,26 @@ mod test { async fn process_proposal_fail_missing_action_commitment() { let (mut consensus_service, _) = new_consensus_service(None).await; let process_proposal = new_process_proposal_request(vec![]); - assert!( - consensus_service - .handle_process_proposal(process_proposal) - .await - .err() - .unwrap() - .to_string() - .contains("no transaction commitment in proposal") - ); + assert!(consensus_service + .handle_process_proposal(process_proposal) + .await + .err() + .unwrap() + .to_string() + .contains("no transaction commitment in proposal")); } #[tokio::test] async fn process_proposal_fail_wrong_commitment_length() { let (mut consensus_service, _) = new_consensus_service(None).await; let process_proposal = new_process_proposal_request(vec![[0u8; 16].to_vec().into()]); - assert!( - consensus_service - .handle_process_proposal(process_proposal) - .await - .err() - .unwrap() - .to_string() - .contains("transaction commitment must be 32 bytes") - ); + assert!(consensus_service + .handle_process_proposal(process_proposal) + .await + .err() + .unwrap() + .to_string() + .contains("transaction commitment must be 32 bytes")); } #[tokio::test] @@ -382,15 +343,13 @@ mod test { [99u8; 32].to_vec().into(), [99u8; 32].to_vec().into(), ]); - assert!( - consensus_service - .handle_process_proposal(process_proposal) - .await - .err() - .unwrap() - .to_string() - .contains("transaction commitment does not match expected") - ); + assert!(consensus_service + .handle_process_proposal(process_proposal) + .await + .err() + .unwrap() + .to_string() + .contains("transaction commitment does not match expected")); } #[tokio::test] @@ -428,19 +387,13 @@ mod test { fn default_header() -> tendermint::block::Header { use tendermint::{ account, - block::{ - header::Version, - Height, - }, + block::{header::Version, Height}, chain, hash::AppHash, }; tendermint::block::Header { - version: Version { - block: 0, - app: 0, - }, + version: Version { block: 0, app: 0 }, chain_id: chain::Id::try_from("test").unwrap(), height: Height::from(1u32), time: Time::now(), diff --git a/crates/astria-sequencer/src/service/info/abci_query_router.rs b/crates/astria-sequencer/src/service/info/abci_query_router.rs index 988e0b779..7c91d691d 100644 --- a/crates/astria-sequencer/src/service/info/abci_query_router.rs +++ b/crates/astria-sequencer/src/service/info/abci_query_router.rs @@ -33,21 +33,11 @@ //! `Clone` to fulfill the `Clone` requirement of the `Info` service. //! 4. finally `MakeErasedAbciQueryHandler` is the glue that allows to go from a non-object safe //! `AbciQueryHandler` to an object-safe `ErasedAbciQueryHandler`. -use std::{ - future::Future, - pin::Pin, -}; +use std::{future::Future, pin::Pin}; use cnidarium::Storage; -use matchit::{ - InsertError, - Match, - MatchError, -}; -use tendermint::abci::{ - request, - response, -}; +use matchit::{InsertError, Match, MatchError}; +use tendermint::abci::{request, response}; /// `Router` is a wrapper around [`matchit::Router`] to route abci queries /// to handlers. @@ -87,9 +77,7 @@ impl BoxedAbciQueryHandler { where H: AbciQueryHandler, { - Self(Box::new(MakeErasedAbciQueryHandler { - handler, - })) + Self(Box::new(MakeErasedAbciQueryHandler { handler })) } pub(super) async fn call( diff --git a/crates/astria-sequencer/src/service/info/mod.rs b/crates/astria-sequencer/src/service/info/mod.rs index 7433c14a0..a00edb6c3 100644 --- a/crates/astria-sequencer/src/service/info/mod.rs +++ b/crates/astria-sequencer/src/service/info/mod.rs @@ -1,34 +1,21 @@ use std::{ pin::Pin, - task::{ - Context, - Poll, - }, + task::{Context, Poll}, }; use anyhow::Context as _; use astria_core::protocol::abci::AbciErrorCode; use cnidarium::Storage; -use futures::{ - Future, - FutureExt, -}; +use futures::{Future, FutureExt}; use penumbra_tower_trace::v038::RequestExt as _; use tendermint::v0_38::abci::{ request, - response::{ - self, - Echo, - }, - InfoRequest, - InfoResponse, + response::{self, Echo}, + InfoRequest, InfoResponse, }; use tower::Service; use tower_abci::BoxError; -use tracing::{ - instrument, - Instrument as _, -}; +use tracing::{instrument, Instrument as _}; mod abci_query_router; @@ -111,10 +98,7 @@ impl Info { }; } - Ok(matchit::Match { - value, - params, - }) => { + Ok(matchit::Match { value, params }) => { let params = params .iter() .map(|(k, v)| (k.to_owned(), v.to_owned())) @@ -149,28 +133,17 @@ impl Service for Info { #[cfg(test)] mod test { use astria_core::primitive::v1::{ - asset::{ - Denom, - DEFAULT_NATIVE_ASSET_DENOM, - }, + asset::{Denom, DEFAULT_NATIVE_ASSET_DENOM}, Address, }; use cnidarium::StateDelta; use prost::Message as _; - use tendermint::v0_38::abci::{ - request, - InfoRequest, - InfoResponse, - }; + use tendermint::v0_38::abci::{request, InfoRequest, InfoResponse}; use super::Info; use crate::{ accounts::state_ext::StateWriteExt as _, - asset::{ - get_native_asset, - initialize_native_asset, - state_ext::StateWriteExt, - }, + asset::{get_native_asset, initialize_native_asset, state_ext::StateWriteExt}, state_ext::StateWriteExt as _, }; diff --git a/crates/astria-sequencer/src/service/mempool.rs b/crates/astria-sequencer/src/service/mempool.rs index b688bf376..22e0e68af 100644 --- a/crates/astria-sequencer/src/service/mempool.rs +++ b/crates/astria-sequencer/src/service/mempool.rs @@ -1,39 +1,22 @@ use std::{ pin::Pin, - task::{ - Context, - Poll, - }, + task::{Context, Poll}, }; use astria_core::{ generated::protocol::transaction::v1alpha1 as raw, - protocol::{ - abci::AbciErrorCode, - transaction::v1alpha1::SignedTransaction, - }, + protocol::{abci::AbciErrorCode, transaction::v1alpha1::SignedTransaction}, }; use cnidarium::Storage; -use futures::{ - Future, - FutureExt, -}; +use futures::{Future, FutureExt}; use prost::Message as _; -use tendermint::v0_38::abci::{ - request, - response, - MempoolRequest, - MempoolResponse, -}; +use tendermint::v0_38::abci::{request, response, MempoolRequest, MempoolResponse}; use tower::Service; use tower_abci::BoxError; use tracing::Instrument as _; use crate::{ - accounts::state_ext::StateReadExt, - mempool::Mempool as AppMempool, - metrics_init, - transaction, + accounts::state_ext::StateReadExt, mempool::Mempool as AppMempool, metrics_init, transaction, }; const MAX_TX_SIZE: usize = 256_000; // 256 KB @@ -50,10 +33,7 @@ pub(crate) struct Mempool { impl Mempool { pub(crate) fn new(storage: Storage, mempool: AppMempool) -> Self { - Self { - storage, - mempool, - } + Self { storage, mempool } } } @@ -100,9 +80,7 @@ async fn handle_check_tx( let tx_hash = sha2::Sha256::digest(&req.tx).into(); - let request::CheckTx { - tx, .. - } = req; + let request::CheckTx { tx, .. } = req; if tx.len() > MAX_TX_SIZE { mempool.remove(tx_hash).await; metrics::counter!(metrics_init::CHECK_TX_REMOVED_TOO_LARGE).increment(1); diff --git a/crates/astria-sequencer/src/service/snapshot.rs b/crates/astria-sequencer/src/service/snapshot.rs index df6aae796..d1290b305 100644 --- a/crates/astria-sequencer/src/service/snapshot.rs +++ b/crates/astria-sequencer/src/service/snapshot.rs @@ -1,25 +1,13 @@ use std::{ pin::Pin, - task::{ - Context, - Poll, - }, + task::{Context, Poll}, }; -use futures::{ - Future, - FutureExt, -}; +use futures::{Future, FutureExt}; use penumbra_tower_trace::v038::RequestExt as _; use tendermint::v0_38::abci::{ - response::{ - ApplySnapshotChunk, - ListSnapshots, - LoadSnapshotChunk, - OfferSnapshot, - }, - SnapshotRequest, - SnapshotResponse, + response::{ApplySnapshotChunk, ListSnapshots, LoadSnapshotChunk, OfferSnapshot}, + SnapshotRequest, SnapshotResponse, }; use tower::Service; use tower_abci::BoxError; diff --git a/crates/astria-sequencer/src/state_ext.rs b/crates/astria-sequencer/src/state_ext.rs index b8ee655d3..fe12e8777 100644 --- a/crates/astria-sequencer/src/state_ext.rs +++ b/crates/astria-sequencer/src/state_ext.rs @@ -1,14 +1,7 @@ -use anyhow::{ - bail, - Context as _, - Result, -}; +use anyhow::{bail, Context as _, Result}; use astria_core::primitive::v1::asset; use async_trait::async_trait; -use cnidarium::{ - StateRead, - StateWrite, -}; +use cnidarium::{StateRead, StateWrite}; use futures::StreamExt as _; use tendermint::Time; use tracing::instrument; @@ -294,11 +287,7 @@ mod test { use cnidarium::StateDelta; use tendermint::Time; - use super::{ - revision_number_from_chain_id, - StateReadExt as _, - StateWriteExt as _, - }; + use super::{revision_number_from_chain_id, StateReadExt as _, StateWriteExt as _}; #[test] fn revision_number_from_chain_id_regex() { diff --git a/crates/astria-sequencer/src/transaction/action_handler.rs b/crates/astria-sequencer/src/transaction/action_handler.rs index 17cfb7345..74aa5b07e 100644 --- a/crates/astria-sequencer/src/transaction/action_handler.rs +++ b/crates/astria-sequencer/src/transaction/action_handler.rs @@ -1,10 +1,7 @@ use anyhow::Result; use astria_core::primitive::v1::Address; use async_trait::async_trait; -use cnidarium::{ - StateRead, - StateWrite, -}; +use cnidarium::{StateRead, StateWrite}; #[async_trait] pub(crate) trait ActionHandler { diff --git a/crates/astria-sequencer/src/transaction/checks.rs b/crates/astria-sequencer/src/transaction/checks.rs index a2074e0e2..174a58804 100644 --- a/crates/astria-sequencer/src/transaction/checks.rs +++ b/crates/astria-sequencer/src/transaction/checks.rs @@ -1,30 +1,17 @@ use std::collections::HashMap; -use anyhow::{ - ensure, - Context as _, -}; +use anyhow::{ensure, Context as _}; use astria_core::{ - primitive::v1::{ - asset, - Address, - RollupId, - }, + primitive::v1::{asset, Address, RollupId}, protocol::transaction::v1alpha1::{ - action::{ - Action, - BridgeLockAction, - }, - SignedTransaction, - UnsignedTransaction, + action::{Action, BridgeLockAction}, + SignedTransaction, UnsignedTransaction, }, }; use crate::{ - accounts::state_ext::StateReadExt, - bridge::state_ext::StateReadExt as _, - ibc::state_ext::StateReadExt as _, - state_ext::StateReadExt as _, + accounts::state_ext::StateReadExt, bridge::state_ext::StateReadExt as _, + ibc::state_ext::StateReadExt as _, state_ext::StateReadExt as _, }; pub(crate) async fn check_nonce_mempool( @@ -267,18 +254,11 @@ async fn bridge_unlock_update_fees( mod test { use astria_core::{ primitive::v1::{ - asset::{ - Denom, - DEFAULT_NATIVE_ASSET_DENOM, - }, - RollupId, - ADDRESS_LEN, + asset::{Denom, DEFAULT_NATIVE_ASSET_DENOM}, + RollupId, ADDRESS_LEN, }, protocol::transaction::v1alpha1::{ - action::{ - SequenceAction, - TransferAction, - }, + action::{SequenceAction, TransferAction}, TransactionParams, }, }; @@ -286,10 +266,8 @@ mod test { use super::*; use crate::{ - accounts::state_ext::StateWriteExt as _, - app::test_utils::*, - bridge::state_ext::StateWriteExt, - ibc::state_ext::StateWriteExt as _, + accounts::state_ext::StateWriteExt as _, app::test_utils::*, + bridge::state_ext::StateWriteExt, ibc::state_ext::StateWriteExt as _, sequence::state_ext::StateWriteExt as _, }; @@ -348,10 +326,7 @@ mod test { nonce: 0, chain_id: "test-chain-id".to_string(), }; - let tx = UnsignedTransaction { - actions, - params, - }; + let tx = UnsignedTransaction { actions, params }; let signed_tx = tx.into_signed(&alice_signing_key); check_balance_mempool(&signed_tx, &state_tx) @@ -410,10 +385,7 @@ mod test { nonce: 0, chain_id: "test-chain-id".to_string(), }; - let tx = UnsignedTransaction { - actions, - params, - }; + let tx = UnsignedTransaction { actions, params }; let signed_tx = tx.into_signed(&alice_signing_key); let err = check_balance_mempool(&signed_tx, &state_tx) diff --git a/crates/astria-sequencer/src/transaction/mod.rs b/crates/astria-sequencer/src/transaction/mod.rs index 1eaa5f2a3..96d2d6cbe 100644 --- a/crates/astria-sequencer/src/transaction/mod.rs +++ b/crates/astria-sequencer/src/transaction/mod.rs @@ -4,35 +4,20 @@ mod checks; use std::fmt; pub(crate) use action_handler::ActionHandler; -use anyhow::{ - ensure, - Context as _, -}; +use anyhow::{ensure, Context as _}; use astria_core::{ primitive::v1::Address, - protocol::transaction::v1alpha1::{ - action::Action, - SignedTransaction, - UnsignedTransaction, - }, + protocol::transaction::v1alpha1::{action::Action, SignedTransaction, UnsignedTransaction}, }; pub(crate) use checks::{ - check_balance_for_total_fees, - check_balance_mempool, - check_chain_id_mempool, + check_balance_for_total_fees, check_balance_mempool, check_chain_id_mempool, check_nonce_mempool, }; use tracing::instrument; use crate::{ - accounts::state_ext::{ - StateReadExt, - StateWriteExt, - }, - ibc::{ - host_interface::AstriaHost, - state_ext::StateReadExt as _, - }, + accounts::state_ext::{StateReadExt, StateWriteExt}, + ibc::{host_interface::AstriaHost, state_ext::StateReadExt as _}, state_ext::StateReadExt as _, }; diff --git a/crates/astria-telemetry/src/display.rs b/crates/astria-telemetry/src/display.rs index a95d4b9c9..480e538da 100644 --- a/crates/astria-telemetry/src/display.rs +++ b/crates/astria-telemetry/src/display.rs @@ -1,13 +1,7 @@ //! Utilities to emit fields using their [`std::fmt::Display`] implementation. use std::{ - fmt::{ - self, - Display, - Formatter, - Result, - }, - io, - str, + fmt::{self, Display, Formatter, Result}, + io, str, }; use base64_serde::base64_serde_type; @@ -24,10 +18,7 @@ pub struct Base64<'a>(&'a [u8]); impl<'a> Display for Base64<'a> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { - use base64::{ - display::Base64Display, - engine::general_purpose::STANDARD, - }; + use base64::{display::Base64Display, engine::general_purpose::STANDARD}; Base64Display::new(self.0, &STANDARD).fmt(f) } } @@ -119,9 +110,7 @@ where io::Error::new(io::ErrorKind::Other, "fmt error") } - let mut wr = WriterFormatter { - inner: f, - }; + let mut wr = WriterFormatter { inner: f }; serde_json::to_writer(&mut wr, self.0).map_err(|_| fmt::Error) } } diff --git a/crates/astria-telemetry/src/lib.rs b/crates/astria-telemetry/src/lib.rs index 6226e7122..8ed61b75c 100644 --- a/crates/astria-telemetry/src/lib.rs +++ b/crates/astria-telemetry/src/lib.rs @@ -10,35 +10,17 @@ //! ``` use std::{ io::IsTerminal as _, - net::{ - AddrParseError, - SocketAddr, - }, + net::{AddrParseError, SocketAddr}, }; -use metrics_exporter_prometheus::{ - BuildError, - PrometheusBuilder, -}; -use opentelemetry::{ - global, - trace::TracerProvider as _, -}; -use opentelemetry_sdk::{ - runtime::Tokio, - trace::TracerProvider, -}; +use metrics_exporter_prometheus::{BuildError, PrometheusBuilder}; +use opentelemetry::{global, trace::TracerProvider as _}; +use opentelemetry_sdk::{runtime::Tokio, trace::TracerProvider}; use opentelemetry_stdout::SpanExporter; use tracing_subscriber::{ - filter::{ - LevelFilter, - ParseError, - }, + filter::{LevelFilter, ParseError}, layer::SubscriberExt as _, - util::{ - SubscriberInitExt as _, - TryInitError, - }, + util::{SubscriberInitExt as _, TryInitError}, EnvFilter, }; @@ -197,10 +179,7 @@ impl Config { #[must_use = "telemetry must be initialized to be useful"] pub fn set_no_otel(self, no_otel: bool) -> Self { - Self { - no_otel, - ..self - } + Self { no_otel, ..self } } #[must_use = "telemetry must be initialized to be useful"] diff --git a/crates/astria-telemetry/src/macros.rs b/crates/astria-telemetry/src/macros.rs index f5799f0a5..79eed19e1 100644 --- a/crates/astria-telemetry/src/macros.rs +++ b/crates/astria-telemetry/src/macros.rs @@ -2,9 +2,7 @@ // hidden because they shouldn't be imported. #[doc(hidden)] pub use const_format::{ - concatcp as __concatcp, - map_ascii_case as __map_ascii_case, - Case as __Case, + concatcp as __concatcp, map_ascii_case as __map_ascii_case, Case as __Case, }; /// Declare a `const` string slice, using the declaring crate's name as a diff --git a/crates/astria-test-utils/src/mock/geth.rs b/crates/astria-test-utils/src/mock/geth.rs index a7f56eee4..98f93393d 100644 --- a/crates/astria-test-utils/src/mock/geth.rs +++ b/crates/astria-test-utils/src/mock/geth.rs @@ -66,22 +66,12 @@ use std::net::SocketAddr; pub use __rpc_traits::GethServer; use ethers::types::Transaction; use jsonrpsee::{ - core::{ - async_trait, - SubscriptionResult, - }, + core::{async_trait, SubscriptionResult}, server::IdProvider, - types::{ - ErrorObjectOwned, - SubscriptionId, - }, + types::{ErrorObjectOwned, SubscriptionId}, PendingSubscriptionSink, }; -use tokio::sync::broadcast::{ - channel, - error::SendError, - Sender, -}; +use tokio::sync::broadcast::{channel, error::SendError, Sender}; #[derive(Debug)] pub struct RandomU256IdProvider; @@ -106,18 +96,14 @@ impl IdProvider for RandomU256IdProvider { } mod __rpc_traits { - use jsonrpsee::{ - core::SubscriptionResult, - proc_macros::rpc, - types::ErrorObjectOwned, - }; + use jsonrpsee::{core::SubscriptionResult, proc_macros::rpc, types::ErrorObjectOwned}; // The mockserver has to be able to handle an `eth_subscribe` RPC with parameters // `"newPendingTransactions"` and `true` #[rpc(server)] pub trait Geth { #[subscription(name = "eth_subscribe", item = Transaction, unsubscribe = "eth_unsubscribe")] async fn eth_subscribe(&self, target: String, full_txs: Option) - -> SubscriptionResult; + -> SubscriptionResult; #[method(name = "net_version")] async fn net_version(&self) -> Result; diff --git a/lint/tracing_debug_field/src/lib.rs b/lint/tracing_debug_field/src/lib.rs index e1cc28839..5e8a05632 100644 --- a/lint/tracing_debug_field/src/lib.rs +++ b/lint/tracing_debug_field/src/lib.rs @@ -4,24 +4,12 @@ extern crate rustc_hir; extern crate rustc_span; -use clippy_utils::{ - diagnostics::span_lint_and_help, - is_expr_path_def_path, -}; +use clippy_utils::{diagnostics::span_lint_and_help, is_expr_path_def_path}; use if_chain::if_chain; -use rustc_hir::{ - Expr, - ExprKind, -}; -use rustc_lint::{ - LateContext, - LateLintPass, -}; +use rustc_hir::{Expr, ExprKind}; +use rustc_lint::{LateContext, LateLintPass}; use rustc_span::{ - hygiene::{ - ExpnKind, - MacroKind, - }, + hygiene::{ExpnKind, MacroKind}, Span, }; @@ -95,14 +83,7 @@ fn first_span_in_crate(arg: &Expr<'_>) -> Span { let mut span = 'get_span: { // Case 1: fields like foo = ?bar that are transformed as debug(&bar). if let Expr { - kind: - ExprKind::AddrOf( - _, - _, - Expr { - span, .. - }, - ), + kind: ExprKind::AddrOf(_, _, Expr { span, .. }), .. } = arg { From c020f7ea3edbb514e0ac1c15421910df6f9ee9c5 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Fri, 7 Jun 2024 17:27:46 -0500 Subject: [PATCH 05/23] Added chain_id check on composer startup. Formatted. --- .../tests/blackbox/helper/mock_sequencer.rs | 83 +++++++++++++++++-- .../tests/blackbox/helper/mod.rs | 36 ++++++-- 2 files changed, 108 insertions(+), 11 deletions(-) diff --git a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs index 9f5a8f291..736ab1c23 100644 --- a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs +++ b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs @@ -1,12 +1,21 @@ use prost::Message; use serde_json::json; -use tendermint_rpc::{response, Id}; +use tendermint_rpc::{ + response, + Id, +}; use wiremock::{ - matchers::{body_partial_json, body_string_contains}, - Mock, MockGuard, MockServer, ResponseTemplate, + matchers::{ + body_partial_json, + body_string_contains, + }, + Mock, + MockGuard, + MockServer, + ResponseTemplate, }; -pub async fn start() -> (MockServer, MockGuard) { +pub async fn start() -> (MockServer, MockGuard, MockGuard) { use astria_core::generated::protocol::account::v1alpha1::NonceResponse; let server = MockServer::start().await; let startup_guard = mount_abci_query_mock( @@ -18,7 +27,8 @@ pub async fn start() -> (MockServer, MockGuard) { }, ) .await; - (server, startup_guard) + let status_guard = mount_cometbft_status_response(&server, "test-chain-1").await; + (server, startup_guard, status_guard) } pub async fn mount_abci_query_mock( @@ -48,3 +58,66 @@ pub async fn mount_abci_query_mock( .mount_as_scoped(server) .await } + +const STATUS_RESPONSE: &str = r#" +{ + "node_info": { + "protocol_version": { + "p2p": "8", + "block": "11", + "app": "0" + }, + "id": "a1d3bbddb7800c6da2e64169fec281494e963ba3", + "listen_addr": "tcp://0.0.0.0:26656", + "network": "test", + "version": "0.38.6", + "channels": "40202122233038606100", + "moniker": "fullnode", + "other": { + "tx_index": "on", + "rpc_address": "tcp://0.0.0.0:26657" + } + }, + "sync_info": { + "latest_block_hash": "A4202E4E367712AC2A797860265A7EBEA8A3ACE513CB0105C2C9058449641202", + "latest_app_hash": "BCC9C9B82A49EC37AADA41D32B4FBECD2441563703955413195BDA2236775A68", + "latest_block_height": "452605", + "latest_block_time": "2024-05-09T15:59:17.849713071Z", + "earliest_block_hash": "C34B7B0B82423554B844F444044D7D08A026D6E413E6F72848DB2F8C77ACE165", + "earliest_app_hash": "6B776065775471CEF46AC75DE09A4B869A0E0EB1D7725A04A342C0E46C16F472", + "earliest_block_height": "1", + "earliest_block_time": "2024-04-23T00:49:11.964127Z", + "catching_up": false + }, + "validator_info": { + "address": "0B46F33BA2FA5C2E2AD4C4C4E5ECE3F1CA03D195", + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "bA6GipHUijVuiYhv+4XymdePBsn8EeTqjGqNQrBGZ4I=" + }, + "voting_power": "0" + } +}"#; + +/// Mounts a `CometBFT` status response with the chain ID set as per +/// `TestSequencerRelayerConfig::sequencer_chain_id`. +async fn mount_cometbft_status_response( + server: &MockServer, + mock_sequencer_chain_id: &str, +) -> MockGuard { + use tendermint_rpc::endpoint::status; + + let mut status_response: status::Response = serde_json::from_str(STATUS_RESPONSE).unwrap(); + status_response.node_info.network = mock_sequencer_chain_id.to_string().parse().unwrap(); + + let response = + tendermint_rpc::response::Wrapper::new_with_id(Id::Num(1), Some(status_response), None); + + Mock::given(body_partial_json(json!({"method": "status"}))) + .respond_with(ResponseTemplate::new(200).set_body_json(response)) + .up_to_n_times(1) + .expect(1..) + .named("CometBFT status") + .mount_as_scoped(server) + .await +} diff --git a/crates/astria-composer/tests/blackbox/helper/mod.rs b/crates/astria-composer/tests/blackbox/helper/mod.rs index 242efc044..9040988ad 100644 --- a/crates/astria-composer/tests/blackbox/helper/mod.rs +++ b/crates/astria-composer/tests/blackbox/helper/mod.rs @@ -1,19 +1,41 @@ -use std::{collections::HashMap, io::Write, net::SocketAddr, time::Duration}; +use std::{ + collections::HashMap, + io::Write, + net::SocketAddr, + time::Duration, +}; -use astria_composer::{config::Config, Composer}; +use astria_composer::{ + config::Config, + Composer, +}; use astria_core::{ primitive::v1::RollupId, - protocol::{abci::AbciErrorCode, transaction::v1alpha1::SignedTransaction}, + protocol::{ + abci::AbciErrorCode, + transaction::v1alpha1::SignedTransaction, + }, }; use astria_eyre::eyre; use ethers::prelude::Transaction; use once_cell::sync::Lazy; use tempfile::NamedTempFile; -use tendermint_rpc::{endpoint::broadcast::tx_sync, request, response, Id}; +use tendermint_rpc::{ + endpoint::broadcast::tx_sync, + request, + response, + Id, +}; use test_utils::mock::Geth; use tokio::task::JoinHandle; use tracing::debug; -use wiremock::{Mock, MockGuard, MockServer, Request, ResponseTemplate}; +use wiremock::{ + Mock, + MockGuard, + MockServer, + Request, + ResponseTemplate, +}; pub mod mock_sequencer; @@ -41,6 +63,7 @@ pub struct TestComposer { pub rollup_nodes: HashMap, pub sequencer: wiremock::MockServer, pub setup_guard: MockGuard, + pub status_guard: MockGuard, pub grpc_collector_addr: SocketAddr, } @@ -60,7 +83,7 @@ pub async fn spawn_composer(rollup_ids: &[&str]) -> TestComposer { rollup_nodes.insert((*id).to_string(), geth); rollups.push_str(&format!("{id}::{execution_url},")); } - let (sequencer, sequencer_setup_guard) = mock_sequencer::start().await; + let (sequencer, sequencer_setup_guard, sequencer_status_guard) = mock_sequencer::start().await; let sequencer_url = sequencer.uri(); let keyfile = NamedTempFile::new().unwrap(); (&keyfile) @@ -98,6 +121,7 @@ pub async fn spawn_composer(rollup_ids: &[&str]) -> TestComposer { rollup_nodes, sequencer, setup_guard: sequencer_setup_guard, + status_guard: sequencer_status_guard, grpc_collector_addr, } } From 406a97a79142799e2f8321f528a12072eb05fcf3 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Fri, 7 Jun 2024 17:32:24 -0500 Subject: [PATCH 06/23] Added chain_id check on composer startup --- crates/astria-bridge-withdrawer/src/api.rs | 32 ++- crates/astria-bridge-withdrawer/src/config.rs | 5 +- crates/astria-bridge-withdrawer/src/main.rs | 18 +- .../src/metrics_init.rs | 15 +- .../src/withdrawer/ethereum/convert.rs | 30 ++- .../src/withdrawer/ethereum/test_utils.rs | 16 +- .../src/withdrawer/ethereum/watcher.rs | 42 +++- .../src/withdrawer/mod.rs | 32 ++- .../src/withdrawer/state.rs | 4 +- .../src/withdrawer/submitter/builder.rs | 5 +- .../src/withdrawer/submitter/mod.rs | 45 +++- .../src/withdrawer/submitter/signer.rs | 10 +- crates/astria-cli/src/cli/mod.rs | 10 +- crates/astria-cli/src/cli/rollup.rs | 10 +- crates/astria-cli/src/cli/sequencer.rs | 10 +- crates/astria-cli/src/commands/mod.rs | 63 ++++-- crates/astria-cli/src/commands/rollup.rs | 25 ++- crates/astria-cli/src/commands/sequencer.rs | 40 +++- crates/astria-cli/src/main.rs | 10 +- crates/astria-cli/src/types.rs | 15 +- crates/astria-cli/test-utils/src/lib.rs | 5 +- crates/astria-composer/src/api.rs | 24 ++- crates/astria-composer/src/collectors/geth.rs | 41 +++- crates/astria-composer/src/collectors/grpc.rs | 28 ++- crates/astria-composer/src/composer.rs | 45 +++- crates/astria-composer/src/config.rs | 5 +- .../astria-composer/src/executor/builder.rs | 11 +- .../src/executor/bundle_factory/mod.rs | 21 +- .../src/executor/bundle_factory/tests.rs | 23 +- crates/astria-composer/src/executor/mod.rs | 66 ++++-- crates/astria-composer/src/executor/tests.rs | 202 +++++++++++++----- crates/astria-composer/src/grpc.rs | 15 +- crates/astria-composer/src/main.rs | 12 +- crates/astria-composer/src/metrics_init.rs | 20 +- crates/astria-composer/src/rollup.rs | 10 +- .../tests/blackbox/geth_collector.rs | 12 +- .../tests/blackbox/grpc_collector.rs | 7 +- crates/astria-conductor/src/block_cache.rs | 20 +- .../src/celestia/block_verifier.rs | 42 +++- .../astria-conductor/src/celestia/builder.rs | 10 +- .../astria-conductor/src/celestia/convert.rs | 28 ++- crates/astria-conductor/src/celestia/fetch.rs | 32 ++- .../src/celestia/latest_height_stream.rs | 17 +- crates/astria-conductor/src/celestia/mod.rs | 76 +++++-- .../src/celestia/reconstruct.rs | 15 +- .../src/celestia/reporting.rs | 11 +- .../astria-conductor/src/celestia/verify.rs | 81 +++++-- crates/astria-conductor/src/conductor.rs | 45 +++- crates/astria-conductor/src/config.rs | 16 +- .../astria-conductor/src/executor/builder.rs | 12 +- .../astria-conductor/src/executor/channel.rs | 26 ++- .../astria-conductor/src/executor/client.rs | 51 ++++- crates/astria-conductor/src/executor/mod.rs | 60 ++++-- crates/astria-conductor/src/executor/state.rs | 29 ++- crates/astria-conductor/src/executor/tests.rs | 101 +++++++-- crates/astria-conductor/src/main.rs | 18 +- crates/astria-conductor/src/metrics_init.rs | 13 +- .../src/sequencer/block_stream.rs | 21 +- .../astria-conductor/src/sequencer/client.rs | 26 ++- crates/astria-conductor/src/sequencer/mod.rs | 40 +++- .../src/sequencer/reporting.rs | 19 +- crates/astria-conductor/src/utils.rs | 5 +- .../tests/blackbox/firm_only.rs | 17 +- .../tests/blackbox/helpers/macros.rs | 5 +- .../tests/blackbox/helpers/mock_grpc.rs | 49 ++++- .../tests/blackbox/helpers/mod.rs | 108 ++++++++-- .../astria-conductor/tests/blackbox/main.rs | 7 +- .../tests/blackbox/soft_and_firm.rs | 21 +- .../tests/blackbox/soft_only.rs | 14 +- crates/astria-config/src/lib.rs | 9 +- crates/astria-config/src/tests.rs | 10 +- crates/astria-core/src/brotli.rs | 6 +- crates/astria-core/src/celestia.rs | 5 +- crates/astria-core/src/crypto.rs | 42 +++- .../astria-core/src/execution/v1alpha2/mod.rs | 11 +- crates/astria-core/src/primitive/v1/asset.rs | 10 +- crates/astria-core/src/primitive/v1/mod.rs | 34 ++- crates/astria-core/src/primitive/v1/u128.rs | 25 ++- crates/astria-core/src/protocol/abci.rs | 5 +- .../src/protocol/account/v1alpha1/mod.rs | 41 +++- .../src/protocol/asset/v1alpha1/mod.rs | 10 +- crates/astria-core/src/protocol/test_utils.rs | 20 +- .../protocol/transaction/v1alpha1/action.rs | 43 +++- .../src/protocol/transaction/v1alpha1/mod.rs | 66 ++++-- .../src/sequencerblock/v1alpha1/block.rs | 38 +++- .../src/sequencerblock/v1alpha1/celestia.rs | 47 +++- .../src/sequencerblock/v1alpha1/mod.rs | 21 +- crates/astria-eyre/src/lib.rs | 5 +- .../tests/health/main.rs | 61 ++++-- crates/astria-grpc-mock/src/lib.rs | 10 +- crates/astria-grpc-mock/src/matcher.rs | 5 +- crates/astria-grpc-mock/src/mock.rs | 23 +- crates/astria-grpc-mock/src/mock_server.rs | 19 +- crates/astria-grpc-mock/src/mock_set.rs | 24 ++- crates/astria-grpc-mock/src/mounted_mock.rs | 15 +- crates/astria-grpc-mock/src/response.rs | 5 +- crates/astria-grpc-mock/src/verification.rs | 5 +- crates/astria-merkle/src/audit.rs | 69 ++++-- crates/astria-merkle/src/lib.rs | 19 +- crates/astria-merkle/src/tests.rs | 10 +- .../src/extension_trait.rs | 69 ++++-- crates/astria-sequencer-client/src/lib.rs | 26 ++- .../astria-sequencer-client/src/tests/http.rs | 81 +++++-- crates/astria-sequencer-relayer/src/api.rs | 32 ++- crates/astria-sequencer-relayer/src/config.rs | 21 +- crates/astria-sequencer-relayer/src/lib.rs | 10 +- crates/astria-sequencer-relayer/src/main.rs | 18 +- .../src/metrics_init.rs | 24 ++- .../src/relayer/builder.rs | 27 ++- .../src/relayer/celestia_client/builder.rs | 16 +- .../relayer/celestia_client/celestia_keys.rs | 14 +- .../src/relayer/celestia_client/error.rs | 6 +- .../src/relayer/celestia_client/mod.rs | 87 ++++++-- .../src/relayer/celestia_client/tests.rs | 22 +- .../src/relayer/mod.rs | 47 +++- .../src/relayer/read.rs | 37 +++- .../src/relayer/state.rs | 4 +- .../src/relayer/submission.rs | 37 +++- .../src/relayer/write/conversion.rs | 58 ++++- .../src/relayer/write/mod.rs | 44 +++- .../src/sequencer_relayer.rs | 25 ++- crates/astria-sequencer-relayer/src/utils.rs | 5 +- .../astria-sequencer-relayer/src/validator.rs | 5 +- .../helpers/mock_celestia_app_server.rs | 78 +++++-- .../blackbox/helpers/mock_sequencer_server.rs | 35 ++- .../tests/blackbox/helpers/mod.rs | 5 +- .../helpers/test_sequencer_relayer.rs | 63 ++++-- .../tests/blackbox/main.rs | 10 +- .../astria-sequencer-utils/src/blob_parser.rs | 49 ++++- crates/astria-sequencer-utils/src/cli.rs | 10 +- .../src/genesis_parser.rs | 17 +- crates/astria-sequencer-utils/src/main.rs | 5 +- .../tests/parse_blob.rs | 10 +- .../astria-sequencer/src/accounts/action.rs | 19 +- .../src/accounts/component.rs | 16 +- crates/astria-sequencer/src/accounts/query.rs | 20 +- .../src/accounts/state_ext.rs | 36 +++- crates/astria-sequencer/src/api_state_ext.rs | 37 +++- crates/astria-sequencer/src/app/mod.rs | 79 +++++-- crates/astria-sequencer/src/app/test_utils.rs | 32 ++- crates/astria-sequencer/src/app/tests_app.rs | 143 +++++++++---- .../src/app/tests_breaking_changes.rs | 60 ++++-- .../src/app/tests_execute_transaction.rs | 174 +++++++++------ crates/astria-sequencer/src/asset/query.rs | 26 ++- .../astria-sequencer/src/asset/state_ext.rs | 30 ++- .../astria-sequencer/src/authority/action.rs | 42 +++- .../src/authority/component.rs | 16 +- .../src/authority/state_ext.rs | 45 +++- .../src/bridge/bridge_lock_action.rs | 59 +++-- .../src/bridge/bridge_unlock_action.rs | 65 ++++-- .../astria-sequencer/src/bridge/component.rs | 10 +- .../src/bridge/init_bridge_account_action.rs | 25 ++- .../astria-sequencer/src/bridge/state_ext.rs | 43 +++- crates/astria-sequencer/src/config.rs | 5 +- .../astria-sequencer/src/fee_asset_change.rs | 20 +- crates/astria-sequencer/src/genesis.rs | 10 +- crates/astria-sequencer/src/grpc/sequencer.rs | 50 ++++- crates/astria-sequencer/src/ibc/component.rs | 20 +- .../src/ibc/ibc_relayer_change.rs | 19 +- .../src/ibc/ics20_transfer.rs | 50 ++++- .../src/ibc/ics20_withdrawal.rs | 32 ++- crates/astria-sequencer/src/ibc/state_ext.rs | 37 +++- crates/astria-sequencer/src/main.rs | 7 +- crates/astria-sequencer/src/mempool.rs | 58 +++-- crates/astria-sequencer/src/metrics_init.rs | 19 +- .../src/proposal/block_size_constraints.rs | 6 +- .../src/proposal/commitment.rs | 23 +- .../astria-sequencer/src/sequence/action.rs | 19 +- .../src/sequence/component.rs | 10 +- .../src/sequence/state_ext.rs | 21 +- crates/astria-sequencer/src/sequencer.rs | 40 +++- .../astria-sequencer/src/service/consensus.rs | 125 +++++++---- .../src/service/info/abci_query_router.rs | 20 +- .../astria-sequencer/src/service/info/mod.rs | 45 +++- .../astria-sequencer/src/service/mempool.rs | 36 +++- .../astria-sequencer/src/service/snapshot.rs | 20 +- crates/astria-sequencer/src/state_ext.rs | 17 +- .../src/transaction/action_handler.rs | 5 +- .../src/transaction/checks.rs | 54 +++-- .../astria-sequencer/src/transaction/mod.rs | 25 ++- crates/astria-telemetry/src/display.rs | 19 +- crates/astria-telemetry/src/lib.rs | 35 ++- crates/astria-telemetry/src/macros.rs | 4 +- crates/astria-test-utils/src/mock/geth.rs | 24 ++- lint/tracing_debug_field/src/lib.rs | 29 ++- 185 files changed, 4368 insertions(+), 1242 deletions(-) diff --git a/crates/astria-bridge-withdrawer/src/api.rs b/crates/astria-bridge-withdrawer/src/api.rs index 47c3c00ee..25e7e786f 100644 --- a/crates/astria-bridge-withdrawer/src/api.rs +++ b/crates/astria-bridge-withdrawer/src/api.rs @@ -1,10 +1,20 @@ use std::net::SocketAddr; use axum::{ - extract::{FromRef, State}, - response::{IntoResponse, Response}, - routing::{get, IntoMakeService}, - Json, Router, + extract::{ + FromRef, + State, + }, + response::{ + IntoResponse, + Response, + }, + routing::{ + get, + IntoMakeService, + }, + Json, + Router, }; use http::status::StatusCode; use hyper::server::conn::AddrIncoming; @@ -34,7 +44,9 @@ pub(crate) fn start(socket_addr: SocketAddr, withdrawer_state: WithdrawerState) .route("/healthz", get(get_healthz)) .route("/readyz", get(get_readyz)) .route("/status", get(get_status)) - .with_state(AppState { withdrawer_state }); + .with_state(AppState { + withdrawer_state, + }); axum::Server::bind(&socket_addr).serve(app.into_make_service()) } @@ -83,7 +95,10 @@ impl IntoResponse for Healthz { Self::Ok => (StatusCode::OK, "ok"), Self::Degraded => (StatusCode::INTERNAL_SERVER_ERROR, "degraded"), }; - let mut response = Json(ReadyzBody { status: msg }).into_response(); + let mut response = Json(ReadyzBody { + status: msg, + }) + .into_response(); *response.status_mut() = status; response } @@ -104,7 +119,10 @@ impl IntoResponse for Readyz { Self::Ok => (StatusCode::OK, "ok"), Self::NotReady => (StatusCode::SERVICE_UNAVAILABLE, "not ready"), }; - let mut response = Json(ReadyzBody { status: msg }).into_response(); + let mut response = Json(ReadyzBody { + status: msg, + }) + .into_response(); *response.status_mut() = status; response } diff --git a/crates/astria-bridge-withdrawer/src/config.rs b/crates/astria-bridge-withdrawer/src/config.rs index 985d45584..4156525d0 100644 --- a/crates/astria-bridge-withdrawer/src/config.rs +++ b/crates/astria-bridge-withdrawer/src/config.rs @@ -1,4 +1,7 @@ -use serde::{Deserialize, Serialize}; +use serde::{ + Deserialize, + Serialize, +}; // Allowed `struct_excessive_bools` because this is used as a container // for deserialization. Making this a builder-pattern is not actionable. diff --git a/crates/astria-bridge-withdrawer/src/main.rs b/crates/astria-bridge-withdrawer/src/main.rs index 0daeaf62f..53ef465bd 100644 --- a/crates/astria-bridge-withdrawer/src/main.rs +++ b/crates/astria-bridge-withdrawer/src/main.rs @@ -1,9 +1,21 @@ use std::process::ExitCode; -use astria_bridge_withdrawer::{metrics_init, Config, Service, BUILD_INFO}; +use astria_bridge_withdrawer::{ + metrics_init, + Config, + Service, + BUILD_INFO, +}; use astria_eyre::eyre::WrapErr as _; -use tokio::signal::unix::{signal, SignalKind}; -use tracing::{error, info, warn}; +use tokio::signal::unix::{ + signal, + SignalKind, +}; +use tracing::{ + error, + info, + warn, +}; #[tokio::main] async fn main() -> ExitCode { diff --git a/crates/astria-bridge-withdrawer/src/metrics_init.rs b/crates/astria-bridge-withdrawer/src/metrics_init.rs index a16898317..bc9f455da 100644 --- a/crates/astria-bridge-withdrawer/src/metrics_init.rs +++ b/crates/astria-bridge-withdrawer/src/metrics_init.rs @@ -2,7 +2,12 @@ //! //! Registers metrics & lists constants to be used as metric names throughout crate. -use metrics::{describe_counter, describe_gauge, describe_histogram, Unit}; +use metrics::{ + describe_counter, + describe_gauge, + describe_histogram, + Unit, +}; use telemetry::metric_name; /// Registers all metrics used by this crate. @@ -45,8 +50,12 @@ metric_name!(pub const SEQUENCER_SUBMISSION_LATENCY); #[cfg(test)] mod tests { use super::{ - CURRENT_NONCE, NONCE_FETCH_COUNT, NONCE_FETCH_FAILURE_COUNT, NONCE_FETCH_LATENCY, - SEQUENCER_SUBMISSION_FAILURE_COUNT, SEQUENCER_SUBMISSION_LATENCY, + CURRENT_NONCE, + NONCE_FETCH_COUNT, + NONCE_FETCH_FAILURE_COUNT, + NONCE_FETCH_LATENCY, + SEQUENCER_SUBMISSION_FAILURE_COUNT, + SEQUENCER_SUBMISSION_LATENCY, }; #[track_caller] diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/convert.rs b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/convert.rs index 5808b1a64..90857f853 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/convert.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/convert.rs @@ -1,19 +1,37 @@ use std::time::Duration; use astria_core::{ - primitive::v1::{asset, asset::Denom, Address}, + primitive::v1::{ + asset, + asset::Denom, + Address, + }, protocol::transaction::v1alpha1::{ - action::{BridgeUnlockAction, Ics20Withdrawal}, + action::{ + BridgeUnlockAction, + Ics20Withdrawal, + }, Action, }, }; -use astria_eyre::eyre::{self, OptionExt, WrapErr as _}; -use ethers::types::{TxHash, U64}; +use astria_eyre::eyre::{ + self, + OptionExt, + WrapErr as _, +}; +use ethers::types::{ + TxHash, + U64, +}; use ibc_types::core::client::Height as IbcHeight; -use serde::{Deserialize, Serialize}; +use serde::{ + Deserialize, + Serialize, +}; use crate::withdrawer::ethereum::astria_withdrawer::{ - Ics20WithdrawalFilter, SequencerWithdrawalFilter, + Ics20WithdrawalFilter, + SequencerWithdrawalFilter, }; #[derive(Debug, PartialEq, Eq)] diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/test_utils.rs b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/test_utils.rs index a9b8c4777..9a91164d2 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/test_utils.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/test_utils.rs @@ -1,6 +1,14 @@ -use std::{path::Path, sync::Arc, time::Duration}; +use std::{ + path::Path, + sync::Arc, + time::Duration, +}; -use ethers::{core::utils::Anvil, prelude::*, utils::AnvilInstance}; +use ethers::{ + core::utils::Anvil, + prelude::*, + utils::AnvilInstance, +}; /// Starts a local anvil instance and deploys the `AstriaWithdrawer` contract to it. /// @@ -12,8 +20,8 @@ use ethers::{core::utils::Anvil, prelude::*, utils::AnvilInstance}; /// - if the contract cannot be compiled /// - if the provider fails to connect to the anvil instance /// - if the contract fails to deploy -pub(crate) async fn deploy_astria_withdrawer( -) -> (Address, Arc>, LocalWallet, AnvilInstance) { +pub(crate) async fn deploy_astria_withdrawer() +-> (Address, Arc>, LocalWallet, AnvilInstance) { // compile contract for testing let source = Path::new(&env!("CARGO_MANIFEST_DIR")).join("ethereum/src/AstriaWithdrawer.sol"); let input = CompilerInput::new(source.clone()) diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/watcher.rs b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/watcher.rs index cbf9af310..c6fde2360 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/watcher.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/watcher.rs @@ -1,24 +1,44 @@ use std::sync::Arc; -use astria_core::primitive::v1::{asset, asset::Denom}; +use astria_core::primitive::v1::{ + asset, + asset::Denom, +}; use astria_eyre::{ - eyre::{eyre, WrapErr as _}, + eyre::{ + eyre, + WrapErr as _, + }, Result, }; use ethers::{ contract::LogMeta, - providers::{Provider, StreamExt as _, Ws}, + providers::{ + Provider, + StreamExt as _, + Ws, + }, utils::hex, }; -use tokio::{select, sync::mpsc}; +use tokio::{ + select, + sync::mpsc, +}; use tokio_util::sync::CancellationToken; -use tracing::{info, warn}; +use tracing::{ + info, + warn, +}; use crate::withdrawer::{ batch::Batch, ethereum::{ astria_withdrawer::AstriaWithdrawer, - convert::{event_to_action, EventWithMetadata, WithdrawalEvent}, + convert::{ + event_to_action, + EventWithMetadata, + WithdrawalEvent, + }, }, state::State, }; @@ -289,13 +309,19 @@ mod tests { prelude::SignerMiddleware, providers::Middleware, signers::Signer as _, - types::{TransactionReceipt, U256}, + types::{ + TransactionReceipt, + U256, + }, utils::hex, }; use super::*; use crate::withdrawer::ethereum::{ - astria_withdrawer::{Ics20WithdrawalFilter, SequencerWithdrawalFilter}, + astria_withdrawer::{ + Ics20WithdrawalFilter, + SequencerWithdrawalFilter, + }, convert::EventWithMetadata, test_utils::deploy_astria_withdrawer, }; diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/mod.rs b/crates/astria-bridge-withdrawer/src/withdrawer/mod.rs index 3508aad3c..5c54075b7 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/mod.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/mod.rs @@ -1,19 +1,39 @@ -use std::{net::SocketAddr, sync::Arc, time::Duration}; +use std::{ + net::SocketAddr, + sync::Arc, + time::Duration, +}; use astria_core::primitive::v1::asset; -use astria_eyre::eyre::{self, WrapErr as _}; +use astria_eyre::eyre::{ + self, + WrapErr as _, +}; use tokio::{ select, sync::oneshot, - task::{JoinError, JoinHandle}, + task::{ + JoinError, + JoinHandle, + }, time::timeout, }; use tokio_util::sync::CancellationToken; -use tracing::{error, info}; +use tracing::{ + error, + info, +}; pub(crate) use self::state::StateSnapshot; -use self::{ethereum::Watcher, state::State, submitter::Submitter}; -use crate::{api, config::Config}; +use self::{ + ethereum::Watcher, + state::State, + submitter::Submitter, +}; +use crate::{ + api, + config::Config, +}; mod batch; mod ethereum; diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/state.rs b/crates/astria-bridge-withdrawer/src/withdrawer/state.rs index 1d8fdb406..647bb489b 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/state.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/state.rs @@ -7,7 +7,9 @@ pub(crate) struct State { impl State { pub(super) fn new() -> Self { let (inner, _) = watch::channel(StateSnapshot::default()); - Self { inner } + Self { + inner, + } } pub(super) fn set_watcher_ready(&self) { diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/submitter/builder.rs b/crates/astria-bridge-withdrawer/src/withdrawer/submitter/builder.rs index 253587f09..d58d7f0a4 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/submitter/builder.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/submitter/builder.rs @@ -1,6 +1,9 @@ use std::sync::Arc; -use astria_eyre::eyre::{self, Context as _}; +use astria_eyre::eyre::{ + self, + Context as _, +}; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; use tracing::info; diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/submitter/mod.rs b/crates/astria-bridge-withdrawer/src/withdrawer/submitter/mod.rs index fe8d0d362..add064182 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/submitter/mod.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/submitter/mod.rs @@ -1,21 +1,50 @@ -use std::{sync::Arc, time::Duration}; +use std::{ + sync::Arc, + time::Duration, +}; use astria_core::protocol::transaction::v1alpha1::{ - Action, TransactionParams, UnsignedTransaction, + Action, + TransactionParams, + UnsignedTransaction, +}; +use astria_eyre::eyre::{ + self, + ensure, + eyre, + Context, }; -use astria_eyre::eyre::{self, ensure, eyre, Context}; pub(crate) use builder::Builder; use sequencer_client::{ - tendermint_rpc, tendermint_rpc::endpoint::broadcast::tx_commit, Address, - SequencerClientExt as _, SignedTransaction, + tendermint_rpc, + tendermint_rpc::endpoint::broadcast::tx_commit, + Address, + SequencerClientExt as _, + SignedTransaction, }; use signer::SequencerKey; use state::State; -use tokio::{select, sync::mpsc, time::Instant}; +use tokio::{ + select, + sync::mpsc, + time::Instant, +}; use tokio_util::sync::CancellationToken; -use tracing::{debug, error, info, info_span, instrument, warn, Instrument as _, Span}; +use tracing::{ + debug, + error, + info, + info_span, + instrument, + warn, + Instrument as _, + Span, +}; -use super::{batch::Batch, state}; +use super::{ + batch::Batch, + state, +}; mod builder; mod signer; diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/submitter/signer.rs b/crates/astria-bridge-withdrawer/src/withdrawer/submitter/signer.rs index a138fba3f..853d08ff9 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/submitter/signer.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/submitter/signer.rs @@ -1,7 +1,13 @@ -use std::{fs, path::Path}; +use std::{ + fs, + path::Path, +}; use astria_core::crypto::SigningKey; -use astria_eyre::eyre::{self, eyre}; +use astria_eyre::eyre::{ + self, + eyre, +}; use sequencer_client::Address; pub(super) struct SequencerKey { diff --git a/crates/astria-cli/src/cli/mod.rs b/crates/astria-cli/src/cli/mod.rs index 8c335fc65..f2c2b2d22 100644 --- a/crates/astria-cli/src/cli/mod.rs +++ b/crates/astria-cli/src/cli/mod.rs @@ -1,10 +1,16 @@ pub(crate) mod rollup; pub(crate) mod sequencer; -use clap::{Parser, Subcommand}; +use clap::{ + Parser, + Subcommand, +}; use color_eyre::eyre; -use crate::cli::{rollup::Command as RollupCommand, sequencer::Command as SequencerCommand}; +use crate::cli::{ + rollup::Command as RollupCommand, + sequencer::Command as SequencerCommand, +}; const DEFAULT_SEQUENCER_RPC: &str = "https://rpc.sequencer.dusk-7.devnet.astria.org"; const DEFAULT_SEQUENCER_CHAIN_ID: &str = "astria-dusk-7"; diff --git a/crates/astria-cli/src/cli/rollup.rs b/crates/astria-cli/src/cli/rollup.rs index 5338182e7..3199397e1 100644 --- a/crates/astria-cli/src/cli/rollup.rs +++ b/crates/astria-cli/src/cli/rollup.rs @@ -1,6 +1,9 @@ use std::str::FromStr; -use clap::{Args, Subcommand}; +use clap::{ + Args, + Subcommand, +}; use color_eyre::eyre; use serde::Serialize; @@ -190,7 +193,10 @@ impl FromStr for GenesisAccountArg { .parse::() .map_err(|e| eyre::eyre!("Invalid balance. Could not parse to u128: {}", e))?; - Ok(GenesisAccountArg { address, balance }) + Ok(GenesisAccountArg { + address, + balance, + }) } } diff --git a/crates/astria-cli/src/cli/sequencer.rs b/crates/astria-cli/src/cli/sequencer.rs index fb7d3da67..cca710530 100644 --- a/crates/astria-cli/src/cli/sequencer.rs +++ b/crates/astria-cli/src/cli/sequencer.rs @@ -1,8 +1,14 @@ use std::str::FromStr; use astria_sequencer_client::Address; -use clap::{Args, Subcommand}; -use color_eyre::{eyre, eyre::Context}; +use clap::{ + Args, + Subcommand, +}; +use color_eyre::{ + eyre, + eyre::Context, +}; /// Interact with a Sequencer node #[derive(Debug, Subcommand)] diff --git a/crates/astria-cli/src/commands/mod.rs b/crates/astria-cli/src/commands/mod.rs index 319815afe..cf7930c60 100644 --- a/crates/astria-cli/src/commands/mod.rs +++ b/crates/astria-cli/src/commands/mod.rs @@ -1,16 +1,29 @@ mod rollup; mod sequencer; -use color_eyre::{eyre, eyre::eyre}; +use color_eyre::{ + eyre, + eyre::eyre, +}; use tracing::instrument; use crate::cli::{ - rollup::{Command as RollupCommand, ConfigCommand, DeploymentCommand}, + rollup::{ + Command as RollupCommand, + ConfigCommand, + DeploymentCommand, + }, sequencer::{ - AccountCommand, BalanceCommand, BlockHeightCommand, Command as SequencerCommand, - FeeAssetChangeCommand, IbcRelayerChangeCommand, SudoCommand, + AccountCommand, + BalanceCommand, + BlockHeightCommand, + Command as SequencerCommand, + FeeAssetChangeCommand, + IbcRelayerChangeCommand, + SudoCommand, }, - Cli, Command, + Cli, + Command, }; /// Checks what function needs to be run and calls it with the appropriate arguments @@ -30,29 +43,45 @@ use crate::cli::{ pub async fn run(cli: Cli) -> eyre::Result<()> { if let Some(command) = cli.command { match command { - Command::Rollup { command } => match command { - RollupCommand::Config { command } => match command { + Command::Rollup { + command, + } => match command { + RollupCommand::Config { + command, + } => match command { ConfigCommand::Create(args) => rollup::create_config(&args).await?, ConfigCommand::Edit(args) => rollup::edit_config(&args)?, ConfigCommand::Delete(args) => rollup::delete_config(&args)?, }, - RollupCommand::Deployment { command } => match command { + RollupCommand::Deployment { + command, + } => match command { DeploymentCommand::Create(args) => rollup::create_deployment(&args)?, DeploymentCommand::Delete(args) => rollup::delete_deployment(&args)?, DeploymentCommand::List => rollup::list_deployments(), }, }, - Command::Sequencer { command } => match command { - SequencerCommand::Account { command } => match command { + Command::Sequencer { + command, + } => match command { + SequencerCommand::Account { + command, + } => match command { AccountCommand::Create => sequencer::create_account(), AccountCommand::Balance(args) => sequencer::get_balance(&args).await?, AccountCommand::Nonce(args) => sequencer::get_nonce(&args).await?, }, - SequencerCommand::Balance { command } => match command { + SequencerCommand::Balance { + command, + } => match command { BalanceCommand::Get(args) => sequencer::get_balance(&args).await?, }, - SequencerCommand::Sudo { command } => match command { - SudoCommand::IbcRelayer { command } => match command { + SequencerCommand::Sudo { + command, + } => match command { + SudoCommand::IbcRelayer { + command, + } => match command { IbcRelayerChangeCommand::Add(args) => { sequencer::ibc_relayer_add(&args).await?; } @@ -60,7 +89,9 @@ pub async fn run(cli: Cli) -> eyre::Result<()> { sequencer::ibc_relayer_remove(&args).await?; } }, - SudoCommand::FeeAsset { command } => match command { + SudoCommand::FeeAsset { + command, + } => match command { FeeAssetChangeCommand::Add(args) => sequencer::fee_asset_add(&args).await?, FeeAssetChangeCommand::Remove(args) => { sequencer::fee_asset_remove(&args).await?; @@ -74,7 +105,9 @@ pub async fn run(cli: Cli) -> eyre::Result<()> { } }, SequencerCommand::Transfer(args) => sequencer::send_transfer(&args).await?, - SequencerCommand::BlockHeight { command } => match command { + SequencerCommand::BlockHeight { + command, + } => match command { BlockHeightCommand::Get(args) => sequencer::get_block_height(&args).await?, }, SequencerCommand::InitBridgeAccount(args) => { diff --git a/crates/astria-cli/src/commands/rollup.rs b/crates/astria-cli/src/commands/rollup.rs index 050b97449..b94771226 100644 --- a/crates/astria-cli/src/commands/rollup.rs +++ b/crates/astria-cli/src/commands/rollup.rs @@ -1,17 +1,32 @@ use std::{ - env::{self, consts::OS}, + env::{ + self, + consts::OS, + }, fs::File, - io::{Read, Write}, + io::{ + Read, + Write, + }, path::PathBuf, process::Command, }; -use astria_sequencer_client::{Client, HttpClient}; -use color_eyre::{eyre, eyre::Context}; +use astria_sequencer_client::{ + Client, + HttpClient, +}; +use color_eyre::{ + eyre, + eyre::Context, +}; use crate::{ cli::rollup::{ - ConfigCreateArgs, ConfigDeleteArgs, ConfigEditArgs, DeploymentCreateArgs, + ConfigCreateArgs, + ConfigDeleteArgs, + ConfigEditArgs, + DeploymentCreateArgs, DeploymentDeleteArgs, }, types::Rollup, diff --git a/crates/astria-cli/src/commands/sequencer.rs b/crates/astria-cli/src/commands/sequencer.rs index 20a1a4e27..9b9460c08 100644 --- a/crates/astria-cli/src/commands/sequencer.rs +++ b/crates/astria-cli/src/commands/sequencer.rs @@ -3,24 +3,45 @@ use astria_core::{ primitive::v1::asset, protocol::transaction::v1alpha1::{ action::{ - Action, BridgeLockAction, FeeAssetChangeAction, IbcRelayerChangeAction, - InitBridgeAccountAction, SudoAddressChangeAction, TransferAction, + Action, + BridgeLockAction, + FeeAssetChangeAction, + IbcRelayerChangeAction, + InitBridgeAccountAction, + SudoAddressChangeAction, + TransferAction, }, - TransactionParams, UnsignedTransaction, + TransactionParams, + UnsignedTransaction, }, }; use astria_sequencer_client::{ - tendermint, tendermint_rpc::endpoint, Client, HttpClient, SequencerClientExt, + tendermint, + tendermint_rpc::endpoint, + Client, + HttpClient, + SequencerClientExt, }; use color_eyre::{ eyre, - eyre::{ensure, eyre, Context}, + eyre::{ + ensure, + eyre, + Context, + }, }; use rand::rngs::OsRng; use crate::cli::sequencer::{ - BasicAccountArgs, BlockHeightGetArgs, BridgeLockArgs, FeeAssetChangeArgs, IbcRelayerChangeArgs, - InitBridgeAccountArgs, SudoAddressChangeArgs, TransferArgs, ValidatorUpdateArgs, + BasicAccountArgs, + BlockHeightGetArgs, + BridgeLockArgs, + FeeAssetChangeArgs, + IbcRelayerChangeArgs, + InitBridgeAccountArgs, + SudoAddressChangeArgs, + TransferArgs, + ValidatorUpdateArgs, }; /// Generate a new signing key (this is also called a secret key by other implementations) @@ -234,7 +255,10 @@ pub(crate) async fn ibc_relayer_remove(args: &IbcRelayerChangeArgs) -> eyre::Res /// * If the http client cannot be created /// * If the transaction failed to be included pub(crate) async fn init_bridge_account(args: &InitBridgeAccountArgs) -> eyre::Result<()> { - use astria_core::primitive::v1::{asset::default_native_asset_id, RollupId}; + use astria_core::primitive::v1::{ + asset::default_native_asset_id, + RollupId, + }; let rollup_id = RollupId::from_unhashed_bytes(args.rollup_name.as_bytes()); let res = submit_transaction( diff --git a/crates/astria-cli/src/main.rs b/crates/astria-cli/src/main.rs index 9ffa5f64e..81c257e2a 100644 --- a/crates/astria-cli/src/main.rs +++ b/crates/astria-cli/src/main.rs @@ -1,7 +1,13 @@ use std::process::ExitCode; -use astria_cli::{cli::Cli, commands}; -use color_eyre::{eyre, eyre::Context}; +use astria_cli::{ + cli::Cli, + commands, +}; +use color_eyre::{ + eyre, + eyre::Context, +}; fn main() -> ExitCode { if let Err(err) = run() { diff --git a/crates/astria-cli/src/types.rs b/crates/astria-cli/src/types.rs index f41b6ae11..773281f3c 100644 --- a/crates/astria-cli/src/types.rs +++ b/crates/astria-cli/src/types.rs @@ -1,7 +1,13 @@ use color_eyre::eyre; -use serde::{Deserialize, Serialize}; +use serde::{ + Deserialize, + Serialize, +}; -use crate::cli::rollup::{ConfigCreateArgs, GenesisAccountArg}; +use crate::cli::rollup::{ + ConfigCreateArgs, + GenesisAccountArg, +}; /// Rollup contains the deployment config for a rollup #[derive(Debug, PartialEq, Serialize, Deserialize)] @@ -327,7 +333,10 @@ impl Resource { #[cfg(test)] mod tests { use super::*; - use crate::cli::rollup::{ConfigCreateArgs, GenesisAccountArg}; + use crate::cli::rollup::{ + ConfigCreateArgs, + GenesisAccountArg, + }; #[test] fn test_from_all_cli_args() -> eyre::Result<()> { diff --git a/crates/astria-cli/test-utils/src/lib.rs b/crates/astria-cli/test-utils/src/lib.rs index 0317545f7..a049c22b2 100644 --- a/crates/astria-cli/test-utils/src/lib.rs +++ b/crates/astria-cli/test-utils/src/lib.rs @@ -1,4 +1,7 @@ -use std::{env, future::Future}; +use std::{ + env, + future::Future, +}; use once_cell::sync::Lazy; use tempfile::TempDir; diff --git a/crates/astria-composer/src/api.rs b/crates/astria-composer/src/api.rs index d638ec641..9866fd5e3 100644 --- a/crates/astria-composer/src/api.rs +++ b/crates/astria-composer/src/api.rs @@ -1,9 +1,18 @@ use std::net::SocketAddr; use axum::{ - extract::{FromRef, State}, - response::{IntoResponse, Response}, - routing::{get, IntoMakeService}, + extract::{ + FromRef, + State, + }, + response::{ + IntoResponse, + Response, + }, + routing::{ + get, + IntoMakeService, + }, Router, }; use hyper::server::conn::AddrIncoming; @@ -32,7 +41,9 @@ impl FromRef for ComposerStatus { pub(super) fn start(listen_addr: SocketAddr, composer_status: ComposerStatus) -> ApiServer { let app = Router::new() .route("/readyz", get(readyz)) - .with_state(AppState { composer_status }); + .with_state(AppState { + composer_status, + }); axum::Server::bind(&listen_addr).serve(app.into_make_service()) } @@ -51,7 +62,10 @@ impl IntoResponse for Readyz { Self::Ok => (axum::http::StatusCode::OK, "ok"), Self::NotReady => (axum::http::StatusCode::SERVICE_UNAVAILABLE, "not ready"), }; - let mut response = axum::Json(ReadyBody { status: msg }).into_response(); + let mut response = axum::Json(ReadyBody { + status: msg, + }) + .into_response(); *response.status_mut() = status; response } diff --git a/crates/astria-composer/src/collectors/geth.rs b/crates/astria-composer/src/collectors/geth.rs index 552146bc4..753da8ce4 100644 --- a/crates/astria-composer/src/collectors/geth.rs +++ b/crates/astria-composer/src/collectors/geth.rs @@ -16,22 +16,49 @@ use std::time::Duration; use astria_core::{ - primitive::v1::{asset::default_native_asset_id, RollupId}, + primitive::v1::{ + asset::default_native_asset_id, + RollupId, + }, protocol::transaction::v1alpha1::action::SequenceAction, }; -use astria_eyre::eyre::{self, eyre, Report, WrapErr as _}; -use ethers::providers::{Provider, ProviderError, Ws}; +use astria_eyre::eyre::{ + self, + eyre, + Report, + WrapErr as _, +}; +use ethers::providers::{ + Provider, + ProviderError, + Ws, +}; use tokio::{ select, - sync::{mpsc::error::SendTimeoutError, watch}, + sync::{ + mpsc::error::SendTimeoutError, + watch, + }, }; use tokio_util::sync::CancellationToken; -use tracing::{debug, error, info, instrument, warn}; +use tracing::{ + debug, + error, + info, + instrument, + warn, +}; use crate::{ - collectors::{EXECUTOR_SEND_TIMEOUT, GETH}, + collectors::{ + EXECUTOR_SEND_TIMEOUT, + GETH, + }, executor, - metrics_init::{COLLECTOR_TYPE_LABEL, ROLLUP_ID_LABEL}, + metrics_init::{ + COLLECTOR_TYPE_LABEL, + ROLLUP_ID_LABEL, + }, }; type StdError = dyn std::error::Error; diff --git a/crates/astria-composer/src/collectors/grpc.rs b/crates/astria-composer/src/collectors/grpc.rs index 7c78b6f6d..49e37fc22 100644 --- a/crates/astria-composer/src/collectors/grpc.rs +++ b/crates/astria-composer/src/collectors/grpc.rs @@ -4,19 +4,33 @@ use std::sync::Arc; use astria_core::{ generated::composer::v1alpha1::{ - grpc_collector_service_server::GrpcCollectorService, SubmitRollupTransactionRequest, + grpc_collector_service_server::GrpcCollectorService, + SubmitRollupTransactionRequest, SubmitRollupTransactionResponse, }, - primitive::v1::{asset::default_native_asset_id, RollupId}, + primitive::v1::{ + asset::default_native_asset_id, + RollupId, + }, protocol::transaction::v1alpha1::action::SequenceAction, }; use tokio::sync::mpsc::error::SendTimeoutError; -use tonic::{Request, Response, Status}; +use tonic::{ + Request, + Response, + Status, +}; use crate::{ - collectors::{EXECUTOR_SEND_TIMEOUT, GRPC}, + collectors::{ + EXECUTOR_SEND_TIMEOUT, + GRPC, + }, executor, - metrics_init::{COLLECTOR_TYPE_LABEL, ROLLUP_ID_LABEL}, + metrics_init::{ + COLLECTOR_TYPE_LABEL, + ROLLUP_ID_LABEL, + }, }; /// Implements the `GrpcCollectorService` which listens for incoming gRPC requests and @@ -28,7 +42,9 @@ pub(crate) struct Grpc { impl Grpc { pub(crate) fn new(executor: executor::Handle) -> Self { - Self { executor } + Self { + executor, + } } } diff --git a/crates/astria-composer/src/composer.rs b/crates/astria-composer/src/composer.rs index e2bae92ab..bf7f46d9f 100644 --- a/crates/astria-composer/src/composer.rs +++ b/crates/astria-composer/src/composer.rs @@ -1,22 +1,46 @@ -use std::{collections::HashMap, net::SocketAddr, time::Duration}; +use std::{ + collections::HashMap, + net::SocketAddr, + time::Duration, +}; -use astria_eyre::eyre::{self, WrapErr as _}; +use astria_eyre::eyre::{ + self, + WrapErr as _, +}; use itertools::Itertools as _; use tokio::{ io, - signal::unix::{signal, SignalKind}, + signal::unix::{ + signal, + SignalKind, + }, sync::watch, - task::{JoinError, JoinHandle}, + task::{ + JoinError, + JoinHandle, + }, time::timeout, }; -use tokio_util::{sync::CancellationToken, task::JoinMap}; -use tracing::{error, info, warn}; +use tokio_util::{ + sync::CancellationToken, + task::JoinMap, +}; +use tracing::{ + error, + info, + warn, +}; use crate::{ - api::{self, ApiServer}, + api::{ + self, + ApiServer, + }, collectors, collectors::geth, - composer, executor, + composer, + executor, executor::Executor, grpc, grpc::GrpcServer, @@ -439,7 +463,10 @@ async fn wait_for_collectors( ) -> eyre::Result<()> { use futures::{ future::FutureExt as _, - stream::{FuturesUnordered, StreamExt as _}, + stream::{ + FuturesUnordered, + StreamExt as _, + }, }; let mut statuses = collector_statuses .iter() diff --git a/crates/astria-composer/src/config.rs b/crates/astria-composer/src/config.rs index 0fd2a6aa7..0dbc55bb8 100644 --- a/crates/astria-composer/src/config.rs +++ b/crates/astria-composer/src/config.rs @@ -1,6 +1,9 @@ use std::net::SocketAddr; -use serde::{Deserialize, Serialize}; +use serde::{ + Deserialize, + Serialize, +}; // this is a config, may have many boolean values #[allow(clippy::struct_excessive_bools)] diff --git a/crates/astria-composer/src/executor/builder.rs b/crates/astria-composer/src/executor/builder.rs index 0969e8aff..3712a01af 100644 --- a/crates/astria-composer/src/executor/builder.rs +++ b/crates/astria-composer/src/executor/builder.rs @@ -12,7 +12,7 @@ use astria_eyre::eyre::{ self, ensure, eyre, - Context + Context, }; use sequencer_client::tendermint_rpc::Client; use tokio::sync::watch; @@ -46,8 +46,11 @@ impl Builder { } = self; let sequencer_client = sequencer_client::HttpClient::new(sequencer_url.as_str()) .wrap_err("failed constructing sequencer client")?; - - let client_response = sequencer_client.status().await.wrap_err("failed to retrieve sequencer network status")?; + + let client_response = sequencer_client + .status() + .await + .wrap_err("failed to retrieve sequencer network status")?; let client_chain_id = client_response.node_info.network.to_string(); ensure!( sequencer_chain_id == client_chain_id, @@ -89,4 +92,4 @@ fn read_signing_key_from_file>(path: P) -> eyre::Result match ready!(fut.poll(cx)) { + SubmitStateProj::WaitingForSend { + fut, + } => match ready!(fut.poll(cx)) { Ok(rsp) => { let tendermint::abci::Code::Err(code) = rsp.code else { info!("sequencer responded with ok; submission successful"); @@ -608,7 +648,9 @@ impl Future for SubmitFut { } }, - SubmitStateProj::WaitingForNonce { fut } => match ready!(fut.poll(cx)) { + SubmitStateProj::WaitingForNonce { + fut, + } => match ready!(fut.poll(cx)) { Ok(nonce) => { *this.nonce = nonce; let params = TransactionParams { diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index 934b0c34f..8d191bbc3 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -1,7 +1,16 @@ -use std::{io::Write, time::Duration}; +use std::{ + io::Write, + time::Duration, +}; use astria_core::{ - primitive::v1::{asset::default_native_asset_id, RollupId, FEE_ASSET_ID_LEN, ROLLUP_ID_LEN}, + generated::protocol::account::v1alpha1::NonceResponse, + primitive::v1::{ + asset::default_native_asset_id, + RollupId, + FEE_ASSET_ID_LEN, + ROLLUP_ID_LEN, + }, protocol::transaction::v1alpha1::action::SequenceAction, }; use astria_eyre::eyre; @@ -10,16 +19,74 @@ use prost::Message; use sequencer_client::SignedTransaction; use serde_json::json; use tempfile::NamedTempFile; -use tendermint_rpc::{endpoint::broadcast::tx_sync, request, response, Id}; -use tokio::{sync::watch, time}; +use tendermint_rpc::{ + endpoint::broadcast::tx_sync, + request, + response, + Id, +}; +use tokio::{ + sync::watch, + time, +}; use tokio_util::sync::CancellationToken; use tracing::debug; use wiremock::{ - matchers::{body_partial_json, body_string_contains}, - Mock, MockGuard, MockServer, Request, ResponseTemplate, + matchers::{ + body_partial_json, + body_string_contains, + }, + Mock, + MockGuard, + MockServer, + Request, + ResponseTemplate, }; -use crate::{executor, Config}; +use crate::{ + executor, + Config, +}; + +const STATUS_RESPONSE: &str = r#" +{ + "node_info": { + "protocol_version": { + "p2p": "8", + "block": "11", + "app": "0" + }, + "id": "a1d3bbddb7800c6da2e64169fec281494e963ba3", + "listen_addr": "tcp://0.0.0.0:26656", + "network": "test", + "version": "0.38.6", + "channels": "40202122233038606100", + "moniker": "fullnode", + "other": { + "tx_index": "on", + "rpc_address": "tcp://0.0.0.0:26657" + } + }, + "sync_info": { + "latest_block_hash": "A4202E4E367712AC2A797860265A7EBEA8A3ACE513CB0105C2C9058449641202", + "latest_app_hash": "BCC9C9B82A49EC37AADA41D32B4FBECD2441563703955413195BDA2236775A68", + "latest_block_height": "452605", + "latest_block_time": "2024-05-09T15:59:17.849713071Z", + "earliest_block_hash": "C34B7B0B82423554B844F444044D7D08A026D6E413E6F72848DB2F8C77ACE165", + "earliest_app_hash": "6B776065775471CEF46AC75DE09A4B869A0E0EB1D7725A04A342C0E46C16F472", + "earliest_block_height": "1", + "earliest_block_time": "2024-04-23T00:49:11.964127Z", + "catching_up": false + }, + "validator_info": { + "address": "0B46F33BA2FA5C2E2AD4C4C4E5ECE3F1CA03D195", + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "bA6GipHUijVuiYhv+4XymdePBsn8EeTqjGqNQrBGZ4I=" + }, + "voting_power": "0" + } +}"#; static TELEMETRY: Lazy<()> = Lazy::new(|| { if std::env::var_os("TEST_LOG").is_some() { @@ -40,19 +107,9 @@ static TELEMETRY: Lazy<()> = Lazy::new(|| { }); /// Start a mock sequencer server and mount a mock for the `accounts/nonce` query. -async fn setup() -> (MockServer, MockGuard, Config, NamedTempFile) { - use astria_core::generated::protocol::account::v1alpha1::NonceResponse; +async fn setup() -> (MockServer, Config, NamedTempFile) { Lazy::force(&TELEMETRY); let server = MockServer::start().await; - let startup_guard = mount_nonce_query_mock( - &server, - "accounts/nonce", - NonceResponse { - height: 0, - nonce: 0, - }, - ) - .await; let keyfile = NamedTempFile::new().unwrap(); (&keyfile) @@ -76,7 +133,7 @@ async fn setup() -> (MockServer, MockGuard, Config, NamedTempFile) { pretty_print: true, grpc_addr: "127.0.0.1:0".parse().unwrap(), }; - (server, startup_guard, cfg, keyfile) + (server, cfg, keyfile) } /// Mount a mock for the `abci_query` endpoint. @@ -155,29 +212,21 @@ async fn mount_broadcast_tx_sync_seq_actions_mock(server: &MockServer) -> MockGu .await } -async fn mount_status_mock(server: &MockServer) -> MockGuard { - let matcher = move |request: &Request| { - let signed_tx = signed_tx_from_request(request); - let actions = signed_tx.actions(); +/// Mounts a `CometBFT` status response with a specified mock sequencer chain id +async fn mount_cometbft_status_response(server: &MockServer,mock_sequencer_chain_id: &str,) -> MockGuard { + use tendermint_rpc::endpoint::status; - // verify all received actions are sequence actions - actions.iter().all(|action| action.as_sequence().is_some()) - }; - let jsonrpc_rsp = response::Wrapper::new_with_id( - Id::Num(1), - Some(tx_sync::Response { - code: 0.into(), - data: vec![].into(), - log: String::new(), - hash: tendermint::Hash::Sha256([0; 32]), - }), - None, - ); + let mut status_response: status::Response = serde_json::from_str(STATUS_RESPONSE).unwrap(); + status_response.node_info.network = mock_sequencer_chain_id.to_string().parse().unwrap(); - Mock::given(matcher) - .respond_with(ResponseTemplate::new(200).set_body_json(&jsonrpc_rsp)) + let response = + tendermint_rpc::response::Wrapper::new_with_id(Id::Num(1), Some(status_response), None); + + Mock::given(body_partial_json(json!({"method": "status"}))) + .respond_with(ResponseTemplate::new(200).set_body_json(response)) .up_to_n_times(1) - .expect(1) + .expect(1..) + .named("CometBFT status") .mount_as_scoped(server) .await } @@ -202,16 +251,18 @@ async fn wait_for_startup( Ok(()) } + /// Test to check that the executor sends a signed transaction to the sequencer as soon as it /// receives a `SequenceAction` that fills it beyond its `max_bundle_size`. #[tokio::test] async fn full_bundle() { // set up the executor, channel for writing seq actions, and the sequencer mock - let (sequencer, nonce_guard, cfg, _keyfile) = setup().await; + let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); + let _status_guard = mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), - sequencer_chain_id: "bad-id".to_string(), + sequencer_chain_id: cfg.sequencer_chain_id.clone(), private_key_file: cfg.private_key_file.clone(), block_time_ms: cfg.block_time_ms, max_bytes_per_bundle: cfg.max_bytes_per_bundle, @@ -222,6 +273,15 @@ async fn full_bundle() { .await .unwrap(); + let nonce_guard = mount_nonce_query_mock( + &sequencer, + "accounts/nonce", + NonceResponse { + height: 0, + nonce: 0, + }, + ) + .await; let status = executor.subscribe(); let _executor_task = tokio::spawn(executor.run_until_stopped()); @@ -299,8 +359,9 @@ async fn full_bundle() { #[tokio::test] async fn bundle_triggered_by_block_timer() { // set up the executor, channel for writing seq actions, and the sequencer mock - let (sequencer, nonce_guard, cfg, _keyfile) = setup().await; + let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); + let _status_guard = mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -314,6 +375,15 @@ async fn bundle_triggered_by_block_timer() { .await .unwrap(); + let nonce_guard = mount_nonce_query_mock( + &sequencer, + "accounts/nonce", + NonceResponse { + height: 0, + nonce: 0, + }, + ) + .await; let status = executor.subscribe(); let _executor_task = tokio::spawn(executor.run_until_stopped()); @@ -384,8 +454,9 @@ async fn bundle_triggered_by_block_timer() { #[tokio::test] async fn two_seq_actions_single_bundle() { // set up the executor, channel for writing seq actions, and the sequencer mock - let (sequencer, nonce_guard, cfg, _keyfile) = setup().await; + let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); + let _status_guard = mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -399,6 +470,15 @@ async fn two_seq_actions_single_bundle() { .await .unwrap(); + let nonce_guard = mount_nonce_query_mock( + &sequencer, + "accounts/nonce", + NonceResponse { + height: 0, + nonce: 0, + }, + ) + .await; let status = executor.subscribe(); let _executor_task = tokio::spawn(executor.run_until_stopped()); @@ -474,19 +554,23 @@ async fn two_seq_actions_single_bundle() { } } -// #[tokio::test] -// async fn should_exit_if_mismatch_sequencer_chain_id() { -// let (sequencer, nonce_guard, cfg, _keyfile) = setup().await; -// let shutdown_token = CancellationToken::new(); -// let (executor, executor_handle) = executor::Builder { -// sequencer_url: cfg.sequencer_url.clone(), -// sequencer_chain_id: "bad-id".to_string(), -// private_key_file: cfg.private_key_file.clone(), -// block_time_ms: cfg.block_time_ms, -// max_bytes_per_bundle: cfg.max_bytes_per_bundle, -// bundle_queue_capacity: cfg.bundle_queue_capacity, -// shutdown_token: shutdown_token.clone(), -// } -// .build() -// .unwrap(); -// } +#[tokio::test] +async fn should_exit_if_mismatch_sequencer_chain_id() { + // set up the executor, channel for writing seq actions, and the sequencer mock + let (sequencer, cfg, _keyfile) = setup().await; + let shutdown_token = CancellationToken::new(); + let _status_guard = mount_cometbft_status_response(&sequencer, "different-chain-id").await; + let build_result = executor::Builder { + sequencer_url: cfg.sequencer_url.clone(), + sequencer_chain_id: cfg.sequencer_chain_id.clone(), + private_key_file: cfg.private_key_file.clone(), + block_time_ms: cfg.block_time_ms, + max_bytes_per_bundle: cfg.max_bytes_per_bundle, + bundle_queue_capacity: cfg.bundle_queue_capacity, + shutdown_token: shutdown_token.clone(), + } + .build() + .await; + + assert!(build_result.is_err()); +} diff --git a/crates/astria-composer/src/grpc.rs b/crates/astria-composer/src/grpc.rs index 72a07747d..9f504ab72 100644 --- a/crates/astria-composer/src/grpc.rs +++ b/crates/astria-composer/src/grpc.rs @@ -9,11 +9,20 @@ use std::net::SocketAddr; use astria_core::generated::composer::v1alpha1::grpc_collector_service_server::GrpcCollectorServiceServer; -use astria_eyre::{eyre, eyre::WrapErr as _}; -use tokio::{io, net::TcpListener}; +use astria_eyre::{ + eyre, + eyre::WrapErr as _, +}; +use tokio::{ + io, + net::TcpListener, +}; use tokio_util::sync::CancellationToken; -use crate::{collectors, executor}; +use crate::{ + collectors, + executor, +}; /// Listens for incoming gRPC requests and sends the Rollup transactions to the /// Executor. The Executor then sends the transactions to the Astria Shared Sequencer. diff --git a/crates/astria-composer/src/main.rs b/crates/astria-composer/src/main.rs index af8324d8f..38f9f21d7 100644 --- a/crates/astria-composer/src/main.rs +++ b/crates/astria-composer/src/main.rs @@ -1,8 +1,16 @@ use std::process::ExitCode; -use astria_composer::{metrics_init, Composer, Config, BUILD_INFO}; +use astria_composer::{ + metrics_init, + Composer, + Config, + BUILD_INFO, +}; use astria_eyre::eyre::WrapErr as _; -use tracing::{error, info}; +use tracing::{ + error, + info, +}; #[tokio::main] async fn main() -> ExitCode { diff --git a/crates/astria-composer/src/metrics_init.rs b/crates/astria-composer/src/metrics_init.rs index dd4720152..a71028b72 100644 --- a/crates/astria-composer/src/metrics_init.rs +++ b/crates/astria-composer/src/metrics_init.rs @@ -2,7 +2,12 @@ //! //! Registers metrics & lists constants to be used as metric names throughout crate. -use metrics::{describe_counter, describe_gauge, describe_histogram, Unit}; +use metrics::{ + describe_counter, + describe_gauge, + describe_histogram, + Unit, +}; use telemetry::metric_name; /// Labels @@ -84,9 +89,16 @@ metric_name!(pub const BYTES_PER_SUBMISSION); #[cfg(test)] mod tests { use super::{ - BYTES_PER_SUBMISSION, CURRENT_NONCE, NONCE_FETCH_COUNT, NONCE_FETCH_FAILURE_COUNT, - NONCE_FETCH_LATENCY, SEQUENCER_SUBMISSION_FAILURE_COUNT, SEQUENCER_SUBMISSION_LATENCY, - TRANSACTIONS_DROPPED, TRANSACTIONS_DROPPED_TOO_LARGE, TRANSACTIONS_PER_SUBMISSION, + BYTES_PER_SUBMISSION, + CURRENT_NONCE, + NONCE_FETCH_COUNT, + NONCE_FETCH_FAILURE_COUNT, + NONCE_FETCH_LATENCY, + SEQUENCER_SUBMISSION_FAILURE_COUNT, + SEQUENCER_SUBMISSION_LATENCY, + TRANSACTIONS_DROPPED, + TRANSACTIONS_DROPPED_TOO_LARGE, + TRANSACTIONS_PER_SUBMISSION, TRANSACTIONS_RECEIVED, }; diff --git a/crates/astria-composer/src/rollup.rs b/crates/astria-composer/src/rollup.rs index de70fca39..a5ebe9425 100644 --- a/crates/astria-composer/src/rollup.rs +++ b/crates/astria-composer/src/rollup.rs @@ -55,11 +55,17 @@ impl Rollup { // match when these capture groups match. let rollup_name = caps["rollup_name"].to_string().to_lowercase(); let url = caps["url"].to_string(); - Ok(Self { rollup_name, url }) + Ok(Self { + rollup_name, + url, + }) } pub(super) fn into_parts(self) -> (String, String) { - let Self { rollup_name, url } = self; + let Self { + rollup_name, + url, + } = self; (rollup_name, url) } } diff --git a/crates/astria-composer/tests/blackbox/geth_collector.rs b/crates/astria-composer/tests/blackbox/geth_collector.rs index 581144165..ae87a59b0 100644 --- a/crates/astria-composer/tests/blackbox/geth_collector.rs +++ b/crates/astria-composer/tests/blackbox/geth_collector.rs @@ -1,11 +1,17 @@ use std::time::Duration; -use astria_core::{generated::protocol::account::v1alpha1::NonceResponse, primitive::v1::RollupId}; +use astria_core::{ + generated::protocol::account::v1alpha1::NonceResponse, + primitive::v1::RollupId, +}; use ethers::types::Transaction; use crate::helper::{ - mount_broadcast_tx_sync_invalid_nonce_mock, mount_broadcast_tx_sync_mock, - mount_matcher_verifying_tx_integrity, spawn_composer, TEST_ETH_TX_JSON, + mount_broadcast_tx_sync_invalid_nonce_mock, + mount_broadcast_tx_sync_mock, + mount_matcher_verifying_tx_integrity, + spawn_composer, + TEST_ETH_TX_JSON, }; #[tokio::test] diff --git a/crates/astria-composer/tests/blackbox/grpc_collector.rs b/crates/astria-composer/tests/blackbox/grpc_collector.rs index 1810770a9..2080c4463 100644 --- a/crates/astria-composer/tests/blackbox/grpc_collector.rs +++ b/crates/astria-composer/tests/blackbox/grpc_collector.rs @@ -13,8 +13,11 @@ use astria_core::{ use ethers::prelude::Transaction; use crate::helper::{ - mount_broadcast_tx_sync_invalid_nonce_mock, mount_broadcast_tx_sync_mock, - mount_matcher_verifying_tx_integrity, spawn_composer, TEST_ETH_TX_JSON, + mount_broadcast_tx_sync_invalid_nonce_mock, + mount_broadcast_tx_sync_mock, + mount_matcher_verifying_tx_integrity, + spawn_composer, + TEST_ETH_TX_JSON, }; #[tokio::test] diff --git a/crates/astria-conductor/src/block_cache.rs b/crates/astria-conductor/src/block_cache.rs index fb15702fe..3b3b3b56e 100644 --- a/crates/astria-conductor/src/block_cache.rs +++ b/crates/astria-conductor/src/block_cache.rs @@ -1,7 +1,13 @@ //! A cache of sequencer blocks that are only yielded in sequential order. -use std::{collections::BTreeMap, future::Future}; - -use astria_core::sequencerblock::v1alpha1::{block::FilteredSequencerBlock, SubmittedMetadata}; +use std::{ + collections::BTreeMap, + future::Future, +}; + +use astria_core::sequencerblock::v1alpha1::{ + block::FilteredSequencerBlock, + SubmittedMetadata, +}; use pin_project_lite::pin_project; use sequencer_client::tendermint::block::Height; @@ -64,7 +70,9 @@ impl BlockCache { /// /// This method exists to make fetching the next block async cancellation safe. pub(crate) fn next_block(&mut self) -> NextBlock<'_, T> { - NextBlock { cache: self } + NextBlock { + cache: self, + } } } @@ -145,7 +153,9 @@ mod tests { impl From for DummyBlock { fn from(height: Height) -> DummyBlock { - DummyBlock { height } + DummyBlock { + height, + } } } diff --git a/crates/astria-conductor/src/celestia/block_verifier.rs b/crates/astria-conductor/src/celestia/block_verifier.rs index 8d04ac0f4..c45ee35fe 100644 --- a/crates/astria-conductor/src/celestia/block_verifier.rs +++ b/crates/astria-conductor/src/celestia/block_verifier.rs @@ -1,9 +1,15 @@ use std::collections::HashMap; -use astria_core::crypto::{Signature, VerificationKey}; +use astria_core::crypto::{ + Signature, + VerificationKey, +}; use prost::Message; use sequencer_client::{ - tendermint::{self, block::Height}, + tendermint::{ + self, + block::Height, + }, tendermint_rpc, }; @@ -218,12 +224,20 @@ mod test { generated::sequencerblock::v1alpha1::SequencerBlockHeader as RawSequencerBlockHeader, primitive::v1::RollupId, sequencerblock::v1alpha1::{ - block::SequencerBlockHeader, celestia::UncheckedSubmittedMetadata, + block::SequencerBlockHeader, + celestia::UncheckedSubmittedMetadata, }, }; use prost::Message as _; use sequencer_client::{ - tendermint::{self, account, block::Commit, validator, validator::Info as Validator, Hash}, + tendermint::{ + self, + account, + block::Commit, + validator, + validator::Info as Validator, + Hash, + }, tendermint_proto, tendermint_rpc::endpoint::validators, }; @@ -241,7 +255,10 @@ mod test { I: IntoIterator, B: AsRef<[u8]>, { - use sha2::{Digest as _, Sha256}; + use sha2::{ + Digest as _, + Sha256, + }; merkle::Tree::from_leaves(iter.into_iter().map(|item| Sha256::digest(&item))) } @@ -464,7 +481,10 @@ mod test { #[test] fn ensure_commit_has_quorum_not_ok() { - use base64::engine::{general_purpose::STANDARD, Engine as _}; + use base64::engine::{ + general_purpose::STANDARD, + Engine as _, + }; let validator_set = validators::Response::new( 78u32.into(), vec![Validator { @@ -508,9 +528,11 @@ mod test { &tendermint::chain::Id::try_from("test-chain-g3ejvw").unwrap(), ); assert!(result.is_err()); - assert!(result - .unwrap_err() - .to_string() - .contains("commit voting power is less than 2/3 of total voting power")); + assert!( + result + .unwrap_err() + .to_string() + .contains("commit voting power is less than 2/3 of total voting power") + ); } } diff --git a/crates/astria-conductor/src/celestia/builder.rs b/crates/astria-conductor/src/celestia/builder.rs index 94e2b54d6..99cf090c9 100644 --- a/crates/astria-conductor/src/celestia/builder.rs +++ b/crates/astria-conductor/src/celestia/builder.rs @@ -2,7 +2,10 @@ use std::time::Duration; -use astria_eyre::eyre::{self, WrapErr as _}; +use astria_eyre::eyre::{ + self, + WrapErr as _, +}; use jsonrpsee::http_client::HttpClient as CelestiaClient; use tendermint_rpc::HttpClient as SequencerClient; use tokio_util::sync::CancellationToken; @@ -48,7 +51,10 @@ impl Builder { } fn create_celestia_client(endpoint: String, bearer_token: &str) -> eyre::Result { - use jsonrpsee::http_client::{HeaderMap, HttpClientBuilder}; + use jsonrpsee::http_client::{ + HeaderMap, + HttpClientBuilder, + }; let mut headers = HeaderMap::new(); let auth_value = format!("Bearer {bearer_token}").parse().wrap_err( "failed to construct Authorization header value from provided Celestia bearer token", diff --git a/crates/astria-conductor/src/celestia/convert.rs b/crates/astria-conductor/src/celestia/convert.rs index 75dd91a1d..6ffe387e3 100644 --- a/crates/astria-conductor/src/celestia/convert.rs +++ b/crates/astria-conductor/src/celestia/convert.rs @@ -1,15 +1,31 @@ use astria_core::{ brotli::decompress_bytes, - generated::sequencerblock::v1alpha1::{SubmittedMetadataList, SubmittedRollupDataList}, + generated::sequencerblock::v1alpha1::{ + SubmittedMetadataList, + SubmittedRollupDataList, + }, sequencerblock::v1alpha1::{ - celestia::{SubmittedMetadataError, SubmittedRollupDataError}, - SubmittedMetadata, SubmittedRollupData, + celestia::{ + SubmittedMetadataError, + SubmittedRollupDataError, + }, + SubmittedMetadata, + SubmittedRollupData, }, }; -use celestia_types::{nmt::Namespace, Blob}; -use prost::{Message as _, Name as _}; +use celestia_types::{ + nmt::Namespace, + Blob, +}; +use prost::{ + Message as _, + Name as _, +}; use telemetry::display::base64; -use tracing::{info, warn}; +use tracing::{ + info, + warn, +}; use super::fetch::RawBlobs; diff --git a/crates/astria-conductor/src/celestia/fetch.rs b/crates/astria-conductor/src/celestia/fetch.rs index 7e3c9e3b4..503c0eef2 100644 --- a/crates/astria-conductor/src/celestia/fetch.rs +++ b/crates/astria-conductor/src/celestia/fetch.rs @@ -1,12 +1,30 @@ -use std::{sync::atomic::AtomicU32, time::Duration}; - -use astria_eyre::{eyre, eyre::WrapErr as _}; -use celestia_types::{nmt::Namespace, Blob}; -use jsonrpsee::{self, http_client::HttpClient as CelestiaClient}; +use std::{ + sync::atomic::AtomicU32, + time::Duration, +}; + +use astria_eyre::{ + eyre, + eyre::WrapErr as _, +}; +use celestia_types::{ + nmt::Namespace, + Blob, +}; +use jsonrpsee::{ + self, + http_client::HttpClient as CelestiaClient, +}; use telemetry::display::base64; use tokio::try_join; -use tracing::{instrument, warn}; -use tryhard::{backoff_strategies::BackoffStrategy, RetryPolicy}; +use tracing::{ + instrument, + warn, +}; +use tryhard::{ + backoff_strategies::BackoffStrategy, + RetryPolicy, +}; use crate::metrics_init::CELESTIA_BLOB_FETCH_ERROR_COUNT; diff --git a/crates/astria-conductor/src/celestia/latest_height_stream.rs b/crates/astria-conductor/src/celestia/latest_height_stream.rs index 2b541cd07..5fe47c98a 100644 --- a/crates/astria-conductor/src/celestia/latest_height_stream.rs +++ b/crates/astria-conductor/src/celestia/latest_height_stream.rs @@ -1,8 +1,19 @@ -use std::{pin::Pin, time::Duration}; +use std::{ + pin::Pin, + time::Duration, +}; -use astria_eyre::eyre::{Result, WrapErr as _}; +use astria_eyre::eyre::{ + Result, + WrapErr as _, +}; use celestia_rpc::HeaderClient as _; -use futures::{Future, FutureExt as _, Stream, StreamExt as _}; +use futures::{ + Future, + FutureExt as _, + Stream, + StreamExt as _, +}; use jsonrpsee::http_client::HttpClient; use tokio_stream::wrappers::IntervalStream; diff --git a/crates/astria-conductor/src/celestia/mod.rs b/crates/astria-conductor/src/celestia/mod.rs index a44086739..d69b87f76 100644 --- a/crates/astria-conductor/src/celestia/mod.rs +++ b/crates/astria-conductor/src/celestia/mod.rs @@ -1,30 +1,72 @@ -use std::{cmp::max, sync::Arc, time::Duration}; +use std::{ + cmp::max, + sync::Arc, + time::Duration, +}; -use astria_core::{primitive::v1::RollupId, sequencerblock::v1alpha1::block::SequencerBlockHeader}; -use astria_eyre::eyre::{self, bail, WrapErr as _}; +use astria_core::{ + primitive::v1::RollupId, + sequencerblock::v1alpha1::block::SequencerBlockHeader, +}; +use astria_eyre::eyre::{ + self, + bail, + WrapErr as _, +}; use celestia_types::nmt::Namespace; use futures::{ - future::{BoxFuture, Fuse, FusedFuture as _}, + future::{ + BoxFuture, + Fuse, + FusedFuture as _, + }, FutureExt as _, }; use jsonrpsee::http_client::HttpClient as CelestiaClient; use metrics::histogram; use sequencer_client::{ - tendermint, tendermint::block::Height as SequencerHeight, tendermint_rpc, + tendermint, + tendermint::block::Height as SequencerHeight, + tendermint_rpc, HttpClient as SequencerClient, }; -use telemetry::display::{base64, json}; -use tokio::{select, sync::mpsc, task::spawn_blocking, try_join}; +use telemetry::display::{ + base64, + json, +}; +use tokio::{ + select, + sync::mpsc, + task::spawn_blocking, + try_join, +}; use tokio_stream::StreamExt as _; -use tokio_util::{sync::CancellationToken, task::JoinMap}; -use tracing::{error, info, info_span, instrument, trace, warn}; +use tokio_util::{ + sync::CancellationToken, + task::JoinMap, +}; +use tracing::{ + error, + info, + info_span, + instrument, + trace, + warn, +}; use crate::{ block_cache::GetSequencerHeight, - executor::{FirmSendError, FirmTrySendError, StateIsInit}, + executor::{ + FirmSendError, + FirmTrySendError, + StateIsInit, + }, metrics_init::{ - BLOBS_PER_CELESTIA_FETCH, DECODED_ITEMS_PER_CELESTIA_FETCH, NAMESPACE_TYPE_LABEL, - NAMESPACE_TYPE_METADATA, NAMESPACE_TYPE_ROLLUP_DATA, + BLOBS_PER_CELESTIA_FETCH, + DECODED_ITEMS_PER_CELESTIA_FETCH, + NAMESPACE_TYPE_LABEL, + NAMESPACE_TYPE_METADATA, + NAMESPACE_TYPE_ROLLUP_DATA, SEQUENCER_BLOCKS_METADATA_VERIFIED_PER_CELESTIA_FETCH, SEQUENCER_BLOCK_INFORMATION_RECONSTRUCTED_PER_CELESTIA_FETCH, }, @@ -50,9 +92,15 @@ use self::{ fetch::fetch_new_blobs, latest_height_stream::stream_latest_heights, reconstruct::reconstruct_blocks_from_verified_blobs, - verify::{verify_metadata, BlobVerifier}, + verify::{ + verify_metadata, + BlobVerifier, + }, +}; +use crate::{ + block_cache::BlockCache, + executor, }; -use crate::{block_cache::BlockCache, executor}; /// Sequencer Block information reconstructed from Celestia blobs. /// diff --git a/crates/astria-conductor/src/celestia/reconstruct.rs b/crates/astria-conductor/src/celestia/reconstruct.rs index 31421d000..9deae218e 100644 --- a/crates/astria-conductor/src/celestia/reconstruct.rs +++ b/crates/astria-conductor/src/celestia/reconstruct.rs @@ -2,12 +2,21 @@ use std::collections::HashMap; use astria_core::{ primitive::v1::RollupId, - sequencerblock::v1alpha1::{SubmittedMetadata, SubmittedRollupData}, + sequencerblock::v1alpha1::{ + SubmittedMetadata, + SubmittedRollupData, + }, }; use telemetry::display::base64; -use tracing::{info, warn}; +use tracing::{ + info, + warn, +}; -use super::{verify::VerifiedBlobs, ReconstructedBlock}; +use super::{ + verify::VerifiedBlobs, + ReconstructedBlock, +}; /// Reconstructs block information from verified blocks. /// diff --git a/crates/astria-conductor/src/celestia/reporting.rs b/crates/astria-conductor/src/celestia/reporting.rs index 13f4cae6e..cd16454b6 100644 --- a/crates/astria-conductor/src/celestia/reporting.rs +++ b/crates/astria-conductor/src/celestia/reporting.rs @@ -1,8 +1,15 @@ //! Various newtype-wrappers to emit serde-serialized tracing event fields. -use serde::ser::{Serialize, SerializeSeq, SerializeStruct}; +use serde::ser::{ + Serialize, + SerializeSeq, + SerializeStruct, +}; use telemetry::display::base64; -use super::{ReconstructedBlock, ReconstructedBlocks}; +use super::{ + ReconstructedBlock, + ReconstructedBlocks, +}; pub(super) struct ReportReconstructedBlocks<'a>(pub(super) &'a ReconstructedBlocks); impl<'a> Serialize for ReportReconstructedBlocks<'a> { diff --git a/crates/astria-conductor/src/celestia/verify.rs b/crates/astria-conductor/src/celestia/verify.rs index 7b4adf4da..1f44662da 100644 --- a/crates/astria-conductor/src/celestia/verify.rs +++ b/crates/astria-conductor/src/celestia/verify.rs @@ -1,23 +1,59 @@ -use std::{collections::HashMap, sync::Arc, time::Duration}; +use std::{ + collections::HashMap, + sync::Arc, + time::Duration, +}; -use astria_core::sequencerblock::v1alpha1::{SubmittedMetadata, SubmittedRollupData}; +use astria_core::sequencerblock::v1alpha1::{ + SubmittedMetadata, + SubmittedRollupData, +}; use astria_eyre::{ eyre, - eyre::{ensure, WrapErr as _}, + eyre::{ + ensure, + WrapErr as _, + }, }; use moka::future::Cache; use sequencer_client::{ - tendermint::block::{signed_header::SignedHeader, Height as SequencerHeight}, - tendermint_rpc, Client as _, HttpClient as SequencerClient, + tendermint::block::{ + signed_header::SignedHeader, + Height as SequencerHeight, + }, + tendermint_rpc, + Client as _, + HttpClient as SequencerClient, }; use telemetry::display::base64; use tokio_util::task::JoinMap; -use tower::{util::BoxService, BoxError, Service as _, ServiceExt as _}; -use tracing::{info, instrument, warn, Instrument}; -use tryhard::{backoff_strategies::BackoffStrategy, retry_fn, RetryFutureConfig, RetryPolicy}; +use tower::{ + util::BoxService, + BoxError, + Service as _, + ServiceExt as _, +}; +use tracing::{ + info, + instrument, + warn, + Instrument, +}; +use tryhard::{ + backoff_strategies::BackoffStrategy, + retry_fn, + RetryFutureConfig, + RetryPolicy, +}; -use super::{block_verifier, convert::ConvertedBlobs}; -use crate::executor::{self, StateIsInit}; +use super::{ + block_verifier, + convert::ConvertedBlobs, +}; +use crate::executor::{ + self, + StateIsInit, +}; pub(super) struct VerifiedBlobs { celestia_height: u64, @@ -290,7 +326,10 @@ async fn fetch_commit_with_retry( .with_config(retry_config) .await .map(Into::into) - .map_err(|source| VerificationMetaError::FetchCommit { height, source }) + .map_err(|source| VerificationMetaError::FetchCommit { + height, + source, + }) } async fn fetch_validators_with_retry( @@ -360,7 +399,11 @@ impl<'a> BackoffStrategy<'a, tendermint_rpc::Error> for CometBftRetryStrategy { } fn should_retry(error: &tendermint_rpc::Error) -> bool { - use tendermint_rpc::error::ErrorDetail::{Http, HttpRequestFailed, Timeout}; + use tendermint_rpc::error::ErrorDetail::{ + Http, + HttpRequestFailed, + Timeout, + }; matches!( error.detail(), Http(..) | HttpRequestFailed(..) | Timeout(..) @@ -415,7 +458,9 @@ impl RateLimitedVerificationClient { .inner .ready() .await? - .call(VerificationRequest::Commit { height }) + .call(VerificationRequest::Commit { + height, + }) .await? { VerificationResponse::Commit(commit) => Ok(commit), @@ -464,9 +509,9 @@ impl RateLimitedVerificationClient { let client = client.clone(); async move { match req { - VerificationRequest::Commit { height } => { - fetch_commit_with_retry(client, height).await - } + VerificationRequest::Commit { + height, + } => fetch_commit_with_retry(client, height).await, VerificationRequest::Validators { prev_height, height, @@ -482,7 +527,9 @@ impl RateLimitedVerificationClient { .try_into() .wrap_err("failed to convert u32 requests-per-second to usize")?, ); - Ok(Self { inner }) + Ok(Self { + inner, + }) } } diff --git a/crates/astria-conductor/src/conductor.rs b/crates/astria-conductor/src/conductor.rs index dd7c8fcc4..4945fae97 100644 --- a/crates/astria-conductor/src/conductor.rs +++ b/crates/astria-conductor/src/conductor.rs @@ -1,14 +1,38 @@ -use std::{future::Future, time::Duration}; - -use astria_eyre::eyre::{self, eyre, WrapErr as _}; +use std::{ + future::Future, + time::Duration, +}; + +use astria_eyre::eyre::{ + self, + eyre, + WrapErr as _, +}; use itertools::Itertools as _; use pin_project_lite::pin_project; use sequencer_client::HttpClient; -use tokio::{select, time::timeout}; -use tokio_util::{sync::CancellationToken, task::JoinMap}; -use tracing::{error, info, instrument, warn}; - -use crate::{celestia, executor, sequencer, utils::flatten, Config}; +use tokio::{ + select, + time::timeout, +}; +use tokio_util::{ + sync::CancellationToken, + task::JoinMap, +}; +use tracing::{ + error, + info, + instrument, + warn, +}; + +use crate::{ + celestia, + executor, + sequencer, + utils::flatten, + Config, +}; pin_project! { /// A handle returned by [`Conductor::spawn`]. @@ -126,7 +150,10 @@ impl Conductor { tasks.spawn(Self::CELESTIA, reader.run_until_stopped()); }; - Ok(Self { shutdown, tasks }) + Ok(Self { + shutdown, + tasks, + }) } /// Runs [`Conductor`] until it receives an exit signal. diff --git a/crates/astria-conductor/src/config.rs b/crates/astria-conductor/src/config.rs index 863f3361f..699f95f1c 100644 --- a/crates/astria-conductor/src/config.rs +++ b/crates/astria-conductor/src/config.rs @@ -1,6 +1,9 @@ //! The conductor configuration. -use serde::{Deserialize, Serialize}; +use serde::{ + Deserialize, + Serialize, +}; #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)] pub enum CommitLevel { @@ -87,7 +90,10 @@ impl config::Config for Config { #[cfg(test)] mod tests { - use super::{CommitLevel, Config}; + use super::{ + CommitLevel, + Config, + }; const EXAMPLE_ENV: &str = include_str!("../local.env.example"); @@ -98,7 +104,11 @@ mod tests { #[test] fn do_commit_levels_correctly_report_mode() { - use CommitLevel::{FirmOnly, SoftAndFirm, SoftOnly}; + use CommitLevel::{ + FirmOnly, + SoftAndFirm, + SoftOnly, + }; assert!(FirmOnly.is_with_firm()); assert!(!FirmOnly.is_with_soft()); diff --git a/crates/astria-conductor/src/executor/builder.rs b/crates/astria-conductor/src/executor/builder.rs index 28bee5a26..67941479a 100644 --- a/crates/astria-conductor/src/executor/builder.rs +++ b/crates/astria-conductor/src/executor/builder.rs @@ -1,10 +1,18 @@ use std::collections::HashMap; -use astria_eyre::eyre::{self, WrapErr as _}; +use astria_eyre::eyre::{ + self, + WrapErr as _, +}; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; -use super::{state, Executor, Handle, StateNotInit}; +use super::{ + state, + Executor, + Handle, + StateNotInit, +}; use crate::config::CommitLevel; pub(crate) struct Builder { diff --git a/crates/astria-conductor/src/executor/channel.rs b/crates/astria-conductor/src/executor/channel.rs index 871dc9272..c4348bd08 100644 --- a/crates/astria-conductor/src/executor/channel.rs +++ b/crates/astria-conductor/src/executor/channel.rs @@ -4,13 +4,21 @@ //! from a sequencer reader to the executor, the channel is generic over the values that are //! being sent to better test its functionality. -use std::sync::{Arc, Weak}; +use std::sync::{ + Arc, + Weak, +}; use tokio::sync::{ mpsc::{ - error::SendError as TokioSendError, unbounded_channel, UnboundedReceiver, UnboundedSender, + error::SendError as TokioSendError, + unbounded_channel, + UnboundedReceiver, + UnboundedSender, }, - AcquireError, Semaphore, TryAcquireError, + AcquireError, + Semaphore, + TryAcquireError, }; /// Creates an mpsc channel for sending soft blocks between asynchronous task. @@ -25,7 +33,11 @@ pub(super) fn soft_block_channel() -> (Sender, Receiver) { chan: tx, sem: Arc::downgrade(&sem), }; - let receiver = Receiver { cap, chan: rx, sem }; + let receiver = Receiver { + cap, + chan: rx, + sem, + }; (sender, receiver) } @@ -146,7 +158,11 @@ impl Receiver { #[cfg(test)] mod tests { - use super::{soft_block_channel, SendError, TrySendError}; + use super::{ + soft_block_channel, + SendError, + TrySendError, + }; #[test] fn fresh_channel_has_no_capacity() { diff --git a/crates/astria-conductor/src/executor/client.rs b/crates/astria-conductor/src/executor/client.rs index 0579b534c..8704ee076 100644 --- a/crates/astria-conductor/src/executor/client.rs +++ b/crates/astria-conductor/src/executor/client.rs @@ -1,19 +1,42 @@ use std::time::Duration; use astria_core::{ - execution::v1alpha2::{Block, CommitmentState, GenesisInfo}, + execution::v1alpha2::{ + Block, + CommitmentState, + GenesisInfo, + }, generated::{ - execution::{v1alpha2 as raw, v1alpha2::execution_service_client::ExecutionServiceClient}, + execution::{ + v1alpha2 as raw, + v1alpha2::execution_service_client::ExecutionServiceClient, + }, sequencerblock::v1alpha1::RollupData, }, Protobuf as _, }; -use astria_eyre::eyre::{self, ensure, WrapErr as _}; +use astria_eyre::eyre::{ + self, + ensure, + WrapErr as _, +}; use bytes::Bytes; use pbjson_types::Timestamp; -use tonic::transport::{Channel, Endpoint, Uri}; -use tracing::{instrument, warn, Instrument, Span}; -use tryhard::{backoff_strategies::BackoffStrategy, RetryPolicy}; +use tonic::transport::{ + Channel, + Endpoint, + Uri, +}; +use tracing::{ + instrument, + warn, + Instrument, + Span, +}; +use tryhard::{ + backoff_strategies::BackoffStrategy, + RetryPolicy, +}; /// A newtype wrapper around [`ExecutionServiceClient`] to work with /// idiomatic types. @@ -30,7 +53,10 @@ impl Client { .wrap_err("failed to parse provided string as uri")?; let endpoint = Endpoint::from(uri.clone()).connect_lazy(); let inner = ExecutionServiceClient::new(endpoint); - Ok(Self { uri, inner }) + Ok(Self { + uri, + inner, + }) } /// Calls RPC astria.execution.v1alpha2.GetBlock @@ -306,9 +332,16 @@ fn should_retry(status: &tonic::Status) -> bool { mod tests { use std::time::Duration; - use tonic::{Code, Status}; + use tonic::{ + Code, + Status, + }; - use super::{BackoffStrategy as _, ExecutionApiRetryStrategy, RetryPolicy}; + use super::{ + BackoffStrategy as _, + ExecutionApiRetryStrategy, + RetryPolicy, + }; #[track_caller] fn assert_retry_policy(code: Code) { diff --git a/crates/astria-conductor/src/executor/mod.rs b/crates/astria-conductor/src/executor/mod.rs index ba8b3655b..56eb5abbf 100644 --- a/crates/astria-conductor/src/executor/mod.rs +++ b/crates/astria-conductor/src/executor/mod.rs @@ -1,25 +1,49 @@ use std::collections::HashMap; use astria_core::{ - execution::v1alpha2::{Block, CommitmentState}, + execution::v1alpha2::{ + Block, + CommitmentState, + }, primitive::v1::RollupId, - sequencerblock::v1alpha1::block::{FilteredSequencerBlock, FilteredSequencerBlockParts}, + sequencerblock::v1alpha1::block::{ + FilteredSequencerBlock, + FilteredSequencerBlockParts, + }, +}; +use astria_eyre::eyre::{ + self, + bail, + ensure, + WrapErr as _, }; -use astria_eyre::eyre::{self, bail, ensure, WrapErr as _}; use bytes::Bytes; -use sequencer_client::tendermint::{block::Height as SequencerHeight, Time as TendermintTime}; +use sequencer_client::tendermint::{ + block::Height as SequencerHeight, + Time as TendermintTime, +}; use tokio::{ select, - sync::{mpsc, watch::error::RecvError}, + sync::{ + mpsc, + watch::error::RecvError, + }, }; use tokio_util::sync::CancellationToken; -use tracing::{debug, error, info, instrument}; +use tracing::{ + debug, + error, + info, + instrument, +}; use crate::{ celestia::ReconstructedBlock, config::CommitLevel, metrics_init::{ - EXECUTED_FIRM_BLOCK_NUMBER, EXECUTED_SOFT_BLOCK_NUMBER, TRANSACTIONS_PER_EXECUTED_BLOCK, + EXECUTED_FIRM_BLOCK_NUMBER, + EXECUTED_SOFT_BLOCK_NUMBER, + TRANSACTIONS_PER_EXECUTED_BLOCK, }, }; @@ -592,7 +616,11 @@ impl Executor { #[instrument(skip_all)] async fn update_commitment_state(&mut self, update: Update) -> eyre::Result<()> { - use Update::{OnlyFirm, OnlySoft, ToSame}; + use Update::{ + OnlyFirm, + OnlySoft, + ToSame, + }; let (firm, soft, celestia_height) = match update { OnlyFirm(firm, celestia_height) => (firm, self.state.soft(), celestia_height), OnlySoft(soft) => ( @@ -702,9 +730,14 @@ impl ExecutableBlock { /// Converts a [`tendermint::Time`] to a [`prost_types::Timestamp`]. fn convert_tendermint_time_to_protobuf_timestamp(value: TendermintTime) -> pbjson_types::Timestamp { - let sequencer_client::tendermint_proto::google::protobuf::Timestamp { seconds, nanos } = - value.into(); - pbjson_types::Timestamp { seconds, nanos } + let sequencer_client::tendermint_proto::google::protobuf::Timestamp { + seconds, + nanos, + } = value.into(); + pbjson_types::Timestamp { + seconds, + nanos, + } } #[derive(Copy, Clone, Debug)] @@ -751,7 +784,10 @@ fn does_block_response_fulfill_contract( let actual = block.number(); let expected = current .checked_add(1) - .ok_or(ContractViolation::CurrentBlockNumberIsMax { kind, actual })?; + .ok_or(ContractViolation::CurrentBlockNumberIsMax { + kind, + actual, + })?; if actual == expected { Ok(()) } else { diff --git a/crates/astria-conductor/src/executor/state.rs b/crates/astria-conductor/src/executor/state.rs index 0ca95499c..f5d1bab6b 100644 --- a/crates/astria-conductor/src/executor/state.rs +++ b/crates/astria-conductor/src/executor/state.rs @@ -3,18 +3,32 @@ //! //! The inner state must not be unset after having been set. use astria_core::{ - execution::v1alpha2::{Block, CommitmentState, GenesisInfo}, + execution::v1alpha2::{ + Block, + CommitmentState, + GenesisInfo, + }, primitive::v1::RollupId, }; -use astria_eyre::{eyre, eyre::WrapErr as _}; +use astria_eyre::{ + eyre, + eyre::WrapErr as _, +}; use bytes::Bytes; use sequencer_client::tendermint::block::Height as SequencerHeight; -use tokio::sync::watch::{self, error::RecvError}; +use tokio::sync::watch::{ + self, + error::RecvError, +}; pub(super) fn channel() -> (StateSender, StateReceiver) { let (tx, rx) = watch::channel(None); - let sender = StateSender { inner: tx }; - let receiver = StateReceiver { inner: rx }; + let sender = StateSender { + inner: tx, + }; + let receiver = StateReceiver { + inner: rx, + }; (sender, receiver) } @@ -326,7 +340,10 @@ pub(super) fn map_sequencer_height_to_rollup_height( #[cfg(test)] mod tests { - use astria_core::{generated::execution::v1alpha2 as raw, Protobuf as _}; + use astria_core::{ + generated::execution::v1alpha2 as raw, + Protobuf as _, + }; use pbjson_types::Timestamp; use super::*; diff --git a/crates/astria-conductor/src/executor/tests.rs b/crates/astria-conductor/src/executor/tests.rs index 0f6960e2a..f6deb4db0 100644 --- a/crates/astria-conductor/src/executor/tests.rs +++ b/crates/astria-conductor/src/executor/tests.rs @@ -1,6 +1,10 @@ use astria_core::{ self, - execution::v1alpha2::{Block, CommitmentState, GenesisInfo}, + execution::v1alpha2::{ + Block, + CommitmentState, + GenesisInfo, + }, generated::execution::v1alpha2 as raw, Protobuf as _, }; @@ -8,7 +12,10 @@ use bytes::Bytes; use super::{ should_execute_firm_block, - state::{StateReceiver, StateSender}, + state::{ + StateReceiver, + StateSender, + }, RollupId, }; use crate::config::CommitLevel; @@ -32,7 +39,12 @@ struct MakeState { soft: u32, } -fn make_state(MakeState { firm, soft }: MakeState) -> (StateSender, StateReceiver) { +fn make_state( + MakeState { + firm, + soft, + }: MakeState, +) -> (StateSender, StateReceiver) { let genesis_info = GenesisInfo::try_from_raw(raw::GenesisInfo { rollup_id: Bytes::copy_from_slice(ROLLUP_ID.as_ref()), sequencer_genesis_block_height: 1, @@ -70,27 +82,90 @@ state", #[test] fn execute_block_contract_violation() { - use super::ExecutionKind::{Firm, Soft}; - assert_contract_fulfilled(Firm, MakeState { firm: 2, soft: 3 }, 3); + use super::ExecutionKind::{ + Firm, + Soft, + }; + assert_contract_fulfilled( + Firm, + MakeState { + firm: 2, + soft: 3, + }, + 3, + ); - assert_contract_fulfilled(Soft, MakeState { firm: 2, soft: 3 }, 4); + assert_contract_fulfilled( + Soft, + MakeState { + firm: 2, + soft: 3, + }, + 4, + ); - assert_contract_violated(Firm, MakeState { firm: 2, soft: 3 }, 1); + assert_contract_violated( + Firm, + MakeState { + firm: 2, + soft: 3, + }, + 1, + ); - assert_contract_violated(Firm, MakeState { firm: 2, soft: 3 }, 2); + assert_contract_violated( + Firm, + MakeState { + firm: 2, + soft: 3, + }, + 2, + ); - assert_contract_violated(Firm, MakeState { firm: 2, soft: 3 }, 4); + assert_contract_violated( + Firm, + MakeState { + firm: 2, + soft: 3, + }, + 4, + ); - assert_contract_violated(Soft, MakeState { firm: 2, soft: 3 }, 2); + assert_contract_violated( + Soft, + MakeState { + firm: 2, + soft: 3, + }, + 2, + ); - assert_contract_violated(Soft, MakeState { firm: 2, soft: 3 }, 3); + assert_contract_violated( + Soft, + MakeState { + firm: 2, + soft: 3, + }, + 3, + ); - assert_contract_violated(Soft, MakeState { firm: 2, soft: 3 }, 5); + assert_contract_violated( + Soft, + MakeState { + firm: 2, + soft: 3, + }, + 5, + ); } #[test] fn should_execute_firm() { - use CommitLevel::{FirmOnly, SoftAndFirm, SoftOnly}; + use CommitLevel::{ + FirmOnly, + SoftAndFirm, + SoftOnly, + }; assert!( should_execute_firm_block(1, 1, FirmOnly), diff --git a/crates/astria-conductor/src/main.rs b/crates/astria-conductor/src/main.rs index c191e586b..4efb85676 100644 --- a/crates/astria-conductor/src/main.rs +++ b/crates/astria-conductor/src/main.rs @@ -1,12 +1,24 @@ use std::process::ExitCode; -use astria_conductor::{metrics_init, Conductor, Config, BUILD_INFO}; +use astria_conductor::{ + metrics_init, + Conductor, + Config, + BUILD_INFO, +}; use astria_eyre::eyre::WrapErr as _; use tokio::{ select, - signal::unix::{signal, SignalKind}, + signal::unix::{ + signal, + SignalKind, + }, +}; +use tracing::{ + error, + info, + warn, }; -use tracing::{error, info, warn}; // Following the BSD convention for failing to read config // See here: https://freedesktop.org/software/systemd/man/systemd.exec.html#Process%20Exit%20Codes diff --git a/crates/astria-conductor/src/metrics_init.rs b/crates/astria-conductor/src/metrics_init.rs index 2c8cff880..f0801c84a 100644 --- a/crates/astria-conductor/src/metrics_init.rs +++ b/crates/astria-conductor/src/metrics_init.rs @@ -2,7 +2,11 @@ //! //! Registers metrics & lists constants to be used as metric names throughout crate. -use metrics::{describe_counter, describe_histogram, Unit}; +use metrics::{ + describe_counter, + describe_histogram, + Unit, +}; use telemetry::metric_name; pub(crate) const NAMESPACE_TYPE_LABEL: &str = "namespace_type"; @@ -69,8 +73,11 @@ metric_name!(pub const TRANSACTIONS_PER_EXECUTED_BLOCK); mod tests { use super::TRANSACTIONS_PER_EXECUTED_BLOCK; use crate::metrics_init::{ - BLOBS_PER_CELESTIA_FETCH, CELESTIA_BLOB_FETCH_ERROR_COUNT, - DECODED_ITEMS_PER_CELESTIA_FETCH, EXECUTED_FIRM_BLOCK_NUMBER, EXECUTED_SOFT_BLOCK_NUMBER, + BLOBS_PER_CELESTIA_FETCH, + CELESTIA_BLOB_FETCH_ERROR_COUNT, + DECODED_ITEMS_PER_CELESTIA_FETCH, + EXECUTED_FIRM_BLOCK_NUMBER, + EXECUTED_SOFT_BLOCK_NUMBER, SEQUENCER_BLOCKS_METADATA_VERIFIED_PER_CELESTIA_FETCH, SEQUENCER_BLOCK_INFORMATION_RECONSTRUCTED_PER_CELESTIA_FETCH, }; diff --git a/crates/astria-conductor/src/sequencer/block_stream.rs b/crates/astria-conductor/src/sequencer/block_stream.rs index 8202e1714..663f9d254 100644 --- a/crates/astria-conductor/src/sequencer/block_stream.rs +++ b/crates/astria-conductor/src/sequencer/block_stream.rs @@ -1,15 +1,28 @@ -use std::{error::Error as StdError, pin::Pin, task::Poll}; +use std::{ + error::Error as StdError, + pin::Pin, + task::Poll, +}; use astria_core::{ - primitive::v1::RollupId, sequencerblock::v1alpha1::block::FilteredSequencerBlock, + primitive::v1::RollupId, + sequencerblock::v1alpha1::block::FilteredSequencerBlock, +}; +use astria_eyre::eyre::{ + self, + WrapErr as _, }; -use astria_eyre::eyre::{self, WrapErr as _}; use futures::Stream; use futures_bounded::FuturesMap; use pin_project_lite::pin_project; use sequencer_client::tendermint::block::Height; use telemetry::display::json; -use tracing::{error, info, instrument, warn}; +use tracing::{ + error, + info, + instrument, + warn, +}; use super::SequencerGrpcClient; use crate::sequencer::reporting::ReportFilteredSequencerBlock; diff --git a/crates/astria-conductor/src/sequencer/client.rs b/crates/astria-conductor/src/sequencer/client.rs index ef1fa50f4..78c1eafc7 100644 --- a/crates/astria-conductor/src/sequencer/client.rs +++ b/crates/astria-conductor/src/sequencer/client.rs @@ -4,14 +4,27 @@ use std::time::Duration; use astria_core::{ generated::sequencerblock::v1alpha1::{ - sequencer_service_client::SequencerServiceClient, GetFilteredSequencerBlockRequest, + sequencer_service_client::SequencerServiceClient, + GetFilteredSequencerBlockRequest, }, primitive::v1::RollupId, sequencerblock::v1alpha1::block::FilteredSequencerBlock, }; -use astria_eyre::eyre::{self, WrapErr as _}; -use tonic::transport::{Channel, Endpoint, Uri}; -use tracing::{debug, instrument, warn, Instrument}; +use astria_eyre::eyre::{ + self, + WrapErr as _, +}; +use tonic::transport::{ + Channel, + Endpoint, + Uri, +}; +use tracing::{ + debug, + instrument, + warn, + Instrument, +}; #[derive(Clone)] pub(crate) struct SequencerGrpcClient { @@ -27,7 +40,10 @@ impl SequencerGrpcClient { .wrap_err("failed parsing provided string as Uri")?; let endpoint = Endpoint::from(uri.clone()); let inner = SequencerServiceClient::new(endpoint.connect_lazy()); - Ok(Self { inner, uri }) + Ok(Self { + inner, + uri, + }) } /// Fetch a sequencer block filtered by `rollup_id`. diff --git a/crates/astria-conductor/src/sequencer/mod.rs b/crates/astria-conductor/src/sequencer/mod.rs index be1ef7632..535c61d4f 100644 --- a/crates/astria-conductor/src/sequencer/mod.rs +++ b/crates/astria-conductor/src/sequencer/mod.rs @@ -3,21 +3,45 @@ use std::time::Duration; use astria_core::sequencerblock::v1alpha1::block::FilteredSequencerBlock; -use astria_eyre::eyre::{self, bail, Report, WrapErr as _}; +use astria_eyre::eyre::{ + self, + bail, + Report, + WrapErr as _, +}; use futures::{ - future::{self, BoxFuture, Fuse}, - FutureExt as _, StreamExt as _, + future::{ + self, + BoxFuture, + Fuse, + }, + FutureExt as _, + StreamExt as _, }; use sequencer_client::{ - tendermint::block::Height, HttpClient, LatestHeightStream, StreamLatestHeight as _, + tendermint::block::Height, + HttpClient, + LatestHeightStream, + StreamLatestHeight as _, }; use tokio::select; use tokio_util::sync::CancellationToken; -use tracing::{debug, error, info, trace, warn}; +use tracing::{ + debug, + error, + info, + trace, + warn, +}; use crate::{ block_cache::BlockCache, - executor::{self, SoftSendError, SoftTrySendError, StateIsInit}, + executor::{ + self, + SoftSendError, + SoftTrySendError, + StateIsInit, + }, sequencer::block_stream::BlocksFromHeightStream, }; @@ -226,7 +250,9 @@ impl RunningReader { fn send_to_executor(&mut self, block: FilteredSequencerBlock) -> eyre::Result<()> { if let Err(err) = self.executor.try_send_soft_block(block) { match err { - SoftTrySendError::Channel { source } => match *source { + SoftTrySendError::Channel { + source, + } => match *source { executor::channel::TrySendError::Closed(_) => { bail!("could not send block to executor because its channel was closed"); } diff --git a/crates/astria-conductor/src/sequencer/reporting.rs b/crates/astria-conductor/src/sequencer/reporting.rs index 610630aa3..285d109a0 100644 --- a/crates/astria-conductor/src/sequencer/reporting.rs +++ b/crates/astria-conductor/src/sequencer/reporting.rs @@ -1,9 +1,16 @@ use astria_core::{ primitive::v1::RollupId, - sequencerblock::v1alpha1::block::{FilteredSequencerBlock, RollupTransactions}, + sequencerblock::v1alpha1::block::{ + FilteredSequencerBlock, + RollupTransactions, + }, }; use indexmap::IndexMap; -use serde::ser::{Serialize, SerializeMap as _, SerializeStruct as _}; +use serde::ser::{ + Serialize, + SerializeMap as _, + SerializeStruct as _, +}; pub(super) struct ReportFilteredSequencerBlock<'a>(pub(super) &'a FilteredSequencerBlock); impl<'a> Serialize for ReportFilteredSequencerBlock<'a> { @@ -36,12 +43,16 @@ impl<'a> Serialize for ReportRollups<'a> { #[cfg(test)] mod tests { use astria_core::{ - primitive::v1::RollupId, protocol::test_utils::ConfigureSequencerBlock, + primitive::v1::RollupId, + protocol::test_utils::ConfigureSequencerBlock, sequencerblock::v1alpha1::block::FilteredSequencerBlock, }; use insta::assert_json_snapshot; - use crate::sequencer::reporting::{ReportFilteredSequencerBlock, ReportRollups}; + use crate::sequencer::reporting::{ + ReportFilteredSequencerBlock, + ReportRollups, + }; const ROLLUP_42: RollupId = RollupId::new([42u8; 32]); const ROLLUP_69: RollupId = RollupId::new([69u8; 32]); diff --git a/crates/astria-conductor/src/utils.rs b/crates/astria-conductor/src/utils.rs index 150752771..efd49c60e 100644 --- a/crates/astria-conductor/src/utils.rs +++ b/crates/astria-conductor/src/utils.rs @@ -1,4 +1,7 @@ -use astria_eyre::eyre::{self, WrapErr as _}; +use astria_eyre::eyre::{ + self, + WrapErr as _, +}; use tokio::task::JoinError; pub(crate) fn flatten(res: Result, JoinError>) -> eyre::Result { diff --git a/crates/astria-conductor/tests/blackbox/firm_only.rs b/crates/astria-conductor/tests/blackbox/firm_only.rs index 4c700a55b..51cf03db5 100644 --- a/crates/astria-conductor/tests/blackbox/firm_only.rs +++ b/crates/astria-conductor/tests/blackbox/firm_only.rs @@ -1,13 +1,22 @@ use std::time::Duration; use astria_conductor::config::CommitLevel; -use futures::future::{join, join4}; +use futures::future::{ + join, + join4, +}; use tokio::time::timeout; use crate::{ - helpers::spawn_conductor, mount_celestia_blobs, mount_celestia_header_network_head, - mount_executed_block, mount_get_commitment_state, mount_get_genesis_info, - mount_sequencer_commit, mount_sequencer_genesis, mount_sequencer_validator_set, + helpers::spawn_conductor, + mount_celestia_blobs, + mount_celestia_header_network_head, + mount_executed_block, + mount_get_commitment_state, + mount_get_genesis_info, + mount_sequencer_commit, + mount_sequencer_genesis, + mount_sequencer_validator_set, mount_update_commitment_state, }; diff --git a/crates/astria-conductor/tests/blackbox/helpers/macros.rs b/crates/astria-conductor/tests/blackbox/helpers/macros.rs index cd307c2bf..4f6779c7d 100644 --- a/crates/astria-conductor/tests/blackbox/helpers/macros.rs +++ b/crates/astria-conductor/tests/blackbox/helpers/macros.rs @@ -19,7 +19,10 @@ macro_rules! celestia_network_head { ::celestia_types::ExtendedHeader { header: ::celestia_tendermint::block::header::Header { height: $height.into(), - version: ::celestia_tendermint::block::header::Version { block: 0, app: 0 }, + version: ::celestia_tendermint::block::header::Version { + block: 0, + app: 0, + }, chain_id: "test_celestia-1000".try_into().unwrap(), time: ::celestia_tendermint::Time::from_unix_timestamp(1, 1).unwrap(), last_block_id: None, diff --git a/crates/astria-conductor/tests/blackbox/helpers/mock_grpc.rs b/crates/astria-conductor/tests/blackbox/helpers/mock_grpc.rs index 86140973b..f9f857f4b 100644 --- a/crates/astria-conductor/tests/blackbox/helpers/mock_grpc.rs +++ b/crates/astria-conductor/tests/blackbox/helpers/mock_grpc.rs @@ -1,22 +1,49 @@ -use std::{net::SocketAddr, sync::Arc}; +use std::{ + net::SocketAddr, + sync::Arc, +}; use astria_core::generated::{ execution::v1alpha2::{ - execution_service_server::{ExecutionService, ExecutionServiceServer}, - BatchGetBlocksRequest, BatchGetBlocksResponse, Block, CommitmentState, ExecuteBlockRequest, - GenesisInfo, GetBlockRequest, GetCommitmentStateRequest, GetGenesisInfoRequest, + execution_service_server::{ + ExecutionService, + ExecutionServiceServer, + }, + BatchGetBlocksRequest, + BatchGetBlocksResponse, + Block, + CommitmentState, + ExecuteBlockRequest, + GenesisInfo, + GetBlockRequest, + GetCommitmentStateRequest, + GetGenesisInfoRequest, UpdateCommitmentStateRequest, }, sequencerblock::v1alpha1::{ - sequencer_service_server::{SequencerService, SequencerServiceServer}, - FilteredSequencerBlock, GetFilteredSequencerBlockRequest, GetPendingNonceRequest, - GetPendingNonceResponse, GetSequencerBlockRequest, SequencerBlock, + sequencer_service_server::{ + SequencerService, + SequencerServiceServer, + }, + FilteredSequencerBlock, + GetFilteredSequencerBlockRequest, + GetPendingNonceRequest, + GetPendingNonceResponse, + GetSequencerBlockRequest, + SequencerBlock, }, }; -use astria_eyre::eyre::{self, WrapErr as _}; +use astria_eyre::eyre::{ + self, + WrapErr as _, +}; use astria_grpc_mock::MockServer; use tokio::task::JoinHandle; -use tonic::{transport::Server, Request, Response}; +use tonic::{ + transport::Server, + Request, + Response, +}; pub struct MockGrpc { pub _server: JoinHandle>, @@ -59,7 +86,9 @@ struct SequencerServiceImpl { impl SequencerServiceImpl { fn new(mock_server: MockServer) -> Self { - Self { mock_server } + Self { + mock_server, + } } } diff --git a/crates/astria-conductor/tests/blackbox/helpers/mod.rs b/crates/astria-conductor/tests/blackbox/helpers/mod.rs index 2e8acbc55..66f415c2b 100644 --- a/crates/astria-conductor/tests/blackbox/helpers/mod.rs +++ b/crates/astria-conductor/tests/blackbox/helpers/mod.rs @@ -1,19 +1,35 @@ use std::time::Duration; -use astria_conductor::{conductor, config::CommitLevel, Conductor, Config}; +use astria_conductor::{ + conductor, + config::CommitLevel, + Conductor, + Config, +}; use astria_core::{ brotli::compress_bytes, generated::{ - execution::v1alpha2::{Block, CommitmentState, GenesisInfo}, + execution::v1alpha2::{ + Block, + CommitmentState, + GenesisInfo, + }, sequencerblock::v1alpha1::FilteredSequencerBlock, }, primitive::v1::RollupId, }; use bytes::Bytes; -use celestia_types::{nmt::Namespace, Blob}; +use celestia_types::{ + nmt::Namespace, + Blob, +}; use once_cell::sync::Lazy; use prost::Message; -use sequencer_client::{tendermint, tendermint_proto, tendermint_rpc}; +use sequencer_client::{ + tendermint, + tendermint_proto, + tendermint_rpc, +}; #[macro_use] mod macros; @@ -107,7 +123,11 @@ impl Drop for TestConductor { impl TestConductor { pub async fn mount_abci_info(&self, latest_block_height: u32) { - use wiremock::{matchers::body_partial_json, Mock, ResponseTemplate}; + use wiremock::{ + matchers::body_partial_json, + Mock, + ResponseTemplate, + }; Mock::given(body_partial_json( json!({"jsonrpc": "2.0", "method": "abci_info", "params": null}), )) @@ -134,7 +154,9 @@ impl TestConductor { block: astria_core::generated::execution::v1alpha2::Block, ) { use astria_grpc_mock::{ - matcher::message_partial_pbjson, response::constant_response, Mock, + matcher::message_partial_pbjson, + response::constant_response, + Mock, }; Mock::for_rpc_given("get_block", message_partial_pbjson(&expected_pbjson)) .respond_with(constant_response(block)) @@ -151,8 +173,13 @@ impl TestConductor { ) { use base64::prelude::*; use wiremock::{ - matchers::{body_partial_json, header}, - Mock, Request, ResponseTemplate, + matchers::{ + body_partial_json, + header, + }, + Mock, + Request, + ResponseTemplate, }; let namespace_params = BASE64_STANDARD.encode(namespace.as_bytes()); Mock::given(body_partial_json(json!({ @@ -183,8 +210,12 @@ impl TestConductor { extended_header: celestia_types::ExtendedHeader, ) { use wiremock::{ - matchers::{body_partial_json, header}, - Mock, ResponseTemplate, + matchers::{ + body_partial_json, + header, + }, + Mock, + ResponseTemplate, }; Mock::given(body_partial_json( json!({"jsonrpc": "2.0", "method": "header.NetworkHead"}), @@ -207,7 +238,11 @@ impl TestConductor { &self, signed_header: tendermint::block::signed_header::SignedHeader, ) { - use wiremock::{matchers::body_partial_json, Mock, ResponseTemplate}; + use wiremock::{ + matchers::body_partial_json, + Mock, + ResponseTemplate, + }; Mock::given(body_partial_json(json!({ "jsonrpc": "2.0", "method": "commit", @@ -232,13 +267,20 @@ impl TestConductor { pub async fn mount_genesis(&self) { use tendermint::{ consensus::{ - params::{AbciParams, ValidatorParams}, + params::{ + AbciParams, + ValidatorParams, + }, Params, }, genesis::Genesis, time::Time, }; - use wiremock::{matchers::body_partial_json, Mock, ResponseTemplate}; + use wiremock::{ + matchers::body_partial_json, + Mock, + ResponseTemplate, + }; Mock::given(body_partial_json( json!({"jsonrpc": "2.0", "method": "genesis", "params": null}), )) @@ -318,7 +360,9 @@ impl TestConductor { response: Block, ) -> astria_grpc_mock::MockGuard { use astria_grpc_mock::{ - matcher::message_partial_pbjson, response::constant_response, Mock, + matcher::message_partial_pbjson, + response::constant_response, + Mock, }; let mut mock = Mock::for_rpc_given("execute_block", message_partial_pbjson(&expected_pbjson)) @@ -337,7 +381,9 @@ impl TestConductor { response: FilteredSequencerBlock, ) { use astria_grpc_mock::{ - matcher::message_partial_pbjson, response::constant_response, Mock, + matcher::message_partial_pbjson, + response::constant_response, + Mock, }; Mock::for_rpc_given( "get_filtered_sequencer_block", @@ -356,7 +402,9 @@ impl TestConductor { ) -> astria_grpc_mock::MockGuard { use astria_core::generated::execution::v1alpha2::UpdateCommitmentStateRequest; use astria_grpc_mock::{ - matcher::message_partial_pbjson, response::constant_response, Mock, + matcher::message_partial_pbjson, + response::constant_response, + Mock, }; let mut mock = Mock::for_rpc_given( "update_commitment_state", @@ -377,7 +425,11 @@ impl TestConductor { &self, validator_set: tendermint_rpc::endpoint::validators::Response, ) { - use wiremock::{matchers::body_partial_json, Mock, ResponseTemplate}; + use wiremock::{ + matchers::body_partial_json, + Mock, + ResponseTemplate, + }; Mock::given(body_partial_json(json!({ "jsonrpc": "2.0", "method": "validators", @@ -452,7 +504,8 @@ pub struct Blobs { #[must_use] pub fn make_blobs(heights: &[u32]) -> Blobs { use astria_core::generated::sequencerblock::v1alpha1::{ - SubmittedMetadataList, SubmittedRollupDataList, + SubmittedMetadataList, + SubmittedRollupDataList, }; let mut metadata = Vec::new(); let mut rollup_data = Vec::new(); @@ -466,7 +519,9 @@ pub fn make_blobs(heights: &[u32]) -> Blobs { ); rollup_data.push(tail.swap_remove(0).into_raw()); } - let header_list = SubmittedMetadataList { entries: metadata }; + let header_list = SubmittedMetadataList { + entries: metadata, + }; let rollup_data_list = SubmittedRollupDataList { entries: rollup_data, }; @@ -479,11 +534,17 @@ pub fn make_blobs(heights: &[u32]) -> Blobs { let rollup_data_list_compressed = compress_bytes(&raw_rollup_data_list).unwrap(); let rollup = Blob::new(rollup_namespace(), rollup_data_list_compressed).unwrap(); - Blobs { header, rollup } + Blobs { + header, + rollup, + } } fn signing_key() -> astria_core::crypto::SigningKey { - use rand_chacha::{rand_core::SeedableRng as _, ChaChaRng}; + use rand_chacha::{ + rand_core::SeedableRng as _, + ChaChaRng, + }; astria_core::crypto::SigningKey::new(ChaChaRng::seed_from_u64(0)) } @@ -547,7 +608,10 @@ pub fn make_commit(height: u32) -> tendermint::block::Commit { pub fn make_signed_header(height: u32) -> tendermint::block::signed_header::SignedHeader { tendermint::block::signed_header::SignedHeader::new( tendermint::block::Header { - version: tendermint::block::header::Version { block: 1, app: 1 }, + version: tendermint::block::header::Version { + block: 1, + app: 1, + }, chain_id: crate::SEQUENCER_CHAIN_ID.try_into().unwrap(), height: height.into(), time: tendermint::time::Time::from_unix_timestamp(1, 1).unwrap(), diff --git a/crates/astria-conductor/tests/blackbox/main.rs b/crates/astria-conductor/tests/blackbox/main.rs index 3cef4d228..ad73c9344 100644 --- a/crates/astria-conductor/tests/blackbox/main.rs +++ b/crates/astria-conductor/tests/blackbox/main.rs @@ -6,4 +6,9 @@ pub mod shutdown; pub mod soft_and_firm; pub mod soft_only; -use helpers::{rollup_namespace, sequencer_namespace, ROLLUP_ID, SEQUENCER_CHAIN_ID}; +use helpers::{ + rollup_namespace, + sequencer_namespace, + ROLLUP_ID, + SEQUENCER_CHAIN_ID, +}; diff --git a/crates/astria-conductor/tests/blackbox/soft_and_firm.rs b/crates/astria-conductor/tests/blackbox/soft_and_firm.rs index 1539676ab..0dacd4af5 100644 --- a/crates/astria-conductor/tests/blackbox/soft_and_firm.rs +++ b/crates/astria-conductor/tests/blackbox/soft_and_firm.rs @@ -1,14 +1,25 @@ use std::time::Duration; use astria_conductor::config::CommitLevel; -use futures::future::{join, join3}; +use futures::future::{ + join, + join3, +}; use tokio::time::timeout; use crate::{ - helpers::spawn_conductor, mount_abci_info, mount_celestia_blobs, - mount_celestia_header_network_head, mount_executed_block, mount_get_block, - mount_get_commitment_state, mount_get_filtered_sequencer_block, mount_get_genesis_info, - mount_sequencer_commit, mount_sequencer_genesis, mount_sequencer_validator_set, + helpers::spawn_conductor, + mount_abci_info, + mount_celestia_blobs, + mount_celestia_header_network_head, + mount_executed_block, + mount_get_block, + mount_get_commitment_state, + mount_get_filtered_sequencer_block, + mount_get_genesis_info, + mount_sequencer_commit, + mount_sequencer_genesis, + mount_sequencer_validator_set, mount_update_commitment_state, }; diff --git a/crates/astria-conductor/tests/blackbox/soft_only.rs b/crates/astria-conductor/tests/blackbox/soft_only.rs index 985249ae9..4795979f2 100644 --- a/crates/astria-conductor/tests/blackbox/soft_only.rs +++ b/crates/astria-conductor/tests/blackbox/soft_only.rs @@ -1,12 +1,20 @@ use std::time::Duration; use astria_conductor::config::CommitLevel; -use futures::future::{join, join4}; +use futures::future::{ + join, + join4, +}; use tokio::time::timeout; use crate::{ - helpers::spawn_conductor, mount_abci_info, mount_executed_block, mount_get_commitment_state, - mount_get_filtered_sequencer_block, mount_get_genesis_info, mount_update_commitment_state, + helpers::spawn_conductor, + mount_abci_info, + mount_executed_block, + mount_get_commitment_state, + mount_get_filtered_sequencer_block, + mount_get_genesis_info, + mount_update_commitment_state, }; #[tokio::test(flavor = "multi_thread", worker_threads = 1)] diff --git a/crates/astria-config/src/lib.rs b/crates/astria-config/src/lib.rs index 1f6f8cfdd..86b488ae8 100644 --- a/crates/astria-config/src/lib.rs +++ b/crates/astria-config/src/lib.rs @@ -69,7 +69,9 @@ impl std::error::Error for Error { impl From for Error { fn from(inner: figment::Error) -> Self { - Self { inner } + Self { + inner, + } } } @@ -126,7 +128,10 @@ pub trait Config: ::core::fmt::Debug + DeserializeOwned { prefix: &str, _internal: _internal::Internal, ) -> Result { - use figment::{providers::Env as FigmentEnv, Figment}; + use figment::{ + providers::Env as FigmentEnv, + Figment, + }; Figment::new() .merge(FigmentEnv::prefixed("RUST_").split("_").only(&["log"])) .merge(FigmentEnv::prefixed(prefix)) diff --git a/crates/astria-config/src/tests.rs b/crates/astria-config/src/tests.rs index df3c3a1c5..6411f4881 100644 --- a/crates/astria-config/src/tests.rs +++ b/crates/astria-config/src/tests.rs @@ -33,10 +33,16 @@ use figment::Jail; use once_cell::sync::Lazy; use regex::Regex; -use crate::{Config, _internal}; +use crate::{ + Config, + _internal, +}; static TEST_PREFIX: Lazy = Lazy::new(|| { - use names::{Generator, Name}; + use names::{ + Generator, + Name, + }; Generator::with_naming(Name::Numbered).next().unwrap() }); diff --git a/crates/astria-core/src/brotli.rs b/crates/astria-core/src/brotli.rs index 5961241c5..211e75bc4 100644 --- a/crates/astria-core/src/brotli.rs +++ b/crates/astria-core/src/brotli.rs @@ -1,6 +1,10 @@ use std::io::Write as _; -use brotli::{enc::BrotliEncoderParams, CompressorWriter, DecompressorWriter}; +use brotli::{ + enc::BrotliEncoderParams, + CompressorWriter, + DecompressorWriter, +}; const BROTLI_BUFFER_SIZE: usize = 4096; diff --git a/crates/astria-core/src/celestia.rs b/crates/astria-core/src/celestia.rs index 22f3179f3..9fc448c52 100644 --- a/crates/astria-core/src/celestia.rs +++ b/crates/astria-core/src/celestia.rs @@ -28,6 +28,9 @@ pub const fn namespace_v0_from_rollup_id(rollup_id: crate::primitive::v1::Rollup /// `bytes`. #[must_use = "a celestia namespace must be used in order to be useful"] pub fn namespace_v0_from_sha256_of_bytes>(bytes: T) -> Namespace { - use sha2::{Digest as _, Sha256}; + use sha2::{ + Digest as _, + Sha256, + }; namespace_v0_from_first_10_bytes(&Sha256::digest(bytes)) } diff --git a/crates/astria-core/src/crypto.rs b/crates/astria-core/src/crypto.rs index 35e8674e6..2c1b6a98e 100644 --- a/crates/astria-core/src/crypto.rs +++ b/crates/astria-core/src/crypto.rs @@ -1,20 +1,46 @@ use std::{ cmp::Ordering, - fmt::{self, Debug, Display, Formatter}, - hash::{Hash, Hasher}, + fmt::{ + self, + Debug, + Display, + Formatter, + }, + hash::{ + Hash, + Hasher, + }, sync::OnceLock, }; -use base64::{display::Base64Display, prelude::BASE64_STANDARD, Engine}; +use base64::{ + display::Base64Display, + prelude::BASE64_STANDARD, + Engine, +}; use ed25519_consensus::{ - Error as Ed25519Error, Signature as Ed25519Signature, SigningKey as Ed25519SigningKey, + Error as Ed25519Error, + Signature as Ed25519Signature, + SigningKey as Ed25519SigningKey, VerificationKey as Ed25519VerificationKey, }; -use rand::{CryptoRng, RngCore}; -use sha2::{Digest as _, Sha256}; -use zeroize::{Zeroize, ZeroizeOnDrop}; +use rand::{ + CryptoRng, + RngCore, +}; +use sha2::{ + Digest as _, + Sha256, +}; +use zeroize::{ + Zeroize, + ZeroizeOnDrop, +}; -use crate::primitive::v1::{Address, ADDRESS_LEN}; +use crate::primitive::v1::{ + Address, + ADDRESS_LEN, +}; /// An Ed25519 signing key. // *Implementation note*: this is currently a refinement type around diff --git a/crates/astria-core/src/execution/v1alpha2/mod.rs b/crates/astria-core/src/execution/v1alpha2/mod.rs index ef7131a97..9e646cf14 100644 --- a/crates/astria-core/src/execution/v1alpha2/mod.rs +++ b/crates/astria-core/src/execution/v1alpha2/mod.rs @@ -3,7 +3,10 @@ use pbjson_types::Timestamp; use crate::{ generated::execution::v1alpha2 as raw, - primitive::v1::{IncorrectRollupIdLength, RollupId}, + primitive::v1::{ + IncorrectRollupIdLength, + RollupId, + }, Protobuf, }; @@ -320,7 +323,11 @@ impl CommitmentStateBuilder CommitmentStateBuilder { - let Self { firm, soft, .. } = self; + let Self { + firm, + soft, + .. + } = self; CommitmentStateBuilder { firm, soft, diff --git a/crates/astria-core/src/primitive/v1/asset.rs b/crates/astria-core/src/primitive/v1/asset.rs index 31cdad242..3415d8ec8 100644 --- a/crates/astria-core/src/primitive/v1/asset.rs +++ b/crates/astria-core/src/primitive/v1/asset.rs @@ -1,6 +1,9 @@ use std::{ fmt, - fmt::{Display, Formatter}, + fmt::{ + Display, + Formatter, + }, }; /// The default sequencer asset base denomination. @@ -172,7 +175,10 @@ impl AsRef<[u8]> for Id { impl Display for Id { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - use base64::{display::Base64Display, prelude::BASE64_STANDARD}; + use base64::{ + display::Base64Display, + prelude::BASE64_STANDARD, + }; Base64Display::new(self.as_ref(), &BASE64_STANDARD).fmt(f) } } diff --git a/crates/astria-core/src/primitive/v1/mod.rs b/crates/astria-core/src/primitive/v1/mod.rs index 1077d2f94..944d6e40b 100644 --- a/crates/astria-core/src/primitive/v1/mod.rs +++ b/crates/astria-core/src/primitive/v1/mod.rs @@ -1,10 +1,19 @@ pub mod asset; pub mod u128; -use base64::{display::Base64Display, prelude::BASE64_STANDARD}; -use sha2::{Digest as _, Sha256}; - -use crate::{generated::primitive::v1 as raw, Protobuf}; +use base64::{ + display::Base64Display, + prelude::BASE64_STANDARD, +}; +use sha2::{ + Digest as _, + Sha256, +}; + +use crate::{ + generated::primitive::v1 as raw, + Protobuf, +}; pub const ADDRESS_LEN: usize = 20; pub const ROLLUP_ID_LEN: usize = 32; @@ -91,7 +100,9 @@ impl RollupId { /// ``` #[must_use] pub const fn new(inner: [u8; ROLLUP_ID_LEN]) -> Self { - Self { inner } + Self { + inner, + } } /// Returns the 32 bytes array representing the rollup ID. @@ -200,13 +211,17 @@ impl AsRef<[u8]> for RollupId { impl From<[u8; ROLLUP_ID_LEN]> for RollupId { fn from(inner: [u8; ROLLUP_ID_LEN]) -> Self { - Self { inner } + Self { + inner, + } } } impl From<&[u8; ROLLUP_ID_LEN]> for RollupId { fn from(inner: &[u8; ROLLUP_ID_LEN]) -> Self { - Self { inner: *inner } + Self { + inner: *inner, + } } } @@ -334,7 +349,10 @@ where mod tests { use insta::assert_json_snapshot; - use super::{Address, IncorrectAddressLength}; + use super::{ + Address, + IncorrectAddressLength, + }; #[test] fn account_of_20_bytes_is_converted_correctly() { diff --git a/crates/astria-core/src/primitive/v1/u128.rs b/crates/astria-core/src/primitive/v1/u128.rs index 87439e916..fbfb4208b 100644 --- a/crates/astria-core/src/primitive/v1/u128.rs +++ b/crates/astria-core/src/primitive/v1/u128.rs @@ -3,11 +3,30 @@ use crate::generated::primitive::v1::Uint128; impl From for Uint128 { fn from(primitive: u128) -> Self { - let [h0, h1, h2, h3, h4, h5, h6, h7, l0, l1, l2, l3, l4, l5, l6, l7] = - primitive.to_be_bytes(); + let [ + h0, + h1, + h2, + h3, + h4, + h5, + h6, + h7, + l0, + l1, + l2, + l3, + l4, + l5, + l6, + l7, + ] = primitive.to_be_bytes(); let lo = u64::from_be_bytes([l0, l1, l2, l3, l4, l5, l6, l7]); let hi = u64::from_be_bytes([h0, h1, h2, h3, h4, h5, h6, h7]); - Self { lo, hi } + Self { + lo, + hi, + } } } diff --git a/crates/astria-core/src/protocol/abci.rs b/crates/astria-core/src/protocol/abci.rs index 7e4694238..76c7bc8c8 100644 --- a/crates/astria-core/src/protocol/abci.rs +++ b/crates/astria-core/src/protocol/abci.rs @@ -1,4 +1,7 @@ -use std::{borrow::Cow, num::NonZeroU32}; +use std::{ + borrow::Cow, + num::NonZeroU32, +}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[allow(clippy::module_name_repetitions)] diff --git a/crates/astria-core/src/protocol/account/v1alpha1/mod.rs b/crates/astria-core/src/protocol/account/v1alpha1/mod.rs index 1fe51975e..90d6af3d6 100644 --- a/crates/astria-core/src/protocol/account/v1alpha1/mod.rs +++ b/crates/astria-core/src/protocol/account/v1alpha1/mod.rs @@ -12,7 +12,10 @@ impl AssetBalance { /// native [`AssetBalance`]. #[must_use] pub fn from_raw(proto: &raw::AssetBalance) -> Self { - let raw::AssetBalance { denom, balance } = proto; + let raw::AssetBalance { + denom, + balance, + } = proto; Self { denom: Denom::from(denom.to_owned()), balance: balance.map_or(0, Into::into), @@ -35,7 +38,10 @@ impl raw::BalanceResponse { /// protobuf [`raw::BalanceResponse`]. #[must_use] pub fn from_native(native: BalanceResponse) -> Self { - let BalanceResponse { height, balances } = native; + let BalanceResponse { + height, + balances, + } = native; Self { height, balances: balances.into_iter().map(AssetBalance::into_raw).collect(), @@ -68,7 +74,10 @@ impl BalanceResponse { /// Converts a protobuf [`raw::BalanceResponse`] to an astria /// native [`BalanceResponse`]. pub fn from_raw(proto: &raw::BalanceResponse) -> Self { - let raw::BalanceResponse { height, balances } = proto; + let raw::BalanceResponse { + height, + balances, + } = proto; Self { height: *height, balances: balances.iter().map(AssetBalance::from_raw).collect(), @@ -88,8 +97,14 @@ impl raw::NonceResponse { /// astria `NonceResponse`. #[must_use] pub fn from_native(native: NonceResponse) -> Self { - let NonceResponse { height, nonce } = native; - Self { height, nonce } + let NonceResponse { + height, + nonce, + } = native; + Self { + height, + nonce, + } } /// Converts a protobuf [`raw::NonceResponse`] to an astria @@ -119,8 +134,14 @@ impl NonceResponse { /// native [`NonceResponse`]. #[must_use] pub fn from_raw(proto: &raw::NonceResponse) -> Self { - let raw::NonceResponse { height, nonce } = *proto; - Self { height, nonce } + let raw::NonceResponse { + height, + nonce, + } = *proto; + Self { + height, + nonce, + } } /// Converts an astria native [`NonceResponse`] to a @@ -133,7 +154,11 @@ impl NonceResponse { #[cfg(test)] mod tests { - use super::{AssetBalance, BalanceResponse, NonceResponse}; + use super::{ + AssetBalance, + BalanceResponse, + NonceResponse, + }; #[test] fn balance_roundtrip_is_correct() { diff --git a/crates/astria-core/src/protocol/asset/v1alpha1/mod.rs b/crates/astria-core/src/protocol/asset/v1alpha1/mod.rs index a9f6f3df3..9c0fb48c5 100644 --- a/crates/astria-core/src/protocol/asset/v1alpha1/mod.rs +++ b/crates/astria-core/src/protocol/asset/v1alpha1/mod.rs @@ -13,7 +13,10 @@ impl DenomResponse { /// native [`DenomResponse`]. #[must_use] pub fn from_raw(proto: &raw::DenomResponse) -> Self { - let raw::DenomResponse { height, denom } = proto; + let raw::DenomResponse { + height, + denom, + } = proto; Self { height: *height, denom: denom.clone().into(), @@ -33,7 +36,10 @@ impl raw::DenomResponse { /// protobuf [`raw::DenomResponse`]. #[must_use] pub fn from_native(native: DenomResponse) -> Self { - let DenomResponse { height, denom } = native; + let DenomResponse { + height, + denom, + } = native; Self { height, denom: denom.to_string(), diff --git a/crates/astria-core/src/protocol/test_utils.rs b/crates/astria-core/src/protocol/test_utils.rs index 5d13dcdb0..4fa099e20 100644 --- a/crates/astria-core/src/protocol/test_utils.rs +++ b/crates/astria-core/src/protocol/test_utils.rs @@ -6,12 +6,23 @@ use prost::Message as _; use super::{ group_sequence_actions_in_signed_transaction_transactions_by_rollup_id, - transaction::v1alpha1::{action::SequenceAction, TransactionParams, UnsignedTransaction}, + transaction::v1alpha1::{ + action::SequenceAction, + TransactionParams, + UnsignedTransaction, + }, }; use crate::{ crypto::SigningKey, - primitive::v1::{asset::default_native_asset_id, derive_merkle_tree_from_rollup_txs, RollupId}, - sequencerblock::v1alpha1::{block::Deposit, SequencerBlock}, + primitive::v1::{ + asset::default_native_asset_id, + derive_merkle_tree_from_rollup_txs, + RollupId, + }, + sequencerblock::v1alpha1::{ + block::Deposit, + SequencerBlock, + }, }; #[derive(Default)] @@ -53,7 +64,8 @@ impl ConfigureSequencerBlock { use tendermint::Time; use crate::{ - protocol::transaction::v1alpha1::Action, sequencerblock::v1alpha1::block::RollupData, + protocol::transaction::v1alpha1::Action, + sequencerblock::v1alpha1::block::RollupData, }; let Self { diff --git a/crates/astria-core/src/protocol/transaction/v1alpha1/action.rs b/crates/astria-core/src/protocol/transaction/v1alpha1/action.rs index 79c5e5737..04034202a 100644 --- a/crates/astria-core/src/protocol/transaction/v1alpha1/action.rs +++ b/crates/astria-core/src/protocol/transaction/v1alpha1/action.rs @@ -1,5 +1,8 @@ use ibc_types::{ - core::{channel::ChannelId, client::Height as IbcHeight}, + core::{ + channel::ChannelId, + client::Height as IbcHeight, + }, IdentifierError, }; use penumbra_ibc::IbcRelay; @@ -8,8 +11,14 @@ use penumbra_proto::penumbra::core::component::ibc::v1::FungibleTokenPacketData; use super::raw; use crate::{ primitive::v1::{ - asset::{self, Denom}, - Address, IncorrectAddressLength, IncorrectRollupIdLength, RollupId, + asset::{ + self, + Denom, + }, + Address, + IncorrectAddressLength, + IncorrectRollupIdLength, + RollupId, }, Protobuf, }; @@ -48,7 +57,9 @@ impl Action { Action::BridgeUnlock(act) => Value::BridgeUnlockAction(act.into_raw()), Action::FeeChange(act) => Value::FeeChangeAction(act.into_raw()), }; - raw::Action { value: Some(kind) } + raw::Action { + value: Some(kind), + } } #[must_use] @@ -70,7 +81,9 @@ impl Action { Action::BridgeUnlock(act) => Value::BridgeUnlockAction(act.to_raw()), Action::FeeChange(act) => Value::FeeChangeAction(act.to_raw()), }; - raw::Action { value: Some(kind) } + raw::Action { + value: Some(kind), + } } /// Attempt to convert from a raw, unchecked protobuf [`raw::Action`]. @@ -81,7 +94,9 @@ impl Action { /// to a native action ([`SequenceAction`] or [`TransferAction`]) fails. pub fn try_from_raw(proto: raw::Action) -> Result { use raw::action::Value; - let raw::Action { value } = proto; + let raw::Action { + value, + } = proto; let Some(action) = value else { return Err(ActionError::unset()); }; @@ -511,7 +526,9 @@ pub struct SudoAddressChangeAction { impl SudoAddressChangeAction { #[must_use] pub fn into_raw(self) -> raw::SudoAddressChangeAction { - let Self { new_address } = self; + let Self { + new_address, + } = self; raw::SudoAddressChangeAction { new_address: Some(new_address.into_raw()), } @@ -519,7 +536,9 @@ impl SudoAddressChangeAction { #[must_use] pub fn to_raw(&self) -> raw::SudoAddressChangeAction { - let Self { new_address } = self; + let Self { + new_address, + } = self; raw::SudoAddressChangeAction { new_address: Some(new_address.to_raw()), } @@ -534,13 +553,17 @@ impl SudoAddressChangeAction { pub fn try_from_raw( proto: raw::SudoAddressChangeAction, ) -> Result { - let raw::SudoAddressChangeAction { new_address } = proto; + let raw::SudoAddressChangeAction { + new_address, + } = proto; let Some(new_address) = new_address else { return Err(SudoAddressChangeActionError::field_not_set("new_address")); }; let new_address = Address::try_from_raw(&new_address).map_err(SudoAddressChangeActionError::address)?; - Ok(Self { new_address }) + Ok(Self { + new_address, + }) } } diff --git a/crates/astria-core/src/protocol/transaction/v1alpha1/mod.rs b/crates/astria-core/src/protocol/transaction/v1alpha1/mod.rs index 4c87ba8ff..25a0d5dcb 100644 --- a/crates/astria-core/src/protocol/transaction/v1alpha1/mod.rs +++ b/crates/astria-core/src/protocol/transaction/v1alpha1/mod.rs @@ -1,7 +1,15 @@ -use prost::{Message as _, Name as _}; +use prost::{ + Message as _, + Name as _, +}; use super::raw; -use crate::crypto::{self, Signature, SigningKey, VerificationKey}; +use crate::crypto::{ + self, + Signature, + SigningKey, + VerificationKey, +}; pub mod action; pub use action::Action; @@ -74,7 +82,10 @@ impl SignedTransaction { /// and hashing the resulting bytes with sha256. #[must_use] pub fn sha256_of_proto_encoding(&self) -> [u8; 32] { - use sha2::{Digest as _, Sha256}; + use sha2::{ + Digest as _, + Sha256, + }; let bytes = self.to_raw().encode_to_vec(); Sha256::digest(bytes).into() } @@ -220,7 +231,10 @@ impl UnsignedTransaction { } pub fn into_raw(self) -> raw::UnsignedTransaction { - let Self { actions, params } = self; + let Self { + actions, + params, + } = self; let actions = actions.into_iter().map(Action::into_raw).collect(); raw::UnsignedTransaction { actions, @@ -238,7 +252,10 @@ impl UnsignedTransaction { } pub fn to_raw(&self) -> raw::UnsignedTransaction { - let Self { actions, params } = self; + let Self { + actions, + params, + } = self; let actions = actions.iter().map(Action::to_raw).collect(); let params = params.clone().into_raw(); raw::UnsignedTransaction { @@ -259,7 +276,10 @@ impl UnsignedTransaction { /// Returns an error if one of the inner raw actions could not be converted to a native /// [`Action`]. pub fn try_from_raw(proto: raw::UnsignedTransaction) -> Result { - let raw::UnsignedTransaction { actions, params } = proto; + let raw::UnsignedTransaction { + actions, + params, + } = proto; let Some(params) = params else { return Err(UnsignedTransactionError::unset_params()); }; @@ -270,7 +290,10 @@ impl UnsignedTransaction { .collect::>() .map_err(UnsignedTransactionError::action)?; - Ok(Self { actions, params }) + Ok(Self { + actions, + params, + }) } /// Attempt to convert from a protobuf [`pbjson_types::Any`]. @@ -304,7 +327,9 @@ impl UnsignedTransactionError { } fn invalid_type_url(got: String) -> Self { - Self(UnsignedTransactionErrorKind::InvalidTypeUrl { got }) + Self(UnsignedTransactionErrorKind::InvalidTypeUrl { + got, + }) } fn decode_any(inner: prost::DecodeError) -> Self { @@ -341,15 +366,27 @@ pub struct TransactionParams { impl TransactionParams { #[must_use] pub fn into_raw(self) -> raw::TransactionParams { - let Self { nonce, chain_id } = self; - raw::TransactionParams { nonce, chain_id } + let Self { + nonce, + chain_id, + } = self; + raw::TransactionParams { + nonce, + chain_id, + } } /// Convert from a raw protobuf [`raw::UnsignedTransaction`]. #[must_use] pub fn from_raw(proto: raw::TransactionParams) -> Self { - let raw::TransactionParams { nonce, chain_id } = proto; - Self { nonce, chain_id } + let raw::TransactionParams { + nonce, + chain_id, + } = proto; + Self { + nonce, + chain_id, + } } } @@ -357,7 +394,10 @@ impl TransactionParams { mod test { use super::*; use crate::{ - primitive::v1::{asset::default_native_asset_id, Address}, + primitive::v1::{ + asset::default_native_asset_id, + Address, + }, protocol::transaction::v1alpha1::action::TransferAction, }; diff --git a/crates/astria-core/src/sequencerblock/v1alpha1/block.rs b/crates/astria-core/src/sequencerblock/v1alpha1/block.rs index 9b402a05e..90ef2f9bf 100644 --- a/crates/astria-core/src/sequencerblock/v1alpha1/block.rs +++ b/crates/astria-core/src/sequencerblock/v1alpha1/block.rs @@ -2,19 +2,35 @@ use std::collections::HashMap; use indexmap::IndexMap; use sha2::Sha256; -use tendermint::{account, Time}; +use tendermint::{ + account, + Time, +}; use super::{ - are_rollup_ids_included, are_rollup_txs_included, - celestia::{self, SubmittedMetadata, SubmittedRollupData}, + are_rollup_ids_included, + are_rollup_txs_included, + celestia::{ + self, + SubmittedMetadata, + SubmittedRollupData, + }, raw, }; use crate::{ primitive::v1::{ - asset, derive_merkle_tree_from_rollup_txs, Address, IncorrectAddressLength, - IncorrectRollupIdLength, RollupId, + asset, + derive_merkle_tree_from_rollup_txs, + Address, + IncorrectAddressLength, + IncorrectRollupIdLength, + RollupId, + }, + protocol::transaction::v1alpha1::{ + action, + SignedTransaction, + SignedTransactionError, }, - protocol::transaction::v1alpha1::{action, SignedTransaction, SignedTransactionError}, Protobuf as _, }; @@ -1208,7 +1224,11 @@ impl FilteredSequencerBlockError { } fn rollup_transaction_for_id_not_in_sequencer_block(id: RollupId) -> Self { - Self(FilteredSequencerBlockErrorKind::RollupTransactionForIdNotInSequencerBlock { id }) + Self( + FilteredSequencerBlockErrorKind::RollupTransactionForIdNotInSequencerBlock { + id, + }, + ) } fn rollup_ids_not_in_sequencer_block() -> Self { @@ -1422,7 +1442,9 @@ impl RollupData { /// - if the `data` field is not set /// - if the variant is `Deposit` but a `Deposit` cannot be constructed from the raw proto pub fn try_from_raw(raw: raw::RollupData) -> Result { - let raw::RollupData { value } = raw; + let raw::RollupData { + value, + } = raw; match value { Some(raw::rollup_data::Value::SequencedData(data)) => Ok(Self::SequencedData(data)), Some(raw::rollup_data::Value::Deposit(deposit)) => Deposit::try_from_raw(deposit) diff --git a/crates/astria-core/src/sequencerblock/v1alpha1/celestia.rs b/crates/astria-core/src/sequencerblock/v1alpha1/celestia.rs index e880e30d2..512ed4df2 100644 --- a/crates/astria-core/src/sequencerblock/v1alpha1/celestia.rs +++ b/crates/astria-core/src/sequencerblock/v1alpha1/celestia.rs @@ -1,10 +1,18 @@ -use sha2::{Digest as _, Sha256}; +use sha2::{ + Digest as _, + Sha256, +}; use super::{ block::{ - RollupTransactionsParts, SequencerBlock, SequencerBlockHeader, SequencerBlockHeaderError, + RollupTransactionsParts, + SequencerBlock, + SequencerBlockHeader, + SequencerBlockHeaderError, }, - raw, IncorrectRollupIdLength, RollupId, + raw, + IncorrectRollupIdLength, + RollupId, }; use crate::Protobuf; @@ -50,7 +58,10 @@ impl PreparedBlock { proof, }); } - Self { head, tail } + Self { + head, + tail, + } } /// Returns the head and the tail of the split block, consuming it. @@ -70,19 +81,25 @@ pub struct SubmittedRollupDataError { impl SubmittedRollupDataError { fn field_not_set(field: &'static str) -> Self { Self { - kind: SubmittedRollupDataErrorKind::FieldNotSet { field }, + kind: SubmittedRollupDataErrorKind::FieldNotSet { + field, + }, } } fn rollup_id(source: IncorrectRollupIdLength) -> Self { Self { - kind: SubmittedRollupDataErrorKind::RollupId { source }, + kind: SubmittedRollupDataErrorKind::RollupId { + source, + }, } } fn proof(source: ::Error) -> Self { Self { - kind: SubmittedRollupDataErrorKind::Proof { source }, + kind: SubmittedRollupDataErrorKind::Proof { + source, + }, } } @@ -276,7 +293,9 @@ impl SubmittedMetadataError { fn header(source: SequencerBlockHeaderError) -> Self { Self { - kind: SubmittedMetadataErrorKind::Header { source }, + kind: SubmittedMetadataErrorKind::Header { + source, + }, } } @@ -288,19 +307,25 @@ impl SubmittedMetadataError { fn rollup_ids(source: IncorrectRollupIdLength) -> Self { Self { - kind: SubmittedMetadataErrorKind::RollupIds { source }, + kind: SubmittedMetadataErrorKind::RollupIds { + source, + }, } } fn rollup_transactions_proof(source: ::Error) -> Self { Self { - kind: SubmittedMetadataErrorKind::RollupTransactionsProof { source }, + kind: SubmittedMetadataErrorKind::RollupTransactionsProof { + source, + }, } } fn rollup_ids_proof(source: ::Error) -> Self { Self { - kind: SubmittedMetadataErrorKind::RollupIdsProof { source }, + kind: SubmittedMetadataErrorKind::RollupIdsProof { + source, + }, } } diff --git a/crates/astria-core/src/sequencerblock/v1alpha1/mod.rs b/crates/astria-core/src/sequencerblock/v1alpha1/mod.rs index 22de5e548..62487151c 100644 --- a/crates/astria-core/src/sequencerblock/v1alpha1/mod.rs +++ b/crates/astria-core/src/sequencerblock/v1alpha1/mod.rs @@ -1,14 +1,27 @@ pub mod block; pub mod celestia; -pub use block::{RollupTransactions, SequencerBlock}; -pub use celestia::{SubmittedMetadata, SubmittedRollupData}; +pub use block::{ + RollupTransactions, + SequencerBlock, +}; +pub use celestia::{ + SubmittedMetadata, + SubmittedRollupData, +}; use indexmap::IndexMap; -use sha2::{Digest as _, Sha256}; +use sha2::{ + Digest as _, + Sha256, +}; use crate::{ generated::sequencerblock::v1alpha1 as raw, - primitive::v1::{derive_merkle_tree_from_rollup_txs, IncorrectRollupIdLength, RollupId}, + primitive::v1::{ + derive_merkle_tree_from_rollup_txs, + IncorrectRollupIdLength, + RollupId, + }, }; pub(crate) fn are_rollup_ids_included<'a, TRollupIds: 'a>( diff --git a/crates/astria-eyre/src/lib.rs b/crates/astria-eyre/src/lib.rs index ee4d14e19..a28cd48d1 100644 --- a/crates/astria-eyre/src/lib.rs +++ b/crates/astria-eyre/src/lib.rs @@ -1,6 +1,9 @@ #![doc = include_str!("../README.md")] -use std::{error::Error, fmt::Write as _}; +use std::{ + error::Error, + fmt::Write as _, +}; pub use eyre; #[doc(hidden)] diff --git a/crates/astria-grpc-mock-test/tests/health/main.rs b/crates/astria-grpc-mock-test/tests/health/main.rs index 8bb1d43e7..beaef29db 100644 --- a/crates/astria-grpc-mock-test/tests/health/main.rs +++ b/crates/astria-grpc-mock-test/tests/health/main.rs @@ -1,17 +1,40 @@ // allow just make the tests work for now #![allow(clippy::should_panic_without_expect)] -use std::{net::SocketAddr, pin::Pin, sync::Arc}; +use std::{ + net::SocketAddr, + pin::Pin, + sync::Arc, +}; -use astria_grpc_mock::{matcher, response, Mock}; +use astria_grpc_mock::{ + matcher, + response, + Mock, +}; use astria_grpc_mock_test::health::{ health_client::HealthClient, - health_server::{Health, HealthServer}, - HealthCheckRequest, HealthCheckResponse, + health_server::{ + Health, + HealthServer, + }, + HealthCheckRequest, + HealthCheckResponse, +}; +use tokio::{ + join, + task::JoinHandle, +}; +use tokio_stream::{ + wrappers::TcpListenerStream, + Stream, +}; +use tonic::{ + transport::Server, + Request, + Response, + Status, }; -use tokio::{join, task::JoinHandle}; -use tokio_stream::{wrappers::TcpListenerStream, Stream}; -use tonic::{transport::Server, Request, Response, Status}; struct MockServer { _server: JoinHandle<()>, @@ -27,7 +50,9 @@ async fn start_mock_server() -> MockServer { let mock_server = mock_server.clone(); async move { let _ = Server::builder() - .add_service(HealthServer::new(HealthService { mock_server })) + .add_service(HealthServer::new(HealthService { + mock_server, + })) .serve_with_incoming(TcpListenerStream::new(listener)) .await; } @@ -87,7 +112,9 @@ async fn constant_response_works() { let mut client = HealthClient::connect(format!("http://{}", server.local_addr)) .await .unwrap(); - let expected_response = HealthCheckResponse { status: 1 }; + let expected_response = HealthCheckResponse { + status: 1, + }; let mock = Mock::for_rpc_given("check", matcher::message_type::()) .respond_with(response::constant_response(expected_response.clone())); server.mocked.register(mock).await; @@ -106,7 +133,9 @@ async fn constant_response_expect_two_works() { let mut client = HealthClient::connect(format!("http://{}", server.local_addr)) .await .unwrap(); - let expected_response = HealthCheckResponse { status: 1 }; + let expected_response = HealthCheckResponse { + status: 1, + }; let mock = Mock::for_rpc_given("check", matcher::message_type::()) .respond_with(response::constant_response(expected_response.clone())) .expect(2); @@ -139,7 +168,9 @@ async fn constant_response_guard_works() { let mut client = HealthClient::connect(format!("http://{}", server.local_addr)) .await .unwrap(); - let expected_response = HealthCheckResponse { status: 1 }; + let expected_response = HealthCheckResponse { + status: 1, + }; let mock = Mock::for_rpc_given("check", matcher::message_type::()) .respond_with(response::constant_response(expected_response.clone())) .expect(1); @@ -163,7 +194,9 @@ async fn exact_pbjson_match_works() { let expected_request = HealthCheckRequest { service: "helloworld".to_string(), }; - let expected_response = HealthCheckResponse { status: 1 }; + let expected_response = HealthCheckResponse { + status: 1, + }; let mock = Mock::for_rpc_given("check", matcher::message_exact_pbjson(&expected_request)) .respond_with(response::constant_response(expected_response.clone())); server.mocked.register(mock).await; @@ -185,7 +218,9 @@ async fn partial_pbjson_match_works() { let expected_request = HealthCheckRequest { service: "helloworld".to_string(), }; - let expected_response = HealthCheckResponse { status: 1 }; + let expected_response = HealthCheckResponse { + status: 1, + }; // FIXME: Right now this is equivalent to an exact check because the request only has one field. let mock = Mock::for_rpc_given("check", matcher::message_partial_pbjson(&expected_request)) .respond_with(response::constant_response(expected_response.clone())); diff --git a/crates/astria-grpc-mock/src/lib.rs b/crates/astria-grpc-mock/src/lib.rs index 813c494bc..c709515f2 100644 --- a/crates/astria-grpc-mock/src/lib.rs +++ b/crates/astria-grpc-mock/src/lib.rs @@ -16,8 +16,14 @@ mod mounted_mock; pub mod response; mod verification; -pub use mock::{Match, Mock}; -pub use mock_server::{MockGuard, MockServer}; +pub use mock::{ + Match, + Mock, +}; +pub use mock_server::{ + MockGuard, + MockServer, +}; pub use response::Respond; pub type AnyMessage = Box; diff --git a/crates/astria-grpc-mock/src/matcher.rs b/crates/astria-grpc-mock/src/matcher.rs index 9b5301128..e6ba265f0 100644 --- a/crates/astria-grpc-mock/src/matcher.rs +++ b/crates/astria-grpc-mock/src/matcher.rs @@ -1,6 +1,9 @@ use std::any::TypeId; -use assert_json_diff::{assert_json_matches_no_panic, CompareMode}; +use assert_json_diff::{ + assert_json_matches_no_panic, + CompareMode, +}; use serde_json::Value; use crate::mock::Match; diff --git a/crates/astria-grpc-mock/src/mock.rs b/crates/astria-grpc-mock/src/mock.rs index 1053df657..f0a7ff3e1 100644 --- a/crates/astria-grpc-mock/src/mock.rs +++ b/crates/astria-grpc-mock/src/mock.rs @@ -1,9 +1,21 @@ use std::ops::{ - Range, RangeBounds as _, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, + Range, + RangeBounds as _, + RangeFrom, + RangeFull, + RangeInclusive, + RangeTo, + RangeToInclusive, }; -use super::{response::Respond, AnyMessage}; -use crate::{mock_server::MockGuard, MockServer}; +use super::{ + response::Respond, + AnyMessage, +}; +use crate::{ + mock_server::MockGuard, + MockServer, +}; pub trait Match: Send + Sync { fn matches(&self, req: &tonic::Request) -> bool; @@ -75,7 +87,10 @@ impl MockBuilder { } pub fn respond_with(self, rsp: impl Respond + 'static) -> Mock { - let Self { rpc, matchers } = self; + let Self { + rpc, + matchers, + } = self; Mock { rpc, matchers, diff --git a/crates/astria-grpc-mock/src/mock_server.rs b/crates/astria-grpc-mock/src/mock_server.rs index 17f1fdf6b..bd74a5b8b 100644 --- a/crates/astria-grpc-mock/src/mock_server.rs +++ b/crates/astria-grpc-mock/src/mock_server.rs @@ -1,17 +1,26 @@ use std::{ fmt::Write as _, pin::pin, - sync::{atomic::AtomicBool, Arc}, + sync::{ + atomic::AtomicBool, + Arc, + }, }; -use tokio::sync::{Notify, RwLock}; +use tokio::sync::{ + Notify, + RwLock, +}; use tracing::debug; use super::clone_request; use crate::{ erase_request, mock::Mock, - mock_set::{MockId, MockSet}, + mock_set::{ + MockId, + MockSet, + }, verification::VerificationOutcome, AnyRequest, }; @@ -147,7 +156,9 @@ impl MockRequest { impl From for MockRequest { fn from(value: AnyRequest) -> Self { - Self { inner: value } + Self { + inner: value, + } } } diff --git a/crates/astria-grpc-mock/src/mock_set.rs b/crates/astria-grpc-mock/src/mock_set.rs index 0891ce852..341d858a4 100644 --- a/crates/astria-grpc-mock/src/mock_set.rs +++ b/crates/astria-grpc-mock/src/mock_set.rs @@ -1,16 +1,28 @@ use std::{ - ops::{Index, IndexMut}, - sync::{atomic::AtomicBool, Arc}, + ops::{ + Index, + IndexMut, + }, + sync::{ + atomic::AtomicBool, + Arc, + }, }; use tokio::sync::Notify; use tracing::debug; -use super::{mock::Mock, mounted_mock::MountedMock}; +use super::{ + mock::Mock, + mounted_mock::MountedMock, +}; use crate::{ erase_request, mounted_mock::MockResult, - verification::{VerificationOutcome, VerificationReport}, + verification::{ + VerificationOutcome, + VerificationReport, + }, }; #[derive(Debug, PartialEq, Eq, Copy, Clone)] @@ -31,7 +43,9 @@ pub(crate) struct MockSet { impl MockSet { pub(crate) fn new() -> Self { - Self { mocks: Vec::new() } + Self { + mocks: Vec::new(), + } } pub(crate) fn handle_request< diff --git a/crates/astria-grpc-mock/src/mounted_mock.rs b/crates/astria-grpc-mock/src/mounted_mock.rs index a07c46e80..efd14f52a 100644 --- a/crates/astria-grpc-mock/src/mounted_mock.rs +++ b/crates/astria-grpc-mock/src/mounted_mock.rs @@ -1,15 +1,24 @@ -use std::sync::{atomic::AtomicBool, Arc}; +use std::sync::{ + atomic::AtomicBool, + Arc, +}; use tokio::sync::Notify; use tonic::Request; use super::{ - mock::{Match as _, Mock}, + mock::{ + Match as _, + Mock, + }, response::MockResponse, AnyMessage, }; use crate::{ - clone_request, clone_response, response::ResponseResult, verification::VerificationReport, + clone_request, + clone_response, + response::ResponseResult, + verification::VerificationReport, }; pub(crate) enum MockResult { diff --git a/crates/astria-grpc-mock/src/response.rs b/crates/astria-grpc-mock/src/response.rs index 9d54e20a8..3e05e669d 100644 --- a/crates/astria-grpc-mock/src/response.rs +++ b/crates/astria-grpc-mock/src/response.rs @@ -1,6 +1,9 @@ use std::marker::PhantomData; -use super::{clone_response, AnyMessage}; +use super::{ + clone_response, + AnyMessage, +}; use crate::erase_response; pub fn constant_response< diff --git a/crates/astria-grpc-mock/src/verification.rs b/crates/astria-grpc-mock/src/verification.rs index 51c9dfb94..81c49f63c 100644 --- a/crates/astria-grpc-mock/src/verification.rs +++ b/crates/astria-grpc-mock/src/verification.rs @@ -1,6 +1,9 @@ use std::fmt::Write as _; -use crate::{mock::Times, mounted_mock::BadResponse}; +use crate::{ + mock::Times, + mounted_mock::BadResponse, +}; /// A report returned by an `MountedMock` detailing what the user expectations were and /// how many calls were actually received since the mock was mounted on the server. diff --git a/crates/astria-merkle/src/audit.rs b/crates/astria-merkle/src/audit.rs index fb09be7b4..4ab383cbd 100644 --- a/crates/astria-merkle/src/audit.rs +++ b/crates/astria-merkle/src/audit.rs @@ -2,7 +2,10 @@ use std::num::NonZeroUsize; -use sha2::{Digest as _, Sha256}; +use sha2::{ + Digest as _, + Sha256, +}; /// Builder to construct a complex leaf ad-hoc without allocation. /// @@ -18,12 +21,19 @@ impl<'a, TLeaf, TRoot> LeafBuilder<'a, TLeaf, TRoot> { /// Returns the internal [`Audit`] with its `TLeaf` typestate set. pub fn finish_leaf(self) -> Audit<'a, WithLeafHash, TRoot> { let Self { - audit: Audit { proof, root, .. }, + audit: + Audit { + proof, + root, + .. + }, hasher, } = self; let leaf_hash = hasher.finalize().into(); Audit { - leaf_hash: WithLeafHash { leaf_hash }, + leaf_hash: WithLeafHash { + leaf_hash, + }, proof, root, } @@ -97,8 +107,14 @@ impl<'a, TLeaf, TRoot> Audit<'a, TLeaf, TRoot> { /// /// Returns a new `Audit` with its `TLeaf` type-state to [`WithLeafHash`]. pub fn with_leaf_hash(self, leaf_hash: [u8; 32]) -> Audit<'a, WithLeafHash, TRoot> { - let Self { proof, root, .. } = self; - let leaf_hash = WithLeafHash { leaf_hash }; + let Self { + proof, + root, + .. + } = self; + let leaf_hash = WithLeafHash { + leaf_hash, + }; Audit { leaf_hash, proof, @@ -111,12 +127,16 @@ impl<'a, TLeaf, TRoot> Audit<'a, TLeaf, TRoot> { /// Returns a new `Audit` with its `TRoot` type-state to [`WithRoot`]. pub fn with_root(self, root: [u8; 32]) -> Audit<'a, TLeaf, WithRoot> { let Self { - proof, leaf_hash, .. + proof, + leaf_hash, + .. } = self; Audit { leaf_hash, proof, - root: WithRoot { root }, + root: WithRoot { + root, + }, } } } @@ -141,7 +161,9 @@ impl<'a, TRoot> Audit<'a, WithLeafHash, TRoot> { /// ``` pub fn reconstruct_root(&self) -> [u8; 32] { let Self { - leaf_hash: WithLeafHash { leaf_hash }, + leaf_hash: WithLeafHash { + leaf_hash, + }, proof, .. } = self; @@ -181,9 +203,13 @@ impl<'a> Audit<'a, WithLeafHash, WithRoot> { #[must_use = "verify the audit result"] pub fn perform(&self) -> bool { let Self { - leaf_hash: WithLeafHash { leaf_hash }, + leaf_hash: WithLeafHash { + leaf_hash, + }, proof, - root: WithRoot { root }, + root: WithRoot { + root, + }, } = self; *root == proof.reconstruct_root_with_leaf_hash(*leaf_hash) } @@ -197,7 +223,9 @@ pub struct InvalidProof { impl InvalidProof { fn audit_path_not_multiple_of_32(len: usize) -> Self { Self { - kind: InvalidProofKind::AuditPathNotMultipleOf32 { len }, + kind: InvalidProofKind::AuditPathNotMultipleOf32 { + len, + }, } } @@ -244,7 +272,9 @@ enum InvalidProofKind { impl std::fmt::Display for InvalidProofKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - InvalidProofKind::AuditPathNotMultipleOf32 { len } => f.write_fmt(format_args!( + InvalidProofKind::AuditPathNotMultipleOf32 { + len, + } => f.write_fmt(format_args!( "audit path byte buffer length must be a multiple of 32 bytes, but was {len} bytes" )), InvalidProofKind::LeafIndexOutsideTree { @@ -304,7 +334,10 @@ impl UncheckedProof { /// from the proof. #[must_use = "an unchecked proof must be turned into a checked proof to be useful"] pub fn audit_path(self, audit_path: Vec) -> Self { - Self { audit_path, ..self } + Self { + audit_path, + ..self + } } /// Sets the index of the leaf that this proof is for. @@ -314,7 +347,10 @@ impl UncheckedProof { /// to a tree index `j = 2 * i`. #[must_use = "an unchecked proof must be turned into a checked proof to be useful"] pub fn leaf_index(self, leaf_index: usize) -> Self { - Self { leaf_index, ..self } + Self { + leaf_index, + ..self + } } /// Sets the tree size of the proof. @@ -323,7 +359,10 @@ impl UncheckedProof { /// not defined for empty trees. #[must_use = "an unchecked proof must be turned into a checked proof to be useful"] pub fn tree_size(self, tree_size: usize) -> Self { - Self { tree_size, ..self } + Self { + tree_size, + ..self + } } /// Constructs the [`Proof`] from the builder inputs. diff --git a/crates/astria-merkle/src/lib.rs b/crates/astria-merkle/src/lib.rs index a08fad64e..a6e68a724 100644 --- a/crates/astria-merkle/src/lib.rs +++ b/crates/astria-merkle/src/lib.rs @@ -132,13 +132,19 @@ use std::num::NonZeroUsize; -use sha2::{Digest as _, Sha256}; +use sha2::{ + Digest as _, + Sha256, +}; pub mod audit; #[cfg(test)] mod tests; -pub use audit::{Audit, Proof}; +pub use audit::{ + Audit, + Proof, +}; /// Calculates `SHA256(0x00 | leaf)` #[must_use] @@ -225,7 +231,10 @@ impl<'a> LeafBuilder<'a> { impl<'a> Drop for LeafBuilder<'a> { fn drop(&mut self) { - let Self { tree, hasher } = self; + let Self { + tree, + hasher, + } = self; let leaf_hash: [u8; 32] = hasher .take() .expect("hasher is set during the leaf builder's lifetime and only taken on drop") @@ -408,7 +417,9 @@ impl Tree { /// ``` #[must_use] pub fn new() -> Self { - Self { nodes: Vec::new() } + Self { + nodes: Vec::new(), + } } /// Returns the number of nodes in the merkle tree. diff --git a/crates/astria-merkle/src/tests.rs b/crates/astria-merkle/src/tests.rs index 86263fa84..d985298bc 100644 --- a/crates/astria-merkle/src/tests.rs +++ b/crates/astria-merkle/src/tests.rs @@ -1,5 +1,11 @@ -use super::{is_perfect, perfect_root}; -use crate::{complete_parent, complete_parent_and_sibling}; +use super::{ + is_perfect, + perfect_root, +}; +use crate::{ + complete_parent, + complete_parent_and_sibling, +}; #[track_caller] fn assert_is_perfect(n: usize) { diff --git a/crates/astria-sequencer-client/src/extension_trait.rs b/crates/astria-sequencer-client/src/extension_trait.rs index 6e3ec9806..b69da4fa9 100644 --- a/crates/astria-sequencer-client/src/extension_trait.rs +++ b/crates/astria-sequencer-client/src/extension_trait.rs @@ -20,28 +20,45 @@ //! # }); //! ``` -use std::{future, pin::Pin, sync::Arc}; +use std::{ + future, + pin::Pin, + sync::Arc, +}; pub use astria_core::{ primitive::v1::Address, protocol::{ - account::v1alpha1::{BalanceResponse, NonceResponse}, + account::v1alpha1::{ + BalanceResponse, + NonceResponse, + }, transaction::v1alpha1::SignedTransaction, }, - sequencerblock::v1alpha1::{block::SequencerBlockError, SequencerBlock}, + sequencerblock::v1alpha1::{ + block::SequencerBlockError, + SequencerBlock, + }, }; use async_trait::async_trait; use futures::Stream; -use prost::{DecodeError, Message as _}; +use prost::{ + DecodeError, + Message as _, +}; use tendermint::block::Height; #[cfg(feature = "http")] use tendermint_rpc::HttpClient; #[cfg(feature = "websocket")] use tendermint_rpc::WebSocketClient; use tendermint_rpc::{ - endpoint::broadcast::{tx_commit, tx_sync}, + endpoint::broadcast::{ + tx_commit, + tx_sync, + }, event::EventData, - Client, SubscriptionClient, + Client, + SubscriptionClient, }; #[cfg(feature = "http")] @@ -249,7 +266,10 @@ impl ErrorKind { /// Convenience method to construct a `TendermintRpc` variant. fn tendermint_rpc(rpc: &'static str, inner: tendermint_rpc::error::Error) -> Self { - Self::TendermintRpc(TendermintRpcError { inner, rpc }) + Self::TendermintRpc(TendermintRpcError { + inner, + rpc, + }) } } @@ -276,9 +296,15 @@ impl NewBlockStreamError { fn unexpected_event(event: &EventData) -> Self { fn event_to_name(event: &EventData) -> &'static str { match event { - EventData::NewBlock { .. } => "new-block", - EventData::LegacyNewBlock { .. } => "legacy-new-block", - EventData::Tx { .. } => "tx", + EventData::NewBlock { + .. + } => "new-block", + EventData::LegacyNewBlock { + .. + } => "legacy-new-block", + EventData::Tx { + .. + } => "tx", EventData::GenericJsonEvent(_) => "generic-json", } } @@ -321,8 +347,14 @@ impl Stream for LatestHeightStream { #[async_trait] pub trait SequencerSubscriptionClientExt: SubscriptionClient { async fn subscribe_latest_height(&self) -> Result { - use futures::stream::{StreamExt as _, TryStreamExt as _}; - use tendermint_rpc::query::{EventType, Query}; + use futures::stream::{ + StreamExt as _, + TryStreamExt as _, + }; + use tendermint_rpc::query::{ + EventType, + Query, + }; let stream = self .subscribe(Query::from(EventType::NewBlock)) .await? @@ -330,18 +362,21 @@ pub trait SequencerSubscriptionClientExt: SubscriptionClient { .and_then(|event| { future::ready(match event.data { EventData::LegacyNewBlock { - block: Some(block), .. + block: Some(block), + .. } => Ok(block.header.height), - EventData::LegacyNewBlock { block: None, .. } => { - Err(NewBlockStreamError::NoBlock) - } + EventData::LegacyNewBlock { + block: None, .. + } => Err(NewBlockStreamError::NoBlock), other => Err(NewBlockStreamError::unexpected_event(&other)), }) }) .boxed(); - Ok(LatestHeightStream { inner: stream }) + Ok(LatestHeightStream { + inner: stream, + }) } } diff --git a/crates/astria-sequencer-client/src/lib.rs b/crates/astria-sequencer-client/src/lib.rs index 773376913..4f8c018f0 100644 --- a/crates/astria-sequencer-client/src/lib.rs +++ b/crates/astria-sequencer-client/src/lib.rs @@ -4,19 +4,30 @@ pub mod extension_trait; #[cfg(not(any(feature = "http", feature = "websocket")))] compile_error!("at least one of the `http` or `websocket` features must be enabled"); -use std::{future::Future, pin::Pin, time::Duration}; +use std::{ + future::Future, + pin::Pin, + time::Duration, +}; #[cfg(any(feature = "http", feature = "websocket"))] pub use __feature_gated_exports::*; pub use astria_core::{ primitive::v1::Address, protocol::{ - account::v1alpha1::{BalanceResponse, NonceResponse}, + account::v1alpha1::{ + BalanceResponse, + NonceResponse, + }, transaction::v1alpha1::SignedTransaction, }, sequencerblock::v1alpha1::SequencerBlock, }; -use futures_util::{FutureExt, Stream, StreamExt}; +use futures_util::{ + FutureExt, + Stream, + StreamExt, +}; pub use tendermint; use tendermint::block::Height; pub use tendermint_proto; @@ -28,10 +39,15 @@ pub use tendermint_rpc::WebSocketClient; use tokio_stream::wrappers::IntervalStream; #[cfg(any(feature = "http", feature = "websocket"))] mod __feature_gated_exports { - pub use tendermint_rpc::{Client, SubscriptionClient}; + pub use tendermint_rpc::{ + Client, + SubscriptionClient, + }; pub use crate::extension_trait::{ - NewBlockStreamError, SequencerClientExt, SequencerSubscriptionClientExt, + NewBlockStreamError, + SequencerClientExt, + SequencerSubscriptionClientExt, }; } diff --git a/crates/astria-sequencer-client/src/tests/http.rs b/crates/astria-sequencer-client/src/tests/http.rs index 615f6b082..34d2b6153 100644 --- a/crates/astria-sequencer-client/src/tests/http.rs +++ b/crates/astria-sequencer-client/src/tests/http.rs @@ -1,22 +1,43 @@ use astria_core::{ crypto::SigningKey, - primitive::v1::{asset::default_native_asset_id, Address}, + primitive::v1::{ + asset::default_native_asset_id, + Address, + }, protocol::transaction::v1alpha1::{ - action::TransferAction, SignedTransaction, TransactionParams, UnsignedTransaction, + action::TransferAction, + SignedTransaction, + TransactionParams, + UnsignedTransaction, }, }; use hex_literal::hex; use serde_json::json; -use tendermint::{block::Height, Hash}; +use tendermint::{ + block::Height, + Hash, +}; use tendermint_rpc::{ - endpoint::broadcast::tx_commit::v0_37::DialectResponse, response::Wrapper, Id, + endpoint::broadcast::tx_commit::v0_37::DialectResponse, + response::Wrapper, + Id, }; use wiremock::{ - matchers::{body_partial_json, body_string_contains}, - Mock, MockGuard, MockServer, ResponseTemplate, + matchers::{ + body_partial_json, + body_string_contains, + }, + Mock, + MockGuard, + MockServer, + ResponseTemplate, }; -use crate::{tendermint_rpc::endpoint::broadcast::tx_sync, HttpClient, SequencerClientExt as _}; +use crate::{ + tendermint_rpc::endpoint::broadcast::tx_sync, + HttpClient, + SequencerClientExt as _, +}; const ALICE_ADDRESS: [u8; 20] = hex!("1c0c490f1b5528d8173c5de46d131160e4b2c0c3"); const BOB_ADDRESS: Address = Address::from_array(hex!("34fec43c7fcab9aef3b3cf8aba855e41ee69ca3a")); @@ -30,7 +51,10 @@ impl MockSequencer { async fn start() -> Self { let server = MockServer::start().await; let client = HttpClient::new(&*format!("http://{}", server.address())).unwrap(); - Self { server, client } + Self { + server, + client, + } } } @@ -104,13 +128,15 @@ fn create_signed_transaction() -> SignedTransaction { .unwrap(); let alice_key = SigningKey::from(alice_secret_bytes); - let actions = vec![TransferAction { - to: BOB_ADDRESS, - amount: 333_333, - asset_id: default_native_asset_id(), - fee_asset_id: default_native_asset_id(), - } - .into()]; + let actions = vec![ + TransferAction { + to: BOB_ADDRESS, + amount: 333_333, + asset_id: default_native_asset_id(), + fee_asset_id: default_native_asset_id(), + } + .into(), + ]; UnsignedTransaction { params: TransactionParams { nonce: 1, @@ -124,7 +150,10 @@ fn create_signed_transaction() -> SignedTransaction { #[tokio::test] async fn get_latest_nonce() { use astria_core::generated::protocol::account::v1alpha1::NonceResponse; - let MockSequencer { server, client } = MockSequencer::start().await; + let MockSequencer { + server, + client, + } = MockSequencer::start().await; let expected_response = NonceResponse { height: 10, @@ -143,9 +172,15 @@ async fn get_latest_nonce() { #[tokio::test] async fn get_latest_balance() { - use astria_core::generated::protocol::account::v1alpha1::{AssetBalance, BalanceResponse}; + use astria_core::generated::protocol::account::v1alpha1::{ + AssetBalance, + BalanceResponse, + }; - let MockSequencer { server, client } = MockSequencer::start().await; + let MockSequencer { + server, + client, + } = MockSequencer::start().await; let expected_response = BalanceResponse { height: 10, @@ -167,7 +202,10 @@ async fn get_latest_balance() { #[tokio::test] async fn submit_tx_sync() { - let MockSequencer { server, client } = MockSequencer::start().await; + let MockSequencer { + server, + client, + } = MockSequencer::start().await; let server_response = tx_sync::Response { code: 0.into(), @@ -189,7 +227,10 @@ async fn submit_tx_sync() { async fn submit_tx_commit() { use tendermint_rpc::dialect; - let MockSequencer { server, client } = MockSequencer::start().await; + let MockSequencer { + server, + client, + } = MockSequencer::start().await; let server_response = DialectResponse { check_tx: dialect::CheckTx::default(), diff --git a/crates/astria-sequencer-relayer/src/api.rs b/crates/astria-sequencer-relayer/src/api.rs index 40f4925f5..382f78a20 100644 --- a/crates/astria-sequencer-relayer/src/api.rs +++ b/crates/astria-sequencer-relayer/src/api.rs @@ -1,10 +1,20 @@ use std::net::SocketAddr; use axum::{ - extract::{FromRef, State}, - response::{IntoResponse, Response}, - routing::{get, IntoMakeService}, - Json, Router, + extract::{ + FromRef, + State, + }, + response::{ + IntoResponse, + Response, + }, + routing::{ + get, + IntoMakeService, + }, + Json, + Router, }; use http::status::StatusCode; use hyper::server::conn::AddrIncoming; @@ -34,7 +44,9 @@ pub(crate) fn start(socket_addr: SocketAddr, relayer_state: RelayerState) -> Api .route("/healthz", get(get_healthz)) .route("/readyz", get(get_readyz)) .route("/status", get(get_status)) - .with_state(AppState { relayer_state }); + .with_state(AppState { + relayer_state, + }); axum::Server::bind(&socket_addr).serve(app.into_make_service()) } @@ -83,7 +95,10 @@ impl IntoResponse for Healthz { Self::Ok => (StatusCode::OK, "ok"), Self::Degraded => (StatusCode::INTERNAL_SERVER_ERROR, "degraded"), }; - let mut response = Json(ReadyzBody { status: msg }).into_response(); + let mut response = Json(ReadyzBody { + status: msg, + }) + .into_response(); *response.status_mut() = status; response } @@ -104,7 +119,10 @@ impl IntoResponse for Readyz { Self::Ok => (StatusCode::OK, "ok"), Self::NotReady => (StatusCode::SERVICE_UNAVAILABLE, "not ready"), }; - let mut response = Json(ReadyzBody { status: msg }).into_response(); + let mut response = Json(ReadyzBody { + status: msg, + }) + .into_response(); *response.status_mut() = status; response } diff --git a/crates/astria-sequencer-relayer/src/config.rs b/crates/astria-sequencer-relayer/src/config.rs index 77b3d76ab..a14d4f0ab 100644 --- a/crates/astria-sequencer-relayer/src/config.rs +++ b/crates/astria-sequencer-relayer/src/config.rs @@ -1,9 +1,22 @@ -use std::{collections::HashSet, path::PathBuf, sync::Arc}; +use std::{ + collections::HashSet, + path::PathBuf, + sync::Arc, +}; use astria_core::primitive::v1::RollupId; -use astria_eyre::eyre::{self, WrapErr}; -use base64::{prelude::BASE64_STANDARD, Engine as _}; -use serde::{Deserialize, Serialize}; +use astria_eyre::eyre::{ + self, + WrapErr, +}; +use base64::{ + prelude::BASE64_STANDARD, + Engine as _, +}; +use serde::{ + Deserialize, + Serialize, +}; // Allowed `struct_excessive_bools` because this is used as a container // for deserialization. Making this a builder-pattern is not actionable. diff --git a/crates/astria-sequencer-relayer/src/lib.rs b/crates/astria-sequencer-relayer/src/lib.rs index 4f61739c5..d6eb436f7 100644 --- a/crates/astria-sequencer-relayer/src/lib.rs +++ b/crates/astria-sequencer-relayer/src/lib.rs @@ -8,5 +8,11 @@ pub(crate) mod utils; pub(crate) mod validator; pub use build_info::BUILD_INFO; -pub use config::{Config, IncludeRollup}; -pub use sequencer_relayer::{SequencerRelayer, ShutdownHandle}; +pub use config::{ + Config, + IncludeRollup, +}; +pub use sequencer_relayer::{ + SequencerRelayer, + ShutdownHandle, +}; diff --git a/crates/astria-sequencer-relayer/src/main.rs b/crates/astria-sequencer-relayer/src/main.rs index cffaccb9a..1f5a7df97 100644 --- a/crates/astria-sequencer-relayer/src/main.rs +++ b/crates/astria-sequencer-relayer/src/main.rs @@ -1,9 +1,21 @@ use std::process::ExitCode; use astria_eyre::eyre::WrapErr as _; -use astria_sequencer_relayer::{metrics_init, Config, SequencerRelayer, BUILD_INFO}; -use tokio::signal::unix::{signal, SignalKind}; -use tracing::{error, info, warn}; +use astria_sequencer_relayer::{ + metrics_init, + Config, + SequencerRelayer, + BUILD_INFO, +}; +use tokio::signal::unix::{ + signal, + SignalKind, +}; +use tracing::{ + error, + info, + warn, +}; #[tokio::main] async fn main() -> ExitCode { diff --git a/crates/astria-sequencer-relayer/src/metrics_init.rs b/crates/astria-sequencer-relayer/src/metrics_init.rs index 00db62f03..ab6ac9940 100644 --- a/crates/astria-sequencer-relayer/src/metrics_init.rs +++ b/crates/astria-sequencer-relayer/src/metrics_init.rs @@ -2,7 +2,12 @@ //! //! Registers metrics & lists constants to be used as metric names throughout crate. -use metrics::{describe_counter, describe_gauge, describe_histogram, Unit}; +use metrics::{ + describe_counter, + describe_gauge, + describe_histogram, + Unit, +}; use telemetry::metric_name; /// Registers all metrics used by this crate. @@ -104,11 +109,18 @@ metric_name!(pub const COMPRESSION_RATIO_FOR_ASTRIA_BLOCK); #[cfg(test)] mod tests { use super::{ - BLOBS_PER_CELESTIA_TX, BLOCKS_PER_CELESTIA_TX, BYTES_PER_CELESTIA_TX, - CELESTIA_PAYLOAD_CREATION_LATENCY, CELESTIA_SUBMISSION_COUNT, - CELESTIA_SUBMISSION_FAILURE_COUNT, CELESTIA_SUBMISSION_HEIGHT, CELESTIA_SUBMISSION_LATENCY, - COMPRESSION_RATIO_FOR_ASTRIA_BLOCK, SEQUENCER_BLOCK_FETCH_FAILURE_COUNT, - SEQUENCER_HEIGHT_FETCH_FAILURE_COUNT, SEQUENCER_SUBMISSION_HEIGHT, + BLOBS_PER_CELESTIA_TX, + BLOCKS_PER_CELESTIA_TX, + BYTES_PER_CELESTIA_TX, + CELESTIA_PAYLOAD_CREATION_LATENCY, + CELESTIA_SUBMISSION_COUNT, + CELESTIA_SUBMISSION_FAILURE_COUNT, + CELESTIA_SUBMISSION_HEIGHT, + CELESTIA_SUBMISSION_LATENCY, + COMPRESSION_RATIO_FOR_ASTRIA_BLOCK, + SEQUENCER_BLOCK_FETCH_FAILURE_COUNT, + SEQUENCER_HEIGHT_FETCH_FAILURE_COUNT, + SEQUENCER_SUBMISSION_HEIGHT, }; #[track_caller] diff --git a/crates/astria-sequencer-relayer/src/relayer/builder.rs b/crates/astria-sequencer-relayer/src/relayer/builder.rs index b36bfeb71..d62fe04e6 100644 --- a/crates/astria-sequencer-relayer/src/relayer/builder.rs +++ b/crates/astria-sequencer-relayer/src/relayer/builder.rs @@ -1,12 +1,29 @@ -use std::{path::PathBuf, sync::Arc, time::Duration}; +use std::{ + path::PathBuf, + sync::Arc, + time::Duration, +}; use astria_core::generated::sequencerblock::v1alpha1::sequencer_service_client::SequencerServiceClient; -use astria_eyre::eyre::{self, WrapErr as _}; +use astria_eyre::eyre::{ + self, + WrapErr as _, +}; use sequencer_client::HttpClient as SequencerClient; -use tonic::transport::{Endpoint, Uri}; +use tonic::transport::{ + Endpoint, + Uri, +}; -use super::{state::State, CelestiaClientBuilder, CelestiaKeys}; -use crate::{validator::Validator, IncludeRollup}; +use super::{ + state::State, + CelestiaClientBuilder, + CelestiaKeys, +}; +use crate::{ + validator::Validator, + IncludeRollup, +}; pub(crate) struct Builder { pub(crate) shutdown_token: tokio_util::sync::CancellationToken, diff --git a/crates/astria-sequencer-relayer/src/relayer/celestia_client/builder.rs b/crates/astria-sequencer-relayer/src/relayer/celestia_client/builder.rs index e17c5329e..b945e3d11 100644 --- a/crates/astria-sequencer-relayer/src/relayer/celestia_client/builder.rs +++ b/crates/astria-sequencer-relayer/src/relayer/celestia_client/builder.rs @@ -2,17 +2,27 @@ use std::sync::Arc; use astria_core::generated::cosmos::{ base::tendermint::v1beta1::{ - service_client::ServiceClient as NodeInfoClient, GetNodeInfoRequest, + service_client::ServiceClient as NodeInfoClient, + GetNodeInfoRequest, }, tx::v1beta1::service_client::ServiceClient as TxClient, }; use http::Uri; use tendermint::account::Id as AccountId; use thiserror::Error; -use tonic::transport::{Channel, Endpoint}; +use tonic::transport::{ + Channel, + Endpoint, +}; use tracing::trace; -use super::{super::State, Bech32Address, CelestiaClient, CelestiaKeys, GrpcResponseError}; +use super::{ + super::State, + Bech32Address, + CelestiaClient, + CelestiaKeys, + GrpcResponseError, +}; /// An error when building the `CelestiaClient`. #[derive(Error, Clone, Debug)] diff --git a/crates/astria-sequencer-relayer/src/relayer/celestia_client/celestia_keys.rs b/crates/astria-sequencer-relayer/src/relayer/celestia_client/celestia_keys.rs index 766a401dc..237c017e4 100644 --- a/crates/astria-sequencer-relayer/src/relayer/celestia_client/celestia_keys.rs +++ b/crates/astria-sequencer-relayer/src/relayer/celestia_client/celestia_keys.rs @@ -1,12 +1,20 @@ use std::{ - fmt::{self, Debug, Formatter}, + fmt::{ + self, + Debug, + Formatter, + }, fs, path::Path, }; -use k256::ecdsa::{signature::Signer, Signature}; +use k256::ecdsa::{ + signature::Signer, + Signature, +}; use tendermint::{ - account::Id as AccountId, private_key::Secp256k1 as SigningKey, + account::Id as AccountId, + private_key::Secp256k1 as SigningKey, public_key::Secp256k1 as VerificationKey, }; use thiserror::Error; diff --git a/crates/astria-sequencer-relayer/src/relayer/celestia_client/error.rs b/crates/astria-sequencer-relayer/src/relayer/celestia_client/error.rs index 50b7eb7b4..b8848d53a 100644 --- a/crates/astria-sequencer-relayer/src/relayer/celestia_client/error.rs +++ b/crates/astria-sequencer-relayer/src/relayer/celestia_client/error.rs @@ -1,5 +1,9 @@ use std::{ - fmt::{self, Display, Formatter}, + fmt::{ + self, + Display, + Formatter, + }, num::ParseFloatError, }; diff --git a/crates/astria-sequencer-relayer/src/relayer/celestia_client/mod.rs b/crates/astria-sequencer-relayer/src/relayer/celestia_client/mod.rs index aaaabe3bd..ac504dbb8 100644 --- a/crates/astria-sequencer-relayer/src/relayer/celestia_client/mod.rs +++ b/crates/astria-sequencer-relayer/src/relayer/celestia_client/mod.rs @@ -8,47 +8,92 @@ mod tests; use std::{ convert::TryInto, sync::Arc, - time::{Duration, Instant}, + time::{ + Duration, + Instant, + }, }; use astria_core::generated::{ celestia::v1::{ - query_client::QueryClient as BlobQueryClient, MsgPayForBlobs, Params as BlobParams, + query_client::QueryClient as BlobQueryClient, + MsgPayForBlobs, + Params as BlobParams, QueryParamsRequest as QueryBlobParamsRequest, }, cosmos::{ auth::v1beta1::{ - query_client::QueryClient as AuthQueryClient, BaseAccount, Params as AuthParams, - QueryAccountRequest, QueryAccountResponse, + query_client::QueryClient as AuthQueryClient, + BaseAccount, + Params as AuthParams, + QueryAccountRequest, + QueryAccountResponse, QueryParamsRequest as QueryAuthParamsRequest, }, base::{ node::v1beta1::{ service_client::ServiceClient as MinGasPriceClient, - ConfigRequest as MinGasPriceRequest, ConfigResponse as MinGasPriceResponse, + ConfigRequest as MinGasPriceRequest, + ConfigResponse as MinGasPriceResponse, }, v1beta1::Coin, }, crypto::secp256k1, tx::v1beta1::{ - mode_info::{Single, Sum}, + mode_info::{ + Single, + Sum, + }, service_client::ServiceClient as TxClient, - AuthInfo, BroadcastMode, BroadcastTxRequest, BroadcastTxResponse, Fee, GetTxRequest, - GetTxResponse, ModeInfo, SignDoc, SignerInfo, Tx, TxBody, + AuthInfo, + BroadcastMode, + BroadcastTxRequest, + BroadcastTxResponse, + Fee, + GetTxRequest, + GetTxResponse, + ModeInfo, + SignDoc, + SignerInfo, + Tx, + TxBody, }, }, - tendermint::types::{Blob as PbBlob, BlobTx}, + tendermint::types::{ + Blob as PbBlob, + BlobTx, + }, }; use astria_eyre::eyre::Report; -pub(super) use builder::{Builder as CelestiaClientBuilder, BuilderError}; +pub(super) use builder::{ + Builder as CelestiaClientBuilder, + BuilderError, +}; use celestia_cost_params::CelestiaCostParams; pub(crate) use celestia_keys::CelestiaKeys; use celestia_types::Blob; -pub(super) use error::{GrpcResponseError, ProtobufDecodeError, TrySubmitError}; -use prost::{bytes::Bytes, Message as _, Name as _}; +pub(super) use error::{ + GrpcResponseError, + ProtobufDecodeError, + TrySubmitError, +}; +use prost::{ + bytes::Bytes, + Message as _, + Name as _, +}; use tokio::sync::watch; -use tonic::{transport::Channel, Response, Status}; -use tracing::{debug, info, trace, warn}; +use tonic::{ + transport::Channel, + Response, + Status, +}; +use tracing::{ + debug, + info, + trace, + warn, +}; // From https://github.com/celestiaorg/cosmos-sdk/blob/v1.18.3-sdk-v0.46.14/types/errors/errors.go#L75 const INSUFFICIENT_FEE_CODE: u32 = 13; @@ -503,11 +548,11 @@ fn calculate_fee( ) -> u64 { // Try to extract the required fee from the last error. let maybe_required_fee = match maybe_last_error { - Some(TrySubmitError::BroadcastTxResponseErrorCode { code, log, .. }) - if code == INSUFFICIENT_FEE_CODE => - { - extract_required_fee_from_log(&log) - } + Some(TrySubmitError::BroadcastTxResponseErrorCode { + code, + log, + .. + }) if code == INSUFFICIENT_FEE_CODE => extract_required_fee_from_log(&log), _ => None, }; @@ -603,7 +648,9 @@ fn new_signed_tx( const FEE_DENOM: &str = "utia"; // From https://github.com/celestiaorg/cosmos-sdk/blob/v1.18.3-sdk-v0.46.14/proto/cosmos/tx/signing/v1beta1/signing.proto#L24 const SIGNING_MODE_INFO: Option = Some(ModeInfo { - sum: Some(Sum::Single(Single { mode: 1 })), + sum: Some(Sum::Single(Single { + mode: 1, + })), }); let fee_coin = Coin { diff --git a/crates/astria-sequencer-relayer/src/relayer/celestia_client/tests.rs b/crates/astria-sequencer-relayer/src/relayer/celestia_client/tests.rs index 93fb9c6d9..2b8500131 100644 --- a/crates/astria-sequencer-relayer/src/relayer/celestia_client/tests.rs +++ b/crates/astria-sequencer-relayer/src/relayer/celestia_client/tests.rs @@ -1,5 +1,8 @@ use astria_core::generated::cosmos::base::abci::v1beta1::TxResponse; -use celestia_types::{blob::Commitment, nmt::Namespace}; +use celestia_types::{ + blob::Commitment, + nmt::Namespace, +}; use prost::bytes::Bytes; use super::*; @@ -91,7 +94,9 @@ fn account_from_bad_response_should_fail() { } // Should return `EmptyAccountInfo` if the inner response's `account` is `None`. - let response = Ok(Response::new(QueryAccountResponse { account: None })); + let response = Ok(Response::new(QueryAccountResponse { + account: None, + })); let error = account_from_response(response).unwrap_err(); // allow: `assert!(matches!(..))` provides poor feedback on failure. #[allow(clippy::manual_assert)] @@ -111,7 +116,10 @@ fn account_from_bad_response_should_fail() { })); let error = account_from_response(response).unwrap_err(); match error { - TrySubmitError::AccountInfoTypeMismatch { expected, received } => { + TrySubmitError::AccountInfoTypeMismatch { + expected, + received, + } => { assert_eq!(expected, BaseAccount::type_url(),); assert_eq!(received, bad_url,); } @@ -184,7 +192,9 @@ fn min_gas_price_from_bad_response_should_fail() { })); let error = min_gas_price_from_response(response).unwrap_err(); match error { - TrySubmitError::FailedToParseMinGasPrice { min_gas_price, .. } => { + TrySubmitError::FailedToParseMinGasPrice { + min_gas_price, .. + } => { assert_eq!(min_gas_price, bad_value,); } _ => panic!("expected `FailedToParseMinGasPrice` error, but got {error:?}"), @@ -272,7 +282,9 @@ fn tx_hash_from_bad_response_should_fail() { } // Should return `EmptyBroadcastTxResponse` if the inner response's `tx_response` is `None`. - let response = Ok(Response::new(BroadcastTxResponse { tx_response: None })); + let response = Ok(Response::new(BroadcastTxResponse { + tx_response: None, + })); let error = tx_hash_from_response(response).unwrap_err(); // allow: `assert!(matches!(..))` provides poor feedback on failure. #[allow(clippy::manual_assert)] diff --git a/crates/astria-sequencer-relayer/src/relayer/mod.rs b/crates/astria-sequencer-relayer/src/relayer/mod.rs index 44f2b2c50..84ce3abf3 100644 --- a/crates/astria-sequencer-relayer/src/relayer/mod.rs +++ b/crates/astria-sequencer-relayer/src/relayer/mod.rs @@ -1,5 +1,8 @@ use std::{ - path::{Path, PathBuf}, + path::{ + Path, + PathBuf, + }, sync::Arc, time::Duration, }; @@ -8,25 +11,48 @@ use astria_core::{ generated::sequencerblock::v1alpha1::sequencer_service_client::SequencerServiceClient, sequencerblock::v1alpha1::SequencerBlock, }; -use astria_eyre::eyre::{self, bail, eyre, WrapErr as _}; +use astria_eyre::eyre::{ + self, + bail, + eyre, + WrapErr as _, +}; use futures::{ - future::{BoxFuture, Fuse, FusedFuture as _}, + future::{ + BoxFuture, + Fuse, + FusedFuture as _, + }, FutureExt as _, }; use sequencer_client::{ - tendermint::block::Height as SequencerHeight, HttpClient as SequencerClient, + tendermint::block::Height as SequencerHeight, + HttpClient as SequencerClient, }; use tokio::{ select, - sync::{mpsc::error::TrySendError, watch}, + sync::{ + mpsc::error::TrySendError, + watch, + }, task::JoinHandle, }; use tokio_stream::StreamExt; use tokio_util::sync::CancellationToken; use tonic::transport::Channel; -use tracing::{debug, error, field::DisplayValue, info, instrument, warn}; +use tracing::{ + debug, + error, + field::DisplayValue, + info, + instrument, + warn, +}; -use crate::{validator::Validator, IncludeRollup}; +use crate::{ + validator::Validator, + IncludeRollup, +}; mod builder; mod celestia_client; @@ -36,7 +62,12 @@ mod submission; mod write; pub(crate) use builder::Builder; -use celestia_client::{BuilderError, CelestiaClientBuilder, CelestiaKeys, TrySubmitError}; +use celestia_client::{ + BuilderError, + CelestiaClientBuilder, + CelestiaKeys, + TrySubmitError, +}; use state::State; pub(crate) use state::StateSnapshot; diff --git a/crates/astria-sequencer-relayer/src/relayer/read.rs b/crates/astria-sequencer-relayer/src/relayer/read.rs index ca58cd3b4..f2de26da0 100644 --- a/crates/astria-sequencer-relayer/src/relayer/read.rs +++ b/crates/astria-sequencer-relayer/src/relayer/read.rs @@ -1,18 +1,40 @@ //! A stream of sequencer blocks. -use std::{future::Future as _, pin::Pin, sync::Arc, task::Poll, time::Duration}; +use std::{ + future::Future as _, + pin::Pin, + sync::Arc, + task::Poll, + time::Duration, +}; use astria_core::{ generated::sequencerblock::v1alpha1::{ - sequencer_service_client::SequencerServiceClient, GetSequencerBlockRequest, + sequencer_service_client::SequencerServiceClient, + GetSequencerBlockRequest, }, sequencerblock::v1alpha1::SequencerBlock, }; -use astria_eyre::eyre::{self, ensure, Report, WrapErr as _}; -use futures::{future::BoxFuture, ready, FutureExt as _}; +use astria_eyre::eyre::{ + self, + ensure, + Report, + WrapErr as _, +}; +use futures::{ + future::BoxFuture, + ready, + FutureExt as _, +}; use pin_project_lite::pin_project; use sequencer_client::tendermint::block::Height; use tokio_stream::Stream; -use tracing::{info, instrument, warn, Instrument as _, Span}; +use tracing::{ + info, + instrument, + warn, + Instrument as _, + Span, +}; /// Tracks the latest sequencer height and returns the next height the stream should fetch. /// @@ -368,7 +390,10 @@ impl BlockStreamBuilder { #[cfg(test)] mod tests { - use super::{Height, Heights}; + use super::{ + Height, + Heights, + }; #[track_caller] fn assert_next_height_is_expected( diff --git a/crates/astria-sequencer-relayer/src/relayer/state.rs b/crates/astria-sequencer-relayer/src/relayer/state.rs index 4404d5dd2..9083cbb3a 100644 --- a/crates/astria-sequencer-relayer/src/relayer/state.rs +++ b/crates/astria-sequencer-relayer/src/relayer/state.rs @@ -7,7 +7,9 @@ pub(super) struct State { impl State { pub(super) fn new() -> Self { let (inner, _) = watch::channel(StateSnapshot::default()); - Self { inner } + Self { + inner, + } } pub(super) fn set_ready(&self) { diff --git a/crates/astria-sequencer-relayer/src/relayer/submission.rs b/crates/astria-sequencer-relayer/src/relayer/submission.rs index 6203bbbcf..71654a850 100644 --- a/crates/astria-sequencer-relayer/src/relayer/submission.rs +++ b/crates/astria-sequencer-relayer/src/relayer/submission.rs @@ -1,11 +1,25 @@ //! Tracks the current submission state of sequencer-relayer and syncs it to disk. -use std::path::{Path, PathBuf}; - -use astria_eyre::eyre::{self, bail, ensure, WrapErr as _}; +use std::path::{ + Path, + PathBuf, +}; + +use astria_eyre::eyre::{ + self, + bail, + ensure, + WrapErr as _, +}; use sequencer_client::tendermint::block::Height as SequencerHeight; -use serde::{Deserialize, Serialize}; -use tracing::{debug, warn}; +use serde::{ + Deserialize, + Serialize, +}; +use tracing::{ + debug, + warn, +}; #[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "snake_case")] @@ -347,7 +361,11 @@ mod as_number { //! This is unfortunately necessary because the [`serde::Serialize`], [`serde::Deserialize`] //! implementations for [`sequencer_client::tendermint::block::Height`] write the integer as //! string, probably due to tendermint's/cometbft's go-legacy. - use serde::{Deserialize as _, Deserializer, Serializer}; + use serde::{ + Deserialize as _, + Deserializer, + Serializer, + }; use super::SequencerHeight; // Allow: the function signature is dictated by the serde(with) attribute. @@ -538,7 +556,12 @@ mod tests { //! These test the same scenarios as the tests of the same name in the super module, but //! whereas those are strict and should fail, the tests in this module should pass - use super::{create_files, json, write, SubmissionState}; + use super::{ + create_files, + json, + write, + SubmissionState, + }; const LENIENT_CONSISTENCY_CHECK: bool = true; diff --git a/crates/astria-sequencer-relayer/src/relayer/write/conversion.rs b/crates/astria-sequencer-relayer/src/relayer/write/conversion.rs index 83e8a3c5b..ba6753e45 100644 --- a/crates/astria-sequencer-relayer/src/relayer/write/conversion.rs +++ b/crates/astria-sequencer-relayer/src/relayer/write/conversion.rs @@ -1,5 +1,9 @@ use std::{ - collections::{BTreeSet, HashMap, HashSet}, + collections::{ + BTreeSet, + HashMap, + HashSet, + }, pin::Pin, task::Poll, }; @@ -7,16 +11,26 @@ use std::{ use astria_core::{ brotli::compress_bytes, generated::sequencerblock::v1alpha1::{ - SubmittedMetadata, SubmittedMetadataList, SubmittedRollupData, SubmittedRollupDataList, + SubmittedMetadata, + SubmittedMetadataList, + SubmittedRollupData, + SubmittedRollupDataList, }, primitive::v1::RollupId, }; -use celestia_types::{nmt::Namespace, Blob}; +use celestia_types::{ + nmt::Namespace, + Blob, +}; use futures::Future; use pin_project_lite::pin_project; use sequencer_client::SequencerBlock; use tendermint::block::Height as SequencerHeight; -use tracing::{error, trace, warn}; +use tracing::{ + error, + trace, + warn, +}; use crate::IncludeRollup; @@ -270,7 +284,12 @@ impl Input { for (namespace, entries) in self.rollup_data_for_namespace { payload - .try_add(namespace, &SubmittedRollupDataList { entries }) + .try_add( + namespace, + &SubmittedRollupDataList { + entries, + }, + ) .map_err(|source| TryIntoPayloadError::AddToPayload { source, type_url: SubmittedRollupDataList::full_name(), @@ -350,7 +369,9 @@ impl NextSubmission { /// Only when the returned [`TakeNextSubmission`] future is polled is the data moved /// out, leaving behind an empty [`NextSubmission`] that can be used to accumulate more blocks. pub(super) fn take(&mut self) -> TakeSubmission<'_> { - TakeSubmission { inner: Some(self) } + TakeSubmission { + inner: Some(self), + } } } @@ -380,7 +401,10 @@ impl<'a> Future for TakeSubmission<'a> { number_of_blocks = input.num_blocks(), "returning payload" ); - Poll::Ready(Some(Submission { input, payload })) + Poll::Ready(Some(Submission { + input, + payload, + })) } } } @@ -447,16 +471,28 @@ where #[cfg(test)] mod tests { - use astria_core::{primitive::v1::RollupId, protocol::test_utils::ConfigureSequencerBlock}; + use astria_core::{ + primitive::v1::RollupId, + protocol::test_utils::ConfigureSequencerBlock, + }; use rand_chacha::{ - rand_core::{RngCore as _, SeedableRng as _}, + rand_core::{ + RngCore as _, + SeedableRng as _, + }, ChaChaRng, }; use sequencer_client::SequencerBlock; - use super::{Input, NextSubmission}; + use super::{ + Input, + NextSubmission, + }; use crate::{ - relayer::write::conversion::{TryAddError, MAX_PAYLOAD_SIZE_BYTES}, + relayer::write::conversion::{ + TryAddError, + MAX_PAYLOAD_SIZE_BYTES, + }, IncludeRollup, }; diff --git a/crates/astria-sequencer-relayer/src/relayer/write/mod.rs b/crates/astria-sequencer-relayer/src/relayer/write/mod.rs index f44f96f94..03eaa6501 100644 --- a/crates/astria-sequencer-relayer/src/relayer/write/mod.rs +++ b/crates/astria-sequencer-relayer/src/relayer/write/mod.rs @@ -8,12 +8,21 @@ //! receives blocks and imposes no extra ordering. This means that if //! another task sends sequencer blocks ordered by their heights, then //! they will be written in that order. -use std::{sync::Arc, time::Duration}; +use std::{ + sync::Arc, + time::Duration, +}; -use astria_eyre::eyre::{self, WrapErr as _}; +use astria_eyre::eyre::{ + self, + WrapErr as _, +}; use celestia_types::Blob; use futures::{ - future::{Fuse, FusedFuture as _}, + future::{ + Fuse, + FusedFuture as _, + }, FutureExt as _, }; use sequencer_client::SequencerBlock; @@ -22,19 +31,36 @@ use tokio::{ sync::{ mpsc::{ self, - error::{SendError, TrySendError}, + error::{ + SendError, + TrySendError, + }, }, watch, }, }; use tokio_util::sync::CancellationToken; -use tracing::{debug, error, info, instrument, warn, Instrument, Span}; +use tracing::{ + debug, + error, + info, + instrument, + warn, + Instrument, + Span, +}; use super::{ - celestia_client::CelestiaClient, BuilderError, CelestiaClientBuilder, SubmissionState, + celestia_client::CelestiaClient, + BuilderError, + CelestiaClientBuilder, + SubmissionState, TrySubmitError, }; -use crate::{metrics_init, IncludeRollup}; +use crate::{ + metrics_init, + IncludeRollup, +}; mod conversion; use conversion::NextSubmission; @@ -116,7 +142,9 @@ impl BlobSubmitter { shutdown_token, pending_block: None, }; - let handle = BlobSubmitterHandle { tx }; + let handle = BlobSubmitterHandle { + tx, + }; (submitter, handle) } diff --git a/crates/astria-sequencer-relayer/src/sequencer_relayer.rs b/crates/astria-sequencer-relayer/src/sequencer_relayer.rs index b8187df4f..a6d64da8c 100644 --- a/crates/astria-sequencer-relayer/src/sequencer_relayer.rs +++ b/crates/astria-sequencer-relayer/src/sequencer_relayer.rs @@ -1,19 +1,34 @@ -use std::{net::SocketAddr, time::Duration}; +use std::{ + net::SocketAddr, + time::Duration, +}; -use astria_eyre::eyre::{self, WrapErr as _}; +use astria_eyre::eyre::{ + self, + WrapErr as _, +}; use tokio::{ select, sync::oneshot, - task::{JoinError, JoinHandle}, + task::{ + JoinError, + JoinHandle, + }, time::timeout, }; use tokio_util::sync::CancellationToken; -use tracing::{error, info}; +use tracing::{ + error, + info, +}; use crate::{ api, config::Config, - relayer::{self, Relayer}, + relayer::{ + self, + Relayer, + }, }; pub struct SequencerRelayer { diff --git a/crates/astria-sequencer-relayer/src/utils.rs b/crates/astria-sequencer-relayer/src/utils.rs index 150752771..efd49c60e 100644 --- a/crates/astria-sequencer-relayer/src/utils.rs +++ b/crates/astria-sequencer-relayer/src/utils.rs @@ -1,4 +1,7 @@ -use astria_eyre::eyre::{self, WrapErr as _}; +use astria_eyre::eyre::{ + self, + WrapErr as _, +}; use tokio::task::JoinError; pub(crate) fn flatten(res: Result, JoinError>) -> eyre::Result { diff --git a/crates/astria-sequencer-relayer/src/validator.rs b/crates/astria-sequencer-relayer/src/validator.rs index 6c3518a94..dc385735a 100644 --- a/crates/astria-sequencer-relayer/src/validator.rs +++ b/crates/astria-sequencer-relayer/src/validator.rs @@ -1,6 +1,9 @@ use std::path::Path; -use astria_eyre::eyre::{self, WrapErr as _}; +use astria_eyre::eyre::{ + self, + WrapErr as _, +}; use tendermint::account; use tendermint_config::PrivValidatorKey; use tracing::instrument; diff --git a/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_celestia_app_server.rs b/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_celestia_app_server.rs index a1074d5a3..0b74ff626 100644 --- a/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_celestia_app_server.rs +++ b/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_celestia_app_server.rs @@ -1,18 +1,31 @@ use std::{ net::SocketAddr, - sync::{Arc, Mutex}, + sync::{ + Arc, + Mutex, + }, }; use astria_core::generated::{ celestia::v1::{ - query_server::{Query as BlobQueryService, QueryServer as BlobQueryServer}, - Params as BlobParams, QueryParamsRequest as QueryBlobParamsRequest, + query_server::{ + Query as BlobQueryService, + QueryServer as BlobQueryServer, + }, + Params as BlobParams, + QueryParamsRequest as QueryBlobParamsRequest, QueryParamsResponse as QueryBlobParamsResponse, }, cosmos::{ auth::v1beta1::{ - query_server::{Query as AuthQueryService, QueryServer as AuthQueryServer}, - BaseAccount, Params as AuthParams, QueryAccountRequest, QueryAccountResponse, + query_server::{ + Query as AuthQueryService, + QueryServer as AuthQueryServer, + }, + BaseAccount, + Params as AuthParams, + QueryAccountRequest, + QueryAccountResponse, QueryParamsRequest as QueryAuthParamsRequest, QueryParamsResponse as QueryAuthParamsResponse, }, @@ -20,32 +33,63 @@ use astria_core::generated::{ abci::v1beta1::TxResponse, node::v1beta1::{ service_server::{ - Service as MinGasPriceService, ServiceServer as MinGasPriceServer, + Service as MinGasPriceService, + ServiceServer as MinGasPriceServer, }, - ConfigRequest as MinGasPriceRequest, ConfigResponse as MinGasPriceResponse, + ConfigRequest as MinGasPriceRequest, + ConfigResponse as MinGasPriceResponse, }, tendermint::v1beta1::{ - service_server::{Service as NodeInfoService, ServiceServer as NodeInfoServer}, - GetNodeInfoRequest, GetNodeInfoResponse, + service_server::{ + Service as NodeInfoService, + ServiceServer as NodeInfoServer, + }, + GetNodeInfoRequest, + GetNodeInfoResponse, }, }, tx::v1beta1::{ - service_server::{Service as TxService, ServiceServer as TxServer}, - BroadcastTxRequest, BroadcastTxResponse, GetTxRequest, GetTxResponse, + service_server::{ + Service as TxService, + ServiceServer as TxServer, + }, + BroadcastTxRequest, + BroadcastTxResponse, + GetTxRequest, + GetTxResponse, }, }, - tendermint::{p2p::DefaultNodeInfo, types::BlobTx}, + tendermint::{ + p2p::DefaultNodeInfo, + types::BlobTx, + }, +}; +use astria_eyre::eyre::{ + self, + WrapErr as _, }; -use astria_eyre::eyre::{self, WrapErr as _}; use astria_grpc_mock::{ matcher::message_type, - response::{constant_response, dynamic_response}, - Mock, MockGuard, MockServer, + response::{ + constant_response, + dynamic_response, + }, + Mock, + MockGuard, + MockServer, }; use celestia_types::nmt::Namespace; -use prost::{Message, Name}; +use prost::{ + Message, + Name, +}; use tokio::task::JoinHandle; -use tonic::{transport::Server, Request, Response, Status}; +use tonic::{ + transport::Server, + Request, + Response, + Status, +}; const CELESTIA_NETWORK_NAME: &str = "test-celestia"; const GET_NODE_INFO_GRPC_NAME: &str = "get_node_info"; diff --git a/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_sequencer_server.rs b/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_sequencer_server.rs index 5b2be674d..24401ee8b 100644 --- a/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_sequencer_server.rs +++ b/crates/astria-sequencer-relayer/tests/blackbox/helpers/mock_sequencer_server.rs @@ -1,23 +1,44 @@ -use std::{net::SocketAddr, sync::Arc}; +use std::{ + net::SocketAddr, + sync::Arc, +}; use astria_core::{ generated::sequencerblock::v1alpha1::{ - sequencer_service_server::{SequencerService, SequencerServiceServer}, - FilteredSequencerBlock as RawFilteredSequencerBlock, GetFilteredSequencerBlockRequest, - GetPendingNonceRequest, GetPendingNonceResponse, GetSequencerBlockRequest, + sequencer_service_server::{ + SequencerService, + SequencerServiceServer, + }, + FilteredSequencerBlock as RawFilteredSequencerBlock, + GetFilteredSequencerBlockRequest, + GetPendingNonceRequest, + GetPendingNonceResponse, + GetSequencerBlockRequest, SequencerBlock as RawSequencerBlock, }, primitive::v1::RollupId, protocol::test_utils::ConfigureSequencerBlock, sequencerblock::v1alpha1::SequencerBlock, }; -use astria_eyre::eyre::{self, WrapErr as _}; +use astria_eyre::eyre::{ + self, + WrapErr as _, +}; use astria_grpc_mock::{ - matcher::message_type, response::constant_response, Mock, MockGuard, MockServer, + matcher::message_type, + response::constant_response, + Mock, + MockGuard, + MockServer, }; use tendermint::account::Id as AccountId; use tokio::task::JoinHandle; -use tonic::{transport::Server, Request, Response, Status}; +use tonic::{ + transport::Server, + Request, + Response, + Status, +}; const GET_SEQUENCER_BLOCK_GRPC_NAME: &str = "get_sequencer_block"; const GET_FILTERED_SEQUENCER_BLOCK_GRPC_NAME: &str = "get_filtered_sequencer_block"; diff --git a/crates/astria-sequencer-relayer/tests/blackbox/helpers/mod.rs b/crates/astria-sequencer-relayer/tests/blackbox/helpers/mod.rs index c6c24b9ba..f9ea1ccd4 100644 --- a/crates/astria-sequencer-relayer/tests/blackbox/helpers/mod.rs +++ b/crates/astria-sequencer-relayer/tests/blackbox/helpers/mod.rs @@ -4,6 +4,9 @@ mod test_sequencer_relayer; pub use self::{ mock_celestia_app_server::MockCelestiaAppServer, - mock_sequencer_server::{MockSequencerServer, SequencerBlockToMount}, + mock_sequencer_server::{ + MockSequencerServer, + SequencerBlockToMount, + }, test_sequencer_relayer::TestSequencerRelayerConfig, }; diff --git a/crates/astria-sequencer-relayer/tests/blackbox/helpers/test_sequencer_relayer.rs b/crates/astria-sequencer-relayer/tests/blackbox/helpers/test_sequencer_relayer.rs index 6ead53d38..3f08ea2c8 100644 --- a/crates/astria-sequencer-relayer/tests/blackbox/helpers/test_sequencer_relayer.rs +++ b/crates/astria-sequencer-relayer/tests/blackbox/helpers/test_sequencer_relayer.rs @@ -1,6 +1,10 @@ use std::{ collections::HashSet, - fmt::{self, Display, Formatter}, + fmt::{ + self, + Display, + Formatter, + }, future::Future, io::Write, mem, @@ -9,26 +13,56 @@ use std::{ }; use assert_json_diff::assert_json_include; -use astria_core::{crypto::SigningKey, primitive::v1::RollupId}; +use astria_core::{ + crypto::SigningKey, + primitive::v1::RollupId, +}; use astria_grpc_mock::MockGuard as GrpcMockGuard; -use astria_sequencer_relayer::{config::Config, SequencerRelayer, ShutdownHandle}; +use astria_sequencer_relayer::{ + config::Config, + SequencerRelayer, + ShutdownHandle, +}; use futures::TryFutureExt; use itertools::Itertools; use once_cell::sync::Lazy; -use reqwest::{Response, StatusCode}; +use reqwest::{ + Response, + StatusCode, +}; use serde::Deserialize; use serde_json::json; use tempfile::NamedTempFile; use tendermint_config::PrivValidatorKey; -use tendermint_rpc::{response::Wrapper, Id}; +use tendermint_rpc::{ + response::Wrapper, + Id, +}; use tokio::{ - runtime::{self, RuntimeFlavor}, - task::{yield_now, JoinHandle}, + runtime::{ + self, + RuntimeFlavor, + }, + task::{ + yield_now, + JoinHandle, + }, +}; +use tracing::{ + error, + info, +}; +use wiremock::{ + matchers::body_partial_json, + MockServer as WireMockServer, + ResponseTemplate, }; -use tracing::{error, info}; -use wiremock::{matchers::body_partial_json, MockServer as WireMockServer, ResponseTemplate}; -use super::{MockCelestiaAppServer, MockSequencerServer, SequencerBlockToMount}; +use super::{ + MockCelestiaAppServer, + MockSequencerServer, + SequencerBlockToMount, +}; /// Copied verbatim from /// [tendermint-rs](https://github.com/informalsystems/tendermint-rs/blob/main/config/tests/support/config/priv_validator_key.ed25519.json) @@ -120,7 +154,10 @@ impl Drop for TestSequencerRelayer { impl TestSequencerRelayer { /// Mounts a `CometBFT` ABCI Info response. pub async fn mount_abci_response(&self, height: u32) { - use tendermint::{abci, hash::AppHash}; + use tendermint::{ + abci, + hash::AppHash, + }; use tendermint_rpc::endpoint::abci_info; let abci_response = abci_info::Response { response: abci::response::Info { @@ -594,7 +631,9 @@ impl TestSequencerRelayerConfig { let validator_keyfile = write_file(PRIVATE_VALIDATOR_KEY.as_bytes()).await; let PrivValidatorKey { - address, priv_key, .. + address, + priv_key, + .. } = PrivValidatorKey::parse_json(PRIVATE_VALIDATOR_KEY).unwrap(); let signing_key = priv_key .ed25519_signing_key() diff --git a/crates/astria-sequencer-relayer/tests/blackbox/main.rs b/crates/astria-sequencer-relayer/tests/blackbox/main.rs index 1f5a6b84c..bcd165f4f 100644 --- a/crates/astria-sequencer-relayer/tests/blackbox/main.rs +++ b/crates/astria-sequencer-relayer/tests/blackbox/main.rs @@ -4,8 +4,14 @@ pub mod helpers; use std::collections::HashSet; -use astria_core::{primitive::v1::RollupId, protocol::test_utils::ConfigureSequencerBlock}; -use helpers::{SequencerBlockToMount, TestSequencerRelayerConfig}; +use astria_core::{ + primitive::v1::RollupId, + protocol::test_utils::ConfigureSequencerBlock, +}; +use helpers::{ + SequencerBlockToMount, + TestSequencerRelayerConfig, +}; use reqwest::StatusCode; use tendermint::account::Id as AccountId; diff --git a/crates/astria-sequencer-utils/src/blob_parser.rs b/crates/astria-sequencer-utils/src/blob_parser.rs index 3610c342f..803f8f716 100644 --- a/crates/astria-sequencer-utils/src/blob_parser.rs +++ b/crates/astria-sequencer-utils/src/blob_parser.rs @@ -1,6 +1,12 @@ use std::{ - fmt::{self, Display, Formatter, Write}, - fs, io, + fmt::{ + self, + Display, + Formatter, + Write, + }, + fs, + io, num::NonZeroUsize, path::Path, }; @@ -8,27 +14,50 @@ use std::{ use astria_core::{ brotli::decompress_bytes, generated::sequencerblock::v1alpha1::{ - rollup_data::Value as RawRollupDataValue, Deposit as RawDeposit, - RollupData as RawRollupData, SubmittedMetadata as RawSubmittedMetadata, + rollup_data::Value as RawRollupDataValue, + Deposit as RawDeposit, + RollupData as RawRollupData, + SubmittedMetadata as RawSubmittedMetadata, SubmittedMetadataList as RawSubmittedMetadataList, SubmittedRollupData as RawSubmittedRollupData, SubmittedRollupDataList as RawSubmittedRollupDataList, }, primitive::v1::RollupId, sequencerblock::v1alpha1::{ - block::{Deposit, DepositError, SequencerBlockHeader}, - celestia::{SubmittedRollupData, UncheckedSubmittedMetadata, UncheckedSubmittedRollupData}, + block::{ + Deposit, + DepositError, + SequencerBlockHeader, + }, + celestia::{ + SubmittedRollupData, + UncheckedSubmittedMetadata, + UncheckedSubmittedRollupData, + }, }, }; -use astria_eyre::eyre::{bail, Result, WrapErr}; +use astria_eyre::eyre::{ + bail, + Result, + WrapErr, +}; use astria_merkle::audit::Proof; -use base64::{prelude::BASE64_STANDARD, Engine}; +use base64::{ + prelude::BASE64_STANDARD, + Engine, +}; use clap::ValueEnum; use colour::write_blue; -use ethers_core::types::{transaction::eip2930::AccessListItem, Transaction}; +use ethers_core::types::{ + transaction::eip2930::AccessListItem, + Transaction, +}; use indenter::indented; use itertools::Itertools; -use prost::{bytes::Bytes, Message}; +use prost::{ + bytes::Bytes, + Message, +}; use serde::Serialize; #[derive(clap::Args, Debug)] diff --git a/crates/astria-sequencer-utils/src/cli.rs b/crates/astria-sequencer-utils/src/cli.rs index 08cabcd1f..acc11b0c2 100644 --- a/crates/astria-sequencer-utils/src/cli.rs +++ b/crates/astria-sequencer-utils/src/cli.rs @@ -1,6 +1,12 @@ -use clap::{Parser, Subcommand}; +use clap::{ + Parser, + Subcommand, +}; -use super::{blob_parser, genesis_parser}; +use super::{ + blob_parser, + genesis_parser, +}; /// Utilities for working with the Astria sequencer network #[derive(Debug, Parser)] diff --git a/crates/astria-sequencer-utils/src/genesis_parser.rs b/crates/astria-sequencer-utils/src/genesis_parser.rs index 66fe69c01..a61d67b68 100644 --- a/crates/astria-sequencer-utils/src/genesis_parser.rs +++ b/crates/astria-sequencer-utils/src/genesis_parser.rs @@ -1,7 +1,16 @@ -use std::{fs::File, path::PathBuf}; - -use astria_eyre::eyre::{Result, WrapErr}; -use serde_json::{to_writer_pretty, Value}; +use std::{ + fs::File, + path::PathBuf, +}; + +use astria_eyre::eyre::{ + Result, + WrapErr, +}; +use serde_json::{ + to_writer_pretty, + Value, +}; #[derive(clap::Args, Debug)] pub struct Args { diff --git a/crates/astria-sequencer-utils/src/main.rs b/crates/astria-sequencer-utils/src/main.rs index b876fd062..6bede2c3c 100644 --- a/crates/astria-sequencer-utils/src/main.rs +++ b/crates/astria-sequencer-utils/src/main.rs @@ -1,7 +1,10 @@ use astria_eyre::eyre::Result; use astria_sequencer_utils::{ blob_parser, - cli::{self, Command}, + cli::{ + self, + Command, + }, genesis_parser, }; diff --git a/crates/astria-sequencer-utils/tests/parse_blob.rs b/crates/astria-sequencer-utils/tests/parse_blob.rs index de42204e3..c6064d748 100644 --- a/crates/astria-sequencer-utils/tests/parse_blob.rs +++ b/crates/astria-sequencer-utils/tests/parse_blob.rs @@ -1,10 +1,16 @@ use std::{ fs, - path::{Path, PathBuf}, + path::{ + Path, + PathBuf, + }, }; use assert_cmd::Command; -use astria_eyre::{eyre::WrapErr, Result}; +use astria_eyre::{ + eyre::WrapErr, + Result, +}; use predicates::prelude::*; struct Resources { diff --git a/crates/astria-sequencer/src/accounts/action.rs b/crates/astria-sequencer/src/accounts/action.rs index 75bbcdcc4..1546add77 100644 --- a/crates/astria-sequencer/src/accounts/action.rs +++ b/crates/astria-sequencer/src/accounts/action.rs @@ -1,12 +1,23 @@ -use anyhow::{ensure, Context, Result}; +use anyhow::{ + ensure, + Context, + Result, +}; use astria_core::{ - primitive::v1::Address, protocol::transaction::v1alpha1::action::TransferAction, + primitive::v1::Address, + protocol::transaction::v1alpha1::action::TransferAction, }; use tracing::instrument; use crate::{ - accounts::state_ext::{StateReadExt, StateWriteExt}, - state_ext::{StateReadExt as _, StateWriteExt as _}, + accounts::state_ext::{ + StateReadExt, + StateWriteExt, + }, + state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, transaction::action_handler::ActionHandler, }; diff --git a/crates/astria-sequencer/src/accounts/component.rs b/crates/astria-sequencer/src/accounts/component.rs index e090cde5d..376b9c6ce 100644 --- a/crates/astria-sequencer/src/accounts/component.rs +++ b/crates/astria-sequencer/src/accounts/component.rs @@ -1,11 +1,21 @@ use std::sync::Arc; -use anyhow::{Context, Result}; -use tendermint::abci::request::{BeginBlock, EndBlock}; +use anyhow::{ + Context, + Result, +}; +use tendermint::abci::request::{ + BeginBlock, + EndBlock, +}; use tracing::instrument; use super::state_ext::StateWriteExt; -use crate::{asset::get_native_asset, component::Component, genesis::GenesisState}; +use crate::{ + asset::get_native_asset, + component::Component, + genesis::GenesisState, +}; #[derive(Default)] pub(crate) struct AccountsComponent; diff --git a/crates/astria-sequencer/src/accounts/query.rs b/crates/astria-sequencer/src/accounts/query.rs index 2850b3bf1..2ac08081b 100644 --- a/crates/astria-sequencer/src/accounts/query.rs +++ b/crates/astria-sequencer/src/accounts/query.rs @@ -1,13 +1,25 @@ use anyhow::Context as _; -use astria_core::{primitive::v1::Address, protocol::abci::AbciErrorCode}; -use cnidarium::{Snapshot, Storage}; +use astria_core::{ + primitive::v1::Address, + protocol::abci::AbciErrorCode, +}; +use cnidarium::{ + Snapshot, + Storage, +}; use prost::Message as _; use tendermint::{ - abci::{request, response}, + abci::{ + request, + response, + }, block::Height, }; -use crate::{accounts::state_ext::StateReadExt as _, state_ext::StateReadExt as _}; +use crate::{ + accounts::state_ext::StateReadExt as _, + state_ext::StateReadExt as _, +}; pub(crate) async fn balance_request( storage: Storage, diff --git a/crates/astria-sequencer/src/accounts/state_ext.rs b/crates/astria-sequencer/src/accounts/state_ext.rs index c964058f2..b1053ea60 100644 --- a/crates/astria-sequencer/src/accounts/state_ext.rs +++ b/crates/astria-sequencer/src/accounts/state_ext.rs @@ -1,11 +1,23 @@ -use anyhow::{Context, Result}; +use anyhow::{ + Context, + Result, +}; use astria_core::{ - primitive::v1::{asset, Address}, + primitive::v1::{ + asset, + Address, + }, protocol::account::v1alpha1::AssetBalance, }; use async_trait::async_trait; -use borsh::{BorshDeserialize, BorshSerialize}; -use cnidarium::{StateRead, StateWrite}; +use borsh::{ + BorshDeserialize, + BorshSerialize, +}; +use cnidarium::{ + StateRead, + StateWrite, +}; use futures::StreamExt; use hex::ToHex as _; use tracing::instrument; @@ -89,7 +101,10 @@ pub(crate) trait StateReadExt: StateRead { .await .context("failed to get ibc asset denom")? .context("asset denom not found when user has balance of it; this is a bug")?; - balances.push(AssetBalance { denom, balance }); + balances.push(AssetBalance { + denom, + balance, + }); } Ok(balances) } @@ -218,14 +233,21 @@ impl StateWriteExt for T {} mod test { use astria_core::{ primitive::v1::{ - asset::{Denom, Id, DEFAULT_NATIVE_ASSET_DENOM}, + asset::{ + Denom, + Id, + DEFAULT_NATIVE_ASSET_DENOM, + }, Address, }, protocol::account::v1alpha1::AssetBalance, }; use cnidarium::StateDelta; - use super::{StateReadExt as _, StateWriteExt as _}; + use super::{ + StateReadExt as _, + StateWriteExt as _, + }; use crate::asset; #[tokio::test] diff --git a/crates/astria-sequencer/src/api_state_ext.rs b/crates/astria-sequencer/src/api_state_ext.rs index 59870fe0e..c7cc067f2 100644 --- a/crates/astria-sequencer/src/api_state_ext.rs +++ b/crates/astria-sequencer/src/api_state_ext.rs @@ -1,15 +1,32 @@ -use anyhow::{anyhow, bail, Context as _, Result}; +use anyhow::{ + anyhow, + bail, + Context as _, + Result, +}; use astria_core::{ - generated::{primitive::v1 as primitiveRaw, sequencerblock::v1alpha1 as raw}, + generated::{ + primitive::v1 as primitiveRaw, + sequencerblock::v1alpha1 as raw, + }, primitive::v1::RollupId, sequencerblock::v1alpha1::block::{ - RollupTransactions, SequencerBlock, SequencerBlockHeader, SequencerBlockParts, + RollupTransactions, + SequencerBlock, + SequencerBlockHeader, + SequencerBlockParts, }, Protobuf as _, }; use async_trait::async_trait; -use borsh::{BorshDeserialize, BorshSerialize}; -use cnidarium::{StateRead, StateWrite}; +use borsh::{ + BorshDeserialize, + BorshSerialize, +}; +use cnidarium::{ + StateRead, + StateWrite, +}; use prost::Message; use tracing::instrument; @@ -53,7 +70,10 @@ impl From> for RollupIdSeq { } mod rollup_id_impl { - use super::{RollupId, RollupIdSer}; + use super::{ + RollupId, + RollupIdSer, + }; pub(super) fn deserialize( reader: &mut R, @@ -363,7 +383,10 @@ impl StateWriteExt for T {} #[cfg(test)] mod test { use astria_core::{ - primitive::v1::{asset::Id, Address}, + primitive::v1::{ + asset::Id, + Address, + }, protocol::test_utils::ConfigureSequencerBlock, sequencerblock::v1alpha1::block::Deposit, }; diff --git a/crates/astria-sequencer/src/app/mod.rs b/crates/astria-sequencer/src/app/mod.rs index 5879a9c0d..bff3d5764 100644 --- a/crates/astria-sequencer/src/app/mod.rs +++ b/crates/astria-sequencer/src/app/mod.rs @@ -7,43 +7,83 @@ mod tests_breaking_changes; #[cfg(test)] mod tests_execute_transaction; -use std::{collections::VecDeque, sync::Arc}; +use std::{ + collections::VecDeque, + sync::Arc, +}; -use anyhow::{anyhow, ensure, Context}; +use anyhow::{ + anyhow, + ensure, + Context, +}; use astria_core::{ generated::protocol::transaction::v1alpha1 as raw, primitive::v1::Address, protocol::{ abci::AbciErrorCode, - transaction::v1alpha1::{Action, SignedTransaction}, + transaction::v1alpha1::{ + Action, + SignedTransaction, + }, }, sequencerblock::v1alpha1::block::SequencerBlock, }; -use cnidarium::{ArcStateDeltaExt, Snapshot, StagedWriteBatch, StateDelta, Storage}; +use cnidarium::{ + ArcStateDeltaExt, + Snapshot, + StagedWriteBatch, + StateDelta, + Storage, +}; use prost::Message as _; -use sha2::{Digest as _, Sha256}; +use sha2::{ + Digest as _, + Sha256, +}; use telemetry::display::json; use tendermint::{ - abci::{self, types::ExecTxResult, Event}, + abci::{ + self, + types::ExecTxResult, + Event, + }, account, block::Header, - AppHash, Hash, + AppHash, + Hash, +}; +use tracing::{ + debug, + info, + instrument, }; -use tracing::{debug, info, instrument}; use crate::{ accounts::{ component::AccountsComponent, - state_ext::{StateReadExt, StateWriteExt as _}, + state_ext::{ + StateReadExt, + StateWriteExt as _, + }, }, api_state_ext::StateWriteExt as _, authority::{ - component::{AuthorityComponent, AuthorityComponentAppState}, - state_ext::{StateReadExt as _, StateWriteExt as _}, + component::{ + AuthorityComponent, + AuthorityComponentAppState, + }, + state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, }, bridge::{ component::BridgeComponent, - state_ext::{StateReadExt as _, StateWriteExt}, + state_ext::{ + StateReadExt as _, + StateWriteExt, + }, }, component::Component as _, genesis::GenesisState, @@ -52,11 +92,20 @@ use crate::{ metrics_init, proposal::{ block_size_constraints::BlockSizeConstraints, - commitment::{generate_rollup_datas_commitment, GeneratedCommitments}, + commitment::{ + generate_rollup_datas_commitment, + GeneratedCommitments, + }, }, sequence::component::SequenceComponent, - state_ext::{StateReadExt as _, StateWriteExt as _}, - transaction::{self, InvalidNonce}, + state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, + transaction::{ + self, + InvalidNonce, + }, }; /// The inter-block state being written to by the application. diff --git a/crates/astria-sequencer/src/app/test_utils.rs b/crates/astria-sequencer/src/app/test_utils.rs index b9a1526c2..09c42c2f0 100644 --- a/crates/astria-sequencer/src/app/test_utils.rs +++ b/crates/astria-sequencer/src/app/test_utils.rs @@ -1,8 +1,16 @@ use astria_core::{ crypto::SigningKey, - primitive::v1::{asset::DEFAULT_NATIVE_ASSET_DENOM, Address, RollupId, ADDRESS_LEN}, + primitive::v1::{ + asset::DEFAULT_NATIVE_ASSET_DENOM, + Address, + RollupId, + ADDRESS_LEN, + }, protocol::transaction::v1alpha1::{ - action::SequenceAction, SignedTransaction, TransactionParams, UnsignedTransaction, + action::SequenceAction, + SignedTransaction, + TransactionParams, + UnsignedTransaction, }, }; use cnidarium::Storage; @@ -10,7 +18,11 @@ use penumbra_ibc::params::IBCParameters; use crate::{ app::App, - genesis::{self, Account, GenesisState}, + genesis::{ + self, + Account, + GenesisState, + }, mempool::Mempool, }; @@ -128,12 +140,14 @@ pub(crate) fn get_mock_tx(nonce: u32) -> SignedTransaction { nonce, chain_id: "test".to_string(), }, - actions: vec![SequenceAction { - rollup_id: RollupId::from_unhashed_bytes([0; 32]), - data: vec![0x99], - fee_asset_id: astria_core::primitive::v1::asset::default_native_asset_id(), - } - .into()], + actions: vec![ + SequenceAction { + rollup_id: RollupId::from_unhashed_bytes([0; 32]), + data: vec![0x99], + fee_asset_id: astria_core::primitive::v1::asset::default_native_asset_id(), + } + .into(), + ], }; tx.into_signed(&alice_signing_key) diff --git a/crates/astria-sequencer/src/app/tests_app.rs b/crates/astria-sequencer/src/app/tests_app.rs index 0cff99128..9e718df32 100644 --- a/crates/astria-sequencer/src/app/tests_app.rs +++ b/crates/astria-sequencer/src/app/tests_app.rs @@ -1,20 +1,40 @@ use std::collections::HashMap; use astria_core::{ - primitive::v1::{asset::DEFAULT_NATIVE_ASSET_DENOM, Address, RollupId}, + primitive::v1::{ + asset::DEFAULT_NATIVE_ASSET_DENOM, + Address, + RollupId, + }, protocol::transaction::v1alpha1::{ - action::{BridgeLockAction, SequenceAction, TransferAction}, - TransactionParams, UnsignedTransaction, + action::{ + BridgeLockAction, + SequenceAction, + TransferAction, + }, + TransactionParams, + UnsignedTransaction, }, sequencerblock::v1alpha1::block::Deposit, }; use cnidarium::StateDelta; use prost::Message as _; use tendermint::{ - abci::{self, request::PrepareProposal, types::CommitInfo}, + abci::{ + self, + request::PrepareProposal, + types::CommitInfo, + }, account, - block::{header::Version, Header, Height, Round}, - AppHash, Hash, Time, + block::{ + header::Version, + Header, + Height, + Round, + }, + AppHash, + Hash, + Time, }; use super::*; @@ -22,8 +42,15 @@ use crate::{ accounts::state_ext::StateReadExt as _, app::test_utils::*, asset::get_native_asset, - authority::state_ext::{StateReadExt as _, StateWriteExt as _, ValidatorSet}, - bridge::state_ext::{StateReadExt as _, StateWriteExt}, + authority::state_ext::{ + StateReadExt as _, + StateWriteExt as _, + ValidatorSet, + }, + bridge::state_ext::{ + StateReadExt as _, + StateWriteExt, + }, genesis::Account, proposal::commitment::generate_rollup_datas_commitment, state_ext::StateReadExt as _, @@ -44,7 +71,10 @@ fn default_tendermint_header() -> Header { proposer_address: account::Id::try_from([0u8; 20].to_vec()).unwrap(), time: Time::now(), validators_hash: Hash::default(), - version: Version { app: 0, block: 0 }, + version: Version { + app: 0, + block: 0, + }, } } @@ -53,7 +83,11 @@ async fn app_genesis_and_init_chain() { let app = initialize_app(None, vec![]).await; assert_eq!(app.state.get_block_height().await.unwrap(), 0); - for Account { address, balance } in default_genesis_accounts() { + for Account { + address, + balance, + } in default_genesis_accounts() + { assert_eq!( balance, app.state @@ -93,7 +127,10 @@ async fn app_pre_execute_transactions() { #[tokio::test] async fn app_begin_block_remove_byzantine_validators() { - use tendermint::{abci::types, validator}; + use tendermint::{ + abci::types, + validator, + }; let pubkey_a = tendermint::public_key::PublicKey::from_raw_ed25519(&[1; 32]).unwrap(); let pubkey_b = tendermint::public_key::PublicKey::from_raw_ed25519(&[2; 32]).unwrap(); @@ -153,7 +190,11 @@ async fn app_commit() { assert_eq!(app.state.get_block_height().await.unwrap(), 0); let native_asset = get_native_asset().id(); - for Account { address, balance } in default_genesis_accounts() { + for Account { + address, + balance, + } in default_genesis_accounts() + { assert_eq!( balance, app.state @@ -170,7 +211,11 @@ async fn app_commit() { let snapshot = storage.latest_snapshot(); assert_eq!(snapshot.get_block_height().await.unwrap(), 0); - for Account { address, balance } in default_genesis_accounts() { + for Account { + address, + balance, + } in default_genesis_accounts() + { assert_eq!( snapshot .get_account_balance(address, native_asset) @@ -196,13 +241,15 @@ async fn app_transfer_block_fees_to_sudo() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![TransferAction { - to: bob_address, - amount, - asset_id: native_asset, - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + TransferAction { + to: bob_address, + amount, + asset_id: native_asset, + fee_asset_id: get_native_asset().id(), + } + .into(), + ], }; let signed_tx = tx.into_signed(&alice_signing_key); @@ -498,12 +545,14 @@ async fn app_prepare_proposal_cometbft_max_bytes_overflow_ok() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![SequenceAction { - rollup_id: RollupId::from([1u8; 32]), - data: vec![1u8; 100_000], - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + SequenceAction { + rollup_id: RollupId::from([1u8; 32]), + data: vec![1u8; 100_000], + fee_asset_id: get_native_asset().id(), + } + .into(), + ], } .into_signed(&alice_signing_key); let tx_overflow = UnsignedTransaction { @@ -511,12 +560,14 @@ async fn app_prepare_proposal_cometbft_max_bytes_overflow_ok() { nonce: 1, chain_id: "test".to_string(), }, - actions: vec![SequenceAction { - rollup_id: RollupId::from([1u8; 32]), - data: vec![1u8; 100_000], - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + SequenceAction { + rollup_id: RollupId::from([1u8; 32]), + data: vec![1u8; 100_000], + fee_asset_id: get_native_asset().id(), + } + .into(), + ], } .into_signed(&alice_signing_key); @@ -567,12 +618,14 @@ async fn app_prepare_proposal_sequencer_max_bytes_overflow_ok() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![SequenceAction { - rollup_id: RollupId::from([1u8; 32]), - data: vec![1u8; 200_000], - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + SequenceAction { + rollup_id: RollupId::from([1u8; 32]), + data: vec![1u8; 200_000], + fee_asset_id: get_native_asset().id(), + } + .into(), + ], } .into_signed(&alice_signing_key); let tx_overflow = UnsignedTransaction { @@ -580,12 +633,14 @@ async fn app_prepare_proposal_sequencer_max_bytes_overflow_ok() { nonce: 1, chain_id: "test".to_string(), }, - actions: vec![SequenceAction { - rollup_id: RollupId::from([1u8; 32]), - data: vec![1u8; 100_000], - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + SequenceAction { + rollup_id: RollupId::from([1u8; 32]), + data: vec![1u8; 100_000], + fee_asset_id: get_native_asset().id(), + } + .into(), + ], } .into_signed(&alice_signing_key); diff --git a/crates/astria-sequencer/src/app/tests_breaking_changes.rs b/crates/astria-sequencer/src/app/tests_breaking_changes.rs index 7afc76f32..cccf427a2 100644 --- a/crates/astria-sequencer/src/app/tests_breaking_changes.rs +++ b/crates/astria-sequencer/src/app/tests_breaking_changes.rs @@ -9,29 +9,53 @@ //! These are due to the extensive setup needed to test them. //! If changes are made to the execution results of these actions, manual testing is required. -use std::{collections::HashMap, sync::Arc}; +use std::{ + collections::HashMap, + sync::Arc, +}; use astria_core::{ - primitive::v1::{asset::DEFAULT_NATIVE_ASSET_DENOM, Address, RollupId}, + primitive::v1::{ + asset::DEFAULT_NATIVE_ASSET_DENOM, + Address, + RollupId, + }, protocol::transaction::v1alpha1::{ action::{ - BridgeLockAction, BridgeUnlockAction, IbcRelayerChangeAction, SequenceAction, + BridgeLockAction, + BridgeUnlockAction, + IbcRelayerChangeAction, + SequenceAction, TransferAction, }, - Action, TransactionParams, UnsignedTransaction, + Action, + TransactionParams, + UnsignedTransaction, }, sequencerblock::v1alpha1::block::Deposit, }; use cnidarium::StateDelta; use penumbra_ibc::params::IBCParameters; use prost::Message as _; -use tendermint::{abci, abci::types::CommitInfo, block::Round, Hash, Time}; +use tendermint::{ + abci, + abci::types::CommitInfo, + block::Round, + Hash, + Time, +}; use crate::{ app::test_utils::{ - address_from_hex_string, default_fees, default_genesis_accounts, - get_alice_signing_key_and_address, get_bridge_signing_key_and_address, initialize_app, - initialize_app_with_storage, BOB_ADDRESS, CAROL_ADDRESS, + address_from_hex_string, + default_fees, + default_genesis_accounts, + get_alice_signing_key_and_address, + get_bridge_signing_key_and_address, + initialize_app, + initialize_app_with_storage, + BOB_ADDRESS, + CAROL_ADDRESS, }, asset::get_native_asset, bridge::state_ext::StateWriteExt as _, @@ -132,7 +156,9 @@ async fn app_execute_transaction_with_every_action_snapshot() { use astria_core::{ primitive::v1::asset, protocol::transaction::v1alpha1::action::{ - FeeAssetChangeAction, InitBridgeAccountAction, SudoAddressChangeAction, + FeeAssetChangeAction, + InitBridgeAccountAction, + SudoAddressChangeAction, }, }; @@ -227,13 +253,15 @@ async fn app_execute_transaction_with_every_action_snapshot() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![BridgeUnlockAction { - to: bob_address, - amount: 10, - fee_asset_id: get_native_asset().id(), - memo: vec![0u8; 32], - } - .into()], + actions: vec![ + BridgeUnlockAction { + to: bob_address, + amount: 10, + fee_asset_id: get_native_asset().id(), + memo: vec![0u8; 32], + } + .into(), + ], }; let signed_tx = Arc::new(tx.into_signed(&bridge_signing_key)); diff --git a/crates/astria-sequencer/src/app/tests_execute_transaction.rs b/crates/astria-sequencer/src/app/tests_execute_transaction.rs index 978d8fb8b..7ea28736c 100644 --- a/crates/astria-sequencer/src/app/tests_execute_transaction.rs +++ b/crates/astria-sequencer/src/app/tests_execute_transaction.rs @@ -2,13 +2,24 @@ use std::sync::Arc; use astria_core::{ crypto::SigningKey, - primitive::v1::{asset, asset::DEFAULT_NATIVE_ASSET_DENOM, Address, RollupId}, + primitive::v1::{ + asset, + asset::DEFAULT_NATIVE_ASSET_DENOM, + Address, + RollupId, + }, protocol::transaction::v1alpha1::{ action::{ - BridgeLockAction, BridgeUnlockAction, IbcRelayerChangeAction, SequenceAction, - SudoAddressChangeAction, TransferAction, + BridgeLockAction, + BridgeUnlockAction, + IbcRelayerChangeAction, + SequenceAction, + SudoAddressChangeAction, + TransferAction, }, - Action, TransactionParams, UnsignedTransaction, + Action, + TransactionParams, + UnsignedTransaction, }, sequencerblock::v1alpha1::block::Deposit, }; @@ -20,12 +31,18 @@ use crate::{ app::test_utils::*, asset::get_native_asset, authority::state_ext::StateReadExt as _, - bridge::state_ext::{StateReadExt as _, StateWriteExt}, + bridge::state_ext::{ + StateReadExt as _, + StateWriteExt, + }, genesis::GenesisState, ibc::state_ext::StateReadExt as _, sequence::calculate_fee_from_state, state_ext::StateReadExt as _, - transaction::{InvalidChainId, InvalidNonce}, + transaction::{ + InvalidChainId, + InvalidNonce, + }, }; #[tokio::test] @@ -41,13 +58,15 @@ async fn app_execute_transaction_transfer() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![TransferAction { - to: bob_address, - amount: value, - asset_id: get_native_asset().id(), - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + TransferAction { + to: bob_address, + amount: value, + asset_id: get_native_asset().id(), + fee_asset_id: get_native_asset().id(), + } + .into(), + ], }; let signed_tx = Arc::new(tx.into_signed(&alice_signing_key)); @@ -96,13 +115,15 @@ async fn app_execute_transaction_transfer_not_native_token() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![TransferAction { - to: bob_address, - amount: value, - asset_id: asset, - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + TransferAction { + to: bob_address, + amount: value, + asset_id: asset, + fee_asset_id: get_native_asset().id(), + } + .into(), + ], }; let signed_tx = Arc::new(tx.into_signed(&alice_signing_key)); @@ -160,13 +181,15 @@ async fn app_execute_transaction_transfer_balance_too_low_for_fee() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![TransferAction { - to: bob, - amount: 0, - asset_id: get_native_asset().id(), - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + TransferAction { + to: bob, + amount: 0, + asset_id: get_native_asset().id(), + fee_asset_id: get_native_asset().id(), + } + .into(), + ], }; let signed_tx = Arc::new(tx.into_signed(&keypair)); @@ -198,12 +221,14 @@ async fn app_execute_transaction_sequence() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![SequenceAction { - rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), - data, - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + SequenceAction { + rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), + data, + fee_asset_id: get_native_asset().id(), + } + .into(), + ], }; let signed_tx = Arc::new(tx.into_signed(&alice_signing_key)); @@ -233,12 +258,14 @@ async fn app_execute_transaction_invalid_fee_asset() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![SequenceAction { - rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), - data, - fee_asset_id, - } - .into()], + actions: vec![ + SequenceAction { + rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), + data, + fee_asset_id, + } + .into(), + ], }; let signed_tx = Arc::new(tx.into_signed(&alice_signing_key)); @@ -518,11 +545,12 @@ async fn app_execute_transaction_fee_asset_change_removal() { app.execute_transaction(signed_tx).await.unwrap(); assert_eq!(app.state.get_account_nonce(alice_address).await.unwrap(), 1); - assert!(!app - .state - .is_allowed_fee_asset(test_asset.id()) - .await - .unwrap()); + assert!( + !app.state + .is_allowed_fee_asset(test_asset.id()) + .await + .unwrap() + ); } #[tokio::test] @@ -791,12 +819,14 @@ async fn app_execute_transaction_invalid_nonce() { nonce: 1, chain_id: "test".to_string(), }, - actions: vec![SequenceAction { - rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), - data, - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + SequenceAction { + rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), + data, + fee_asset_id: get_native_asset().id(), + } + .into(), + ], }; let signed_tx = Arc::new(tx.into_signed(&alice_signing_key)); @@ -835,12 +865,14 @@ async fn app_execute_transaction_invalid_chain_id() { nonce: 0, chain_id: "wrong-chain".to_string(), }, - actions: vec![SequenceAction { - rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), - data, - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + SequenceAction { + rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), + data, + fee_asset_id: get_native_asset().id(), + } + .into(), + ], }; let signed_tx = Arc::new(tx.into_signed(&alice_signing_key)); @@ -892,13 +924,15 @@ async fn app_stateful_check_fails_insufficient_total_balance() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![TransferAction { - to: keypair_address, - amount: fee, - asset_id: get_native_asset().id(), - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + TransferAction { + to: keypair_address, + amount: fee, + asset_id: get_native_asset().id(), + fee_asset_id: get_native_asset().id(), + } + .into(), + ], } .into_signed(&alice_signing_key); @@ -942,12 +976,14 @@ async fn app_stateful_check_fails_insufficient_total_balance() { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![SequenceAction { - rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), - data, - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + SequenceAction { + rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), + data, + fee_asset_id: get_native_asset().id(), + } + .into(), + ], } .into_signed(&keypair); diff --git a/crates/astria-sequencer/src/asset/query.rs b/crates/astria-sequencer/src/asset/query.rs index 12e80f9a8..7b938704c 100644 --- a/crates/astria-sequencer/src/asset/query.rs +++ b/crates/astria-sequencer/src/asset/query.rs @@ -1,10 +1,19 @@ use anyhow::Context as _; -use astria_core::{primitive::v1::asset, protocol::abci::AbciErrorCode}; +use astria_core::{ + primitive::v1::asset, + protocol::abci::AbciErrorCode, +}; use cnidarium::Storage; use prost::Message as _; -use tendermint::abci::{request, response}; +use tendermint::abci::{ + request, + response, +}; -use crate::{asset::state_ext::StateReadExt as _, state_ext::StateReadExt}; +use crate::{ + asset::state_ext::StateReadExt as _, + state_ext::StateReadExt, +}; // Retrieve the full asset denomination given the asset ID. // @@ -57,10 +66,13 @@ pub(crate) async fn denom_request( }; }; - let payload = DenomResponse { height, denom } - .into_raw() - .encode_to_vec() - .into(); + let payload = DenomResponse { + height, + denom, + } + .into_raw() + .encode_to_vec() + .into(); let height = tendermint::block::Height::try_from(height).expect("height must fit into an i64"); response::Query { diff --git a/crates/astria-sequencer/src/asset/state_ext.rs b/crates/astria-sequencer/src/asset/state_ext.rs index 177d2555b..34161c2cf 100644 --- a/crates/astria-sequencer/src/asset/state_ext.rs +++ b/crates/astria-sequencer/src/asset/state_ext.rs @@ -1,8 +1,20 @@ -use anyhow::{Context as _, Result}; -use astria_core::primitive::v1::{asset, asset::Denom}; +use anyhow::{ + Context as _, + Result, +}; +use astria_core::primitive::v1::{ + asset, + asset::Denom, +}; use async_trait::async_trait; -use borsh::{BorshDeserialize, BorshSerialize}; -use cnidarium::{StateRead, StateWrite}; +use borsh::{ + BorshDeserialize, + BorshSerialize, +}; +use cnidarium::{ + StateRead, + StateWrite, +}; use hex::ToHex as _; use tracing::instrument; @@ -62,10 +74,16 @@ impl StateWriteExt for T {} #[cfg(test)] mod test { - use astria_core::primitive::v1::asset::{Denom, Id}; + use astria_core::primitive::v1::asset::{ + Denom, + Id, + }; use cnidarium::StateDelta; - use super::{StateReadExt as _, StateWriteExt as _}; + use super::{ + StateReadExt as _, + StateWriteExt as _, + }; #[tokio::test] async fn get_ibc_asset_non_existent() { diff --git a/crates/astria-sequencer/src/authority/action.rs b/crates/astria-sequencer/src/authority/action.rs index 9be23f907..6c5386e0b 100644 --- a/crates/astria-sequencer/src/authority/action.rs +++ b/crates/astria-sequencer/src/authority/action.rs @@ -1,15 +1,25 @@ -use anyhow::{bail, ensure, Context as _, Result}; +use anyhow::{ + bail, + ensure, + Context as _, + Result, +}; use astria_core::{ primitive::v1::Address, protocol::transaction::v1alpha1::action::{ - FeeChange, FeeChangeAction, SudoAddressChangeAction, + FeeChange, + FeeChangeAction, + SudoAddressChangeAction, }, }; use tendermint::account; use tracing::instrument; use crate::{ - authority::state_ext::{StateReadExt, StateWriteExt}, + authority::state_ext::{ + StateReadExt, + StateWriteExt, + }, transaction::action_handler::ActionHandler, }; @@ -110,8 +120,10 @@ impl ActionHandler for FeeChangeAction { #[instrument(skip_all)] async fn execute(&self, state: &mut S, _: Address) -> Result<()> { use crate::{ - accounts::state_ext::StateWriteExt as _, bridge::state_ext::StateWriteExt as _, - ibc::state_ext::StateWriteExt as _, sequence::state_ext::StateWriteExt as _, + accounts::state_ext::StateWriteExt as _, + bridge::state_ext::StateWriteExt as _, + ibc::state_ext::StateWriteExt as _, + sequence::state_ext::StateWriteExt as _, }; match self.fee_change { @@ -147,10 +159,22 @@ mod test { use super::*; use crate::{ - accounts::state_ext::{StateReadExt as _, StateWriteExt as _}, - bridge::state_ext::{StateReadExt as _, StateWriteExt as _}, - ibc::state_ext::{StateReadExt as _, StateWriteExt as _}, - sequence::state_ext::{StateReadExt as _, StateWriteExt as _}, + accounts::state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, + bridge::state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, + ibc::state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, + sequence::state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, }; #[tokio::test] diff --git a/crates/astria-sequencer/src/authority/component.rs b/crates/astria-sequencer/src/authority/component.rs index 0e15f5d00..c73514356 100644 --- a/crates/astria-sequencer/src/authority/component.rs +++ b/crates/astria-sequencer/src/authority/component.rs @@ -1,14 +1,24 @@ use std::sync::Arc; -use anyhow::{Context, Result}; +use anyhow::{ + Context, + Result, +}; use astria_core::primitive::v1::Address; use tendermint::{ - abci::request::{BeginBlock, EndBlock}, + abci::request::{ + BeginBlock, + EndBlock, + }, validator, }; use tracing::instrument; -use super::state_ext::{StateReadExt, StateWriteExt, ValidatorSet}; +use super::state_ext::{ + StateReadExt, + StateWriteExt, + ValidatorSet, +}; use crate::component::Component; #[derive(Default)] diff --git a/crates/astria-sequencer/src/authority/state_ext.rs b/crates/astria-sequencer/src/authority/state_ext.rs index 5e1fa256c..c1da43989 100644 --- a/crates/astria-sequencer/src/authority/state_ext.rs +++ b/crates/astria-sequencer/src/authority/state_ext.rs @@ -1,12 +1,31 @@ use std::collections::BTreeMap; -use anyhow::{bail, Context, Result}; -use astria_core::primitive::v1::{Address, ADDRESS_LEN}; +use anyhow::{ + bail, + Context, + Result, +}; +use astria_core::primitive::v1::{ + Address, + ADDRESS_LEN, +}; use async_trait::async_trait; -use borsh::{BorshDeserialize, BorshSerialize}; -use cnidarium::{StateRead, StateWrite}; -use serde::{Deserialize, Serialize}; -use tendermint::{account, validator}; +use borsh::{ + BorshDeserialize, + BorshSerialize, +}; +use cnidarium::{ + StateRead, + StateWrite, +}; +use serde::{ + Deserialize, + Serialize, +}; +use tendermint::{ + account, + validator, +}; use tracing::instrument; /// Newtype wrapper to read and write an address from rocksdb. @@ -162,9 +181,17 @@ impl StateWriteExt for T {} mod test { use astria_core::primitive::v1::Address; use cnidarium::StateDelta; - use tendermint::{validator, vote, PublicKey}; - - use super::{StateReadExt as _, StateWriteExt as _, ValidatorSet}; + use tendermint::{ + validator, + vote, + PublicKey, + }; + + use super::{ + StateReadExt as _, + StateWriteExt as _, + ValidatorSet, + }; #[tokio::test] async fn sudo_address() { diff --git a/crates/astria-sequencer/src/bridge/bridge_lock_action.rs b/crates/astria-sequencer/src/bridge/bridge_lock_action.rs index 01002ac8c..dd356054b 100644 --- a/crates/astria-sequencer/src/bridge/bridge_lock_action.rs +++ b/crates/astria-sequencer/src/bridge/bridge_lock_action.rs @@ -1,7 +1,14 @@ -use anyhow::{ensure, Context as _, Result}; +use anyhow::{ + ensure, + Context as _, + Result, +}; use astria_core::{ primitive::v1::Address, - protocol::transaction::v1alpha1::action::{BridgeLockAction, TransferAction}, + protocol::transaction::v1alpha1::action::{ + BridgeLockAction, + TransferAction, + }, sequencerblock::v1alpha1::block::Deposit, }; use tracing::instrument; @@ -9,10 +16,19 @@ use tracing::instrument; use crate::{ accounts::{ action::transfer_check_stateful, - state_ext::{StateReadExt as _, StateWriteExt as _}, + state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, + }, + bridge::state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, + state_ext::{ + StateReadExt, + StateWriteExt, }, - bridge::state_ext::{StateReadExt as _, StateWriteExt as _}, - state_ext::{StateReadExt, StateWriteExt}, transaction::action_handler::ActionHandler, }; @@ -134,7 +150,10 @@ pub(crate) fn get_deposit_byte_len(deposit: &Deposit) -> u128 { #[cfg(test)] mod test { - use astria_core::primitive::v1::{asset, RollupId}; + use astria_core::primitive::v1::{ + asset, + RollupId, + }; use cnidarium::StateDelta; use super::*; @@ -171,12 +190,14 @@ mod test { state .put_account_balance(from_address, asset_id, 100) .unwrap(); - assert!(bridge_lock - .check_stateful(&state, from_address) - .await - .unwrap_err() - .to_string() - .contains("insufficient funds for fee payment")); + assert!( + bridge_lock + .check_stateful(&state, from_address) + .await + .unwrap_err() + .to_string() + .contains("insufficient funds for fee payment") + ); // enough balance; should pass let expected_deposit_fee = transfer_fee @@ -228,12 +249,14 @@ mod test { state .put_account_balance(from_address, asset_id, 100 + transfer_fee) .unwrap(); - assert!(bridge_lock - .execute(&mut state, from_address) - .await - .unwrap_err() - .to_string() - .eq("failed to deduct fee from account balance")); + assert!( + bridge_lock + .execute(&mut state, from_address) + .await + .unwrap_err() + .to_string() + .eq("failed to deduct fee from account balance") + ); // enough balance; should pass let expected_deposit_fee = transfer_fee diff --git a/crates/astria-sequencer/src/bridge/bridge_unlock_action.rs b/crates/astria-sequencer/src/bridge/bridge_unlock_action.rs index e14c1eb72..ba6abcdfa 100644 --- a/crates/astria-sequencer/src/bridge/bridge_unlock_action.rs +++ b/crates/astria-sequencer/src/bridge/bridge_unlock_action.rs @@ -1,14 +1,23 @@ -use anyhow::{Context as _, Result}; +use anyhow::{ + Context as _, + Result, +}; use astria_core::{ primitive::v1::Address, - protocol::transaction::v1alpha1::action::{BridgeUnlockAction, TransferAction}, + protocol::transaction::v1alpha1::action::{ + BridgeUnlockAction, + TransferAction, + }, }; use tracing::instrument; use crate::{ accounts::action::transfer_check_stateful, bridge::state_ext::StateReadExt as _, - state_ext::{StateReadExt, StateWriteExt}, + state_ext::{ + StateReadExt, + StateWriteExt, + }, transaction::action_handler::ActionHandler, }; @@ -63,12 +72,16 @@ impl ActionHandler for BridgeUnlockAction { #[cfg(test)] mod test { - use astria_core::primitive::v1::{asset, RollupId}; + use astria_core::primitive::v1::{ + asset, + RollupId, + }; use cnidarium::StateDelta; use super::*; use crate::{ - accounts::state_ext::StateWriteExt as _, bridge::state_ext::StateWriteExt, + accounts::state_ext::StateWriteExt as _, + bridge::state_ext::StateWriteExt, state_ext::StateWriteExt as _, }; @@ -92,12 +105,14 @@ mod test { }; // not a bridge account, should fail - assert!(bridge_unlock - .check_stateful(&state, address) - .await - .unwrap_err() - .to_string() - .contains("failed to get bridge's asset id, must be a bridge account")); + assert!( + bridge_unlock + .check_stateful(&state, address) + .await + .unwrap_err() + .to_string() + .contains("failed to get bridge's asset id, must be a bridge account") + ); } #[tokio::test] @@ -132,12 +147,14 @@ mod test { state .put_account_balance(bridge_address, asset_id, transfer_amount) .unwrap(); - assert!(bridge_unlock - .check_stateful(&state, bridge_address) - .await - .unwrap_err() - .to_string() - .contains("insufficient funds for transfer and fee payment")); + assert!( + bridge_unlock + .check_stateful(&state, bridge_address) + .await + .unwrap_err() + .to_string() + .contains("insufficient funds for transfer and fee payment") + ); // enough balance; should pass state @@ -181,12 +198,14 @@ mod test { state .put_account_balance(bridge_address, asset_id, transfer_amount) .unwrap(); - assert!(bridge_unlock - .execute(&mut state, bridge_address) - .await - .unwrap_err() - .to_string() - .eq("failed to execute bridge unlock action as transfer action")); + assert!( + bridge_unlock + .execute(&mut state, bridge_address) + .await + .unwrap_err() + .to_string() + .eq("failed to execute bridge unlock action as transfer action") + ); // enough balance; should pass state diff --git a/crates/astria-sequencer/src/bridge/component.rs b/crates/astria-sequencer/src/bridge/component.rs index 8877ae738..b9e27ba32 100644 --- a/crates/astria-sequencer/src/bridge/component.rs +++ b/crates/astria-sequencer/src/bridge/component.rs @@ -1,11 +1,17 @@ use std::sync::Arc; use anyhow::Result; -use tendermint::abci::request::{BeginBlock, EndBlock}; +use tendermint::abci::request::{ + BeginBlock, + EndBlock, +}; use tracing::instrument; use super::state_ext::StateWriteExt; -use crate::{component::Component, genesis::GenesisState}; +use crate::{ + component::Component, + genesis::GenesisState, +}; #[derive(Default)] pub(crate) struct BridgeComponent; diff --git a/crates/astria-sequencer/src/bridge/init_bridge_account_action.rs b/crates/astria-sequencer/src/bridge/init_bridge_account_action.rs index 7a232dd18..86cd28a56 100644 --- a/crates/astria-sequencer/src/bridge/init_bridge_account_action.rs +++ b/crates/astria-sequencer/src/bridge/init_bridge_account_action.rs @@ -1,13 +1,28 @@ -use anyhow::{bail, ensure, Context as _, Result}; +use anyhow::{ + bail, + ensure, + Context as _, + Result, +}; use astria_core::{ - primitive::v1::Address, protocol::transaction::v1alpha1::action::InitBridgeAccountAction, + primitive::v1::Address, + protocol::transaction::v1alpha1::action::InitBridgeAccountAction, }; use tracing::instrument; use crate::{ - accounts::state_ext::{StateReadExt as _, StateWriteExt as _}, - bridge::state_ext::{StateReadExt as _, StateWriteExt as _}, - state_ext::{StateReadExt, StateWriteExt}, + accounts::state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, + bridge::state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, + state_ext::{ + StateReadExt, + StateWriteExt, + }, transaction::action_handler::ActionHandler, }; diff --git a/crates/astria-sequencer/src/bridge/state_ext.rs b/crates/astria-sequencer/src/bridge/state_ext.rs index d839b0703..b30373337 100644 --- a/crates/astria-sequencer/src/bridge/state_ext.rs +++ b/crates/astria-sequencer/src/bridge/state_ext.rs @@ -1,18 +1,38 @@ -use std::collections::{HashMap, HashSet}; +use std::collections::{ + HashMap, + HashSet, +}; -use anyhow::{anyhow, Context, Result}; +use anyhow::{ + anyhow, + Context, + Result, +}; use astria_core::{ generated::sequencerblock::v1alpha1::Deposit as RawDeposit, - primitive::v1::{asset, Address, RollupId}, + primitive::v1::{ + asset, + Address, + RollupId, + }, sequencerblock::v1alpha1::block::Deposit, }; use async_trait::async_trait; -use borsh::{BorshDeserialize, BorshSerialize}; -use cnidarium::{StateRead, StateWrite}; +use borsh::{ + BorshDeserialize, + BorshSerialize, +}; +use cnidarium::{ + StateRead, + StateWrite, +}; use futures::StreamExt as _; use hex::ToHex as _; use prost::Message as _; -use tracing::{debug, instrument}; +use tracing::{ + debug, + instrument, +}; /// Newtype wrapper to read and write a u128 from rocksdb. #[derive(BorshSerialize, BorshDeserialize, Debug)] @@ -279,12 +299,19 @@ impl StateWriteExt for T {} #[cfg(test)] mod test { use astria_core::{ - primitive::v1::{asset::Id, Address, RollupId}, + primitive::v1::{ + asset::Id, + Address, + RollupId, + }, sequencerblock::v1alpha1::block::Deposit, }; use cnidarium::StateDelta; - use super::{StateReadExt as _, StateWriteExt as _}; + use super::{ + StateReadExt as _, + StateWriteExt as _, + }; #[tokio::test] async fn get_bridge_account_rollup_id_uninitialized_ok() { diff --git a/crates/astria-sequencer/src/config.rs b/crates/astria-sequencer/src/config.rs index 8c603abcc..234a67ca5 100644 --- a/crates/astria-sequencer/src/config.rs +++ b/crates/astria-sequencer/src/config.rs @@ -1,6 +1,9 @@ use std::path::PathBuf; -use serde::{Deserialize, Serialize}; +use serde::{ + Deserialize, + Serialize, +}; // Allowed `struct_excessive_bools` because this is used as a container // for deserialization. Making this a builder-pattern is not actionable. diff --git a/crates/astria-sequencer/src/fee_asset_change.rs b/crates/astria-sequencer/src/fee_asset_change.rs index c20591883..0abbcf0f9 100644 --- a/crates/astria-sequencer/src/fee_asset_change.rs +++ b/crates/astria-sequencer/src/fee_asset_change.rs @@ -1,13 +1,25 @@ -use anyhow::{bail, ensure, Context as _, Result}; +use anyhow::{ + bail, + ensure, + Context as _, + Result, +}; use astria_core::{ - primitive::v1::Address, protocol::transaction::v1alpha1::action::FeeAssetChangeAction, + primitive::v1::Address, + protocol::transaction::v1alpha1::action::FeeAssetChangeAction, }; use async_trait::async_trait; -use cnidarium::{StateRead, StateWrite}; +use cnidarium::{ + StateRead, + StateWrite, +}; use crate::{ authority::state_ext::StateReadExt as _, - state_ext::{StateReadExt as _, StateWriteExt as _}, + state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, transaction::action_handler::ActionHandler, }; diff --git a/crates/astria-sequencer/src/genesis.rs b/crates/astria-sequencer/src/genesis.rs index 09eab2d8a..f6972f841 100644 --- a/crates/astria-sequencer/src/genesis.rs +++ b/crates/astria-sequencer/src/genesis.rs @@ -1,6 +1,12 @@ -use astria_core::primitive::v1::{asset, Address}; +use astria_core::primitive::v1::{ + asset, + Address, +}; use penumbra_ibc::params::IBCParameters; -use serde::{Deserialize, Deserializer}; +use serde::{ + Deserialize, + Deserializer, +}; /// The genesis state for the application. #[derive(Debug, Deserialize)] diff --git a/crates/astria-sequencer/src/grpc/sequencer.rs b/crates/astria-sequencer/src/grpc/sequencer.rs index 78433cd02..f8fb17e0c 100644 --- a/crates/astria-sequencer/src/grpc/sequencer.rs +++ b/crates/astria-sequencer/src/grpc/sequencer.rs @@ -3,17 +3,32 @@ use std::sync::Arc; use astria_core::{ generated::sequencerblock::v1alpha1::{ sequencer_service_server::SequencerService, - FilteredSequencerBlock as RawFilteredSequencerBlock, GetFilteredSequencerBlockRequest, - GetPendingNonceRequest, GetPendingNonceResponse, GetSequencerBlockRequest, + FilteredSequencerBlock as RawFilteredSequencerBlock, + GetFilteredSequencerBlockRequest, + GetPendingNonceRequest, + GetPendingNonceResponse, + GetSequencerBlockRequest, SequencerBlock as RawSequencerBlock, }, primitive::v1::RollupId, }; use cnidarium::Storage; -use tonic::{Request, Response, Status}; -use tracing::{error, info, instrument}; +use tonic::{ + Request, + Response, + Status, +}; +use tracing::{ + error, + info, + instrument, +}; -use crate::{api_state_ext::StateReadExt as _, mempool::Mempool, state_ext::StateReadExt as _}; +use crate::{ + api_state_ext::StateReadExt as _, + mempool::Mempool, + state_ext::StateReadExt as _, +}; pub(crate) struct SequencerServer { storage: Storage, @@ -22,7 +37,10 @@ pub(crate) struct SequencerServer { impl SequencerServer { pub(crate) fn new(storage: Storage, mempool: Mempool) -> Self { - Self { storage, mempool } + Self { + storage, + mempool, + } } } @@ -171,7 +189,9 @@ impl SequencerService for SequencerServer { let nonce = self.mempool.pending_nonce(&address).await; if let Some(nonce) = nonce { - return Ok(Response::new(GetPendingNonceResponse { inner: nonce })); + return Ok(Response::new(GetPendingNonceResponse { + inner: nonce, + })); } // nonce wasn't in mempool, so just look it up from storage @@ -184,19 +204,25 @@ impl SequencerService for SequencerServer { Status::internal(format!("failed to get account nonce from storage: {e}")) })?; - Ok(Response::new(GetPendingNonceResponse { inner: nonce })) + Ok(Response::new(GetPendingNonceResponse { + inner: nonce, + })) } } #[cfg(test)] mod test { use astria_core::{ - protocol::test_utils::ConfigureSequencerBlock, sequencerblock::v1alpha1::SequencerBlock, + protocol::test_utils::ConfigureSequencerBlock, + sequencerblock::v1alpha1::SequencerBlock, }; use cnidarium::StateDelta; use super::*; - use crate::{api_state_ext::StateWriteExt as _, state_ext::StateWriteExt}; + use crate::{ + api_state_ext::StateWriteExt as _, + state_ext::StateWriteExt, + }; fn make_test_sequencer_block(height: u32) -> SequencerBlock { ConfigureSequencerBlock { @@ -217,7 +243,9 @@ mod test { storage.commit(state_tx).await.unwrap(); let server = Arc::new(SequencerServer::new(storage.clone(), mempool)); - let request = GetSequencerBlockRequest { height: 1 }; + let request = GetSequencerBlockRequest { + height: 1, + }; let request = Request::new(request); let response = server.get_sequencer_block(request).await.unwrap(); assert_eq!(response.into_inner().header.unwrap().height, 1); diff --git a/crates/astria-sequencer/src/ibc/component.rs b/crates/astria-sequencer/src/ibc/component.rs index 6fb7a6df5..7d7a61b50 100644 --- a/crates/astria-sequencer/src/ibc/component.rs +++ b/crates/astria-sequencer/src/ibc/component.rs @@ -1,14 +1,26 @@ use std::sync::Arc; -use anyhow::{Context, Result}; -use penumbra_ibc::{component::Ibc, genesis::Content}; -use tendermint::abci::request::{BeginBlock, EndBlock}; +use anyhow::{ + Context, + Result, +}; +use penumbra_ibc::{ + component::Ibc, + genesis::Content, +}; +use tendermint::abci::request::{ + BeginBlock, + EndBlock, +}; use tracing::instrument; use crate::{ component::Component, genesis::GenesisState, - ibc::{host_interface::AstriaHost, state_ext::StateWriteExt}, + ibc::{ + host_interface::AstriaHost, + state_ext::StateWriteExt, + }, }; #[derive(Default)] diff --git a/crates/astria-sequencer/src/ibc/ibc_relayer_change.rs b/crates/astria-sequencer/src/ibc/ibc_relayer_change.rs index 73f989435..b9a12b17c 100644 --- a/crates/astria-sequencer/src/ibc/ibc_relayer_change.rs +++ b/crates/astria-sequencer/src/ibc/ibc_relayer_change.rs @@ -1,12 +1,23 @@ -use anyhow::{ensure, Context as _, Result}; +use anyhow::{ + ensure, + Context as _, + Result, +}; use astria_core::{ - primitive::v1::Address, protocol::transaction::v1alpha1::action::IbcRelayerChangeAction, + primitive::v1::Address, + protocol::transaction::v1alpha1::action::IbcRelayerChangeAction, }; use async_trait::async_trait; -use cnidarium::{StateRead, StateWrite}; +use cnidarium::{ + StateRead, + StateWrite, +}; use crate::{ - ibc::state_ext::{StateReadExt, StateWriteExt}, + ibc::state_ext::{ + StateReadExt, + StateWriteExt, + }, transaction::action_handler::ActionHandler, }; diff --git a/crates/astria-sequencer/src/ibc/ics20_transfer.rs b/crates/astria-sequencer/src/ibc/ics20_transfer.rs index fe2bef3b1..a477a8e23 100644 --- a/crates/astria-sequencer/src/ibc/ics20_transfer.rs +++ b/crates/astria-sequencer/src/ibc/ics20_transfer.rs @@ -11,32 +11,62 @@ //! [`AppHandlerExecute`] is used for execution. use std::borrow::Cow; -use anyhow::{ensure, Context as _, Result}; +use anyhow::{ + ensure, + Context as _, + Result, +}; use astria_core::{ - primitive::v1::{asset::Denom, Address}, + primitive::v1::{ + asset::Denom, + Address, + }, sequencerblock::v1alpha1::block::Deposit, }; -use cnidarium::{StateRead, StateWrite}; +use cnidarium::{ + StateRead, + StateWrite, +}; use ibc_types::{ core::channel::{ channel, msgs::{ - MsgAcknowledgement, MsgChannelCloseConfirm, MsgChannelCloseInit, MsgChannelOpenAck, - MsgChannelOpenConfirm, MsgChannelOpenInit, MsgChannelOpenTry, MsgRecvPacket, + MsgAcknowledgement, + MsgChannelCloseConfirm, + MsgChannelCloseInit, + MsgChannelOpenAck, + MsgChannelOpenConfirm, + MsgChannelOpenInit, + MsgChannelOpenTry, + MsgRecvPacket, MsgTimeout, }, - ChannelId, PortId, + ChannelId, + PortId, }, transfer::acknowledgement::TokenTransferAcknowledgement, }; -use penumbra_ibc::component::app_handler::{AppHandler, AppHandlerCheck, AppHandlerExecute}; +use penumbra_ibc::component::app_handler::{ + AppHandler, + AppHandlerCheck, + AppHandlerExecute, +}; use penumbra_proto::penumbra::core::component::ibc::v1::FungibleTokenPacketData; use crate::{ accounts::state_ext::StateWriteExt as _, - asset::state_ext::{StateReadExt as _, StateWriteExt as _}, - bridge::state_ext::{StateReadExt as _, StateWriteExt as _}, - ibc::state_ext::{StateReadExt, StateWriteExt}, + asset::state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, + bridge::state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, + ibc::state_ext::{ + StateReadExt, + StateWriteExt, + }, }; /// The ICS20 transfer handler. diff --git a/crates/astria-sequencer/src/ibc/ics20_withdrawal.rs b/crates/astria-sequencer/src/ibc/ics20_withdrawal.rs index 30011fc46..55377de80 100644 --- a/crates/astria-sequencer/src/ibc/ics20_withdrawal.rs +++ b/crates/astria-sequencer/src/ibc/ics20_withdrawal.rs @@ -1,17 +1,37 @@ -use anyhow::{anyhow, ensure, Context as _, Result}; +use anyhow::{ + anyhow, + ensure, + Context as _, + Result, +}; use astria_core::{ - primitive::v1::{asset::Denom, Address}, + primitive::v1::{ + asset::Denom, + Address, + }, protocol::transaction::v1alpha1::action, }; -use ibc_types::core::channel::{ChannelId, PortId}; +use ibc_types::core::channel::{ + ChannelId, + PortId, +}; use penumbra_ibc::component::packet::{ - IBCPacket, SendPacketRead as _, SendPacketWrite as _, Unchecked, + IBCPacket, + SendPacketRead as _, + SendPacketWrite as _, + Unchecked, }; use tracing::instrument; use crate::{ - accounts::state_ext::{StateReadExt, StateWriteExt}, - ibc::state_ext::{StateReadExt as _, StateWriteExt as _}, + accounts::state_ext::{ + StateReadExt, + StateWriteExt, + }, + ibc::state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, transaction::action_handler::ActionHandler, }; diff --git a/crates/astria-sequencer/src/ibc/state_ext.rs b/crates/astria-sequencer/src/ibc/state_ext.rs index f88ecfb54..5e02e0193 100644 --- a/crates/astria-sequencer/src/ibc/state_ext.rs +++ b/crates/astria-sequencer/src/ibc/state_ext.rs @@ -1,11 +1,28 @@ -use anyhow::{bail, Context, Result}; -use astria_core::primitive::v1::{asset, Address, ADDRESS_LEN}; +use anyhow::{ + bail, + Context, + Result, +}; +use astria_core::primitive::v1::{ + asset, + Address, + ADDRESS_LEN, +}; use async_trait::async_trait; -use borsh::{BorshDeserialize, BorshSerialize}; -use cnidarium::{StateRead, StateWrite}; +use borsh::{ + BorshDeserialize, + BorshSerialize, +}; +use cnidarium::{ + StateRead, + StateWrite, +}; use hex::ToHex as _; use ibc_types::core::channel::ChannelId; -use tracing::{debug, instrument}; +use tracing::{ + debug, + instrument, +}; /// Newtype wrapper to read and write a u128 from rocksdb. #[derive(BorshSerialize, BorshDeserialize, Debug)] @@ -137,11 +154,17 @@ impl StateWriteExt for T {} #[cfg(test)] mod test { - use astria_core::primitive::v1::{asset::Id, Address}; + use astria_core::primitive::v1::{ + asset::Id, + Address, + }; use cnidarium::StateDelta; use ibc_types::core::channel::ChannelId; - use super::{StateReadExt as _, StateWriteExt as _}; + use super::{ + StateReadExt as _, + StateWriteExt as _, + }; #[tokio::test] async fn get_ibc_sudo_address_fails_if_not_set() { diff --git a/crates/astria-sequencer/src/main.rs b/crates/astria-sequencer/src/main.rs index 3689ac1a5..1adb08e16 100644 --- a/crates/astria-sequencer/src/main.rs +++ b/crates/astria-sequencer/src/main.rs @@ -1,7 +1,12 @@ use std::process::ExitCode; use anyhow::Context as _; -use astria_sequencer::{metrics_init, Config, Sequencer, BUILD_INFO}; +use astria_sequencer::{ + metrics_init, + Config, + Sequencer, + BUILD_INFO, +}; use tracing::info; // Following the BSD convention for failing to read config diff --git a/crates/astria-sequencer/src/mempool.rs b/crates/astria-sequencer/src/mempool.rs index a0decd426..5cd5addc6 100644 --- a/crates/astria-sequencer/src/mempool.rs +++ b/crates/astria-sequencer/src/mempool.rs @@ -1,15 +1,25 @@ use std::{ - cmp::{self, Ordering}, + cmp::{ + self, + Ordering, + }, collections::HashMap, future::Future, - sync::{Arc, OnceLock}, + sync::{ + Arc, + OnceLock, + }, }; use anyhow::Context; use astria_core::{ crypto::SigningKey, primitive::v1::Address, - protocol::transaction::v1alpha1::{SignedTransaction, TransactionParams, UnsignedTransaction}, + protocol::transaction::v1alpha1::{ + SignedTransaction, + TransactionParams, + UnsignedTransaction, + }, }; use priority_queue::PriorityQueue; use tokio::sync::RwLock; @@ -70,7 +80,9 @@ impl EnqueuedTransaction { )); }; - Ok(TransactionPriority { nonce_diff }) + Ok(TransactionPriority { + nonce_diff, + }) } pub(crate) fn tx_hash(&self) -> [u8; 32] { @@ -250,14 +262,20 @@ fn dummy_signed_tx() -> &'static Arc { chain_id: String::new(), }; let signing_key = SigningKey::from([0; 32]); - let unsigned_tx = UnsignedTransaction { actions, params }; + let unsigned_tx = UnsignedTransaction { + actions, + params, + }; Arc::new(unsigned_tx.into_signed(&signing_key)) }) } #[cfg(test)] mod test { - use std::hash::{Hash, Hasher}; + use std::hash::{ + Hash, + Hasher, + }; use super::*; use crate::app::test_utils::get_mock_tx; @@ -266,10 +284,12 @@ mod test { fn transaction_priority_should_error_if_invalid() { let enqueued_tx = EnqueuedTransaction::new(get_mock_tx(0)); let priority = enqueued_tx.priority(1); - assert!(priority - .unwrap_err() - .to_string() - .contains("less than current account nonce")); + assert!( + priority + .unwrap_err() + .to_string() + .contains("less than current account nonce") + ); } // From https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html @@ -277,8 +297,12 @@ mod test { // allow: we want explicit assertions here to match the documented expected behavior. #[allow(clippy::nonminimal_bool)] fn transaction_priority_comparisons_should_be_consistent() { - let high = TransactionPriority { nonce_diff: 0 }; - let low = TransactionPriority { nonce_diff: 1 }; + let high = TransactionPriority { + nonce_diff: 0, + }; + let low = TransactionPriority { + nonce_diff: 1, + }; assert!(high.partial_cmp(&high) == Some(Ordering::Equal)); assert!(high.partial_cmp(&low) == Some(Ordering::Greater)); @@ -518,9 +542,11 @@ mod test { assert_eq!(mempool.pending_nonce(&other_address).await.unwrap(), 101); // Check the pending nonce for an address with no enqueued txs is `None`. - assert!(mempool - .pending_nonce(&Address::from([1; 20])) - .await - .is_none()); + assert!( + mempool + .pending_nonce(&Address::from([1; 20])) + .await + .is_none() + ); } } diff --git a/crates/astria-sequencer/src/metrics_init.rs b/crates/astria-sequencer/src/metrics_init.rs index f961651be..777ce1833 100644 --- a/crates/astria-sequencer/src/metrics_init.rs +++ b/crates/astria-sequencer/src/metrics_init.rs @@ -2,7 +2,12 @@ //! //! Registers metrics & lists constants to be used as metric names throughout crate. -use metrics::{describe_counter, describe_gauge, describe_histogram, Unit}; +use metrics::{ + describe_counter, + describe_gauge, + describe_histogram, + Unit, +}; use telemetry::metric_name; /// Registers all metrics used by this crate. @@ -101,14 +106,18 @@ metric_name!(pub const CHECK_TX_REMOVED_ACCOUNT_BALANCE); #[cfg(test)] mod tests { use super::{ - CHECK_TX_REMOVED_ACCOUNT_BALANCE, CHECK_TX_REMOVED_FAILED_STATELESS, - CHECK_TX_REMOVED_STALE_NONCE, CHECK_TX_REMOVED_TOO_LARGE, + CHECK_TX_REMOVED_ACCOUNT_BALANCE, + CHECK_TX_REMOVED_FAILED_STATELESS, + CHECK_TX_REMOVED_STALE_NONCE, + CHECK_TX_REMOVED_TOO_LARGE, PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS, PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_COMETBFT_SPACE, PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_DECODE_FAILURE, PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_FAILED_EXECUTION, - PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_SEQUENCER_SPACE, PROCESS_PROPOSAL_SKIPPED_PROPOSAL, - PROPOSAL_DEPOSITS, PROPOSAL_TRANSACTIONS, + PREPARE_PROPOSAL_EXCLUDED_TRANSACTIONS_SEQUENCER_SPACE, + PROCESS_PROPOSAL_SKIPPED_PROPOSAL, + PROPOSAL_DEPOSITS, + PROPOSAL_TRANSACTIONS, }; #[track_caller] diff --git a/crates/astria-sequencer/src/proposal/block_size_constraints.rs b/crates/astria-sequencer/src/proposal/block_size_constraints.rs index 090101378..e20d3be64 100644 --- a/crates/astria-sequencer/src/proposal/block_size_constraints.rs +++ b/crates/astria-sequencer/src/proposal/block_size_constraints.rs @@ -1,4 +1,8 @@ -use anyhow::{anyhow, ensure, Context}; +use anyhow::{ + anyhow, + ensure, + Context, +}; use super::commitment::GeneratedCommitments; diff --git a/crates/astria-sequencer/src/proposal/commitment.rs b/crates/astria-sequencer/src/proposal/commitment.rs index efc8bb42e..65914b849 100644 --- a/crates/astria-sequencer/src/proposal/commitment.rs +++ b/crates/astria-sequencer/src/proposal/commitment.rs @@ -6,7 +6,10 @@ use astria_core::{ group_sequence_actions_in_signed_transaction_transactions_by_rollup_id, transaction::v1alpha1::SignedTransaction, }, - sequencerblock::v1alpha1::block::{Deposit, RollupData}, + sequencerblock::v1alpha1::block::{ + Deposit, + RollupData, + }, }; use bytes::Bytes; @@ -87,18 +90,28 @@ mod test { use astria_core::{ crypto::SigningKey, primitive::v1::{ - asset::{Denom, DEFAULT_NATIVE_ASSET_DENOM}, + asset::{ + Denom, + DEFAULT_NATIVE_ASSET_DENOM, + }, Address, }, protocol::transaction::v1alpha1::{ - action::{SequenceAction, TransferAction}, - TransactionParams, UnsignedTransaction, + action::{ + SequenceAction, + TransferAction, + }, + TransactionParams, + UnsignedTransaction, }, }; use rand::rngs::OsRng; use super::*; - use crate::asset::{get_native_asset, NATIVE_ASSET}; + use crate::asset::{ + get_native_asset, + NATIVE_ASSET, + }; #[test] fn generate_rollup_datas_commitment_should_ignore_transfers() { diff --git a/crates/astria-sequencer/src/sequence/action.rs b/crates/astria-sequencer/src/sequence/action.rs index 84c4afc81..d646c5f1b 100644 --- a/crates/astria-sequencer/src/sequence/action.rs +++ b/crates/astria-sequencer/src/sequence/action.rs @@ -1,13 +1,24 @@ -use anyhow::{ensure, Context, Result}; +use anyhow::{ + ensure, + Context, + Result, +}; use astria_core::{ - primitive::v1::Address, protocol::transaction::v1alpha1::action::SequenceAction, + primitive::v1::Address, + protocol::transaction::v1alpha1::action::SequenceAction, }; use tracing::instrument; use crate::{ - accounts::state_ext::{StateReadExt, StateWriteExt}, + accounts::state_ext::{ + StateReadExt, + StateWriteExt, + }, sequence::state_ext::StateReadExt as SequenceStateReadExt, - state_ext::{StateReadExt as _, StateWriteExt as _}, + state_ext::{ + StateReadExt as _, + StateWriteExt as _, + }, transaction::action_handler::ActionHandler, }; diff --git a/crates/astria-sequencer/src/sequence/component.rs b/crates/astria-sequencer/src/sequence/component.rs index 17d50ec4e..28b733f2d 100644 --- a/crates/astria-sequencer/src/sequence/component.rs +++ b/crates/astria-sequencer/src/sequence/component.rs @@ -1,11 +1,17 @@ use std::sync::Arc; use anyhow::Result; -use tendermint::abci::request::{BeginBlock, EndBlock}; +use tendermint::abci::request::{ + BeginBlock, + EndBlock, +}; use tracing::instrument; use super::state_ext::StateWriteExt; -use crate::{component::Component, genesis::GenesisState}; +use crate::{ + component::Component, + genesis::GenesisState, +}; #[derive(Default)] pub(crate) struct SequenceComponent; diff --git a/crates/astria-sequencer/src/sequence/state_ext.rs b/crates/astria-sequencer/src/sequence/state_ext.rs index 66f3d2f10..50345e42e 100644 --- a/crates/astria-sequencer/src/sequence/state_ext.rs +++ b/crates/astria-sequencer/src/sequence/state_ext.rs @@ -1,7 +1,17 @@ -use anyhow::{anyhow, Context, Result}; +use anyhow::{ + anyhow, + Context, + Result, +}; use async_trait::async_trait; -use borsh::{BorshDeserialize, BorshSerialize}; -use cnidarium::{StateRead, StateWrite}; +use borsh::{ + BorshDeserialize, + BorshSerialize, +}; +use cnidarium::{ + StateRead, + StateWrite, +}; use tracing::instrument; const SEQUENCE_ACTION_BASE_FEE_STORAGE_KEY: &str = "seqbasefee"; @@ -63,7 +73,10 @@ impl StateWriteExt for T {} mod test { use cnidarium::StateDelta; - use super::{StateReadExt as _, StateWriteExt as _}; + use super::{ + StateReadExt as _, + StateWriteExt as _, + }; #[tokio::test] async fn sequence_action_base_fee() { diff --git a/crates/astria-sequencer/src/sequencer.rs b/crates/astria-sequencer/src/sequencer.rs index 0b6a3585a..ed60debb4 100644 --- a/crates/astria-sequencer/src/sequencer.rs +++ b/crates/astria-sequencer/src/sequencer.rs @@ -1,19 +1,41 @@ -use anyhow::{anyhow, Context as _, Result}; +use anyhow::{ + anyhow, + Context as _, + Result, +}; use astria_core::generated::sequencerblock::v1alpha1::sequencer_service_server::SequencerServiceServer; -use penumbra_tower_trace::{trace::request_span, v038::RequestExt as _}; +use penumbra_tower_trace::{ + trace::request_span, + v038::RequestExt as _, +}; use tendermint::v0_38::abci::ConsensusRequest; use tokio::{ select, - signal::unix::{signal, SignalKind}, - sync::{oneshot, watch}, + signal::unix::{ + signal, + SignalKind, + }, + sync::{ + oneshot, + watch, + }, task::JoinHandle, }; use tower_abci::v038::Server; -use tracing::{error, info, instrument}; +use tracing::{ + error, + info, + instrument, +}; use crate::{ - app::App, config::Config, grpc::sequencer::SequencerServer, ibc::host_interface::AstriaHost, - mempool::Mempool, service, state_ext::StateReadExt as _, + app::App, + config::Config, + grpc::sequencer::SequencerServer, + ibc::host_interface::AstriaHost, + mempool::Mempool, + service, + state_ext::StateReadExt as _, }; pub struct Sequencer; @@ -211,5 +233,7 @@ fn spawn_signal_handler() -> SignalReceiver { } }); - SignalReceiver { stop_rx } + SignalReceiver { + stop_rx, + } } diff --git a/crates/astria-sequencer/src/service/consensus.rs b/crates/astria-sequencer/src/service/consensus.rs index 5c34ee31a..993cf74d9 100644 --- a/crates/astria-sequencer/src/service/consensus.rs +++ b/crates/astria-sequencer/src/service/consensus.rs @@ -1,12 +1,27 @@ -use anyhow::{bail, Context}; +use anyhow::{ + bail, + Context, +}; use cnidarium::Storage; -use tendermint::v0_38::abci::{request, response, ConsensusRequest, ConsensusResponse}; +use tendermint::v0_38::abci::{ + request, + response, + ConsensusRequest, + ConsensusResponse, +}; use tokio::sync::mpsc; use tower_abci::BoxError; use tower_actor::Message; -use tracing::{instrument, warn, Instrument}; +use tracing::{ + instrument, + warn, + Instrument, +}; -use crate::{app::App, genesis::GenesisState}; +use crate::{ + app::App, + genesis::GenesisState, +}; pub(crate) struct Consensus { queue: mpsc::Receiver>, @@ -198,23 +213,41 @@ impl Consensus { #[cfg(test)] mod test { - use std::{collections::HashMap, str::FromStr}; + use std::{ + collections::HashMap, + str::FromStr, + }; use astria_core::{ - crypto::{SigningKey, VerificationKey}, - primitive::v1::{asset::DEFAULT_NATIVE_ASSET_DENOM, Address, RollupId}, + crypto::{ + SigningKey, + VerificationKey, + }, + primitive::v1::{ + asset::DEFAULT_NATIVE_ASSET_DENOM, + Address, + RollupId, + }, protocol::transaction::v1alpha1::{ - action::SequenceAction, TransactionParams, UnsignedTransaction, + action::SequenceAction, + TransactionParams, + UnsignedTransaction, }, }; use bytes::Bytes; use prost::Message as _; use rand::rngs::OsRng; - use tendermint::{account::Id, Hash, Time}; + use tendermint::{ + account::Id, + Hash, + Time, + }; use super::*; use crate::{ - app::test_utils::default_fees, asset::get_native_asset, mempool::Mempool, + app::test_utils::default_fees, + asset::get_native_asset, + mempool::Mempool, proposal::commitment::generate_rollup_datas_commitment, }; @@ -224,12 +257,14 @@ mod test { nonce: 0, chain_id: "test".to_string(), }, - actions: vec![SequenceAction { - rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), - data: b"helloworld".to_vec(), - fee_asset_id: get_native_asset().id(), - } - .into()], + actions: vec![ + SequenceAction { + rollup_id: RollupId::from_unhashed_bytes(b"testchainid"), + data: b"helloworld".to_vec(), + fee_asset_id: get_native_asset().id(), + } + .into(), + ], } } @@ -314,26 +349,30 @@ mod test { async fn process_proposal_fail_missing_action_commitment() { let (mut consensus_service, _) = new_consensus_service(None).await; let process_proposal = new_process_proposal_request(vec![]); - assert!(consensus_service - .handle_process_proposal(process_proposal) - .await - .err() - .unwrap() - .to_string() - .contains("no transaction commitment in proposal")); + assert!( + consensus_service + .handle_process_proposal(process_proposal) + .await + .err() + .unwrap() + .to_string() + .contains("no transaction commitment in proposal") + ); } #[tokio::test] async fn process_proposal_fail_wrong_commitment_length() { let (mut consensus_service, _) = new_consensus_service(None).await; let process_proposal = new_process_proposal_request(vec![[0u8; 16].to_vec().into()]); - assert!(consensus_service - .handle_process_proposal(process_proposal) - .await - .err() - .unwrap() - .to_string() - .contains("transaction commitment must be 32 bytes")); + assert!( + consensus_service + .handle_process_proposal(process_proposal) + .await + .err() + .unwrap() + .to_string() + .contains("transaction commitment must be 32 bytes") + ); } #[tokio::test] @@ -343,13 +382,15 @@ mod test { [99u8; 32].to_vec().into(), [99u8; 32].to_vec().into(), ]); - assert!(consensus_service - .handle_process_proposal(process_proposal) - .await - .err() - .unwrap() - .to_string() - .contains("transaction commitment does not match expected")); + assert!( + consensus_service + .handle_process_proposal(process_proposal) + .await + .err() + .unwrap() + .to_string() + .contains("transaction commitment does not match expected") + ); } #[tokio::test] @@ -387,13 +428,19 @@ mod test { fn default_header() -> tendermint::block::Header { use tendermint::{ account, - block::{header::Version, Height}, + block::{ + header::Version, + Height, + }, chain, hash::AppHash, }; tendermint::block::Header { - version: Version { block: 0, app: 0 }, + version: Version { + block: 0, + app: 0, + }, chain_id: chain::Id::try_from("test").unwrap(), height: Height::from(1u32), time: Time::now(), diff --git a/crates/astria-sequencer/src/service/info/abci_query_router.rs b/crates/astria-sequencer/src/service/info/abci_query_router.rs index 7c91d691d..988e0b779 100644 --- a/crates/astria-sequencer/src/service/info/abci_query_router.rs +++ b/crates/astria-sequencer/src/service/info/abci_query_router.rs @@ -33,11 +33,21 @@ //! `Clone` to fulfill the `Clone` requirement of the `Info` service. //! 4. finally `MakeErasedAbciQueryHandler` is the glue that allows to go from a non-object safe //! `AbciQueryHandler` to an object-safe `ErasedAbciQueryHandler`. -use std::{future::Future, pin::Pin}; +use std::{ + future::Future, + pin::Pin, +}; use cnidarium::Storage; -use matchit::{InsertError, Match, MatchError}; -use tendermint::abci::{request, response}; +use matchit::{ + InsertError, + Match, + MatchError, +}; +use tendermint::abci::{ + request, + response, +}; /// `Router` is a wrapper around [`matchit::Router`] to route abci queries /// to handlers. @@ -77,7 +87,9 @@ impl BoxedAbciQueryHandler { where H: AbciQueryHandler, { - Self(Box::new(MakeErasedAbciQueryHandler { handler })) + Self(Box::new(MakeErasedAbciQueryHandler { + handler, + })) } pub(super) async fn call( diff --git a/crates/astria-sequencer/src/service/info/mod.rs b/crates/astria-sequencer/src/service/info/mod.rs index a00edb6c3..7433c14a0 100644 --- a/crates/astria-sequencer/src/service/info/mod.rs +++ b/crates/astria-sequencer/src/service/info/mod.rs @@ -1,21 +1,34 @@ use std::{ pin::Pin, - task::{Context, Poll}, + task::{ + Context, + Poll, + }, }; use anyhow::Context as _; use astria_core::protocol::abci::AbciErrorCode; use cnidarium::Storage; -use futures::{Future, FutureExt}; +use futures::{ + Future, + FutureExt, +}; use penumbra_tower_trace::v038::RequestExt as _; use tendermint::v0_38::abci::{ request, - response::{self, Echo}, - InfoRequest, InfoResponse, + response::{ + self, + Echo, + }, + InfoRequest, + InfoResponse, }; use tower::Service; use tower_abci::BoxError; -use tracing::{instrument, Instrument as _}; +use tracing::{ + instrument, + Instrument as _, +}; mod abci_query_router; @@ -98,7 +111,10 @@ impl Info { }; } - Ok(matchit::Match { value, params }) => { + Ok(matchit::Match { + value, + params, + }) => { let params = params .iter() .map(|(k, v)| (k.to_owned(), v.to_owned())) @@ -133,17 +149,28 @@ impl Service for Info { #[cfg(test)] mod test { use astria_core::primitive::v1::{ - asset::{Denom, DEFAULT_NATIVE_ASSET_DENOM}, + asset::{ + Denom, + DEFAULT_NATIVE_ASSET_DENOM, + }, Address, }; use cnidarium::StateDelta; use prost::Message as _; - use tendermint::v0_38::abci::{request, InfoRequest, InfoResponse}; + use tendermint::v0_38::abci::{ + request, + InfoRequest, + InfoResponse, + }; use super::Info; use crate::{ accounts::state_ext::StateWriteExt as _, - asset::{get_native_asset, initialize_native_asset, state_ext::StateWriteExt}, + asset::{ + get_native_asset, + initialize_native_asset, + state_ext::StateWriteExt, + }, state_ext::StateWriteExt as _, }; diff --git a/crates/astria-sequencer/src/service/mempool.rs b/crates/astria-sequencer/src/service/mempool.rs index 22e0e68af..b688bf376 100644 --- a/crates/astria-sequencer/src/service/mempool.rs +++ b/crates/astria-sequencer/src/service/mempool.rs @@ -1,22 +1,39 @@ use std::{ pin::Pin, - task::{Context, Poll}, + task::{ + Context, + Poll, + }, }; use astria_core::{ generated::protocol::transaction::v1alpha1 as raw, - protocol::{abci::AbciErrorCode, transaction::v1alpha1::SignedTransaction}, + protocol::{ + abci::AbciErrorCode, + transaction::v1alpha1::SignedTransaction, + }, }; use cnidarium::Storage; -use futures::{Future, FutureExt}; +use futures::{ + Future, + FutureExt, +}; use prost::Message as _; -use tendermint::v0_38::abci::{request, response, MempoolRequest, MempoolResponse}; +use tendermint::v0_38::abci::{ + request, + response, + MempoolRequest, + MempoolResponse, +}; use tower::Service; use tower_abci::BoxError; use tracing::Instrument as _; use crate::{ - accounts::state_ext::StateReadExt, mempool::Mempool as AppMempool, metrics_init, transaction, + accounts::state_ext::StateReadExt, + mempool::Mempool as AppMempool, + metrics_init, + transaction, }; const MAX_TX_SIZE: usize = 256_000; // 256 KB @@ -33,7 +50,10 @@ pub(crate) struct Mempool { impl Mempool { pub(crate) fn new(storage: Storage, mempool: AppMempool) -> Self { - Self { storage, mempool } + Self { + storage, + mempool, + } } } @@ -80,7 +100,9 @@ async fn handle_check_tx( let tx_hash = sha2::Sha256::digest(&req.tx).into(); - let request::CheckTx { tx, .. } = req; + let request::CheckTx { + tx, .. + } = req; if tx.len() > MAX_TX_SIZE { mempool.remove(tx_hash).await; metrics::counter!(metrics_init::CHECK_TX_REMOVED_TOO_LARGE).increment(1); diff --git a/crates/astria-sequencer/src/service/snapshot.rs b/crates/astria-sequencer/src/service/snapshot.rs index d1290b305..df6aae796 100644 --- a/crates/astria-sequencer/src/service/snapshot.rs +++ b/crates/astria-sequencer/src/service/snapshot.rs @@ -1,13 +1,25 @@ use std::{ pin::Pin, - task::{Context, Poll}, + task::{ + Context, + Poll, + }, }; -use futures::{Future, FutureExt}; +use futures::{ + Future, + FutureExt, +}; use penumbra_tower_trace::v038::RequestExt as _; use tendermint::v0_38::abci::{ - response::{ApplySnapshotChunk, ListSnapshots, LoadSnapshotChunk, OfferSnapshot}, - SnapshotRequest, SnapshotResponse, + response::{ + ApplySnapshotChunk, + ListSnapshots, + LoadSnapshotChunk, + OfferSnapshot, + }, + SnapshotRequest, + SnapshotResponse, }; use tower::Service; use tower_abci::BoxError; diff --git a/crates/astria-sequencer/src/state_ext.rs b/crates/astria-sequencer/src/state_ext.rs index fe12e8777..b8ee655d3 100644 --- a/crates/astria-sequencer/src/state_ext.rs +++ b/crates/astria-sequencer/src/state_ext.rs @@ -1,7 +1,14 @@ -use anyhow::{bail, Context as _, Result}; +use anyhow::{ + bail, + Context as _, + Result, +}; use astria_core::primitive::v1::asset; use async_trait::async_trait; -use cnidarium::{StateRead, StateWrite}; +use cnidarium::{ + StateRead, + StateWrite, +}; use futures::StreamExt as _; use tendermint::Time; use tracing::instrument; @@ -287,7 +294,11 @@ mod test { use cnidarium::StateDelta; use tendermint::Time; - use super::{revision_number_from_chain_id, StateReadExt as _, StateWriteExt as _}; + use super::{ + revision_number_from_chain_id, + StateReadExt as _, + StateWriteExt as _, + }; #[test] fn revision_number_from_chain_id_regex() { diff --git a/crates/astria-sequencer/src/transaction/action_handler.rs b/crates/astria-sequencer/src/transaction/action_handler.rs index 74aa5b07e..17cfb7345 100644 --- a/crates/astria-sequencer/src/transaction/action_handler.rs +++ b/crates/astria-sequencer/src/transaction/action_handler.rs @@ -1,7 +1,10 @@ use anyhow::Result; use astria_core::primitive::v1::Address; use async_trait::async_trait; -use cnidarium::{StateRead, StateWrite}; +use cnidarium::{ + StateRead, + StateWrite, +}; #[async_trait] pub(crate) trait ActionHandler { diff --git a/crates/astria-sequencer/src/transaction/checks.rs b/crates/astria-sequencer/src/transaction/checks.rs index 174a58804..a2074e0e2 100644 --- a/crates/astria-sequencer/src/transaction/checks.rs +++ b/crates/astria-sequencer/src/transaction/checks.rs @@ -1,17 +1,30 @@ use std::collections::HashMap; -use anyhow::{ensure, Context as _}; +use anyhow::{ + ensure, + Context as _, +}; use astria_core::{ - primitive::v1::{asset, Address, RollupId}, + primitive::v1::{ + asset, + Address, + RollupId, + }, protocol::transaction::v1alpha1::{ - action::{Action, BridgeLockAction}, - SignedTransaction, UnsignedTransaction, + action::{ + Action, + BridgeLockAction, + }, + SignedTransaction, + UnsignedTransaction, }, }; use crate::{ - accounts::state_ext::StateReadExt, bridge::state_ext::StateReadExt as _, - ibc::state_ext::StateReadExt as _, state_ext::StateReadExt as _, + accounts::state_ext::StateReadExt, + bridge::state_ext::StateReadExt as _, + ibc::state_ext::StateReadExt as _, + state_ext::StateReadExt as _, }; pub(crate) async fn check_nonce_mempool( @@ -254,11 +267,18 @@ async fn bridge_unlock_update_fees( mod test { use astria_core::{ primitive::v1::{ - asset::{Denom, DEFAULT_NATIVE_ASSET_DENOM}, - RollupId, ADDRESS_LEN, + asset::{ + Denom, + DEFAULT_NATIVE_ASSET_DENOM, + }, + RollupId, + ADDRESS_LEN, }, protocol::transaction::v1alpha1::{ - action::{SequenceAction, TransferAction}, + action::{ + SequenceAction, + TransferAction, + }, TransactionParams, }, }; @@ -266,8 +286,10 @@ mod test { use super::*; use crate::{ - accounts::state_ext::StateWriteExt as _, app::test_utils::*, - bridge::state_ext::StateWriteExt, ibc::state_ext::StateWriteExt as _, + accounts::state_ext::StateWriteExt as _, + app::test_utils::*, + bridge::state_ext::StateWriteExt, + ibc::state_ext::StateWriteExt as _, sequence::state_ext::StateWriteExt as _, }; @@ -326,7 +348,10 @@ mod test { nonce: 0, chain_id: "test-chain-id".to_string(), }; - let tx = UnsignedTransaction { actions, params }; + let tx = UnsignedTransaction { + actions, + params, + }; let signed_tx = tx.into_signed(&alice_signing_key); check_balance_mempool(&signed_tx, &state_tx) @@ -385,7 +410,10 @@ mod test { nonce: 0, chain_id: "test-chain-id".to_string(), }; - let tx = UnsignedTransaction { actions, params }; + let tx = UnsignedTransaction { + actions, + params, + }; let signed_tx = tx.into_signed(&alice_signing_key); let err = check_balance_mempool(&signed_tx, &state_tx) diff --git a/crates/astria-sequencer/src/transaction/mod.rs b/crates/astria-sequencer/src/transaction/mod.rs index 96d2d6cbe..1eaa5f2a3 100644 --- a/crates/astria-sequencer/src/transaction/mod.rs +++ b/crates/astria-sequencer/src/transaction/mod.rs @@ -4,20 +4,35 @@ mod checks; use std::fmt; pub(crate) use action_handler::ActionHandler; -use anyhow::{ensure, Context as _}; +use anyhow::{ + ensure, + Context as _, +}; use astria_core::{ primitive::v1::Address, - protocol::transaction::v1alpha1::{action::Action, SignedTransaction, UnsignedTransaction}, + protocol::transaction::v1alpha1::{ + action::Action, + SignedTransaction, + UnsignedTransaction, + }, }; pub(crate) use checks::{ - check_balance_for_total_fees, check_balance_mempool, check_chain_id_mempool, + check_balance_for_total_fees, + check_balance_mempool, + check_chain_id_mempool, check_nonce_mempool, }; use tracing::instrument; use crate::{ - accounts::state_ext::{StateReadExt, StateWriteExt}, - ibc::{host_interface::AstriaHost, state_ext::StateReadExt as _}, + accounts::state_ext::{ + StateReadExt, + StateWriteExt, + }, + ibc::{ + host_interface::AstriaHost, + state_ext::StateReadExt as _, + }, state_ext::StateReadExt as _, }; diff --git a/crates/astria-telemetry/src/display.rs b/crates/astria-telemetry/src/display.rs index 480e538da..a95d4b9c9 100644 --- a/crates/astria-telemetry/src/display.rs +++ b/crates/astria-telemetry/src/display.rs @@ -1,7 +1,13 @@ //! Utilities to emit fields using their [`std::fmt::Display`] implementation. use std::{ - fmt::{self, Display, Formatter, Result}, - io, str, + fmt::{ + self, + Display, + Formatter, + Result, + }, + io, + str, }; use base64_serde::base64_serde_type; @@ -18,7 +24,10 @@ pub struct Base64<'a>(&'a [u8]); impl<'a> Display for Base64<'a> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { - use base64::{display::Base64Display, engine::general_purpose::STANDARD}; + use base64::{ + display::Base64Display, + engine::general_purpose::STANDARD, + }; Base64Display::new(self.0, &STANDARD).fmt(f) } } @@ -110,7 +119,9 @@ where io::Error::new(io::ErrorKind::Other, "fmt error") } - let mut wr = WriterFormatter { inner: f }; + let mut wr = WriterFormatter { + inner: f, + }; serde_json::to_writer(&mut wr, self.0).map_err(|_| fmt::Error) } } diff --git a/crates/astria-telemetry/src/lib.rs b/crates/astria-telemetry/src/lib.rs index 8ed61b75c..6226e7122 100644 --- a/crates/astria-telemetry/src/lib.rs +++ b/crates/astria-telemetry/src/lib.rs @@ -10,17 +10,35 @@ //! ``` use std::{ io::IsTerminal as _, - net::{AddrParseError, SocketAddr}, + net::{ + AddrParseError, + SocketAddr, + }, }; -use metrics_exporter_prometheus::{BuildError, PrometheusBuilder}; -use opentelemetry::{global, trace::TracerProvider as _}; -use opentelemetry_sdk::{runtime::Tokio, trace::TracerProvider}; +use metrics_exporter_prometheus::{ + BuildError, + PrometheusBuilder, +}; +use opentelemetry::{ + global, + trace::TracerProvider as _, +}; +use opentelemetry_sdk::{ + runtime::Tokio, + trace::TracerProvider, +}; use opentelemetry_stdout::SpanExporter; use tracing_subscriber::{ - filter::{LevelFilter, ParseError}, + filter::{ + LevelFilter, + ParseError, + }, layer::SubscriberExt as _, - util::{SubscriberInitExt as _, TryInitError}, + util::{ + SubscriberInitExt as _, + TryInitError, + }, EnvFilter, }; @@ -179,7 +197,10 @@ impl Config { #[must_use = "telemetry must be initialized to be useful"] pub fn set_no_otel(self, no_otel: bool) -> Self { - Self { no_otel, ..self } + Self { + no_otel, + ..self + } } #[must_use = "telemetry must be initialized to be useful"] diff --git a/crates/astria-telemetry/src/macros.rs b/crates/astria-telemetry/src/macros.rs index 79eed19e1..f5799f0a5 100644 --- a/crates/astria-telemetry/src/macros.rs +++ b/crates/astria-telemetry/src/macros.rs @@ -2,7 +2,9 @@ // hidden because they shouldn't be imported. #[doc(hidden)] pub use const_format::{ - concatcp as __concatcp, map_ascii_case as __map_ascii_case, Case as __Case, + concatcp as __concatcp, + map_ascii_case as __map_ascii_case, + Case as __Case, }; /// Declare a `const` string slice, using the declaring crate's name as a diff --git a/crates/astria-test-utils/src/mock/geth.rs b/crates/astria-test-utils/src/mock/geth.rs index 98f93393d..a7f56eee4 100644 --- a/crates/astria-test-utils/src/mock/geth.rs +++ b/crates/astria-test-utils/src/mock/geth.rs @@ -66,12 +66,22 @@ use std::net::SocketAddr; pub use __rpc_traits::GethServer; use ethers::types::Transaction; use jsonrpsee::{ - core::{async_trait, SubscriptionResult}, + core::{ + async_trait, + SubscriptionResult, + }, server::IdProvider, - types::{ErrorObjectOwned, SubscriptionId}, + types::{ + ErrorObjectOwned, + SubscriptionId, + }, PendingSubscriptionSink, }; -use tokio::sync::broadcast::{channel, error::SendError, Sender}; +use tokio::sync::broadcast::{ + channel, + error::SendError, + Sender, +}; #[derive(Debug)] pub struct RandomU256IdProvider; @@ -96,14 +106,18 @@ impl IdProvider for RandomU256IdProvider { } mod __rpc_traits { - use jsonrpsee::{core::SubscriptionResult, proc_macros::rpc, types::ErrorObjectOwned}; + use jsonrpsee::{ + core::SubscriptionResult, + proc_macros::rpc, + types::ErrorObjectOwned, + }; // The mockserver has to be able to handle an `eth_subscribe` RPC with parameters // `"newPendingTransactions"` and `true` #[rpc(server)] pub trait Geth { #[subscription(name = "eth_subscribe", item = Transaction, unsubscribe = "eth_unsubscribe")] async fn eth_subscribe(&self, target: String, full_txs: Option) - -> SubscriptionResult; + -> SubscriptionResult; #[method(name = "net_version")] async fn net_version(&self) -> Result; diff --git a/lint/tracing_debug_field/src/lib.rs b/lint/tracing_debug_field/src/lib.rs index 5e8a05632..e1cc28839 100644 --- a/lint/tracing_debug_field/src/lib.rs +++ b/lint/tracing_debug_field/src/lib.rs @@ -4,12 +4,24 @@ extern crate rustc_hir; extern crate rustc_span; -use clippy_utils::{diagnostics::span_lint_and_help, is_expr_path_def_path}; +use clippy_utils::{ + diagnostics::span_lint_and_help, + is_expr_path_def_path, +}; use if_chain::if_chain; -use rustc_hir::{Expr, ExprKind}; -use rustc_lint::{LateContext, LateLintPass}; +use rustc_hir::{ + Expr, + ExprKind, +}; +use rustc_lint::{ + LateContext, + LateLintPass, +}; use rustc_span::{ - hygiene::{ExpnKind, MacroKind}, + hygiene::{ + ExpnKind, + MacroKind, + }, Span, }; @@ -83,7 +95,14 @@ fn first_span_in_crate(arg: &Expr<'_>) -> Span { let mut span = 'get_span: { // Case 1: fields like foo = ?bar that are transformed as debug(&bar). if let Expr { - kind: ExprKind::AddrOf(_, _, Expr { span, .. }), + kind: + ExprKind::AddrOf( + _, + _, + Expr { + span, .. + }, + ), .. } = arg { From 31ad1e90cde2554fc43734c5301cf36354581537 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Fri, 7 Jun 2024 18:03:02 -0500 Subject: [PATCH 07/23] minor syntax changes, added comments for test cases --- crates/astria-composer/src/executor/tests.rs | 12 ++++-- .../tests/blackbox/helper/mock_sequencer.rs | 41 ++++++++----------- 2 files changed, 27 insertions(+), 26 deletions(-) diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index 8d191bbc3..27ea9626e 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -212,8 +212,8 @@ async fn mount_broadcast_tx_sync_seq_actions_mock(server: &MockServer) -> MockGu .await } -/// Mounts a `CometBFT` status response with a specified mock sequencer chain id -async fn mount_cometbft_status_response(server: &MockServer,mock_sequencer_chain_id: &str,) -> MockGuard { +// Mounts a `CometBFT` status response with a specified mock sequencer chain id +async fn mount_cometbft_status_response(server: &MockServer, mock_sequencer_chain_id: &str) -> MockGuard { use tendermint_rpc::endpoint::status; let mut status_response: status::Response = serde_json::from_str(STATUS_RESPONSE).unwrap(); @@ -554,12 +554,17 @@ async fn two_seq_actions_single_bundle() { } } +/// Test to check that executor's configured sequencer chain id and sequencer's actual chain id match #[tokio::test] async fn should_exit_if_mismatch_sequencer_chain_id() { - // set up the executor, channel for writing seq actions, and the sequencer mock + // set up sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); + + // mount a status response with an incorrect chain_id let _status_guard = mount_cometbft_status_response(&sequencer, "different-chain-id").await; + + // build the executor with the correct chain_id let build_result = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -572,5 +577,6 @@ async fn should_exit_if_mismatch_sequencer_chain_id() { .build() .await; + // verify that the executor build resulted in an error assert!(build_result.is_err()); } diff --git a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs index 736ab1c23..159111f56 100644 --- a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs +++ b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs @@ -59,6 +59,24 @@ pub async fn mount_abci_query_mock( .await } +async fn mount_cometbft_status_response(server: &MockServer, mock_sequencer_chain_id: &str) -> MockGuard { + use tendermint_rpc::endpoint::status; + + let mut status_response: status::Response = serde_json::from_str(STATUS_RESPONSE).unwrap(); + status_response.node_info.network = mock_sequencer_chain_id.to_string().parse().unwrap(); + + let response = + tendermint_rpc::response::Wrapper::new_with_id(Id::Num(1), Some(status_response), None); + + Mock::given(body_partial_json(json!({"method": "status"}))) + .respond_with(ResponseTemplate::new(200).set_body_json(response)) + .up_to_n_times(1) + .expect(1..) + .named("CometBFT status") + .mount_as_scoped(server) + .await +} + const STATUS_RESPONSE: &str = r#" { "node_info": { @@ -98,26 +116,3 @@ const STATUS_RESPONSE: &str = r#" "voting_power": "0" } }"#; - -/// Mounts a `CometBFT` status response with the chain ID set as per -/// `TestSequencerRelayerConfig::sequencer_chain_id`. -async fn mount_cometbft_status_response( - server: &MockServer, - mock_sequencer_chain_id: &str, -) -> MockGuard { - use tendermint_rpc::endpoint::status; - - let mut status_response: status::Response = serde_json::from_str(STATUS_RESPONSE).unwrap(); - status_response.node_info.network = mock_sequencer_chain_id.to_string().parse().unwrap(); - - let response = - tendermint_rpc::response::Wrapper::new_with_id(Id::Num(1), Some(status_response), None); - - Mock::given(body_partial_json(json!({"method": "status"}))) - .respond_with(ResponseTemplate::new(200).set_body_json(response)) - .up_to_n_times(1) - .expect(1..) - .named("CometBFT status") - .mount_as_scoped(server) - .await -} From e915b8fe3c363fd6db4d35912446da220ca98db6 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Fri, 7 Jun 2024 18:09:16 -0500 Subject: [PATCH 08/23] merge upstream changes --- .../generated/astria_bridgeable_erc20.rs | 1644 +++++++++-------- .../ethereum/generated/astria_withdrawer.rs | 388 ++-- .../generated/astria_withdrawer_interface.rs | 236 +-- 3 files changed, 1252 insertions(+), 1016 deletions(-) diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/generated/astria_bridgeable_erc20.rs b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/generated/astria_bridgeable_erc20.rs index 29dd31f71..1b5189061 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/generated/astria_bridgeable_erc20.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/generated/astria_bridgeable_erc20.rs @@ -7,7 +7,7 @@ pub use astria_bridgeable_erc20::*; clippy::upper_case_acronyms, clippy::type_complexity, dead_code, - non_camel_case_types + non_camel_case_types, )] pub mod astria_bridgeable_erc20 { #[allow(deprecated)] @@ -23,7 +23,9 @@ pub mod astria_bridgeable_erc20 { ), }, ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("_baseChainAssetPrecision",), + name: ::std::borrow::ToOwned::to_owned( + "_baseChainAssetPrecision", + ), kind: ::ethers::core::abi::ethabi::ParamType::Uint(32usize), internal_type: ::core::option::Option::Some( ::std::borrow::ToOwned::to_owned("uint32"), @@ -48,587 +50,732 @@ pub mod astria_bridgeable_erc20 { functions: ::core::convert::From::from([ ( ::std::borrow::ToOwned::to_owned("BASE_CHAIN_ASSET_PRECISION"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("BASE_CHAIN_ASSET_PRECISION",), - inputs: ::std::vec![], - outputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::string::String::new(), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(32usize), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint32"), + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned( + "BASE_CHAIN_ASSET_PRECISION", ), - },], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, - },], + inputs: ::std::vec![], + outputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::string::String::new(), + kind: ::ethers::core::abi::ethabi::ParamType::Uint(32usize), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint32"), + ), + }, + ], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("BRIDGE"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("BRIDGE"), - inputs: ::std::vec![], - outputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::string::String::new(), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), - ), - },], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned("BRIDGE"), + inputs: ::std::vec![], + outputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::string::String::new(), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("allowance"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("allowance"), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("owner"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("spender"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), - ), - }, - ], - outputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::string::String::new(), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint256"), - ), - },], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned("allowance"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("owner"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("spender"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ], + outputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::string::String::new(), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint256"), + ), + }, + ], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("approve"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("approve"), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("spender"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("value"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint256"), - ), - }, - ], - outputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::string::String::new(), - kind: ::ethers::core::abi::ethabi::ParamType::Bool, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("bool"), - ), - },], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::NonPayable, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned("approve"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("spender"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("value"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint256"), + ), + }, + ], + outputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::string::String::new(), + kind: ::ethers::core::abi::ethabi::ParamType::Bool, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("bool"), + ), + }, + ], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::NonPayable, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("balanceOf"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("balanceOf"), - inputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("account"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), - ), - },], - outputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::string::String::new(), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint256"), - ), - },], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned("balanceOf"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("account"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ], + outputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::string::String::new(), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint256"), + ), + }, + ], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("decimals"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("decimals"), - inputs: ::std::vec![], - outputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::string::String::new(), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(8usize), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint8"), - ), - },], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned("decimals"), + inputs: ::std::vec![], + outputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::string::String::new(), + kind: ::ethers::core::abi::ethabi::ParamType::Uint(8usize), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint8"), + ), + }, + ], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("mint"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("mint"), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("_to"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("_amount"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint256"), - ), - }, - ], - outputs: ::std::vec![], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::NonPayable, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned("mint"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("_to"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("_amount"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint256"), + ), + }, + ], + outputs: ::std::vec![], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::NonPayable, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("name"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("name"), - inputs: ::std::vec![], - outputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::string::String::new(), - kind: ::ethers::core::abi::ethabi::ParamType::String, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("string"), - ), - },], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned("name"), + inputs: ::std::vec![], + outputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::string::String::new(), + kind: ::ethers::core::abi::ethabi::ParamType::String, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("string"), + ), + }, + ], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("symbol"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("symbol"), - inputs: ::std::vec![], - outputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::string::String::new(), - kind: ::ethers::core::abi::ethabi::ParamType::String, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("string"), - ), - },], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned("symbol"), + inputs: ::std::vec![], + outputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::string::String::new(), + kind: ::ethers::core::abi::ethabi::ParamType::String, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("string"), + ), + }, + ], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("totalSupply"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("totalSupply"), - inputs: ::std::vec![], - outputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::string::String::new(), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint256"), - ), - },], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned("totalSupply"), + inputs: ::std::vec![], + outputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::string::String::new(), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint256"), + ), + }, + ], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("transfer"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("transfer"), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("to"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("value"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint256"), - ), - }, - ], - outputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::string::String::new(), - kind: ::ethers::core::abi::ethabi::ParamType::Bool, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("bool"), - ), - },], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::NonPayable, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned("transfer"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("to"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("value"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint256"), + ), + }, + ], + outputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::string::String::new(), + kind: ::ethers::core::abi::ethabi::ParamType::Bool, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("bool"), + ), + }, + ], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::NonPayable, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("transferFrom"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("transferFrom"), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("from"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("to"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("value"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint256"), - ), - }, - ], - outputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::string::String::new(), - kind: ::ethers::core::abi::ethabi::ParamType::Bool, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("bool"), - ), - },], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::NonPayable, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned("transferFrom"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("from"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("to"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("value"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint256"), + ), + }, + ], + outputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::string::String::new(), + kind: ::ethers::core::abi::ethabi::ParamType::Bool, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("bool"), + ), + }, + ], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::NonPayable, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("withdrawToIbcChain"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("withdrawToIbcChain"), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("_amount"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint256"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("_destinationChainAddress",), - kind: ::ethers::core::abi::ethabi::ParamType::String, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("string"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("_memo"), - kind: ::ethers::core::abi::ethabi::ParamType::String, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("string"), - ), - }, - ], - outputs: ::std::vec![], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::NonPayable, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned("withdrawToIbcChain"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("_amount"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint256"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned( + "_destinationChainAddress", + ), + kind: ::ethers::core::abi::ethabi::ParamType::String, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("string"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("_memo"), + kind: ::ethers::core::abi::ethabi::ParamType::String, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("string"), + ), + }, + ], + outputs: ::std::vec![], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::NonPayable, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("withdrawToSequencer"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("withdrawToSequencer",), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("_amount"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint256"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("_destinationChainAddress",), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), - ), - }, - ], - outputs: ::std::vec![], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::NonPayable, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned( + "withdrawToSequencer", + ), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("_amount"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint256"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned( + "_destinationChainAddress", + ), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ], + outputs: ::std::vec![], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::NonPayable, + }, + ], ), ]), events: ::core::convert::From::from([ ( ::std::borrow::ToOwned::to_owned("Approval"), - ::std::vec![::ethers::core::abi::ethabi::Event { - name: ::std::borrow::ToOwned::to_owned("Approval"), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("owner"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("spender"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("value"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - indexed: false, - }, - ], - anonymous: false, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Event { + name: ::std::borrow::ToOwned::to_owned("Approval"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("owner"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("spender"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("value"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + indexed: false, + }, + ], + anonymous: false, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("Ics20Withdrawal"), - ::std::vec![::ethers::core::abi::ethabi::Event { - name: ::std::borrow::ToOwned::to_owned("Ics20Withdrawal"), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("sender"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("amount"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("destinationChainAddress",), - kind: ::ethers::core::abi::ethabi::ParamType::String, - indexed: false, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("memo"), - kind: ::ethers::core::abi::ethabi::ParamType::String, - indexed: false, - }, - ], - anonymous: false, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Event { + name: ::std::borrow::ToOwned::to_owned("Ics20Withdrawal"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("sender"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("amount"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned( + "destinationChainAddress", + ), + kind: ::ethers::core::abi::ethabi::ParamType::String, + indexed: false, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("memo"), + kind: ::ethers::core::abi::ethabi::ParamType::String, + indexed: false, + }, + ], + anonymous: false, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("Mint"), - ::std::vec![::ethers::core::abi::ethabi::Event { - name: ::std::borrow::ToOwned::to_owned("Mint"), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("account"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("amount"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - indexed: false, - }, - ], - anonymous: false, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Event { + name: ::std::borrow::ToOwned::to_owned("Mint"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("account"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("amount"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + indexed: false, + }, + ], + anonymous: false, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("SequencerWithdrawal"), - ::std::vec![::ethers::core::abi::ethabi::Event { - name: ::std::borrow::ToOwned::to_owned("SequencerWithdrawal",), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("sender"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("amount"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("destinationChainAddress",), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: false, - }, - ], - anonymous: false, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Event { + name: ::std::borrow::ToOwned::to_owned( + "SequencerWithdrawal", + ), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("sender"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("amount"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned( + "destinationChainAddress", + ), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: false, + }, + ], + anonymous: false, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("Transfer"), - ::std::vec![::ethers::core::abi::ethabi::Event { - name: ::std::borrow::ToOwned::to_owned("Transfer"), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("from"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("to"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("value"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - indexed: false, - }, - ], - anonymous: false, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Event { + name: ::std::borrow::ToOwned::to_owned("Transfer"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("from"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("to"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("value"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + indexed: false, + }, + ], + anonymous: false, + }, + ], ), ]), errors: ::core::convert::From::from([ ( ::std::borrow::ToOwned::to_owned("ERC20InsufficientAllowance"), - ::std::vec![::ethers::core::abi::ethabi::AbiError { - name: ::std::borrow::ToOwned::to_owned("ERC20InsufficientAllowance",), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("spender"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("allowance"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint256"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("needed"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint256"), - ), - }, - ], - },], + ::std::vec![ + ::ethers::core::abi::ethabi::AbiError { + name: ::std::borrow::ToOwned::to_owned( + "ERC20InsufficientAllowance", + ), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("spender"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("allowance"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint256"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("needed"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint256"), + ), + }, + ], + }, + ], ), ( ::std::borrow::ToOwned::to_owned("ERC20InsufficientBalance"), - ::std::vec![::ethers::core::abi::ethabi::AbiError { - name: ::std::borrow::ToOwned::to_owned("ERC20InsufficientBalance",), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("sender"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("balance"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint256"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("needed"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint256"), - ), - }, - ], - },], + ::std::vec![ + ::ethers::core::abi::ethabi::AbiError { + name: ::std::borrow::ToOwned::to_owned( + "ERC20InsufficientBalance", + ), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("sender"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("balance"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint256"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("needed"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint256"), + ), + }, + ], + }, + ], ), ( ::std::borrow::ToOwned::to_owned("ERC20InvalidApprover"), - ::std::vec![::ethers::core::abi::ethabi::AbiError { - name: ::std::borrow::ToOwned::to_owned("ERC20InvalidApprover",), - inputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("approver"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), + ::std::vec![ + ::ethers::core::abi::ethabi::AbiError { + name: ::std::borrow::ToOwned::to_owned( + "ERC20InvalidApprover", ), - },], - },], + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("approver"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ], + }, + ], ), ( ::std::borrow::ToOwned::to_owned("ERC20InvalidReceiver"), - ::std::vec![::ethers::core::abi::ethabi::AbiError { - name: ::std::borrow::ToOwned::to_owned("ERC20InvalidReceiver",), - inputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("receiver"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), + ::std::vec![ + ::ethers::core::abi::ethabi::AbiError { + name: ::std::borrow::ToOwned::to_owned( + "ERC20InvalidReceiver", ), - },], - },], + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("receiver"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ], + }, + ], ), ( ::std::borrow::ToOwned::to_owned("ERC20InvalidSender"), - ::std::vec![::ethers::core::abi::ethabi::AbiError { - name: ::std::borrow::ToOwned::to_owned("ERC20InvalidSender"), - inputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("sender"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), - ), - },], - },], + ::std::vec![ + ::ethers::core::abi::ethabi::AbiError { + name: ::std::borrow::ToOwned::to_owned("ERC20InvalidSender"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("sender"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ], + }, + ], ), ( ::std::borrow::ToOwned::to_owned("ERC20InvalidSpender"), - ::std::vec![::ethers::core::abi::ethabi::AbiError { - name: ::std::borrow::ToOwned::to_owned("ERC20InvalidSpender",), - inputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("spender"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), + ::std::vec![ + ::ethers::core::abi::ethabi::AbiError { + name: ::std::borrow::ToOwned::to_owned( + "ERC20InvalidSpender", ), - },], - },], + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("spender"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ], + }, + ], ), ]), receive: false, fallback: false, } } - /// The parsed JSON ABI of the contract. - pub static ASTRIABRIDGEABLEERC20_ABI: ::ethers::contract::Lazy<::ethers::core::abi::Abi> = - ::ethers::contract::Lazy::new(__abi); + ///The parsed JSON ABI of the contract. + pub static ASTRIABRIDGEABLEERC20_ABI: ::ethers::contract::Lazy< + ::ethers::core::abi::Abi, + > = ::ethers::contract::Lazy::new(__abi); #[rustfmt::skip] const __BYTECODE: &[u8] = b"`\xE0`@R4\x80\x15b\0\0\x11W`\0\x80\xFD[P`@Qb\0\x12b8\x03\x80b\0\x12b\x839\x81\x01`@\x81\x90Rb\0\x004\x91b\0\x02\x1DV[\x81\x81`\x03b\0\0D\x83\x82b\0\x03TV[P`\x04b\0\0S\x82\x82b\0\x03TV[PPP`\0b\0\0hb\0\x01S` \x1B` \x1CV[\x90P\x80`\xFF\x16\x84c\xFF\xFF\xFF\xFF\x16\x11\x15b\0\x01\x14W`@QbF\x1B\xCD`\xE5\x1B\x81R` `\x04\x82\x01R`^`$\x82\x01R\x7FAstriaBridgeableERC20: base chai`D\x82\x01R\x7Fn asset precision must be less t`d\x82\x01R\x7Fhan or equal to token decimals\0\0`\x84\x82\x01R`\xA4\x01`@Q\x80\x91\x03\x90\xFD[c\xFF\xFF\xFF\xFF\x84\x16`\x80Rb\0\x01-\x84`\xFF\x83\x16b\0\x046V[b\0\x01:\x90`\nb\0\x05\\V[`\xC0RPPPP`\x01`\x01`\xA0\x1B\x03\x16`\xA0Rb\0\x05wV[`\x12\x90V[cNH{q`\xE0\x1B`\0R`A`\x04R`$`\0\xFD[`\0\x82`\x1F\x83\x01\x12b\0\x01\x80W`\0\x80\xFD[\x81Q`\x01`\x01`@\x1B\x03\x80\x82\x11\x15b\0\x01\x9DWb\0\x01\x9Db\0\x01XV[`@Q`\x1F\x83\x01`\x1F\x19\x90\x81\x16`?\x01\x16\x81\x01\x90\x82\x82\x11\x81\x83\x10\x17\x15b\0\x01\xC8Wb\0\x01\xC8b\0\x01XV[\x81`@R\x83\x81R` \x92P\x86\x83\x85\x88\x01\x01\x11\x15b\0\x01\xE5W`\0\x80\xFD[`\0\x91P[\x83\x82\x10\x15b\0\x02\tW\x85\x82\x01\x83\x01Q\x81\x83\x01\x84\x01R\x90\x82\x01\x90b\0\x01\xEAV[`\0\x93\x81\x01\x90\x92\x01\x92\x90\x92R\x94\x93PPPPV[`\0\x80`\0\x80`\x80\x85\x87\x03\x12\x15b\0\x024W`\0\x80\xFD[\x84Q`\x01`\x01`\xA0\x1B\x03\x81\x16\x81\x14b\0\x02LW`\0\x80\xFD[` \x86\x01Q\x90\x94Pc\xFF\xFF\xFF\xFF\x81\x16\x81\x14b\0\x02gW`\0\x80\xFD[`@\x86\x01Q\x90\x93P`\x01`\x01`@\x1B\x03\x80\x82\x11\x15b\0\x02\x85W`\0\x80\xFD[b\0\x02\x93\x88\x83\x89\x01b\0\x01nV[\x93P``\x87\x01Q\x91P\x80\x82\x11\x15b\0\x02\xAAW`\0\x80\xFD[Pb\0\x02\xB9\x87\x82\x88\x01b\0\x01nV[\x91PP\x92\x95\x91\x94P\x92PV[`\x01\x81\x81\x1C\x90\x82\x16\x80b\0\x02\xDAW`\x7F\x82\x16\x91P[` \x82\x10\x81\x03b\0\x02\xFBWcNH{q`\xE0\x1B`\0R`\"`\x04R`$`\0\xFD[P\x91\x90PV[`\x1F\x82\x11\x15b\0\x03OW`\0\x81\x81R` \x81 `\x1F\x85\x01`\x05\x1C\x81\x01` \x86\x10\x15b\0\x03*WP\x80[`\x1F\x85\x01`\x05\x1C\x82\x01\x91P[\x81\x81\x10\x15b\0\x03KW\x82\x81U`\x01\x01b\0\x036V[PPP[PPPV[\x81Q`\x01`\x01`@\x1B\x03\x81\x11\x15b\0\x03pWb\0\x03pb\0\x01XV[b\0\x03\x88\x81b\0\x03\x81\x84Tb\0\x02\xC5V[\x84b\0\x03\x01V[` \x80`\x1F\x83\x11`\x01\x81\x14b\0\x03\xC0W`\0\x84\x15b\0\x03\xA7WP\x85\x83\x01Q[`\0\x19`\x03\x86\x90\x1B\x1C\x19\x16`\x01\x85\x90\x1B\x17\x85Ub\0\x03KV[`\0\x85\x81R` \x81 `\x1F\x19\x86\x16\x91[\x82\x81\x10\x15b\0\x03\xF1W\x88\x86\x01Q\x82U\x94\x84\x01\x94`\x01\x90\x91\x01\x90\x84\x01b\0\x03\xD0V[P\x85\x82\x10\x15b\0\x04\x10W\x87\x85\x01Q`\0\x19`\x03\x88\x90\x1B`\xF8\x16\x1C\x19\x16\x81U[PPPPP`\x01\x90\x81\x1B\x01\x90UPV[cNH{q`\xE0\x1B`\0R`\x11`\x04R`$`\0\xFD[c\xFF\xFF\xFF\xFF\x82\x81\x16\x82\x82\x16\x03\x90\x80\x82\x11\x15b\0\x04VWb\0\x04Vb\0\x04 V[P\x92\x91PPV[`\x01\x81\x81[\x80\x85\x11\x15b\0\x04\x9EW\x81`\0\x19\x04\x82\x11\x15b\0\x04\x82Wb\0\x04\x82b\0\x04 V[\x80\x85\x16\x15b\0\x04\x90W\x91\x81\x02\x91[\x93\x84\x1C\x93\x90\x80\x02\x90b\0\x04bV[P\x92P\x92\x90PV[`\0\x82b\0\x04\xB7WP`\x01b\0\x05VV[\x81b\0\x04\xC6WP`\0b\0\x05VV[\x81`\x01\x81\x14b\0\x04\xDFW`\x02\x81\x14b\0\x04\xEAWb\0\x05\nV[`\x01\x91PPb\0\x05VV[`\xFF\x84\x11\x15b\0\x04\xFEWb\0\x04\xFEb\0\x04 V[PP`\x01\x82\x1Bb\0\x05VV[P` \x83\x10a\x013\x83\x10\x16`N\x84\x10`\x0B\x84\x10\x16\x17\x15b\0\x05/WP\x81\x81\nb\0\x05VV[b\0\x05;\x83\x83b\0\x04]V[\x80`\0\x19\x04\x82\x11\x15b\0\x05RWb\0\x05Rb\0\x04 V[\x02\x90P[\x92\x91PPV[`\0b\0\x05pc\xFF\xFF\xFF\xFF\x84\x16\x83b\0\x04\xA6V[\x93\x92PPPV[`\x80Q`\xA0Q`\xC0Qa\x0C\xADb\0\x05\xB5`\09`\0\x81\x81a\x04Q\x01Ra\x04\xF5\x01R`\0\x81\x81a\x02]\x01Ra\x03r\x01R`\0a\x01\xCD\x01Ra\x0C\xAD`\0\xF3\xFE`\x80`@R4\x80\x15a\0\x10W`\0\x80\xFD[P`\x046\x10a\0\xEAW`\x005`\xE0\x1C\x80cp\xA0\x821\x11a\0\x8CW\x80c\x95\xD8\x9BA\x11a\0fW\x80c\x95\xD8\x9BA\x14a\x02\x04W\x80c\xA9\x05\x9C\xBB\x14a\x02\x0CW\x80c\xDDb\xED>\x14a\x02\x1FW\x80c\xEE\x9A1\xA2\x14a\x02XW`\0\x80\xFD[\x80cp\xA0\x821\x14a\x01\x8CW\x80cu~\x98t\x14a\x01\xB5W\x80c~\xB6\xDE\xC7\x14a\x01\xC8W`\0\x80\xFD[\x80c#\xB8r\xDD\x11a\0\xC8W\x80c#\xB8r\xDD\x14a\x01BW\x80c1<\xE5g\x14a\x01UW\x80c@\xC1\x0F\x19\x14a\x01dW\x80c_\xE5k\t\x14a\x01yW`\0\x80\xFD[\x80c\x06\xFD\xDE\x03\x14a\0\xEFW\x80c\t^\xA7\xB3\x14a\x01\rW\x80c\x18\x16\r\xDD\x14a\x010W[`\0\x80\xFD[a\0\xF7a\x02\x97V[`@Qa\x01\x04\x91\x90a\x08\xF5V[`@Q\x80\x91\x03\x90\xF3[a\x01 a\x01\x1B6`\x04a\t_V[a\x03)V[`@Q\x90\x15\x15\x81R` \x01a\x01\x04V[`\x02T[`@Q\x90\x81R` \x01a\x01\x04V[a\x01 a\x01P6`\x04a\t\x89V[a\x03CV[`@Q`\x12\x81R` \x01a\x01\x04V[a\x01wa\x01r6`\x04a\t_V[a\x03gV[\0[a\x01wa\x01\x876`\x04a\n\x0EV[a\x04IV[a\x014a\x01\x9A6`\x04a\n\x88V[`\x01`\x01`\xA0\x1B\x03\x16`\0\x90\x81R` \x81\x90R`@\x90 T\x90V[a\x01wa\x01\xC36`\x04a\n\xAAV[a\x04\xEDV[a\x01\xEF\x7F\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x81V[`@Qc\xFF\xFF\xFF\xFF\x90\x91\x16\x81R` \x01a\x01\x04V[a\0\xF7a\x05\x87V[a\x01 a\x02\x1A6`\x04a\t_V[a\x05\x96V[a\x014a\x02-6`\x04a\n\xD6V[`\x01`\x01`\xA0\x1B\x03\x91\x82\x16`\0\x90\x81R`\x01` \x90\x81R`@\x80\x83 \x93\x90\x94\x16\x82R\x91\x90\x91R T\x90V[a\x02\x7F\x7F\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x81V[`@Q`\x01`\x01`\xA0\x1B\x03\x90\x91\x16\x81R` \x01a\x01\x04V[```\x03\x80Ta\x02\xA6\x90a\x0B\0V[\x80`\x1F\x01` \x80\x91\x04\x02` \x01`@Q\x90\x81\x01`@R\x80\x92\x91\x90\x81\x81R` \x01\x82\x80Ta\x02\xD2\x90a\x0B\0V[\x80\x15a\x03\x1FW\x80`\x1F\x10a\x02\xF4Wa\x01\0\x80\x83T\x04\x02\x83R\x91` \x01\x91a\x03\x1FV[\x82\x01\x91\x90`\0R` `\0 \x90[\x81T\x81R\x90`\x01\x01\x90` \x01\x80\x83\x11a\x03\x02W\x82\x90\x03`\x1F\x16\x82\x01\x91[PPPPP\x90P\x90V[`\x003a\x037\x81\x85\x85a\x05\xA4V[`\x01\x91PP[\x92\x91PPV[`\x003a\x03Q\x85\x82\x85a\x05\xB6V[a\x03\\\x85\x85\x85a\x064V[P`\x01\x94\x93PPPPV[3`\x01`\x01`\xA0\x1B\x03\x7F\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x16\x14a\x03\xF8W`@QbF\x1B\xCD`\xE5\x1B\x81R` `\x04\x82\x01R`+`$\x82\x01R\x7FAstriaBridgeableERC20: only brid`D\x82\x01Rj\x19\xD9H\x18\xD8[\x88\x1BZ[\x9D`\xAA\x1B`d\x82\x01R`\x84\x01[`@Q\x80\x91\x03\x90\xFD[a\x04\x02\x82\x82a\x06\x93V[\x81`\x01`\x01`\xA0\x1B\x03\x16\x7F\x0Fg\x98\xA5`y:T\xC3\xBC\xFE\x86\xA9<\xDE\x1Es\x08}\x94L\x0E\xA2\x05D\x13}A!9h\x85\x82`@Qa\x04=\x91\x81R` \x01\x90V[`@Q\x80\x91\x03\x90\xA2PPV[\x84`\0a\x04v\x7F\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x83a\x0B:V[\x11a\x04\x93W`@QbF\x1B\xCD`\xE5\x1B\x81R`\x04\x01a\x03\xEF\x90a\x0B\\V[a\x04\x9D3\x87a\x06\xCDV[\x853`\x01`\x01`\xA0\x1B\x03\x16\x7F\x0Cd\xE2\x9ART\xA7\x1C\x7FNR\xB3\xD2\xD264\x8C\x80\xE0\n\0\xBA.\x19a\x96+\xD2\x82|\x03\xFB\x87\x87\x87\x87`@Qa\x04\xDD\x94\x93\x92\x91\x90a\x0C$V[`@Q\x80\x91\x03\x90\xA3PPPPPPV[\x81`\0a\x05\x1A\x7F\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x83a\x0B:V[\x11a\x057W`@QbF\x1B\xCD`\xE5\x1B\x81R`\x04\x01a\x03\xEF\x90a\x0B\\V[a\x05A3\x84a\x06\xCDV[`@Q`\x01`\x01`\xA0\x1B\x03\x83\x16\x81R\x83\x903\x90\x7F\xAE\x8EffM\x10\x85DP\x9C\x9A[j\x9F3\xC3\xB5\xFE\xF3\xF8\x8E]?\xA6\x80pjo\xEB\x13`\xE3\x90` \x01[`@Q\x80\x91\x03\x90\xA3PPPV[```\x04\x80Ta\x02\xA6\x90a\x0B\0V[`\x003a\x037\x81\x85\x85a\x064V[a\x05\xB1\x83\x83\x83`\x01a\x07\x03V[PPPV[`\x01`\x01`\xA0\x1B\x03\x83\x81\x16`\0\x90\x81R`\x01` \x90\x81R`@\x80\x83 \x93\x86\x16\x83R\x92\x90R T`\0\x19\x81\x14a\x06.W\x81\x81\x10\x15a\x06\x1FW`@Qc}\xC7\xA0\xD9`\xE1\x1B\x81R`\x01`\x01`\xA0\x1B\x03\x84\x16`\x04\x82\x01R`$\x81\x01\x82\x90R`D\x81\x01\x83\x90R`d\x01a\x03\xEFV[a\x06.\x84\x84\x84\x84\x03`\0a\x07\x03V[PPPPV[`\x01`\x01`\xA0\x1B\x03\x83\x16a\x06^W`@QcKc~\x8F`\xE1\x1B\x81R`\0`\x04\x82\x01R`$\x01a\x03\xEFV[`\x01`\x01`\xA0\x1B\x03\x82\x16a\x06\x88W`@Qc\xECD/\x05`\xE0\x1B\x81R`\0`\x04\x82\x01R`$\x01a\x03\xEFV[a\x05\xB1\x83\x83\x83a\x07\xD8V[`\x01`\x01`\xA0\x1B\x03\x82\x16a\x06\xBDW`@Qc\xECD/\x05`\xE0\x1B\x81R`\0`\x04\x82\x01R`$\x01a\x03\xEFV[a\x06\xC9`\0\x83\x83a\x07\xD8V[PPV[`\x01`\x01`\xA0\x1B\x03\x82\x16a\x06\xF7W`@QcKc~\x8F`\xE1\x1B\x81R`\0`\x04\x82\x01R`$\x01a\x03\xEFV[a\x06\xC9\x82`\0\x83a\x07\xD8V[`\x01`\x01`\xA0\x1B\x03\x84\x16a\x07-W`@Qc\xE6\x02\xDF\x05`\xE0\x1B\x81R`\0`\x04\x82\x01R`$\x01a\x03\xEFV[`\x01`\x01`\xA0\x1B\x03\x83\x16a\x07WW`@QcJ\x14\x06\xB1`\xE1\x1B\x81R`\0`\x04\x82\x01R`$\x01a\x03\xEFV[`\x01`\x01`\xA0\x1B\x03\x80\x85\x16`\0\x90\x81R`\x01` \x90\x81R`@\x80\x83 \x93\x87\x16\x83R\x92\x90R \x82\x90U\x80\x15a\x06.W\x82`\x01`\x01`\xA0\x1B\x03\x16\x84`\x01`\x01`\xA0\x1B\x03\x16\x7F\x8C[\xE1\xE5\xEB\xEC}[\xD1OqB}\x1E\x84\xF3\xDD\x03\x14\xC0\xF7\xB2)\x1E[ \n\xC8\xC7\xC3\xB9%\x84`@Qa\x07\xCA\x91\x81R` \x01\x90V[`@Q\x80\x91\x03\x90\xA3PPPPV[`\x01`\x01`\xA0\x1B\x03\x83\x16a\x08\x03W\x80`\x02`\0\x82\x82Ta\x07\xF8\x91\x90a\x0CVV[\x90\x91UPa\x08u\x90PV[`\x01`\x01`\xA0\x1B\x03\x83\x16`\0\x90\x81R` \x81\x90R`@\x90 T\x81\x81\x10\x15a\x08VW`@Qc9\x144\xE3`\xE2\x1B\x81R`\x01`\x01`\xA0\x1B\x03\x85\x16`\x04\x82\x01R`$\x81\x01\x82\x90R`D\x81\x01\x83\x90R`d\x01a\x03\xEFV[`\x01`\x01`\xA0\x1B\x03\x84\x16`\0\x90\x81R` \x81\x90R`@\x90 \x90\x82\x90\x03\x90U[`\x01`\x01`\xA0\x1B\x03\x82\x16a\x08\x91W`\x02\x80T\x82\x90\x03\x90Ua\x08\xB0V[`\x01`\x01`\xA0\x1B\x03\x82\x16`\0\x90\x81R` \x81\x90R`@\x90 \x80T\x82\x01\x90U[\x81`\x01`\x01`\xA0\x1B\x03\x16\x83`\x01`\x01`\xA0\x1B\x03\x16\x7F\xDD\xF2R\xAD\x1B\xE2\xC8\x9Bi\xC2\xB0h\xFC7\x8D\xAA\x95+\xA7\xF1c\xC4\xA1\x16(\xF5ZM\xF5#\xB3\xEF\x83`@Qa\x05z\x91\x81R` \x01\x90V[`\0` \x80\x83R\x83Q\x80\x82\x85\x01R`\0[\x81\x81\x10\x15a\t\"W\x85\x81\x01\x83\x01Q\x85\x82\x01`@\x01R\x82\x01a\t\x06V[P`\0`@\x82\x86\x01\x01R`@`\x1F\x19`\x1F\x83\x01\x16\x85\x01\x01\x92PPP\x92\x91PPV[\x805`\x01`\x01`\xA0\x1B\x03\x81\x16\x81\x14a\tZW`\0\x80\xFD[\x91\x90PV[`\0\x80`@\x83\x85\x03\x12\x15a\trW`\0\x80\xFD[a\t{\x83a\tCV[\x94` \x93\x90\x93\x015\x93PPPV[`\0\x80`\0``\x84\x86\x03\x12\x15a\t\x9EW`\0\x80\xFD[a\t\xA7\x84a\tCV[\x92Pa\t\xB5` \x85\x01a\tCV[\x91P`@\x84\x015\x90P\x92P\x92P\x92V[`\0\x80\x83`\x1F\x84\x01\x12a\t\xD7W`\0\x80\xFD[P\x815g\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x81\x11\x15a\t\xEFW`\0\x80\xFD[` \x83\x01\x91P\x83` \x82\x85\x01\x01\x11\x15a\n\x07W`\0\x80\xFD[\x92P\x92\x90PV[`\0\x80`\0\x80`\0``\x86\x88\x03\x12\x15a\n&W`\0\x80\xFD[\x855\x94P` \x86\x015g\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x80\x82\x11\x15a\nEW`\0\x80\xFD[a\nQ\x89\x83\x8A\x01a\t\xC5V[\x90\x96P\x94P`@\x88\x015\x91P\x80\x82\x11\x15a\njW`\0\x80\xFD[Pa\nw\x88\x82\x89\x01a\t\xC5V[\x96\x99\x95\x98P\x93\x96P\x92\x94\x93\x92PPPV[`\0` \x82\x84\x03\x12\x15a\n\x9AW`\0\x80\xFD[a\n\xA3\x82a\tCV[\x93\x92PPPV[`\0\x80`@\x83\x85\x03\x12\x15a\n\xBDW`\0\x80\xFD[\x825\x91Pa\n\xCD` \x84\x01a\tCV[\x90P\x92P\x92\x90PV[`\0\x80`@\x83\x85\x03\x12\x15a\n\xE9W`\0\x80\xFD[a\n\xF2\x83a\tCV[\x91Pa\n\xCD` \x84\x01a\tCV[`\x01\x81\x81\x1C\x90\x82\x16\x80a\x0B\x14W`\x7F\x82\x16\x91P[` \x82\x10\x81\x03a\x0B4WcNH{q`\xE0\x1B`\0R`\"`\x04R`$`\0\xFD[P\x91\x90PV[`\0\x82a\x0BWWcNH{q`\xE0\x1B`\0R`\x12`\x04R`$`\0\xFD[P\x04\x90V[` \x80\x82R`s\x90\x82\x01R\x7FAstriaBridgeableERC20: insuffici`@\x82\x01R\x7Fent value, must be greater than ``\x82\x01R\x7F10 ** (TOKEN_DECIMALS - BASE_CHA`\x80\x82\x01RrIN_ASSET_PRECISION)`h\x1B`\xA0\x82\x01R`\xC0\x01\x90V[\x81\x83R\x81\x81` \x85\x017P`\0\x82\x82\x01` \x90\x81\x01\x91\x90\x91R`\x1F\x90\x91\x01`\x1F\x19\x16\x90\x91\x01\x01\x90V[`@\x81R`\0a\x0C8`@\x83\x01\x86\x88a\x0B\xFBV[\x82\x81\x03` \x84\x01Ra\x0CK\x81\x85\x87a\x0B\xFBV[\x97\x96PPPPPPPV[\x80\x82\x01\x80\x82\x11\x15a\x03=WcNH{q`\xE0\x1B`\0R`\x11`\x04R`$`\0\xFD\xFE\xA2dipfsX\"\x12 \xEB\x94\xAB\xA7N\xD6\xA0\x81F1\xB5\n\xF4;\x84]\xC4\xAE\x1C0g\x192\x83\xA3\x82.?\xCC\xE9^\xDBdsolcC\0\x08\x15\x003"; /// The bytecode of the contract. - pub static ASTRIABRIDGEABLEERC20_BYTECODE: ::ethers::core::types::Bytes = - ::ethers::core::types::Bytes::from_static(__BYTECODE); + pub static ASTRIABRIDGEABLEERC20_BYTECODE: ::ethers::core::types::Bytes = ::ethers::core::types::Bytes::from_static( + __BYTECODE, + ); #[rustfmt::skip] const __DEPLOYED_BYTECODE: &[u8] = b"`\x80`@R4\x80\x15a\0\x10W`\0\x80\xFD[P`\x046\x10a\0\xEAW`\x005`\xE0\x1C\x80cp\xA0\x821\x11a\0\x8CW\x80c\x95\xD8\x9BA\x11a\0fW\x80c\x95\xD8\x9BA\x14a\x02\x04W\x80c\xA9\x05\x9C\xBB\x14a\x02\x0CW\x80c\xDDb\xED>\x14a\x02\x1FW\x80c\xEE\x9A1\xA2\x14a\x02XW`\0\x80\xFD[\x80cp\xA0\x821\x14a\x01\x8CW\x80cu~\x98t\x14a\x01\xB5W\x80c~\xB6\xDE\xC7\x14a\x01\xC8W`\0\x80\xFD[\x80c#\xB8r\xDD\x11a\0\xC8W\x80c#\xB8r\xDD\x14a\x01BW\x80c1<\xE5g\x14a\x01UW\x80c@\xC1\x0F\x19\x14a\x01dW\x80c_\xE5k\t\x14a\x01yW`\0\x80\xFD[\x80c\x06\xFD\xDE\x03\x14a\0\xEFW\x80c\t^\xA7\xB3\x14a\x01\rW\x80c\x18\x16\r\xDD\x14a\x010W[`\0\x80\xFD[a\0\xF7a\x02\x97V[`@Qa\x01\x04\x91\x90a\x08\xF5V[`@Q\x80\x91\x03\x90\xF3[a\x01 a\x01\x1B6`\x04a\t_V[a\x03)V[`@Q\x90\x15\x15\x81R` \x01a\x01\x04V[`\x02T[`@Q\x90\x81R` \x01a\x01\x04V[a\x01 a\x01P6`\x04a\t\x89V[a\x03CV[`@Q`\x12\x81R` \x01a\x01\x04V[a\x01wa\x01r6`\x04a\t_V[a\x03gV[\0[a\x01wa\x01\x876`\x04a\n\x0EV[a\x04IV[a\x014a\x01\x9A6`\x04a\n\x88V[`\x01`\x01`\xA0\x1B\x03\x16`\0\x90\x81R` \x81\x90R`@\x90 T\x90V[a\x01wa\x01\xC36`\x04a\n\xAAV[a\x04\xEDV[a\x01\xEF\x7F\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x81V[`@Qc\xFF\xFF\xFF\xFF\x90\x91\x16\x81R` \x01a\x01\x04V[a\0\xF7a\x05\x87V[a\x01 a\x02\x1A6`\x04a\t_V[a\x05\x96V[a\x014a\x02-6`\x04a\n\xD6V[`\x01`\x01`\xA0\x1B\x03\x91\x82\x16`\0\x90\x81R`\x01` \x90\x81R`@\x80\x83 \x93\x90\x94\x16\x82R\x91\x90\x91R T\x90V[a\x02\x7F\x7F\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x81V[`@Q`\x01`\x01`\xA0\x1B\x03\x90\x91\x16\x81R` \x01a\x01\x04V[```\x03\x80Ta\x02\xA6\x90a\x0B\0V[\x80`\x1F\x01` \x80\x91\x04\x02` \x01`@Q\x90\x81\x01`@R\x80\x92\x91\x90\x81\x81R` \x01\x82\x80Ta\x02\xD2\x90a\x0B\0V[\x80\x15a\x03\x1FW\x80`\x1F\x10a\x02\xF4Wa\x01\0\x80\x83T\x04\x02\x83R\x91` \x01\x91a\x03\x1FV[\x82\x01\x91\x90`\0R` `\0 \x90[\x81T\x81R\x90`\x01\x01\x90` \x01\x80\x83\x11a\x03\x02W\x82\x90\x03`\x1F\x16\x82\x01\x91[PPPPP\x90P\x90V[`\x003a\x037\x81\x85\x85a\x05\xA4V[`\x01\x91PP[\x92\x91PPV[`\x003a\x03Q\x85\x82\x85a\x05\xB6V[a\x03\\\x85\x85\x85a\x064V[P`\x01\x94\x93PPPPV[3`\x01`\x01`\xA0\x1B\x03\x7F\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x16\x14a\x03\xF8W`@QbF\x1B\xCD`\xE5\x1B\x81R` `\x04\x82\x01R`+`$\x82\x01R\x7FAstriaBridgeableERC20: only brid`D\x82\x01Rj\x19\xD9H\x18\xD8[\x88\x1BZ[\x9D`\xAA\x1B`d\x82\x01R`\x84\x01[`@Q\x80\x91\x03\x90\xFD[a\x04\x02\x82\x82a\x06\x93V[\x81`\x01`\x01`\xA0\x1B\x03\x16\x7F\x0Fg\x98\xA5`y:T\xC3\xBC\xFE\x86\xA9<\xDE\x1Es\x08}\x94L\x0E\xA2\x05D\x13}A!9h\x85\x82`@Qa\x04=\x91\x81R` \x01\x90V[`@Q\x80\x91\x03\x90\xA2PPV[\x84`\0a\x04v\x7F\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x83a\x0B:V[\x11a\x04\x93W`@QbF\x1B\xCD`\xE5\x1B\x81R`\x04\x01a\x03\xEF\x90a\x0B\\V[a\x04\x9D3\x87a\x06\xCDV[\x853`\x01`\x01`\xA0\x1B\x03\x16\x7F\x0Cd\xE2\x9ART\xA7\x1C\x7FNR\xB3\xD2\xD264\x8C\x80\xE0\n\0\xBA.\x19a\x96+\xD2\x82|\x03\xFB\x87\x87\x87\x87`@Qa\x04\xDD\x94\x93\x92\x91\x90a\x0C$V[`@Q\x80\x91\x03\x90\xA3PPPPPPV[\x81`\0a\x05\x1A\x7F\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x83a\x0B:V[\x11a\x057W`@QbF\x1B\xCD`\xE5\x1B\x81R`\x04\x01a\x03\xEF\x90a\x0B\\V[a\x05A3\x84a\x06\xCDV[`@Q`\x01`\x01`\xA0\x1B\x03\x83\x16\x81R\x83\x903\x90\x7F\xAE\x8EffM\x10\x85DP\x9C\x9A[j\x9F3\xC3\xB5\xFE\xF3\xF8\x8E]?\xA6\x80pjo\xEB\x13`\xE3\x90` \x01[`@Q\x80\x91\x03\x90\xA3PPPV[```\x04\x80Ta\x02\xA6\x90a\x0B\0V[`\x003a\x037\x81\x85\x85a\x064V[a\x05\xB1\x83\x83\x83`\x01a\x07\x03V[PPPV[`\x01`\x01`\xA0\x1B\x03\x83\x81\x16`\0\x90\x81R`\x01` \x90\x81R`@\x80\x83 \x93\x86\x16\x83R\x92\x90R T`\0\x19\x81\x14a\x06.W\x81\x81\x10\x15a\x06\x1FW`@Qc}\xC7\xA0\xD9`\xE1\x1B\x81R`\x01`\x01`\xA0\x1B\x03\x84\x16`\x04\x82\x01R`$\x81\x01\x82\x90R`D\x81\x01\x83\x90R`d\x01a\x03\xEFV[a\x06.\x84\x84\x84\x84\x03`\0a\x07\x03V[PPPPV[`\x01`\x01`\xA0\x1B\x03\x83\x16a\x06^W`@QcKc~\x8F`\xE1\x1B\x81R`\0`\x04\x82\x01R`$\x01a\x03\xEFV[`\x01`\x01`\xA0\x1B\x03\x82\x16a\x06\x88W`@Qc\xECD/\x05`\xE0\x1B\x81R`\0`\x04\x82\x01R`$\x01a\x03\xEFV[a\x05\xB1\x83\x83\x83a\x07\xD8V[`\x01`\x01`\xA0\x1B\x03\x82\x16a\x06\xBDW`@Qc\xECD/\x05`\xE0\x1B\x81R`\0`\x04\x82\x01R`$\x01a\x03\xEFV[a\x06\xC9`\0\x83\x83a\x07\xD8V[PPV[`\x01`\x01`\xA0\x1B\x03\x82\x16a\x06\xF7W`@QcKc~\x8F`\xE1\x1B\x81R`\0`\x04\x82\x01R`$\x01a\x03\xEFV[a\x06\xC9\x82`\0\x83a\x07\xD8V[`\x01`\x01`\xA0\x1B\x03\x84\x16a\x07-W`@Qc\xE6\x02\xDF\x05`\xE0\x1B\x81R`\0`\x04\x82\x01R`$\x01a\x03\xEFV[`\x01`\x01`\xA0\x1B\x03\x83\x16a\x07WW`@QcJ\x14\x06\xB1`\xE1\x1B\x81R`\0`\x04\x82\x01R`$\x01a\x03\xEFV[`\x01`\x01`\xA0\x1B\x03\x80\x85\x16`\0\x90\x81R`\x01` \x90\x81R`@\x80\x83 \x93\x87\x16\x83R\x92\x90R \x82\x90U\x80\x15a\x06.W\x82`\x01`\x01`\xA0\x1B\x03\x16\x84`\x01`\x01`\xA0\x1B\x03\x16\x7F\x8C[\xE1\xE5\xEB\xEC}[\xD1OqB}\x1E\x84\xF3\xDD\x03\x14\xC0\xF7\xB2)\x1E[ \n\xC8\xC7\xC3\xB9%\x84`@Qa\x07\xCA\x91\x81R` \x01\x90V[`@Q\x80\x91\x03\x90\xA3PPPPV[`\x01`\x01`\xA0\x1B\x03\x83\x16a\x08\x03W\x80`\x02`\0\x82\x82Ta\x07\xF8\x91\x90a\x0CVV[\x90\x91UPa\x08u\x90PV[`\x01`\x01`\xA0\x1B\x03\x83\x16`\0\x90\x81R` \x81\x90R`@\x90 T\x81\x81\x10\x15a\x08VW`@Qc9\x144\xE3`\xE2\x1B\x81R`\x01`\x01`\xA0\x1B\x03\x85\x16`\x04\x82\x01R`$\x81\x01\x82\x90R`D\x81\x01\x83\x90R`d\x01a\x03\xEFV[`\x01`\x01`\xA0\x1B\x03\x84\x16`\0\x90\x81R` \x81\x90R`@\x90 \x90\x82\x90\x03\x90U[`\x01`\x01`\xA0\x1B\x03\x82\x16a\x08\x91W`\x02\x80T\x82\x90\x03\x90Ua\x08\xB0V[`\x01`\x01`\xA0\x1B\x03\x82\x16`\0\x90\x81R` \x81\x90R`@\x90 \x80T\x82\x01\x90U[\x81`\x01`\x01`\xA0\x1B\x03\x16\x83`\x01`\x01`\xA0\x1B\x03\x16\x7F\xDD\xF2R\xAD\x1B\xE2\xC8\x9Bi\xC2\xB0h\xFC7\x8D\xAA\x95+\xA7\xF1c\xC4\xA1\x16(\xF5ZM\xF5#\xB3\xEF\x83`@Qa\x05z\x91\x81R` \x01\x90V[`\0` \x80\x83R\x83Q\x80\x82\x85\x01R`\0[\x81\x81\x10\x15a\t\"W\x85\x81\x01\x83\x01Q\x85\x82\x01`@\x01R\x82\x01a\t\x06V[P`\0`@\x82\x86\x01\x01R`@`\x1F\x19`\x1F\x83\x01\x16\x85\x01\x01\x92PPP\x92\x91PPV[\x805`\x01`\x01`\xA0\x1B\x03\x81\x16\x81\x14a\tZW`\0\x80\xFD[\x91\x90PV[`\0\x80`@\x83\x85\x03\x12\x15a\trW`\0\x80\xFD[a\t{\x83a\tCV[\x94` \x93\x90\x93\x015\x93PPPV[`\0\x80`\0``\x84\x86\x03\x12\x15a\t\x9EW`\0\x80\xFD[a\t\xA7\x84a\tCV[\x92Pa\t\xB5` \x85\x01a\tCV[\x91P`@\x84\x015\x90P\x92P\x92P\x92V[`\0\x80\x83`\x1F\x84\x01\x12a\t\xD7W`\0\x80\xFD[P\x815g\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x81\x11\x15a\t\xEFW`\0\x80\xFD[` \x83\x01\x91P\x83` \x82\x85\x01\x01\x11\x15a\n\x07W`\0\x80\xFD[\x92P\x92\x90PV[`\0\x80`\0\x80`\0``\x86\x88\x03\x12\x15a\n&W`\0\x80\xFD[\x855\x94P` \x86\x015g\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x80\x82\x11\x15a\nEW`\0\x80\xFD[a\nQ\x89\x83\x8A\x01a\t\xC5V[\x90\x96P\x94P`@\x88\x015\x91P\x80\x82\x11\x15a\njW`\0\x80\xFD[Pa\nw\x88\x82\x89\x01a\t\xC5V[\x96\x99\x95\x98P\x93\x96P\x92\x94\x93\x92PPPV[`\0` \x82\x84\x03\x12\x15a\n\x9AW`\0\x80\xFD[a\n\xA3\x82a\tCV[\x93\x92PPPV[`\0\x80`@\x83\x85\x03\x12\x15a\n\xBDW`\0\x80\xFD[\x825\x91Pa\n\xCD` \x84\x01a\tCV[\x90P\x92P\x92\x90PV[`\0\x80`@\x83\x85\x03\x12\x15a\n\xE9W`\0\x80\xFD[a\n\xF2\x83a\tCV[\x91Pa\n\xCD` \x84\x01a\tCV[`\x01\x81\x81\x1C\x90\x82\x16\x80a\x0B\x14W`\x7F\x82\x16\x91P[` \x82\x10\x81\x03a\x0B4WcNH{q`\xE0\x1B`\0R`\"`\x04R`$`\0\xFD[P\x91\x90PV[`\0\x82a\x0BWWcNH{q`\xE0\x1B`\0R`\x12`\x04R`$`\0\xFD[P\x04\x90V[` \x80\x82R`s\x90\x82\x01R\x7FAstriaBridgeableERC20: insuffici`@\x82\x01R\x7Fent value, must be greater than ``\x82\x01R\x7F10 ** (TOKEN_DECIMALS - BASE_CHA`\x80\x82\x01RrIN_ASSET_PRECISION)`h\x1B`\xA0\x82\x01R`\xC0\x01\x90V[\x81\x83R\x81\x81` \x85\x017P`\0\x82\x82\x01` \x90\x81\x01\x91\x90\x91R`\x1F\x90\x91\x01`\x1F\x19\x16\x90\x91\x01\x01\x90V[`@\x81R`\0a\x0C8`@\x83\x01\x86\x88a\x0B\xFBV[\x82\x81\x03` \x84\x01Ra\x0CK\x81\x85\x87a\x0B\xFBV[\x97\x96PPPPPPPV[\x80\x82\x01\x80\x82\x11\x15a\x03=WcNH{q`\xE0\x1B`\0R`\x11`\x04R`$`\0\xFD\xFE\xA2dipfsX\"\x12 \xEB\x94\xAB\xA7N\xD6\xA0\x81F1\xB5\n\xF4;\x84]\xC4\xAE\x1C0g\x192\x83\xA3\x82.?\xCC\xE9^\xDBdsolcC\0\x08\x15\x003"; /// The deployed bytecode of the contract. - pub static ASTRIABRIDGEABLEERC20_DEPLOYED_BYTECODE: ::ethers::core::types::Bytes = - ::ethers::core::types::Bytes::from_static(__DEPLOYED_BYTECODE); + pub static ASTRIABRIDGEABLEERC20_DEPLOYED_BYTECODE: ::ethers::core::types::Bytes = ::ethers::core::types::Bytes::from_static( + __DEPLOYED_BYTECODE, + ); pub struct AstriaBridgeableERC20(::ethers::contract::Contract); impl ::core::clone::Clone for AstriaBridgeableERC20 { fn clone(&self) -> Self { @@ -637,7 +784,6 @@ pub mod astria_bridgeable_erc20 { } impl ::core::ops::Deref for AstriaBridgeableERC20 { type Target = ::ethers::contract::Contract; - fn deref(&self) -> &Self::Target { &self.0 } @@ -661,16 +807,16 @@ pub mod astria_bridgeable_erc20 { address: T, client: ::std::sync::Arc, ) -> Self { - Self(::ethers::contract::Contract::new( - address.into(), - ASTRIABRIDGEABLEERC20_ABI.clone(), - client, - )) + Self( + ::ethers::contract::Contract::new( + address.into(), + ASTRIABRIDGEABLEERC20_ABI.clone(), + client, + ), + ) } - - /// Constructs the general purpose `Deployer` instance based on the provided constructor - /// arguments and sends it. Returns a new instance of a deployer that returns an - /// instance of this contract after sending the transaction + /// Constructs the general purpose `Deployer` instance based on the provided constructor arguments and sends it. + /// Returns a new instance of a deployer that returns an instance of this contract after sending the transaction /// /// Notes: /// - If there are no constructor arguments, you should pass `()` as the argument. @@ -708,8 +854,7 @@ pub mod astria_bridgeable_erc20 { let deployer = ::ethers::contract::ContractDeployer::new(deployer); Ok(deployer) } - - /// Calls the contract's `BASE_CHAIN_ASSET_PRECISION` (0x7eb6dec7) function + ///Calls the contract's `BASE_CHAIN_ASSET_PRECISION` (0x7eb6dec7) function pub fn base_chain_asset_precision( &self, ) -> ::ethers::contract::builders::ContractCall { @@ -717,17 +862,18 @@ pub mod astria_bridgeable_erc20 { .method_hash([126, 182, 222, 199], ()) .expect("method not found (this should never happen)") } - - /// Calls the contract's `BRIDGE` (0xee9a31a2) function + ///Calls the contract's `BRIDGE` (0xee9a31a2) function pub fn bridge( &self, - ) -> ::ethers::contract::builders::ContractCall { + ) -> ::ethers::contract::builders::ContractCall< + M, + ::ethers::core::types::Address, + > { self.0 .method_hash([238, 154, 49, 162], ()) .expect("method not found (this should never happen)") } - - /// Calls the contract's `allowance` (0xdd62ed3e) function + ///Calls the contract's `allowance` (0xdd62ed3e) function pub fn allowance( &self, owner: ::ethers::core::types::Address, @@ -737,8 +883,7 @@ pub mod astria_bridgeable_erc20 { .method_hash([221, 98, 237, 62], (owner, spender)) .expect("method not found (this should never happen)") } - - /// Calls the contract's `approve` (0x095ea7b3) function + ///Calls the contract's `approve` (0x095ea7b3) function pub fn approve( &self, spender: ::ethers::core::types::Address, @@ -748,8 +893,7 @@ pub mod astria_bridgeable_erc20 { .method_hash([9, 94, 167, 179], (spender, value)) .expect("method not found (this should never happen)") } - - /// Calls the contract's `balanceOf` (0x70a08231) function + ///Calls the contract's `balanceOf` (0x70a08231) function pub fn balance_of( &self, account: ::ethers::core::types::Address, @@ -758,15 +902,13 @@ pub mod astria_bridgeable_erc20 { .method_hash([112, 160, 130, 49], account) .expect("method not found (this should never happen)") } - - /// Calls the contract's `decimals` (0x313ce567) function + ///Calls the contract's `decimals` (0x313ce567) function pub fn decimals(&self) -> ::ethers::contract::builders::ContractCall { self.0 .method_hash([49, 60, 229, 103], ()) .expect("method not found (this should never happen)") } - - /// Calls the contract's `mint` (0x40c10f19) function + ///Calls the contract's `mint` (0x40c10f19) function pub fn mint( &self, to: ::ethers::core::types::Address, @@ -776,15 +918,15 @@ pub mod astria_bridgeable_erc20 { .method_hash([64, 193, 15, 25], (to, amount)) .expect("method not found (this should never happen)") } - - /// Calls the contract's `name` (0x06fdde03) function - pub fn name(&self) -> ::ethers::contract::builders::ContractCall { + ///Calls the contract's `name` (0x06fdde03) function + pub fn name( + &self, + ) -> ::ethers::contract::builders::ContractCall { self.0 .method_hash([6, 253, 222, 3], ()) .expect("method not found (this should never happen)") } - - /// Calls the contract's `symbol` (0x95d89b41) function + ///Calls the contract's `symbol` (0x95d89b41) function pub fn symbol( &self, ) -> ::ethers::contract::builders::ContractCall { @@ -792,8 +934,7 @@ pub mod astria_bridgeable_erc20 { .method_hash([149, 216, 155, 65], ()) .expect("method not found (this should never happen)") } - - /// Calls the contract's `totalSupply` (0x18160ddd) function + ///Calls the contract's `totalSupply` (0x18160ddd) function pub fn total_supply( &self, ) -> ::ethers::contract::builders::ContractCall { @@ -801,8 +942,7 @@ pub mod astria_bridgeable_erc20 { .method_hash([24, 22, 13, 221], ()) .expect("method not found (this should never happen)") } - - /// Calls the contract's `transfer` (0xa9059cbb) function + ///Calls the contract's `transfer` (0xa9059cbb) function pub fn transfer( &self, to: ::ethers::core::types::Address, @@ -812,8 +952,7 @@ pub mod astria_bridgeable_erc20 { .method_hash([169, 5, 156, 187], (to, value)) .expect("method not found (this should never happen)") } - - /// Calls the contract's `transferFrom` (0x23b872dd) function + ///Calls the contract's `transferFrom` (0x23b872dd) function pub fn transfer_from( &self, from: ::ethers::core::types::Address, @@ -824,8 +963,7 @@ pub mod astria_bridgeable_erc20 { .method_hash([35, 184, 114, 221], (from, to, value)) .expect("method not found (this should never happen)") } - - /// Calls the contract's `withdrawToIbcChain` (0x5fe56b09) function + ///Calls the contract's `withdrawToIbcChain` (0x5fe56b09) function pub fn withdraw_to_ibc_chain( &self, amount: ::ethers::core::types::U256, @@ -833,11 +971,13 @@ pub mod astria_bridgeable_erc20 { memo: ::std::string::String, ) -> ::ethers::contract::builders::ContractCall { self.0 - .method_hash([95, 229, 107, 9], (amount, destination_chain_address, memo)) + .method_hash( + [95, 229, 107, 9], + (amount, destination_chain_address, memo), + ) .expect("method not found (this should never happen)") } - - /// Calls the contract's `withdrawToSequencer` (0x757e9874) function + ///Calls the contract's `withdrawToSequencer` (0x757e9874) function pub fn withdraw_to_sequencer( &self, amount: ::ethers::core::types::U256, @@ -847,62 +987,70 @@ pub mod astria_bridgeable_erc20 { .method_hash([117, 126, 152, 116], (amount, destination_chain_address)) .expect("method not found (this should never happen)") } - - /// Gets the contract's `Approval` event + ///Gets the contract's `Approval` event pub fn approval_filter( &self, - ) -> ::ethers::contract::builders::Event<::std::sync::Arc, M, ApprovalFilter> { + ) -> ::ethers::contract::builders::Event< + ::std::sync::Arc, + M, + ApprovalFilter, + > { self.0.event() } - - /// Gets the contract's `Ics20Withdrawal` event + ///Gets the contract's `Ics20Withdrawal` event pub fn ics_20_withdrawal_filter( &self, - ) -> ::ethers::contract::builders::Event<::std::sync::Arc, M, Ics20WithdrawalFilter> - { + ) -> ::ethers::contract::builders::Event< + ::std::sync::Arc, + M, + Ics20WithdrawalFilter, + > { self.0.event() } - - /// Gets the contract's `Mint` event + ///Gets the contract's `Mint` event pub fn mint_filter( &self, ) -> ::ethers::contract::builders::Event<::std::sync::Arc, M, MintFilter> { self.0.event() } - - /// Gets the contract's `SequencerWithdrawal` event + ///Gets the contract's `SequencerWithdrawal` event pub fn sequencer_withdrawal_filter( &self, - ) -> ::ethers::contract::builders::Event<::std::sync::Arc, M, SequencerWithdrawalFilter> - { + ) -> ::ethers::contract::builders::Event< + ::std::sync::Arc, + M, + SequencerWithdrawalFilter, + > { self.0.event() } - - /// Gets the contract's `Transfer` event + ///Gets the contract's `Transfer` event pub fn transfer_filter( &self, - ) -> ::ethers::contract::builders::Event<::std::sync::Arc, M, TransferFilter> { + ) -> ::ethers::contract::builders::Event< + ::std::sync::Arc, + M, + TransferFilter, + > { self.0.event() } - /// Returns an `Event` builder for all the events of this contract. pub fn events( &self, - ) -> ::ethers::contract::builders::Event<::std::sync::Arc, M, AstriaBridgeableERC20Events> - { - self.0 - .event_with_filter(::core::default::Default::default()) + ) -> ::ethers::contract::builders::Event< + ::std::sync::Arc, + M, + AstriaBridgeableERC20Events, + > { + self.0.event_with_filter(::core::default::Default::default()) } } impl From<::ethers::contract::Contract> - for AstriaBridgeableERC20 - { + for AstriaBridgeableERC20 { fn from(contract: ::ethers::contract::Contract) -> Self { Self::new(contract.address(), contract.client()) } } - /// Custom Error type `ERC20InsufficientAllowance` with signature - /// `ERC20InsufficientAllowance(address,uint256,uint256)` and selector `0xfb8f41b2` + ///Custom Error type `ERC20InsufficientAllowance` with signature `ERC20InsufficientAllowance(address,uint256,uint256)` and selector `0xfb8f41b2` #[derive( Clone, ::ethers::contract::EthError, @@ -911,7 +1059,7 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[etherror( name = "ERC20InsufficientAllowance", @@ -922,8 +1070,7 @@ pub mod astria_bridgeable_erc20 { pub allowance: ::ethers::core::types::U256, pub needed: ::ethers::core::types::U256, } - /// Custom Error type `ERC20InsufficientBalance` with signature - /// `ERC20InsufficientBalance(address,uint256,uint256)` and selector `0xe450d38c` + ///Custom Error type `ERC20InsufficientBalance` with signature `ERC20InsufficientBalance(address,uint256,uint256)` and selector `0xe450d38c` #[derive( Clone, ::ethers::contract::EthError, @@ -932,7 +1079,7 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[etherror( name = "ERC20InsufficientBalance", @@ -943,8 +1090,7 @@ pub mod astria_bridgeable_erc20 { pub balance: ::ethers::core::types::U256, pub needed: ::ethers::core::types::U256, } - /// Custom Error type `ERC20InvalidApprover` with signature `ERC20InvalidApprover(address)` and - /// selector `0xe602df05` + ///Custom Error type `ERC20InvalidApprover` with signature `ERC20InvalidApprover(address)` and selector `0xe602df05` #[derive( Clone, ::ethers::contract::EthError, @@ -953,14 +1099,13 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[etherror(name = "ERC20InvalidApprover", abi = "ERC20InvalidApprover(address)")] pub struct ERC20InvalidApprover { pub approver: ::ethers::core::types::Address, } - /// Custom Error type `ERC20InvalidReceiver` with signature `ERC20InvalidReceiver(address)` and - /// selector `0xec442f05` + ///Custom Error type `ERC20InvalidReceiver` with signature `ERC20InvalidReceiver(address)` and selector `0xec442f05` #[derive( Clone, ::ethers::contract::EthError, @@ -969,14 +1114,13 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[etherror(name = "ERC20InvalidReceiver", abi = "ERC20InvalidReceiver(address)")] pub struct ERC20InvalidReceiver { pub receiver: ::ethers::core::types::Address, } - /// Custom Error type `ERC20InvalidSender` with signature `ERC20InvalidSender(address)` and - /// selector `0x96c6fd1e` + ///Custom Error type `ERC20InvalidSender` with signature `ERC20InvalidSender(address)` and selector `0x96c6fd1e` #[derive( Clone, ::ethers::contract::EthError, @@ -985,14 +1129,13 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[etherror(name = "ERC20InvalidSender", abi = "ERC20InvalidSender(address)")] pub struct ERC20InvalidSender { pub sender: ::ethers::core::types::Address, } - /// Custom Error type `ERC20InvalidSpender` with signature `ERC20InvalidSpender(address)` and - /// selector `0x94280d62` + ///Custom Error type `ERC20InvalidSpender` with signature `ERC20InvalidSpender(address)` and selector `0x94280d62` #[derive( Clone, ::ethers::contract::EthError, @@ -1001,13 +1144,13 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[etherror(name = "ERC20InvalidSpender", abi = "ERC20InvalidSpender(address)")] pub struct ERC20InvalidSpender { pub spender: ::ethers::core::types::Address, } - /// Container type for all of the contract's custom errors + ///Container type for all of the contract's custom errors #[derive(Clone, ::ethers::contract::EthAbiType, Debug, PartialEq, Eq, Hash)] pub enum AstriaBridgeableERC20Errors { ERC20InsufficientAllowance(ERC20InsufficientAllowance), @@ -1025,39 +1168,39 @@ pub mod astria_bridgeable_erc20 { data: impl AsRef<[u8]>, ) -> ::core::result::Result { let data = data.as_ref(); - if let Ok(decoded) = - <::std::string::String as ::ethers::core::abi::AbiDecode>::decode(data) - { + if let Ok(decoded) = <::std::string::String as ::ethers::core::abi::AbiDecode>::decode( + data, + ) { return Ok(Self::RevertString(decoded)); } - if let Ok(decoded) = - ::decode(data) - { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::ERC20InsufficientAllowance(decoded)); } - if let Ok(decoded) = - ::decode(data) - { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::ERC20InsufficientBalance(decoded)); } - if let Ok(decoded) = - ::decode(data) - { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::ERC20InvalidApprover(decoded)); } - if let Ok(decoded) = - ::decode(data) - { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::ERC20InvalidReceiver(decoded)); } - if let Ok(decoded) = - ::decode(data) - { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::ERC20InvalidSender(decoded)); } - if let Ok(decoded) = - ::decode(data) - { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::ERC20InvalidSpender(decoded)); } Err(::ethers::core::abi::Error::InvalidData.into()) @@ -1093,33 +1236,27 @@ pub mod astria_bridgeable_erc20 { match selector { [0x08, 0xc3, 0x79, 0xa0] => true, _ if selector - == ::selector() => - { + == ::selector() => { true } _ if selector - == ::selector() => - { + == ::selector() => { true } _ if selector - == ::selector() => - { + == ::selector() => { true } _ if selector - == ::selector() => - { + == ::selector() => { true } _ if selector - == ::selector() => - { + == ::selector() => { true } _ if selector - == ::selector() => - { + == ::selector() => { true } _ => false, @@ -1129,12 +1266,24 @@ pub mod astria_bridgeable_erc20 { impl ::core::fmt::Display for AstriaBridgeableERC20Errors { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { - Self::ERC20InsufficientAllowance(element) => ::core::fmt::Display::fmt(element, f), - Self::ERC20InsufficientBalance(element) => ::core::fmt::Display::fmt(element, f), - Self::ERC20InvalidApprover(element) => ::core::fmt::Display::fmt(element, f), - Self::ERC20InvalidReceiver(element) => ::core::fmt::Display::fmt(element, f), - Self::ERC20InvalidSender(element) => ::core::fmt::Display::fmt(element, f), - Self::ERC20InvalidSpender(element) => ::core::fmt::Display::fmt(element, f), + Self::ERC20InsufficientAllowance(element) => { + ::core::fmt::Display::fmt(element, f) + } + Self::ERC20InsufficientBalance(element) => { + ::core::fmt::Display::fmt(element, f) + } + Self::ERC20InvalidApprover(element) => { + ::core::fmt::Display::fmt(element, f) + } + Self::ERC20InvalidReceiver(element) => { + ::core::fmt::Display::fmt(element, f) + } + Self::ERC20InvalidSender(element) => { + ::core::fmt::Display::fmt(element, f) + } + Self::ERC20InvalidSpender(element) => { + ::core::fmt::Display::fmt(element, f) + } Self::RevertString(s) => ::core::fmt::Display::fmt(s, f), } } @@ -1144,12 +1293,14 @@ pub mod astria_bridgeable_erc20 { Self::RevertString(value) } } - impl ::core::convert::From for AstriaBridgeableERC20Errors { + impl ::core::convert::From + for AstriaBridgeableERC20Errors { fn from(value: ERC20InsufficientAllowance) -> Self { Self::ERC20InsufficientAllowance(value) } } - impl ::core::convert::From for AstriaBridgeableERC20Errors { + impl ::core::convert::From + for AstriaBridgeableERC20Errors { fn from(value: ERC20InsufficientBalance) -> Self { Self::ERC20InsufficientBalance(value) } @@ -1182,7 +1333,7 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethevent(name = "Approval", abi = "Approval(address,address,uint256)")] pub struct ApprovalFilter { @@ -1200,7 +1351,7 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethevent( name = "Ics20Withdrawal", @@ -1222,7 +1373,7 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethevent(name = "Mint", abi = "Mint(address,uint256)")] pub struct MintFilter { @@ -1238,7 +1389,7 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethevent( name = "SequencerWithdrawal", @@ -1259,7 +1410,7 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethevent(name = "Transfer", abi = "Transfer(address,address,uint256)")] pub struct TransferFilter { @@ -1269,7 +1420,7 @@ pub mod astria_bridgeable_erc20 { pub to: ::ethers::core::types::Address, pub value: ::ethers::core::types::U256, } - /// Container type for all of the contract's events + ///Container type for all of the contract's events #[derive(Clone, ::ethers::contract::EthAbiType, Debug, PartialEq, Eq, Hash)] pub enum AstriaBridgeableERC20Events { ApprovalFilter(ApprovalFilter), @@ -1292,9 +1443,9 @@ pub mod astria_bridgeable_erc20 { return Ok(AstriaBridgeableERC20Events::MintFilter(decoded)); } if let Ok(decoded) = SequencerWithdrawalFilter::decode_log(log) { - return Ok(AstriaBridgeableERC20Events::SequencerWithdrawalFilter( - decoded, - )); + return Ok( + AstriaBridgeableERC20Events::SequencerWithdrawalFilter(decoded), + ); } if let Ok(decoded) = TransferFilter::decode_log(log) { return Ok(AstriaBridgeableERC20Events::TransferFilter(decoded)); @@ -1306,9 +1457,13 @@ pub mod astria_bridgeable_erc20 { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { Self::ApprovalFilter(element) => ::core::fmt::Display::fmt(element, f), - Self::Ics20WithdrawalFilter(element) => ::core::fmt::Display::fmt(element, f), + Self::Ics20WithdrawalFilter(element) => { + ::core::fmt::Display::fmt(element, f) + } Self::MintFilter(element) => ::core::fmt::Display::fmt(element, f), - Self::SequencerWithdrawalFilter(element) => ::core::fmt::Display::fmt(element, f), + Self::SequencerWithdrawalFilter(element) => { + ::core::fmt::Display::fmt(element, f) + } Self::TransferFilter(element) => ::core::fmt::Display::fmt(element, f), } } @@ -1328,7 +1483,8 @@ pub mod astria_bridgeable_erc20 { Self::MintFilter(value) } } - impl ::core::convert::From for AstriaBridgeableERC20Events { + impl ::core::convert::From + for AstriaBridgeableERC20Events { fn from(value: SequencerWithdrawalFilter) -> Self { Self::SequencerWithdrawalFilter(value) } @@ -1338,8 +1494,7 @@ pub mod astria_bridgeable_erc20 { Self::TransferFilter(value) } } - /// Container type for all input parameters for the `BASE_CHAIN_ASSET_PRECISION` function with - /// signature `BASE_CHAIN_ASSET_PRECISION()` and selector `0x7eb6dec7` + ///Container type for all input parameters for the `BASE_CHAIN_ASSET_PRECISION` function with signature `BASE_CHAIN_ASSET_PRECISION()` and selector `0x7eb6dec7` #[derive( Clone, ::ethers::contract::EthCall, @@ -1348,15 +1503,11 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, - )] - #[ethcall( - name = "BASE_CHAIN_ASSET_PRECISION", - abi = "BASE_CHAIN_ASSET_PRECISION()" + Hash )] + #[ethcall(name = "BASE_CHAIN_ASSET_PRECISION", abi = "BASE_CHAIN_ASSET_PRECISION()")] pub struct BaseChainAssetPrecisionCall; - /// Container type for all input parameters for the `BRIDGE` function with signature `BRIDGE()` - /// and selector `0xee9a31a2` + ///Container type for all input parameters for the `BRIDGE` function with signature `BRIDGE()` and selector `0xee9a31a2` #[derive( Clone, ::ethers::contract::EthCall, @@ -1365,12 +1516,11 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall(name = "BRIDGE", abi = "BRIDGE()")] pub struct BridgeCall; - /// Container type for all input parameters for the `allowance` function with signature - /// `allowance(address,address)` and selector `0xdd62ed3e` + ///Container type for all input parameters for the `allowance` function with signature `allowance(address,address)` and selector `0xdd62ed3e` #[derive( Clone, ::ethers::contract::EthCall, @@ -1379,15 +1529,14 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall(name = "allowance", abi = "allowance(address,address)")] pub struct AllowanceCall { pub owner: ::ethers::core::types::Address, pub spender: ::ethers::core::types::Address, } - /// Container type for all input parameters for the `approve` function with signature - /// `approve(address,uint256)` and selector `0x095ea7b3` + ///Container type for all input parameters for the `approve` function with signature `approve(address,uint256)` and selector `0x095ea7b3` #[derive( Clone, ::ethers::contract::EthCall, @@ -1396,15 +1545,14 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall(name = "approve", abi = "approve(address,uint256)")] pub struct ApproveCall { pub spender: ::ethers::core::types::Address, pub value: ::ethers::core::types::U256, } - /// Container type for all input parameters for the `balanceOf` function with signature - /// `balanceOf(address)` and selector `0x70a08231` + ///Container type for all input parameters for the `balanceOf` function with signature `balanceOf(address)` and selector `0x70a08231` #[derive( Clone, ::ethers::contract::EthCall, @@ -1413,14 +1561,13 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall(name = "balanceOf", abi = "balanceOf(address)")] pub struct BalanceOfCall { pub account: ::ethers::core::types::Address, } - /// Container type for all input parameters for the `decimals` function with signature - /// `decimals()` and selector `0x313ce567` + ///Container type for all input parameters for the `decimals` function with signature `decimals()` and selector `0x313ce567` #[derive( Clone, ::ethers::contract::EthCall, @@ -1429,12 +1576,11 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall(name = "decimals", abi = "decimals()")] pub struct DecimalsCall; - /// Container type for all input parameters for the `mint` function with signature - /// `mint(address,uint256)` and selector `0x40c10f19` + ///Container type for all input parameters for the `mint` function with signature `mint(address,uint256)` and selector `0x40c10f19` #[derive( Clone, ::ethers::contract::EthCall, @@ -1443,15 +1589,14 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall(name = "mint", abi = "mint(address,uint256)")] pub struct MintCall { pub to: ::ethers::core::types::Address, pub amount: ::ethers::core::types::U256, } - /// Container type for all input parameters for the `name` function with signature `name()` and - /// selector `0x06fdde03` + ///Container type for all input parameters for the `name` function with signature `name()` and selector `0x06fdde03` #[derive( Clone, ::ethers::contract::EthCall, @@ -1460,12 +1605,11 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall(name = "name", abi = "name()")] pub struct NameCall; - /// Container type for all input parameters for the `symbol` function with signature `symbol()` - /// and selector `0x95d89b41` + ///Container type for all input parameters for the `symbol` function with signature `symbol()` and selector `0x95d89b41` #[derive( Clone, ::ethers::contract::EthCall, @@ -1474,12 +1618,11 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall(name = "symbol", abi = "symbol()")] pub struct SymbolCall; - /// Container type for all input parameters for the `totalSupply` function with signature - /// `totalSupply()` and selector `0x18160ddd` + ///Container type for all input parameters for the `totalSupply` function with signature `totalSupply()` and selector `0x18160ddd` #[derive( Clone, ::ethers::contract::EthCall, @@ -1488,12 +1631,11 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall(name = "totalSupply", abi = "totalSupply()")] pub struct TotalSupplyCall; - /// Container type for all input parameters for the `transfer` function with signature - /// `transfer(address,uint256)` and selector `0xa9059cbb` + ///Container type for all input parameters for the `transfer` function with signature `transfer(address,uint256)` and selector `0xa9059cbb` #[derive( Clone, ::ethers::contract::EthCall, @@ -1502,15 +1644,14 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall(name = "transfer", abi = "transfer(address,uint256)")] pub struct TransferCall { pub to: ::ethers::core::types::Address, pub value: ::ethers::core::types::U256, } - /// Container type for all input parameters for the `transferFrom` function with signature - /// `transferFrom(address,address,uint256)` and selector `0x23b872dd` + ///Container type for all input parameters for the `transferFrom` function with signature `transferFrom(address,address,uint256)` and selector `0x23b872dd` #[derive( Clone, ::ethers::contract::EthCall, @@ -1519,7 +1660,7 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall(name = "transferFrom", abi = "transferFrom(address,address,uint256)")] pub struct TransferFromCall { @@ -1527,8 +1668,7 @@ pub mod astria_bridgeable_erc20 { pub to: ::ethers::core::types::Address, pub value: ::ethers::core::types::U256, } - /// Container type for all input parameters for the `withdrawToIbcChain` function with signature - /// `withdrawToIbcChain(uint256,string,string)` and selector `0x5fe56b09` + ///Container type for all input parameters for the `withdrawToIbcChain` function with signature `withdrawToIbcChain(uint256,string,string)` and selector `0x5fe56b09` #[derive( Clone, ::ethers::contract::EthCall, @@ -1537,7 +1677,7 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall( name = "withdrawToIbcChain", @@ -1548,8 +1688,7 @@ pub mod astria_bridgeable_erc20 { pub destination_chain_address: ::std::string::String, pub memo: ::std::string::String, } - /// Container type for all input parameters for the `withdrawToSequencer` function with - /// signature `withdrawToSequencer(uint256,address)` and selector `0x757e9874` + ///Container type for all input parameters for the `withdrawToSequencer` function with signature `withdrawToSequencer(uint256,address)` and selector `0x757e9874` #[derive( Clone, ::ethers::contract::EthCall, @@ -1558,7 +1697,7 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall( name = "withdrawToSequencer", @@ -1568,7 +1707,7 @@ pub mod astria_bridgeable_erc20 { pub amount: ::ethers::core::types::U256, pub destination_chain_address: ::ethers::core::types::Address, } - /// Container type for all of the contract's call + ///Container type for all of the contract's call #[derive(Clone, ::ethers::contract::EthAbiType, Debug, PartialEq, Eq, Hash)] pub enum AstriaBridgeableERC20Calls { BaseChainAssetPrecision(BaseChainAssetPrecisionCall), @@ -1591,53 +1730,74 @@ pub mod astria_bridgeable_erc20 { data: impl AsRef<[u8]>, ) -> ::core::result::Result { let data = data.as_ref(); - if let Ok(decoded) = - ::decode(data) - { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::BaseChainAssetPrecision(decoded)); } - if let Ok(decoded) = ::decode(data) { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::Bridge(decoded)); } - if let Ok(decoded) = ::decode(data) { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::Allowance(decoded)); } - if let Ok(decoded) = ::decode(data) { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::Approve(decoded)); } - if let Ok(decoded) = ::decode(data) { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::BalanceOf(decoded)); } - if let Ok(decoded) = ::decode(data) { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::Decimals(decoded)); } - if let Ok(decoded) = ::decode(data) { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::Mint(decoded)); } - if let Ok(decoded) = ::decode(data) { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::Name(decoded)); } - if let Ok(decoded) = ::decode(data) { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::Symbol(decoded)); } - if let Ok(decoded) = ::decode(data) { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::TotalSupply(decoded)); } - if let Ok(decoded) = ::decode(data) { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::Transfer(decoded)); } - if let Ok(decoded) = ::decode(data) - { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::TransferFrom(decoded)); } - if let Ok(decoded) = - ::decode(data) - { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::WithdrawToIbcChain(decoded)); } - if let Ok(decoded) = - ::decode(data) - { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::WithdrawToSequencer(decoded)); } Err(::ethers::core::abi::Error::InvalidData.into()) @@ -1650,16 +1810,28 @@ pub mod astria_bridgeable_erc20 { ::ethers::core::abi::AbiEncode::encode(element) } Self::Bridge(element) => ::ethers::core::abi::AbiEncode::encode(element), - Self::Allowance(element) => ::ethers::core::abi::AbiEncode::encode(element), + Self::Allowance(element) => { + ::ethers::core::abi::AbiEncode::encode(element) + } Self::Approve(element) => ::ethers::core::abi::AbiEncode::encode(element), - Self::BalanceOf(element) => ::ethers::core::abi::AbiEncode::encode(element), - Self::Decimals(element) => ::ethers::core::abi::AbiEncode::encode(element), + Self::BalanceOf(element) => { + ::ethers::core::abi::AbiEncode::encode(element) + } + Self::Decimals(element) => { + ::ethers::core::abi::AbiEncode::encode(element) + } Self::Mint(element) => ::ethers::core::abi::AbiEncode::encode(element), Self::Name(element) => ::ethers::core::abi::AbiEncode::encode(element), Self::Symbol(element) => ::ethers::core::abi::AbiEncode::encode(element), - Self::TotalSupply(element) => ::ethers::core::abi::AbiEncode::encode(element), - Self::Transfer(element) => ::ethers::core::abi::AbiEncode::encode(element), - Self::TransferFrom(element) => ::ethers::core::abi::AbiEncode::encode(element), + Self::TotalSupply(element) => { + ::ethers::core::abi::AbiEncode::encode(element) + } + Self::Transfer(element) => { + ::ethers::core::abi::AbiEncode::encode(element) + } + Self::TransferFrom(element) => { + ::ethers::core::abi::AbiEncode::encode(element) + } Self::WithdrawToIbcChain(element) => { ::ethers::core::abi::AbiEncode::encode(element) } @@ -1672,7 +1844,9 @@ pub mod astria_bridgeable_erc20 { impl ::core::fmt::Display for AstriaBridgeableERC20Calls { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { - Self::BaseChainAssetPrecision(element) => ::core::fmt::Display::fmt(element, f), + Self::BaseChainAssetPrecision(element) => { + ::core::fmt::Display::fmt(element, f) + } Self::Bridge(element) => ::core::fmt::Display::fmt(element, f), Self::Allowance(element) => ::core::fmt::Display::fmt(element, f), Self::Approve(element) => ::core::fmt::Display::fmt(element, f), @@ -1684,12 +1858,17 @@ pub mod astria_bridgeable_erc20 { Self::TotalSupply(element) => ::core::fmt::Display::fmt(element, f), Self::Transfer(element) => ::core::fmt::Display::fmt(element, f), Self::TransferFrom(element) => ::core::fmt::Display::fmt(element, f), - Self::WithdrawToIbcChain(element) => ::core::fmt::Display::fmt(element, f), - Self::WithdrawToSequencer(element) => ::core::fmt::Display::fmt(element, f), + Self::WithdrawToIbcChain(element) => { + ::core::fmt::Display::fmt(element, f) + } + Self::WithdrawToSequencer(element) => { + ::core::fmt::Display::fmt(element, f) + } } } } - impl ::core::convert::From for AstriaBridgeableERC20Calls { + impl ::core::convert::From + for AstriaBridgeableERC20Calls { fn from(value: BaseChainAssetPrecisionCall) -> Self { Self::BaseChainAssetPrecision(value) } @@ -1759,8 +1938,7 @@ pub mod astria_bridgeable_erc20 { Self::WithdrawToSequencer(value) } } - /// Container type for all return fields from the `BASE_CHAIN_ASSET_PRECISION` function with - /// signature `BASE_CHAIN_ASSET_PRECISION()` and selector `0x7eb6dec7` + ///Container type for all return fields from the `BASE_CHAIN_ASSET_PRECISION` function with signature `BASE_CHAIN_ASSET_PRECISION()` and selector `0x7eb6dec7` #[derive( Clone, ::ethers::contract::EthAbiType, @@ -1769,11 +1947,10 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] pub struct BaseChainAssetPrecisionReturn(pub u32); - /// Container type for all return fields from the `BRIDGE` function with signature `BRIDGE()` - /// and selector `0xee9a31a2` + ///Container type for all return fields from the `BRIDGE` function with signature `BRIDGE()` and selector `0xee9a31a2` #[derive( Clone, ::ethers::contract::EthAbiType, @@ -1782,11 +1959,10 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] pub struct BridgeReturn(pub ::ethers::core::types::Address); - /// Container type for all return fields from the `allowance` function with signature - /// `allowance(address,address)` and selector `0xdd62ed3e` + ///Container type for all return fields from the `allowance` function with signature `allowance(address,address)` and selector `0xdd62ed3e` #[derive( Clone, ::ethers::contract::EthAbiType, @@ -1795,11 +1971,10 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] pub struct AllowanceReturn(pub ::ethers::core::types::U256); - /// Container type for all return fields from the `approve` function with signature - /// `approve(address,uint256)` and selector `0x095ea7b3` + ///Container type for all return fields from the `approve` function with signature `approve(address,uint256)` and selector `0x095ea7b3` #[derive( Clone, ::ethers::contract::EthAbiType, @@ -1808,11 +1983,10 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] pub struct ApproveReturn(pub bool); - /// Container type for all return fields from the `balanceOf` function with signature - /// `balanceOf(address)` and selector `0x70a08231` + ///Container type for all return fields from the `balanceOf` function with signature `balanceOf(address)` and selector `0x70a08231` #[derive( Clone, ::ethers::contract::EthAbiType, @@ -1821,11 +1995,10 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] pub struct BalanceOfReturn(pub ::ethers::core::types::U256); - /// Container type for all return fields from the `decimals` function with signature - /// `decimals()` and selector `0x313ce567` + ///Container type for all return fields from the `decimals` function with signature `decimals()` and selector `0x313ce567` #[derive( Clone, ::ethers::contract::EthAbiType, @@ -1834,11 +2007,10 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] pub struct DecimalsReturn(pub u8); - /// Container type for all return fields from the `name` function with signature `name()` and - /// selector `0x06fdde03` + ///Container type for all return fields from the `name` function with signature `name()` and selector `0x06fdde03` #[derive( Clone, ::ethers::contract::EthAbiType, @@ -1847,11 +2019,10 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] pub struct NameReturn(pub ::std::string::String); - /// Container type for all return fields from the `symbol` function with signature `symbol()` - /// and selector `0x95d89b41` + ///Container type for all return fields from the `symbol` function with signature `symbol()` and selector `0x95d89b41` #[derive( Clone, ::ethers::contract::EthAbiType, @@ -1860,11 +2031,10 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] pub struct SymbolReturn(pub ::std::string::String); - /// Container type for all return fields from the `totalSupply` function with signature - /// `totalSupply()` and selector `0x18160ddd` + ///Container type for all return fields from the `totalSupply` function with signature `totalSupply()` and selector `0x18160ddd` #[derive( Clone, ::ethers::contract::EthAbiType, @@ -1873,11 +2043,10 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] pub struct TotalSupplyReturn(pub ::ethers::core::types::U256); - /// Container type for all return fields from the `transfer` function with signature - /// `transfer(address,uint256)` and selector `0xa9059cbb` + ///Container type for all return fields from the `transfer` function with signature `transfer(address,uint256)` and selector `0xa9059cbb` #[derive( Clone, ::ethers::contract::EthAbiType, @@ -1886,11 +2055,10 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] pub struct TransferReturn(pub bool); - /// Container type for all return fields from the `transferFrom` function with signature - /// `transferFrom(address,address,uint256)` and selector `0x23b872dd` + ///Container type for all return fields from the `transferFrom` function with signature `transferFrom(address,address,uint256)` and selector `0x23b872dd` #[derive( Clone, ::ethers::contract::EthAbiType, @@ -1899,7 +2067,7 @@ pub mod astria_bridgeable_erc20 { Debug, PartialEq, Eq, - Hash, + Hash )] pub struct TransferFromReturn(pub bool); } diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/generated/astria_withdrawer.rs b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/generated/astria_withdrawer.rs index 0ab771e47..e289f478b 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/generated/astria_withdrawer.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/generated/astria_withdrawer.rs @@ -7,133 +7,169 @@ pub use astria_withdrawer::*; clippy::upper_case_acronyms, clippy::type_complexity, dead_code, - non_camel_case_types + non_camel_case_types, )] pub mod astria_withdrawer { #[allow(deprecated)] fn __abi() -> ::ethers::core::abi::Abi { ::ethers::core::abi::ethabi::Contract { constructor: ::core::option::Option::Some(::ethers::core::abi::ethabi::Constructor { - inputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("_baseChainAssetPrecision",), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(32usize), - internal_type: ::core::option::Option::Some(::std::borrow::ToOwned::to_owned( - "uint32" - ),), - },], + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned( + "_baseChainAssetPrecision", + ), + kind: ::ethers::core::abi::ethabi::ParamType::Uint(32usize), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint32"), + ), + }, + ], }), functions: ::core::convert::From::from([ ( ::std::borrow::ToOwned::to_owned("BASE_CHAIN_ASSET_PRECISION"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("BASE_CHAIN_ASSET_PRECISION",), - inputs: ::std::vec![], - outputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::string::String::new(), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(32usize), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint32"), + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned( + "BASE_CHAIN_ASSET_PRECISION", ), - },], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, - },], + inputs: ::std::vec![], + outputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::string::String::new(), + kind: ::ethers::core::abi::ethabi::ParamType::Uint(32usize), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint32"), + ), + }, + ], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("withdrawToIbcChain"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("withdrawToIbcChain"), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("destinationChainAddress",), - kind: ::ethers::core::abi::ethabi::ParamType::String, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("string"), - ), - }, - ::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("memo"), - kind: ::ethers::core::abi::ethabi::ParamType::String, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("string"), - ), - }, - ], - outputs: ::std::vec![], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::Payable, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned("withdrawToIbcChain"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned( + "destinationChainAddress", + ), + kind: ::ethers::core::abi::ethabi::ParamType::String, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("string"), + ), + }, + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned("memo"), + kind: ::ethers::core::abi::ethabi::ParamType::String, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("string"), + ), + }, + ], + outputs: ::std::vec![], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::Payable, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("withdrawToSequencer"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("withdrawToSequencer",), - inputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::borrow::ToOwned::to_owned("destinationChainAddress",), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("address"), + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned( + "withdrawToSequencer", ), - },], - outputs: ::std::vec![], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::Payable, - },], + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::borrow::ToOwned::to_owned( + "destinationChainAddress", + ), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("address"), + ), + }, + ], + outputs: ::std::vec![], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::Payable, + }, + ], ), ]), events: ::core::convert::From::from([ ( ::std::borrow::ToOwned::to_owned("Ics20Withdrawal"), - ::std::vec![::ethers::core::abi::ethabi::Event { - name: ::std::borrow::ToOwned::to_owned("Ics20Withdrawal"), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("sender"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("amount"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("destinationChainAddress",), - kind: ::ethers::core::abi::ethabi::ParamType::String, - indexed: false, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("memo"), - kind: ::ethers::core::abi::ethabi::ParamType::String, - indexed: false, - }, - ], - anonymous: false, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Event { + name: ::std::borrow::ToOwned::to_owned("Ics20Withdrawal"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("sender"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("amount"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned( + "destinationChainAddress", + ), + kind: ::ethers::core::abi::ethabi::ParamType::String, + indexed: false, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("memo"), + kind: ::ethers::core::abi::ethabi::ParamType::String, + indexed: false, + }, + ], + anonymous: false, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("SequencerWithdrawal"), - ::std::vec![::ethers::core::abi::ethabi::Event { - name: ::std::borrow::ToOwned::to_owned("SequencerWithdrawal",), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("sender"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("amount"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("destinationChainAddress",), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: false, - }, - ], - anonymous: false, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Event { + name: ::std::borrow::ToOwned::to_owned( + "SequencerWithdrawal", + ), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("sender"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("amount"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned( + "destinationChainAddress", + ), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: false, + }, + ], + anonymous: false, + }, + ], ), ]), errors: ::std::collections::BTreeMap::new(), @@ -141,19 +177,22 @@ pub mod astria_withdrawer { fallback: false, } } - /// The parsed JSON ABI of the contract. - pub static ASTRIAWITHDRAWER_ABI: ::ethers::contract::Lazy<::ethers::core::abi::Abi> = - ::ethers::contract::Lazy::new(__abi); + ///The parsed JSON ABI of the contract. + pub static ASTRIAWITHDRAWER_ABI: ::ethers::contract::Lazy< + ::ethers::core::abi::Abi, + > = ::ethers::contract::Lazy::new(__abi); #[rustfmt::skip] const __BYTECODE: &[u8] = b"`\xC0`@R4\x80\x15a\0\x10W`\0\x80\xFD[P`@Qa\x06|8\x03\x80a\x06|\x839\x81\x01`@\x81\x90Ra\0/\x91a\0\xEFV[`\x12\x81c\xFF\xFF\xFF\xFF\x16\x11\x15a\0\xC6W`@QbF\x1B\xCD`\xE5\x1B\x81R` `\x04\x82\x01R`M`$\x82\x01R\x7FAstriaWithdrawer: base chain ass`D\x82\x01R\x7Fet precision must be less than o`d\x82\x01Rl\x0ED\x0C\xAE.\xAC-\x84\x0E\x8D\xE4\x06'`\x9B\x1B`\x84\x82\x01R`\xA4\x01`@Q\x80\x91\x03\x90\xFD[c\xFF\xFF\xFF\xFF\x81\x16`\x80Ra\0\xDB\x81`\x12a\x012V[a\0\xE6\x90`\na\x02\x0C\x97d\xAD2S-\x90\xB9x\xA3\xC3\xB0\xB2\xF5G\x8C\xE8\xE5\xDB>\x85\xD3\xA0dsolcC\0\x08\x15\x003"; /// The bytecode of the contract. - pub static ASTRIAWITHDRAWER_BYTECODE: ::ethers::core::types::Bytes = - ::ethers::core::types::Bytes::from_static(__BYTECODE); + pub static ASTRIAWITHDRAWER_BYTECODE: ::ethers::core::types::Bytes = ::ethers::core::types::Bytes::from_static( + __BYTECODE, + ); #[rustfmt::skip] const __DEPLOYED_BYTECODE: &[u8] = b"`\x80`@R`\x046\x10a\x004W`\x005`\xE0\x1C\x80c~\xB6\xDE\xC7\x14a\09W\x80c\x9A\x97z\xFE\x14a\0\x86W\x80c\xA9\x96\xE0 \x14a\0\x9BW[`\0\x80\xFD[4\x80\x15a\0EW`\0\x80\xFD[Pa\0m\x7F\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x81V[`@Qc\xFF\xFF\xFF\xFF\x90\x91\x16\x81R` \x01`@Q\x80\x91\x03\x90\xF3[a\0\x99a\0\x946`\x04a\x01\xDEV[a\0\xAEV[\0[a\0\x99a\0\xA96`\x04a\x02WV[a\x01EV[4`\0a\0\xDB\x7F\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x83a\x02\xC3V[\x11a\x01\x01W`@QbF\x1B\xCD`\xE5\x1B\x81R`\x04\x01a\0\xF8\x90a\x02\xE5V[`@Q\x80\x91\x03\x90\xFD[`@Q`\x01`\x01`\xA0\x1B\x03\x83\x16\x81R4\x903\x90\x7F\xAE\x8EffM\x10\x85DP\x9C\x9A[j\x9F3\xC3\xB5\xFE\xF3\xF8\x8E]?\xA6\x80pjo\xEB\x13`\xE3\x90` \x01`@Q\x80\x91\x03\x90\xA3PPV[4`\0a\x01r\x7F\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x83a\x02\xC3V[\x11a\x01\x8FW`@QbF\x1B\xCD`\xE5\x1B\x81R`\x04\x01a\0\xF8\x90a\x02\xE5V[43`\x01`\x01`\xA0\x1B\x03\x16\x7F\x0Cd\xE2\x9ART\xA7\x1C\x7FNR\xB3\xD2\xD264\x8C\x80\xE0\n\0\xBA.\x19a\x96+\xD2\x82|\x03\xFB\x87\x87\x87\x87`@Qa\x01\xCF\x94\x93\x92\x91\x90a\x03\x9CV[`@Q\x80\x91\x03\x90\xA3PPPPPV[`\0` \x82\x84\x03\x12\x15a\x01\xF0W`\0\x80\xFD[\x815`\x01`\x01`\xA0\x1B\x03\x81\x16\x81\x14a\x02\x07W`\0\x80\xFD[\x93\x92PPPV[`\0\x80\x83`\x1F\x84\x01\x12a\x02 W`\0\x80\xFD[P\x815g\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x81\x11\x15a\x028W`\0\x80\xFD[` \x83\x01\x91P\x83` \x82\x85\x01\x01\x11\x15a\x02PW`\0\x80\xFD[\x92P\x92\x90PV[`\0\x80`\0\x80`@\x85\x87\x03\x12\x15a\x02mW`\0\x80\xFD[\x845g\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x80\x82\x11\x15a\x02\x85W`\0\x80\xFD[a\x02\x91\x88\x83\x89\x01a\x02\x0EV[\x90\x96P\x94P` \x87\x015\x91P\x80\x82\x11\x15a\x02\xAAW`\0\x80\xFD[Pa\x02\xB7\x87\x82\x88\x01a\x02\x0EV[\x95\x98\x94\x97P\x95PPPPV[`\0\x82a\x02\xE0WcNH{q`\xE0\x1B`\0R`\x12`\x04R`$`\0\xFD[P\x04\x90V[` \x80\x82R`b\x90\x82\x01R\x7FAstriaWithdrawer: insufficient v`@\x82\x01R\x7Falue, must be greater than 10 **``\x82\x01R\x7F (18 - BASE_CHAIN_ASSET_PRECISIO`\x80\x82\x01RaN)`\xF0\x1B`\xA0\x82\x01R`\xC0\x01\x90V[\x81\x83R\x81\x81` \x85\x017P`\0\x82\x82\x01` \x90\x81\x01\x91\x90\x91R`\x1F\x90\x91\x01`\x1F\x19\x16\x90\x91\x01\x01\x90V[`@\x81R`\0a\x03\xB0`@\x83\x01\x86\x88a\x03sV[\x82\x81\x03` \x84\x01Ra\x03\xC3\x81\x85\x87a\x03sV[\x97\x96PPPPPPPV\xFE\xA2dipfsX\"\x12 \xBFH[\xDE\xF8\xBB^>\x0C\x97d\xAD2S-\x90\xB9x\xA3\xC3\xB0\xB2\xF5G\x8C\xE8\xE5\xDB>\x85\xD3\xA0dsolcC\0\x08\x15\x003"; /// The deployed bytecode of the contract. - pub static ASTRIAWITHDRAWER_DEPLOYED_BYTECODE: ::ethers::core::types::Bytes = - ::ethers::core::types::Bytes::from_static(__DEPLOYED_BYTECODE); + pub static ASTRIAWITHDRAWER_DEPLOYED_BYTECODE: ::ethers::core::types::Bytes = ::ethers::core::types::Bytes::from_static( + __DEPLOYED_BYTECODE, + ); pub struct AstriaWithdrawer(::ethers::contract::Contract); impl ::core::clone::Clone for AstriaWithdrawer { fn clone(&self) -> Self { @@ -162,7 +201,6 @@ pub mod astria_withdrawer { } impl ::core::ops::Deref for AstriaWithdrawer { type Target = ::ethers::contract::Contract; - fn deref(&self) -> &Self::Target { &self.0 } @@ -186,16 +224,16 @@ pub mod astria_withdrawer { address: T, client: ::std::sync::Arc, ) -> Self { - Self(::ethers::contract::Contract::new( - address.into(), - ASTRIAWITHDRAWER_ABI.clone(), - client, - )) + Self( + ::ethers::contract::Contract::new( + address.into(), + ASTRIAWITHDRAWER_ABI.clone(), + client, + ), + ) } - - /// Constructs the general purpose `Deployer` instance based on the provided constructor - /// arguments and sends it. Returns a new instance of a deployer that returns an - /// instance of this contract after sending the transaction + /// Constructs the general purpose `Deployer` instance based on the provided constructor arguments and sends it. + /// Returns a new instance of a deployer that returns an instance of this contract after sending the transaction /// /// Notes: /// - If there are no constructor arguments, you should pass `()` as the argument. @@ -233,8 +271,7 @@ pub mod astria_withdrawer { let deployer = ::ethers::contract::ContractDeployer::new(deployer); Ok(deployer) } - - /// Calls the contract's `BASE_CHAIN_ASSET_PRECISION` (0x7eb6dec7) function + ///Calls the contract's `BASE_CHAIN_ASSET_PRECISION` (0x7eb6dec7) function pub fn base_chain_asset_precision( &self, ) -> ::ethers::contract::builders::ContractCall { @@ -242,8 +279,7 @@ pub mod astria_withdrawer { .method_hash([126, 182, 222, 199], ()) .expect("method not found (this should never happen)") } - - /// Calls the contract's `withdrawToIbcChain` (0xa996e020) function + ///Calls the contract's `withdrawToIbcChain` (0xa996e020) function pub fn withdraw_to_ibc_chain( &self, destination_chain_address: ::std::string::String, @@ -253,8 +289,7 @@ pub mod astria_withdrawer { .method_hash([169, 150, 224, 32], (destination_chain_address, memo)) .expect("method not found (this should never happen)") } - - /// Calls the contract's `withdrawToSequencer` (0x9a977afe) function + ///Calls the contract's `withdrawToSequencer` (0x9a977afe) function pub fn withdraw_to_sequencer( &self, destination_chain_address: ::ethers::core::types::Address, @@ -263,35 +298,39 @@ pub mod astria_withdrawer { .method_hash([154, 151, 122, 254], destination_chain_address) .expect("method not found (this should never happen)") } - - /// Gets the contract's `Ics20Withdrawal` event + ///Gets the contract's `Ics20Withdrawal` event pub fn ics_20_withdrawal_filter( &self, - ) -> ::ethers::contract::builders::Event<::std::sync::Arc, M, Ics20WithdrawalFilter> - { + ) -> ::ethers::contract::builders::Event< + ::std::sync::Arc, + M, + Ics20WithdrawalFilter, + > { self.0.event() } - - /// Gets the contract's `SequencerWithdrawal` event + ///Gets the contract's `SequencerWithdrawal` event pub fn sequencer_withdrawal_filter( &self, - ) -> ::ethers::contract::builders::Event<::std::sync::Arc, M, SequencerWithdrawalFilter> - { + ) -> ::ethers::contract::builders::Event< + ::std::sync::Arc, + M, + SequencerWithdrawalFilter, + > { self.0.event() } - /// Returns an `Event` builder for all the events of this contract. pub fn events( &self, - ) -> ::ethers::contract::builders::Event<::std::sync::Arc, M, AstriaWithdrawerEvents> - { - self.0 - .event_with_filter(::core::default::Default::default()) + ) -> ::ethers::contract::builders::Event< + ::std::sync::Arc, + M, + AstriaWithdrawerEvents, + > { + self.0.event_with_filter(::core::default::Default::default()) } } impl From<::ethers::contract::Contract> - for AstriaWithdrawer - { + for AstriaWithdrawer { fn from(contract: ::ethers::contract::Contract) -> Self { Self::new(contract.address(), contract.client()) } @@ -304,7 +343,7 @@ pub mod astria_withdrawer { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethevent( name = "Ics20Withdrawal", @@ -326,7 +365,7 @@ pub mod astria_withdrawer { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethevent( name = "SequencerWithdrawal", @@ -339,7 +378,7 @@ pub mod astria_withdrawer { pub amount: ::ethers::core::types::U256, pub destination_chain_address: ::ethers::core::types::Address, } - /// Container type for all of the contract's events + ///Container type for all of the contract's events #[derive(Clone, ::ethers::contract::EthAbiType, Debug, PartialEq, Eq, Hash)] pub enum AstriaWithdrawerEvents { Ics20WithdrawalFilter(Ics20WithdrawalFilter), @@ -361,8 +400,12 @@ pub mod astria_withdrawer { impl ::core::fmt::Display for AstriaWithdrawerEvents { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { - Self::Ics20WithdrawalFilter(element) => ::core::fmt::Display::fmt(element, f), - Self::SequencerWithdrawalFilter(element) => ::core::fmt::Display::fmt(element, f), + Self::Ics20WithdrawalFilter(element) => { + ::core::fmt::Display::fmt(element, f) + } + Self::SequencerWithdrawalFilter(element) => { + ::core::fmt::Display::fmt(element, f) + } } } } @@ -376,8 +419,7 @@ pub mod astria_withdrawer { Self::SequencerWithdrawalFilter(value) } } - /// Container type for all input parameters for the `BASE_CHAIN_ASSET_PRECISION` function with - /// signature `BASE_CHAIN_ASSET_PRECISION()` and selector `0x7eb6dec7` + ///Container type for all input parameters for the `BASE_CHAIN_ASSET_PRECISION` function with signature `BASE_CHAIN_ASSET_PRECISION()` and selector `0x7eb6dec7` #[derive( Clone, ::ethers::contract::EthCall, @@ -386,15 +428,11 @@ pub mod astria_withdrawer { Debug, PartialEq, Eq, - Hash, - )] - #[ethcall( - name = "BASE_CHAIN_ASSET_PRECISION", - abi = "BASE_CHAIN_ASSET_PRECISION()" + Hash )] + #[ethcall(name = "BASE_CHAIN_ASSET_PRECISION", abi = "BASE_CHAIN_ASSET_PRECISION()")] pub struct BaseChainAssetPrecisionCall; - /// Container type for all input parameters for the `withdrawToIbcChain` function with signature - /// `withdrawToIbcChain(string,string)` and selector `0xa996e020` + ///Container type for all input parameters for the `withdrawToIbcChain` function with signature `withdrawToIbcChain(string,string)` and selector `0xa996e020` #[derive( Clone, ::ethers::contract::EthCall, @@ -403,15 +441,14 @@ pub mod astria_withdrawer { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall(name = "withdrawToIbcChain", abi = "withdrawToIbcChain(string,string)")] pub struct WithdrawToIbcChainCall { pub destination_chain_address: ::std::string::String, pub memo: ::std::string::String, } - /// Container type for all input parameters for the `withdrawToSequencer` function with - /// signature `withdrawToSequencer(address)` and selector `0x9a977afe` + ///Container type for all input parameters for the `withdrawToSequencer` function with signature `withdrawToSequencer(address)` and selector `0x9a977afe` #[derive( Clone, ::ethers::contract::EthCall, @@ -420,13 +457,13 @@ pub mod astria_withdrawer { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethcall(name = "withdrawToSequencer", abi = "withdrawToSequencer(address)")] pub struct WithdrawToSequencerCall { pub destination_chain_address: ::ethers::core::types::Address, } - /// Container type for all of the contract's call + ///Container type for all of the contract's call #[derive(Clone, ::ethers::contract::EthAbiType, Debug, PartialEq, Eq, Hash)] pub enum AstriaWithdrawerCalls { BaseChainAssetPrecision(BaseChainAssetPrecisionCall), @@ -438,19 +475,19 @@ pub mod astria_withdrawer { data: impl AsRef<[u8]>, ) -> ::core::result::Result { let data = data.as_ref(); - if let Ok(decoded) = - ::decode(data) - { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::BaseChainAssetPrecision(decoded)); } - if let Ok(decoded) = - ::decode(data) - { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::WithdrawToIbcChain(decoded)); } - if let Ok(decoded) = - ::decode(data) - { + if let Ok(decoded) = ::decode( + data, + ) { return Ok(Self::WithdrawToSequencer(decoded)); } Err(::ethers::core::abi::Error::InvalidData.into()) @@ -474,9 +511,15 @@ pub mod astria_withdrawer { impl ::core::fmt::Display for AstriaWithdrawerCalls { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { - Self::BaseChainAssetPrecision(element) => ::core::fmt::Display::fmt(element, f), - Self::WithdrawToIbcChain(element) => ::core::fmt::Display::fmt(element, f), - Self::WithdrawToSequencer(element) => ::core::fmt::Display::fmt(element, f), + Self::BaseChainAssetPrecision(element) => { + ::core::fmt::Display::fmt(element, f) + } + Self::WithdrawToIbcChain(element) => { + ::core::fmt::Display::fmt(element, f) + } + Self::WithdrawToSequencer(element) => { + ::core::fmt::Display::fmt(element, f) + } } } } @@ -495,8 +538,7 @@ pub mod astria_withdrawer { Self::WithdrawToSequencer(value) } } - /// Container type for all return fields from the `BASE_CHAIN_ASSET_PRECISION` function with - /// signature `BASE_CHAIN_ASSET_PRECISION()` and selector `0x7eb6dec7` + ///Container type for all return fields from the `BASE_CHAIN_ASSET_PRECISION` function with signature `BASE_CHAIN_ASSET_PRECISION()` and selector `0x7eb6dec7` #[derive( Clone, ::ethers::contract::EthAbiType, @@ -505,7 +547,7 @@ pub mod astria_withdrawer { Debug, PartialEq, Eq, - Hash, + Hash )] pub struct BaseChainAssetPrecisionReturn(pub u32); } diff --git a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/generated/astria_withdrawer_interface.rs b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/generated/astria_withdrawer_interface.rs index d65d12b24..722b3f454 100644 --- a/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/generated/astria_withdrawer_interface.rs +++ b/crates/astria-bridge-withdrawer/src/withdrawer/ethereum/generated/astria_withdrawer_interface.rs @@ -7,82 +7,104 @@ pub use i_astria_withdrawer::*; clippy::upper_case_acronyms, clippy::type_complexity, dead_code, - non_camel_case_types + non_camel_case_types, )] pub mod i_astria_withdrawer { #[allow(deprecated)] fn __abi() -> ::ethers::core::abi::Abi { ::ethers::core::abi::ethabi::Contract { constructor: ::core::option::Option::None, - functions: ::core::convert::From::from([( - ::std::borrow::ToOwned::to_owned("BASE_CHAIN_ASSET_PRECISION"), - ::std::vec![::ethers::core::abi::ethabi::Function { - name: ::std::borrow::ToOwned::to_owned("BASE_CHAIN_ASSET_PRECISION",), - inputs: ::std::vec![], - outputs: ::std::vec![::ethers::core::abi::ethabi::Param { - name: ::std::string::String::new(), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(32usize), - internal_type: ::core::option::Option::Some( - ::std::borrow::ToOwned::to_owned("uint32"), - ), - },], - constant: ::core::option::Option::None, - state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, - },], - )]), + functions: ::core::convert::From::from([ + ( + ::std::borrow::ToOwned::to_owned("BASE_CHAIN_ASSET_PRECISION"), + ::std::vec![ + ::ethers::core::abi::ethabi::Function { + name: ::std::borrow::ToOwned::to_owned( + "BASE_CHAIN_ASSET_PRECISION", + ), + inputs: ::std::vec![], + outputs: ::std::vec![ + ::ethers::core::abi::ethabi::Param { + name: ::std::string::String::new(), + kind: ::ethers::core::abi::ethabi::ParamType::Uint(32usize), + internal_type: ::core::option::Option::Some( + ::std::borrow::ToOwned::to_owned("uint32"), + ), + }, + ], + constant: ::core::option::Option::None, + state_mutability: ::ethers::core::abi::ethabi::StateMutability::View, + }, + ], + ), + ]), events: ::core::convert::From::from([ ( ::std::borrow::ToOwned::to_owned("Ics20Withdrawal"), - ::std::vec![::ethers::core::abi::ethabi::Event { - name: ::std::borrow::ToOwned::to_owned("Ics20Withdrawal"), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("sender"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("amount"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("destinationChainAddress",), - kind: ::ethers::core::abi::ethabi::ParamType::String, - indexed: false, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("memo"), - kind: ::ethers::core::abi::ethabi::ParamType::String, - indexed: false, - }, - ], - anonymous: false, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Event { + name: ::std::borrow::ToOwned::to_owned("Ics20Withdrawal"), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("sender"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("amount"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned( + "destinationChainAddress", + ), + kind: ::ethers::core::abi::ethabi::ParamType::String, + indexed: false, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("memo"), + kind: ::ethers::core::abi::ethabi::ParamType::String, + indexed: false, + }, + ], + anonymous: false, + }, + ], ), ( ::std::borrow::ToOwned::to_owned("SequencerWithdrawal"), - ::std::vec![::ethers::core::abi::ethabi::Event { - name: ::std::borrow::ToOwned::to_owned("SequencerWithdrawal",), - inputs: ::std::vec![ - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("sender"), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("amount"), - kind: ::ethers::core::abi::ethabi::ParamType::Uint(256usize,), - indexed: true, - }, - ::ethers::core::abi::ethabi::EventParam { - name: ::std::borrow::ToOwned::to_owned("destinationChainAddress",), - kind: ::ethers::core::abi::ethabi::ParamType::Address, - indexed: false, - }, - ], - anonymous: false, - },], + ::std::vec![ + ::ethers::core::abi::ethabi::Event { + name: ::std::borrow::ToOwned::to_owned( + "SequencerWithdrawal", + ), + inputs: ::std::vec![ + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("sender"), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned("amount"), + kind: ::ethers::core::abi::ethabi::ParamType::Uint( + 256usize, + ), + indexed: true, + }, + ::ethers::core::abi::ethabi::EventParam { + name: ::std::borrow::ToOwned::to_owned( + "destinationChainAddress", + ), + kind: ::ethers::core::abi::ethabi::ParamType::Address, + indexed: false, + }, + ], + anonymous: false, + }, + ], ), ]), errors: ::std::collections::BTreeMap::new(), @@ -90,9 +112,10 @@ pub mod i_astria_withdrawer { fallback: false, } } - /// The parsed JSON ABI of the contract. - pub static IASTRIAWITHDRAWER_ABI: ::ethers::contract::Lazy<::ethers::core::abi::Abi> = - ::ethers::contract::Lazy::new(__abi); + ///The parsed JSON ABI of the contract. + pub static IASTRIAWITHDRAWER_ABI: ::ethers::contract::Lazy< + ::ethers::core::abi::Abi, + > = ::ethers::contract::Lazy::new(__abi); pub struct IAstriaWithdrawer(::ethers::contract::Contract); impl ::core::clone::Clone for IAstriaWithdrawer { fn clone(&self) -> Self { @@ -101,7 +124,6 @@ pub mod i_astria_withdrawer { } impl ::core::ops::Deref for IAstriaWithdrawer { type Target = ::ethers::contract::Contract; - fn deref(&self) -> &Self::Target { &self.0 } @@ -125,14 +147,15 @@ pub mod i_astria_withdrawer { address: T, client: ::std::sync::Arc, ) -> Self { - Self(::ethers::contract::Contract::new( - address.into(), - IASTRIAWITHDRAWER_ABI.clone(), - client, - )) + Self( + ::ethers::contract::Contract::new( + address.into(), + IASTRIAWITHDRAWER_ABI.clone(), + client, + ), + ) } - - /// Calls the contract's `BASE_CHAIN_ASSET_PRECISION` (0x7eb6dec7) function + ///Calls the contract's `BASE_CHAIN_ASSET_PRECISION` (0x7eb6dec7) function pub fn base_chain_asset_precision( &self, ) -> ::ethers::contract::builders::ContractCall { @@ -140,35 +163,39 @@ pub mod i_astria_withdrawer { .method_hash([126, 182, 222, 199], ()) .expect("method not found (this should never happen)") } - - /// Gets the contract's `Ics20Withdrawal` event + ///Gets the contract's `Ics20Withdrawal` event pub fn ics_20_withdrawal_filter( &self, - ) -> ::ethers::contract::builders::Event<::std::sync::Arc, M, Ics20WithdrawalFilter> - { + ) -> ::ethers::contract::builders::Event< + ::std::sync::Arc, + M, + Ics20WithdrawalFilter, + > { self.0.event() } - - /// Gets the contract's `SequencerWithdrawal` event + ///Gets the contract's `SequencerWithdrawal` event pub fn sequencer_withdrawal_filter( &self, - ) -> ::ethers::contract::builders::Event<::std::sync::Arc, M, SequencerWithdrawalFilter> - { + ) -> ::ethers::contract::builders::Event< + ::std::sync::Arc, + M, + SequencerWithdrawalFilter, + > { self.0.event() } - /// Returns an `Event` builder for all the events of this contract. pub fn events( &self, - ) -> ::ethers::contract::builders::Event<::std::sync::Arc, M, IAstriaWithdrawerEvents> - { - self.0 - .event_with_filter(::core::default::Default::default()) + ) -> ::ethers::contract::builders::Event< + ::std::sync::Arc, + M, + IAstriaWithdrawerEvents, + > { + self.0.event_with_filter(::core::default::Default::default()) } } impl From<::ethers::contract::Contract> - for IAstriaWithdrawer - { + for IAstriaWithdrawer { fn from(contract: ::ethers::contract::Contract) -> Self { Self::new(contract.address(), contract.client()) } @@ -181,7 +208,7 @@ pub mod i_astria_withdrawer { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethevent( name = "Ics20Withdrawal", @@ -203,7 +230,7 @@ pub mod i_astria_withdrawer { Debug, PartialEq, Eq, - Hash, + Hash )] #[ethevent( name = "SequencerWithdrawal", @@ -216,7 +243,7 @@ pub mod i_astria_withdrawer { pub amount: ::ethers::core::types::U256, pub destination_chain_address: ::ethers::core::types::Address, } - /// Container type for all of the contract's events + ///Container type for all of the contract's events #[derive(Clone, ::ethers::contract::EthAbiType, Debug, PartialEq, Eq, Hash)] pub enum IAstriaWithdrawerEvents { Ics20WithdrawalFilter(Ics20WithdrawalFilter), @@ -238,8 +265,12 @@ pub mod i_astria_withdrawer { impl ::core::fmt::Display for IAstriaWithdrawerEvents { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { - Self::Ics20WithdrawalFilter(element) => ::core::fmt::Display::fmt(element, f), - Self::SequencerWithdrawalFilter(element) => ::core::fmt::Display::fmt(element, f), + Self::Ics20WithdrawalFilter(element) => { + ::core::fmt::Display::fmt(element, f) + } + Self::SequencerWithdrawalFilter(element) => { + ::core::fmt::Display::fmt(element, f) + } } } } @@ -253,8 +284,7 @@ pub mod i_astria_withdrawer { Self::SequencerWithdrawalFilter(value) } } - /// Container type for all input parameters for the `BASE_CHAIN_ASSET_PRECISION` function with - /// signature `BASE_CHAIN_ASSET_PRECISION()` and selector `0x7eb6dec7` + ///Container type for all input parameters for the `BASE_CHAIN_ASSET_PRECISION` function with signature `BASE_CHAIN_ASSET_PRECISION()` and selector `0x7eb6dec7` #[derive( Clone, ::ethers::contract::EthCall, @@ -263,15 +293,11 @@ pub mod i_astria_withdrawer { Debug, PartialEq, Eq, - Hash, - )] - #[ethcall( - name = "BASE_CHAIN_ASSET_PRECISION", - abi = "BASE_CHAIN_ASSET_PRECISION()" + Hash )] + #[ethcall(name = "BASE_CHAIN_ASSET_PRECISION", abi = "BASE_CHAIN_ASSET_PRECISION()")] pub struct BaseChainAssetPrecisionCall; - /// Container type for all return fields from the `BASE_CHAIN_ASSET_PRECISION` function with - /// signature `BASE_CHAIN_ASSET_PRECISION()` and selector `0x7eb6dec7` + ///Container type for all return fields from the `BASE_CHAIN_ASSET_PRECISION` function with signature `BASE_CHAIN_ASSET_PRECISION()` and selector `0x7eb6dec7` #[derive( Clone, ::ethers::contract::EthAbiType, @@ -280,7 +306,7 @@ pub mod i_astria_withdrawer { Debug, PartialEq, Eq, - Hash, + Hash )] pub struct BaseChainAssetPrecisionReturn(pub u32); } From abf0144e7e60d77a29fed3f3ddef3a122710a649 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Mon, 10 Jun 2024 16:00:53 -0500 Subject: [PATCH 09/23] minor updates --- crates/astria-composer/src/executor/tests.rs | 90 +++++++++---------- .../tests/blackbox/helper/mock_sequencer.rs | 9 +- .../tests/blackbox/helper/mod.rs | 4 +- 3 files changed, 51 insertions(+), 52 deletions(-) diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index 27ea9626e..5e1400318 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -48,46 +48,6 @@ use crate::{ Config, }; -const STATUS_RESPONSE: &str = r#" -{ - "node_info": { - "protocol_version": { - "p2p": "8", - "block": "11", - "app": "0" - }, - "id": "a1d3bbddb7800c6da2e64169fec281494e963ba3", - "listen_addr": "tcp://0.0.0.0:26656", - "network": "test", - "version": "0.38.6", - "channels": "40202122233038606100", - "moniker": "fullnode", - "other": { - "tx_index": "on", - "rpc_address": "tcp://0.0.0.0:26657" - } - }, - "sync_info": { - "latest_block_hash": "A4202E4E367712AC2A797860265A7EBEA8A3ACE513CB0105C2C9058449641202", - "latest_app_hash": "BCC9C9B82A49EC37AADA41D32B4FBECD2441563703955413195BDA2236775A68", - "latest_block_height": "452605", - "latest_block_time": "2024-05-09T15:59:17.849713071Z", - "earliest_block_hash": "C34B7B0B82423554B844F444044D7D08A026D6E413E6F72848DB2F8C77ACE165", - "earliest_app_hash": "6B776065775471CEF46AC75DE09A4B869A0E0EB1D7725A04A342C0E46C16F472", - "earliest_block_height": "1", - "earliest_block_time": "2024-04-23T00:49:11.964127Z", - "catching_up": false - }, - "validator_info": { - "address": "0B46F33BA2FA5C2E2AD4C4C4E5ECE3F1CA03D195", - "pub_key": { - "type": "tendermint/PubKeyEd25519", - "value": "bA6GipHUijVuiYhv+4XymdePBsn8EeTqjGqNQrBGZ4I=" - }, - "voting_power": "0" - } -}"#; - static TELEMETRY: Lazy<()> = Lazy::new(|| { if std::env::var_os("TEST_LOG").is_some() { let filter_directives = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".into()); @@ -259,7 +219,7 @@ async fn full_bundle() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - let _status_guard = mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + let _status_response_guard = mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -361,7 +321,7 @@ async fn bundle_triggered_by_block_timer() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - let _status_guard = mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + let _status_response_guard = mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -456,7 +416,7 @@ async fn two_seq_actions_single_bundle() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - let _status_guard = mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + let _status_response_guard = mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -562,7 +522,7 @@ async fn should_exit_if_mismatch_sequencer_chain_id() { let shutdown_token = CancellationToken::new(); // mount a status response with an incorrect chain_id - let _status_guard = mount_cometbft_status_response(&sequencer, "different-chain-id").await; + let _status_response_guard = mount_cometbft_status_response(&sequencer, "bad-chain-id").await; // build the executor with the correct chain_id let build_result = executor::Builder { @@ -577,6 +537,46 @@ async fn should_exit_if_mismatch_sequencer_chain_id() { .build() .await; - // verify that the executor build resulted in an error + // verify that the executor build results in an error assert!(build_result.is_err()); } + +const STATUS_RESPONSE: &str = r#" +{ + "node_info": { + "protocol_version": { + "p2p": "8", + "block": "11", + "app": "0" + }, + "id": "a1d3bbddb7800c6da2e64169fec281494e963ba3", + "listen_addr": "tcp://0.0.0.0:26656", + "network": "test-chain-1", + "version": "0.38.6", + "channels": "40202122233038606100", + "moniker": "fullnode", + "other": { + "tx_index": "on", + "rpc_address": "tcp://0.0.0.0:26657" + } + }, + "sync_info": { + "latest_block_hash": "A4202E4E367712AC2A797860265A7EBEA8A3ACE513CB0105C2C9058449641202", + "latest_app_hash": "BCC9C9B82A49EC37AADA41D32B4FBECD2441563703955413195BDA2236775A68", + "latest_block_height": "452605", + "latest_block_time": "2024-05-09T15:59:17.849713071Z", + "earliest_block_hash": "C34B7B0B82423554B844F444044D7D08A026D6E413E6F72848DB2F8C77ACE165", + "earliest_app_hash": "6B776065775471CEF46AC75DE09A4B869A0E0EB1D7725A04A342C0E46C16F472", + "earliest_block_height": "1", + "earliest_block_time": "2024-04-23T00:49:11.964127Z", + "catching_up": false + }, + "validator_info": { + "address": "0B46F33BA2FA5C2E2AD4C4C4E5ECE3F1CA03D195", + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "bA6GipHUijVuiYhv+4XymdePBsn8EeTqjGqNQrBGZ4I=" + }, + "voting_power": "0" + } +}"#; \ No newline at end of file diff --git a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs index 159111f56..9bec9d4c7 100644 --- a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs +++ b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs @@ -14,6 +14,7 @@ use wiremock::{ MockServer, ResponseTemplate, }; +use tendermint_rpc::endpoint::status; pub async fn start() -> (MockServer, MockGuard, MockGuard) { use astria_core::generated::protocol::account::v1alpha1::NonceResponse; @@ -27,8 +28,8 @@ pub async fn start() -> (MockServer, MockGuard, MockGuard) { }, ) .await; - let status_guard = mount_cometbft_status_response(&server, "test-chain-1").await; - (server, startup_guard, status_guard) + let status_response_guard = mount_cometbft_status_response(&server, "test-chain-1").await; + (server, startup_guard, status_response_guard) } pub async fn mount_abci_query_mock( @@ -60,8 +61,6 @@ pub async fn mount_abci_query_mock( } async fn mount_cometbft_status_response(server: &MockServer, mock_sequencer_chain_id: &str) -> MockGuard { - use tendermint_rpc::endpoint::status; - let mut status_response: status::Response = serde_json::from_str(STATUS_RESPONSE).unwrap(); status_response.node_info.network = mock_sequencer_chain_id.to_string().parse().unwrap(); @@ -87,7 +86,7 @@ const STATUS_RESPONSE: &str = r#" }, "id": "a1d3bbddb7800c6da2e64169fec281494e963ba3", "listen_addr": "tcp://0.0.0.0:26656", - "network": "test", + "network": "test-chain-1", "version": "0.38.6", "channels": "40202122233038606100", "moniker": "fullnode", diff --git a/crates/astria-composer/tests/blackbox/helper/mod.rs b/crates/astria-composer/tests/blackbox/helper/mod.rs index 5eba2229f..1d2135fbf 100644 --- a/crates/astria-composer/tests/blackbox/helper/mod.rs +++ b/crates/astria-composer/tests/blackbox/helper/mod.rs @@ -83,7 +83,7 @@ pub async fn spawn_composer(rollup_ids: &[&str]) -> TestComposer { rollup_nodes.insert((*id).to_string(), geth); rollups.push_str(&format!("{id}::{execution_url},")); } - let (sequencer, sequencer_setup_guard, sequencer_status_guard) = mock_sequencer::start().await; + let (sequencer, sequencer_setup_guard, sequencer_status_response_guard) = mock_sequencer::start().await; let sequencer_url = sequencer.uri(); let keyfile = NamedTempFile::new().unwrap(); (&keyfile) @@ -121,7 +121,7 @@ pub async fn spawn_composer(rollup_ids: &[&str]) -> TestComposer { rollup_nodes, sequencer, setup_guard: sequencer_setup_guard, - status_guard: sequencer_status_guard, + status_guard: sequencer_status_response_guard, grpc_collector_addr, } } From 42250cbf40ce8e247af3f0b64e97eb564a5302e3 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Mon, 10 Jun 2024 16:23:21 -0500 Subject: [PATCH 10/23] minor changes --- crates/astria-composer/src/executor/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index 404ed4216..5dbaf893c 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -66,7 +66,7 @@ static TELEMETRY: Lazy<()> = Lazy::new(|| { } }); -/// Start a mock sequencer server and mount a mock for the `accounts/nonce` query. +/// Start a mock sequencer server. async fn setup() -> (MockServer, Config, NamedTempFile) { Lazy::force(&TELEMETRY); let server = MockServer::start().await; From edf423eee7c4694d1790d5a718d478a33c027753 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Wed, 12 Jun 2024 20:16:58 -0500 Subject: [PATCH 11/23] cargo format --- .../astria-composer/src/executor/builder.rs | 3 ++- crates/astria-composer/src/executor/tests.rs | 19 +++++++++++++------ .../tests/blackbox/helper/mock_sequencer.rs | 7 +++++-- .../tests/blackbox/helper/mod.rs | 3 ++- 4 files changed, 22 insertions(+), 10 deletions(-) diff --git a/crates/astria-composer/src/executor/builder.rs b/crates/astria-composer/src/executor/builder.rs index e8552ad5a..e487b4bcc 100644 --- a/crates/astria-composer/src/executor/builder.rs +++ b/crates/astria-composer/src/executor/builder.rs @@ -58,7 +58,8 @@ impl Builder { let client_chain_id = client_response.node_info.network.to_string(); ensure!( sequencer_chain_id == client_chain_id, - "mismatch in sequencer_chain_id: {sequencer_chain_id} and client chain_id: {client_chain_id}" + "mismatch in sequencer_chain_id: {sequencer_chain_id} and client chain_id: \ + {client_chain_id}" ); let (status, _) = watch::channel(Status::new()); diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index 5dbaf893c..86eaabede 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -173,7 +173,10 @@ async fn mount_broadcast_tx_sync_seq_actions_mock(server: &MockServer) -> MockGu } // Mounts a `CometBFT` status response with a specified mock sequencer chain id -async fn mount_cometbft_status_response(server: &MockServer, mock_sequencer_chain_id: &str) -> MockGuard { +async fn mount_cometbft_status_response( + server: &MockServer, + mock_sequencer_chain_id: &str, +) -> MockGuard { use tendermint_rpc::endpoint::status; let mut status_response: status::Response = serde_json::from_str(STATUS_RESPONSE).unwrap(); @@ -219,7 +222,8 @@ async fn full_bundle() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - let _status_response_guard = mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + let _status_response_guard = + mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -321,7 +325,8 @@ async fn bundle_triggered_by_block_timer() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - let _status_response_guard = mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + let _status_response_guard = + mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -416,7 +421,8 @@ async fn two_seq_actions_single_bundle() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - let _status_response_guard = mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + let _status_response_guard = + mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -514,7 +520,8 @@ async fn two_seq_actions_single_bundle() { } } -/// Test to check that executor's configured sequencer chain id and sequencer's actual chain id match +/// Test to check that executor's configured sequencer chain id and sequencer's actual chain id +/// match #[tokio::test] async fn should_exit_if_mismatch_sequencer_chain_id() { // set up sequencer mock @@ -579,4 +586,4 @@ const STATUS_RESPONSE: &str = r#" }, "voting_power": "0" } -}"#; \ No newline at end of file +}"#; diff --git a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs index 9bec9d4c7..084be868f 100644 --- a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs +++ b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs @@ -1,6 +1,7 @@ use prost::Message; use serde_json::json; use tendermint_rpc::{ + endpoint::status, response, Id, }; @@ -14,7 +15,6 @@ use wiremock::{ MockServer, ResponseTemplate, }; -use tendermint_rpc::endpoint::status; pub async fn start() -> (MockServer, MockGuard, MockGuard) { use astria_core::generated::protocol::account::v1alpha1::NonceResponse; @@ -60,7 +60,10 @@ pub async fn mount_abci_query_mock( .await } -async fn mount_cometbft_status_response(server: &MockServer, mock_sequencer_chain_id: &str) -> MockGuard { +async fn mount_cometbft_status_response( + server: &MockServer, + mock_sequencer_chain_id: &str, +) -> MockGuard { let mut status_response: status::Response = serde_json::from_str(STATUS_RESPONSE).unwrap(); status_response.node_info.network = mock_sequencer_chain_id.to_string().parse().unwrap(); diff --git a/crates/astria-composer/tests/blackbox/helper/mod.rs b/crates/astria-composer/tests/blackbox/helper/mod.rs index 1d2135fbf..fa671140f 100644 --- a/crates/astria-composer/tests/blackbox/helper/mod.rs +++ b/crates/astria-composer/tests/blackbox/helper/mod.rs @@ -83,7 +83,8 @@ pub async fn spawn_composer(rollup_ids: &[&str]) -> TestComposer { rollup_nodes.insert((*id).to_string(), geth); rollups.push_str(&format!("{id}::{execution_url},")); } - let (sequencer, sequencer_setup_guard, sequencer_status_response_guard) = mock_sequencer::start().await; + let (sequencer, sequencer_setup_guard, sequencer_status_response_guard) = + mock_sequencer::start().await; let sequencer_url = sequencer.uri(); let keyfile = NamedTempFile::new().unwrap(); (&keyfile) From 7f1d9a19fff11d97a96d22841c6ac3c2f93ad6ae Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Thu, 13 Jun 2024 12:32:50 -0500 Subject: [PATCH 12/23] make build function sync, remove status mock guard, ad-hoc json creation --- crates/astria-composer/src/composer.rs | 1 - .../astria-composer/src/executor/builder.rs | 15 +--- crates/astria-composer/src/executor/mod.rs | 27 +++++- crates/astria-composer/src/executor/tests.rs | 82 ++++--------------- .../tests/blackbox/helper/mock_sequencer.rs | 63 +++----------- .../tests/blackbox/helper/mod.rs | 5 +- 6 files changed, 58 insertions(+), 135 deletions(-) diff --git a/crates/astria-composer/src/composer.rs b/crates/astria-composer/src/composer.rs index 748d4525b..e22bba724 100644 --- a/crates/astria-composer/src/composer.rs +++ b/crates/astria-composer/src/composer.rs @@ -127,7 +127,6 @@ impl Composer { shutdown_token: shutdown_token.clone(), } .build() - .await .wrap_err("executor construction from config failed")?; let grpc_server = grpc::Builder { diff --git a/crates/astria-composer/src/executor/builder.rs b/crates/astria-composer/src/executor/builder.rs index e487b4bcc..fcc357f69 100644 --- a/crates/astria-composer/src/executor/builder.rs +++ b/crates/astria-composer/src/executor/builder.rs @@ -14,11 +14,9 @@ use astria_core::{ }; use astria_eyre::eyre::{ self, - ensure, eyre, Context, }; -use sequencer_client::tendermint_rpc::Client; use tokio::sync::watch; use tokio_util::sync::CancellationToken; @@ -38,7 +36,7 @@ pub(crate) struct Builder { } impl Builder { - pub(crate) async fn build(self) -> eyre::Result<(super::Executor, executor::Handle)> { + pub(crate) fn build(self) -> eyre::Result<(super::Executor, executor::Handle)> { let Self { sequencer_url, sequencer_chain_id, @@ -51,17 +49,6 @@ impl Builder { let sequencer_client = sequencer_client::HttpClient::new(sequencer_url.as_str()) .wrap_err("failed constructing sequencer client")?; - let client_response = sequencer_client - .status() - .await - .wrap_err("failed to retrieve sequencer network status")?; - let client_chain_id = client_response.node_info.network.to_string(); - ensure!( - sequencer_chain_id == client_chain_id, - "mismatch in sequencer_chain_id: {sequencer_chain_id} and client chain_id: \ - {client_chain_id}" - ); - let (status, _) = watch::channel(Status::new()); let sequencer_key = read_signing_key_from_file(&private_key_file).wrap_err_with(|| { diff --git a/crates/astria-composer/src/executor/mod.rs b/crates/astria-composer/src/executor/mod.rs index 131446583..8cf5eba00 100644 --- a/crates/astria-composer/src/executor/mod.rs +++ b/crates/astria-composer/src/executor/mod.rs @@ -24,6 +24,7 @@ use astria_core::{ }; use astria_eyre::eyre::{ self, + ensure, eyre, WrapErr as _, }; @@ -40,7 +41,10 @@ use futures::{ use pin_project_lite::pin_project; use prost::Message as _; use sequencer_client::{ - tendermint_rpc::endpoint::broadcast::tx_sync, + tendermint_rpc::{ + endpoint::broadcast::tx_sync, + Client, + }, Address, SequencerClientExt as _, }; @@ -192,6 +196,10 @@ impl Executor { /// An error is returned if connecting to the sequencer fails. #[instrument(skip_all, fields(address = %self.address))] pub(super) async fn run_until_stopped(mut self) -> eyre::Result<()> { + let _chain_id_result = self + .check_chain_ids() + .await + .wrap_err("failed chain_id check"); let mut submission_fut: Fuse> = Fuse::terminated(); let mut nonce = get_latest_nonce(self.sequencer_client.clone(), self.address) .await @@ -415,6 +423,23 @@ impl Executor { reason.map(|_| ()) } + + // check for mismatched configured chain_id and sequencer client chain_id + pub(crate) async fn check_chain_ids(&self) -> eyre::Result<()> { + let client_response = self + .sequencer_client + .status() + .await + .wrap_err("failed to retrieve sequencer network status")?; + let client_chain_id = client_response.node_info.network.to_string(); + let configured_chain_id = self.sequencer_chain_id.clone(); + ensure!( + configured_chain_id == client_chain_id, + "mismatch in configured chain_id: {configured_chain_id} and sequencer chain_id: \ + {client_chain_id}" + ); + Ok(()) + } } /// Queries the sequencer for the latest nonce with an exponential backoff diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index 86eaabede..e63c27be3 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -172,25 +172,25 @@ async fn mount_broadcast_tx_sync_seq_actions_mock(server: &MockServer) -> MockGu .await } -// Mounts a `CometBFT` status response with a specified mock sequencer chain id -async fn mount_cometbft_status_response( +// Mounts a `CometBFT` status response with only a specified mock sequencer chain id +async fn mount_partial_cometbft_status_response( server: &MockServer, mock_sequencer_chain_id: &str, -) -> MockGuard { - use tendermint_rpc::endpoint::status; - - let mut status_response: status::Response = serde_json::from_str(STATUS_RESPONSE).unwrap(); - status_response.node_info.network = mock_sequencer_chain_id.to_string().parse().unwrap(); +) { + let partial_status_response = json!({"node_info": {"network": mock_sequencer_chain_id}}); - let response = - tendermint_rpc::response::Wrapper::new_with_id(Id::Num(1), Some(status_response), None); + let response = tendermint_rpc::response::Wrapper::new_with_id( + Id::Num(1), + Some(partial_status_response), + None, + ); Mock::given(body_partial_json(json!({"method": "status"}))) .respond_with(ResponseTemplate::new(200).set_body_json(response)) .up_to_n_times(1) .expect(1..) .named("CometBFT status") - .mount_as_scoped(server) + .mount(server) .await } @@ -222,8 +222,7 @@ async fn full_bundle() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - let _status_response_guard = - mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + mount_partial_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -234,7 +233,6 @@ async fn full_bundle() { shutdown_token: shutdown_token.clone(), } .build() - .await .unwrap(); let nonce_guard = mount_nonce_query_mock( @@ -325,8 +323,7 @@ async fn bundle_triggered_by_block_timer() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - let _status_response_guard = - mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + mount_partial_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -337,7 +334,6 @@ async fn bundle_triggered_by_block_timer() { shutdown_token: shutdown_token.clone(), } .build() - .await .unwrap(); let nonce_guard = mount_nonce_query_mock( @@ -421,8 +417,7 @@ async fn two_seq_actions_single_bundle() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - let _status_response_guard = - mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + mount_partial_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -433,7 +428,6 @@ async fn two_seq_actions_single_bundle() { shutdown_token: shutdown_token.clone(), } .build() - .await .unwrap(); let nonce_guard = mount_nonce_query_mock( @@ -529,10 +523,10 @@ async fn should_exit_if_mismatch_sequencer_chain_id() { let shutdown_token = CancellationToken::new(); // mount a status response with an incorrect chain_id - let _status_response_guard = mount_cometbft_status_response(&sequencer, "bad-chain-id").await; + mount_partial_cometbft_status_response(&sequencer, "bad-chain-id").await; // build the executor with the correct chain_id - let build_result = executor::Builder { + let (executor, _executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), private_key_file: cfg.private_key_file.clone(), @@ -542,48 +536,8 @@ async fn should_exit_if_mismatch_sequencer_chain_id() { shutdown_token: shutdown_token.clone(), } .build() - .await; + .unwrap(); - // verify that the executor build results in an error - assert!(build_result.is_err()); + // verify that the executor chain_id check results in an error + assert!(executor.check_chain_ids().await.is_err()); } - -const STATUS_RESPONSE: &str = r#" -{ - "node_info": { - "protocol_version": { - "p2p": "8", - "block": "11", - "app": "0" - }, - "id": "a1d3bbddb7800c6da2e64169fec281494e963ba3", - "listen_addr": "tcp://0.0.0.0:26656", - "network": "test-chain-1", - "version": "0.38.6", - "channels": "40202122233038606100", - "moniker": "fullnode", - "other": { - "tx_index": "on", - "rpc_address": "tcp://0.0.0.0:26657" - } - }, - "sync_info": { - "latest_block_hash": "A4202E4E367712AC2A797860265A7EBEA8A3ACE513CB0105C2C9058449641202", - "latest_app_hash": "BCC9C9B82A49EC37AADA41D32B4FBECD2441563703955413195BDA2236775A68", - "latest_block_height": "452605", - "latest_block_time": "2024-05-09T15:59:17.849713071Z", - "earliest_block_hash": "C34B7B0B82423554B844F444044D7D08A026D6E413E6F72848DB2F8C77ACE165", - "earliest_app_hash": "6B776065775471CEF46AC75DE09A4B869A0E0EB1D7725A04A342C0E46C16F472", - "earliest_block_height": "1", - "earliest_block_time": "2024-04-23T00:49:11.964127Z", - "catching_up": false - }, - "validator_info": { - "address": "0B46F33BA2FA5C2E2AD4C4C4E5ECE3F1CA03D195", - "pub_key": { - "type": "tendermint/PubKeyEd25519", - "value": "bA6GipHUijVuiYhv+4XymdePBsn8EeTqjGqNQrBGZ4I=" - }, - "voting_power": "0" - } -}"#; diff --git a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs index 084be868f..71b0f9f17 100644 --- a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs +++ b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs @@ -1,7 +1,6 @@ use prost::Message; use serde_json::json; use tendermint_rpc::{ - endpoint::status, response, Id, }; @@ -16,7 +15,7 @@ use wiremock::{ ResponseTemplate, }; -pub async fn start() -> (MockServer, MockGuard, MockGuard) { +pub async fn start() -> (MockServer, MockGuard) { use astria_core::generated::protocol::account::v1alpha1::NonceResponse; let server = MockServer::start().await; let startup_guard = mount_abci_query_mock( @@ -28,8 +27,8 @@ pub async fn start() -> (MockServer, MockGuard, MockGuard) { }, ) .await; - let status_response_guard = mount_cometbft_status_response(&server, "test-chain-1").await; - (server, startup_guard, status_response_guard) + mount_partial_cometbft_status_response(&server, "test-chain-1").await; + (server, startup_guard) } pub async fn mount_abci_query_mock( @@ -60,61 +59,23 @@ pub async fn mount_abci_query_mock( .await } -async fn mount_cometbft_status_response( +async fn mount_partial_cometbft_status_response( server: &MockServer, mock_sequencer_chain_id: &str, -) -> MockGuard { - let mut status_response: status::Response = serde_json::from_str(STATUS_RESPONSE).unwrap(); - status_response.node_info.network = mock_sequencer_chain_id.to_string().parse().unwrap(); +) { + let partial_status_response = json!({"node_info": {"network": mock_sequencer_chain_id}}); - let response = - tendermint_rpc::response::Wrapper::new_with_id(Id::Num(1), Some(status_response), None); + let response = tendermint_rpc::response::Wrapper::new_with_id( + Id::Num(1), + Some(partial_status_response), + None, + ); Mock::given(body_partial_json(json!({"method": "status"}))) .respond_with(ResponseTemplate::new(200).set_body_json(response)) .up_to_n_times(1) .expect(1..) .named("CometBFT status") - .mount_as_scoped(server) + .mount(server) .await } - -const STATUS_RESPONSE: &str = r#" -{ - "node_info": { - "protocol_version": { - "p2p": "8", - "block": "11", - "app": "0" - }, - "id": "a1d3bbddb7800c6da2e64169fec281494e963ba3", - "listen_addr": "tcp://0.0.0.0:26656", - "network": "test-chain-1", - "version": "0.38.6", - "channels": "40202122233038606100", - "moniker": "fullnode", - "other": { - "tx_index": "on", - "rpc_address": "tcp://0.0.0.0:26657" - } - }, - "sync_info": { - "latest_block_hash": "A4202E4E367712AC2A797860265A7EBEA8A3ACE513CB0105C2C9058449641202", - "latest_app_hash": "BCC9C9B82A49EC37AADA41D32B4FBECD2441563703955413195BDA2236775A68", - "latest_block_height": "452605", - "latest_block_time": "2024-05-09T15:59:17.849713071Z", - "earliest_block_hash": "C34B7B0B82423554B844F444044D7D08A026D6E413E6F72848DB2F8C77ACE165", - "earliest_app_hash": "6B776065775471CEF46AC75DE09A4B869A0E0EB1D7725A04A342C0E46C16F472", - "earliest_block_height": "1", - "earliest_block_time": "2024-04-23T00:49:11.964127Z", - "catching_up": false - }, - "validator_info": { - "address": "0B46F33BA2FA5C2E2AD4C4C4E5ECE3F1CA03D195", - "pub_key": { - "type": "tendermint/PubKeyEd25519", - "value": "bA6GipHUijVuiYhv+4XymdePBsn8EeTqjGqNQrBGZ4I=" - }, - "voting_power": "0" - } -}"#; diff --git a/crates/astria-composer/tests/blackbox/helper/mod.rs b/crates/astria-composer/tests/blackbox/helper/mod.rs index fa671140f..ea802b289 100644 --- a/crates/astria-composer/tests/blackbox/helper/mod.rs +++ b/crates/astria-composer/tests/blackbox/helper/mod.rs @@ -63,7 +63,6 @@ pub struct TestComposer { pub rollup_nodes: HashMap, pub sequencer: wiremock::MockServer, pub setup_guard: MockGuard, - pub status_guard: MockGuard, pub grpc_collector_addr: SocketAddr, } @@ -83,8 +82,7 @@ pub async fn spawn_composer(rollup_ids: &[&str]) -> TestComposer { rollup_nodes.insert((*id).to_string(), geth); rollups.push_str(&format!("{id}::{execution_url},")); } - let (sequencer, sequencer_setup_guard, sequencer_status_response_guard) = - mock_sequencer::start().await; + let (sequencer, sequencer_setup_guard) = mock_sequencer::start().await; let sequencer_url = sequencer.uri(); let keyfile = NamedTempFile::new().unwrap(); (&keyfile) @@ -122,7 +120,6 @@ pub async fn spawn_composer(rollup_ids: &[&str]) -> TestComposer { rollup_nodes, sequencer, setup_guard: sequencer_setup_guard, - status_guard: sequencer_status_response_guard, grpc_collector_addr, } } From b69f7a76e8366919728ed4a0a5ccc43b1a265c65 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Thu, 13 Jun 2024 17:04:14 -0500 Subject: [PATCH 13/23] move response json inside mount, move chain_id check out of run_until_stopped --- crates/astria-composer/src/composer.rs | 1 + crates/astria-composer/src/executor/mod.rs | 4 -- crates/astria-composer/src/executor/tests.rs | 64 +++++++++++++++---- .../tests/blackbox/helper/mock_sequencer.rs | 47 ++++++++++++-- 4 files changed, 96 insertions(+), 20 deletions(-) diff --git a/crates/astria-composer/src/composer.rs b/crates/astria-composer/src/composer.rs index e22bba724..27c35b006 100644 --- a/crates/astria-composer/src/composer.rs +++ b/crates/astria-composer/src/composer.rs @@ -240,6 +240,7 @@ impl Composer { // run the collectors and executor spawn_geth_collectors(&mut geth_collectors, &mut geth_collector_tasks); + let _chain_id_result = executor.check_chain_ids().await.wrap_err("chain_id mismatch"); let executor_status = executor.subscribe().clone(); let mut executor_task = tokio::spawn(executor.run_until_stopped()); diff --git a/crates/astria-composer/src/executor/mod.rs b/crates/astria-composer/src/executor/mod.rs index 8cf5eba00..4733c1260 100644 --- a/crates/astria-composer/src/executor/mod.rs +++ b/crates/astria-composer/src/executor/mod.rs @@ -196,10 +196,6 @@ impl Executor { /// An error is returned if connecting to the sequencer fails. #[instrument(skip_all, fields(address = %self.address))] pub(super) async fn run_until_stopped(mut self) -> eyre::Result<()> { - let _chain_id_result = self - .check_chain_ids() - .await - .wrap_err("failed chain_id check"); let mut submission_fut: Fuse> = Fuse::terminated(); let mut nonce = get_latest_nonce(self.sequencer_client.clone(), self.address) .await diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index e63c27be3..bcac3c267 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -1,6 +1,5 @@ use std::{ - io::Write, - time::Duration, + io::Write, time::Duration }; use astria_core::{ @@ -20,7 +19,7 @@ use sequencer_client::SignedTransaction; use serde_json::json; use tempfile::NamedTempFile; use tendermint_rpc::{ - endpoint::broadcast::tx_sync, + endpoint::{broadcast::tx_sync, status}, request, response, Id, @@ -172,16 +171,54 @@ async fn mount_broadcast_tx_sync_seq_actions_mock(server: &MockServer) -> MockGu .await } -// Mounts a `CometBFT` status response with only a specified mock sequencer chain id -async fn mount_partial_cometbft_status_response( +/// Mounts a `CometBFT` status response with a specified mock sequencer chain id +async fn mount_cometbft_status_response( server: &MockServer, mock_sequencer_chain_id: &str, ) { - let partial_status_response = json!({"node_info": {"network": mock_sequencer_chain_id}}); + let mut status_response: status::Response = serde_json::from_value(json!({ + "node_info": { + "protocol_version": { + "p2p": "8", + "block": "11", + "app": "0" + }, + "id": "a1d3bbddb7800c6da2e64169fec281494e963ba3", + "listen_addr": "tcp://0.0.0.0:26656", + "network": "test", + "version": "0.38.6", + "channels": "40202122233038606100", + "moniker": "fullnode", + "other": { + "tx_index": "on", + "rpc_address": "tcp://0.0.0.0:26657" + } + }, + "sync_info": { + "latest_block_hash": "A4202E4E367712AC2A797860265A7EBEA8A3ACE513CB0105C2C9058449641202", + "latest_app_hash": "BCC9C9B82A49EC37AADA41D32B4FBECD2441563703955413195BDA2236775A68", + "latest_block_height": "452605", + "latest_block_time": "2024-05-09T15:59:17.849713071Z", + "earliest_block_hash": "C34B7B0B82423554B844F444044D7D08A026D6E413E6F72848DB2F8C77ACE165", + "earliest_app_hash": "6B776065775471CEF46AC75DE09A4B869A0E0EB1D7725A04A342C0E46C16F472", + "earliest_block_height": "1", + "earliest_block_time": "2024-04-23T00:49:11.964127Z", + "catching_up": false + }, + "validator_info": { + "address": "0B46F33BA2FA5C2E2AD4C4C4E5ECE3F1CA03D195", + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "bA6GipHUijVuiYhv+4XymdePBsn8EeTqjGqNQrBGZ4I=" + }, + "voting_power": "0" + } + })).unwrap(); + status_response.node_info.network = mock_sequencer_chain_id.to_string().parse().unwrap(); let response = tendermint_rpc::response::Wrapper::new_with_id( Id::Num(1), - Some(partial_status_response), + Some(status_response), None, ); @@ -222,7 +259,7 @@ async fn full_bundle() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - mount_partial_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -246,6 +283,7 @@ async fn full_bundle() { .await; let status = executor.subscribe(); + executor.check_chain_ids().await.unwrap(); let _executor_task = tokio::spawn(executor.run_until_stopped()); // wait for sequencer to get the initial nonce request from sequencer wait_for_startup(status, nonce_guard).await.unwrap(); @@ -323,7 +361,7 @@ async fn bundle_triggered_by_block_timer() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - mount_partial_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -347,6 +385,7 @@ async fn bundle_triggered_by_block_timer() { .await; let status = executor.subscribe(); + executor.check_chain_ids().await.unwrap(); let _executor_task = tokio::spawn(executor.run_until_stopped()); // wait for sequencer to get the initial nonce request from sequencer @@ -417,7 +456,7 @@ async fn two_seq_actions_single_bundle() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - mount_partial_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -441,6 +480,7 @@ async fn two_seq_actions_single_bundle() { .await; let status = executor.subscribe(); + executor.check_chain_ids().await.unwrap(); let _executor_task = tokio::spawn(executor.run_until_stopped()); // wait for sequencer to get the initial nonce request from sequencer @@ -523,7 +563,7 @@ async fn should_exit_if_mismatch_sequencer_chain_id() { let shutdown_token = CancellationToken::new(); // mount a status response with an incorrect chain_id - mount_partial_cometbft_status_response(&sequencer, "bad-chain-id").await; + mount_cometbft_status_response(&sequencer, "bad-chain-id").await; // build the executor with the correct chain_id let (executor, _executor_handle) = executor::Builder { @@ -538,6 +578,6 @@ async fn should_exit_if_mismatch_sequencer_chain_id() { .build() .unwrap(); - // verify that the executor chain_id check results in an error + //verify that the executor chain_id check results in an error assert!(executor.check_chain_ids().await.is_err()); } diff --git a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs index 71b0f9f17..5d668fc0f 100644 --- a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs +++ b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs @@ -14,6 +14,7 @@ use wiremock::{ MockServer, ResponseTemplate, }; +use tendermint_rpc::endpoint::status; pub async fn start() -> (MockServer, MockGuard) { use astria_core::generated::protocol::account::v1alpha1::NonceResponse; @@ -27,7 +28,7 @@ pub async fn start() -> (MockServer, MockGuard) { }, ) .await; - mount_partial_cometbft_status_response(&server, "test-chain-1").await; + mount_cometbft_status_response(&server, "test-chain-1").await; (server, startup_guard) } @@ -59,15 +60,53 @@ pub async fn mount_abci_query_mock( .await } -async fn mount_partial_cometbft_status_response( +async fn mount_cometbft_status_response( server: &MockServer, mock_sequencer_chain_id: &str, ) { - let partial_status_response = json!({"node_info": {"network": mock_sequencer_chain_id}}); + let mut status_response: status::Response = serde_json::from_value(json!({ + "node_info": { + "protocol_version": { + "p2p": "8", + "block": "11", + "app": "0" + }, + "id": "a1d3bbddb7800c6da2e64169fec281494e963ba3", + "listen_addr": "tcp://0.0.0.0:26656", + "network": "test", + "version": "0.38.6", + "channels": "40202122233038606100", + "moniker": "fullnode", + "other": { + "tx_index": "on", + "rpc_address": "tcp://0.0.0.0:26657" + } + }, + "sync_info": { + "latest_block_hash": "A4202E4E367712AC2A797860265A7EBEA8A3ACE513CB0105C2C9058449641202", + "latest_app_hash": "BCC9C9B82A49EC37AADA41D32B4FBECD2441563703955413195BDA2236775A68", + "latest_block_height": "452605", + "latest_block_time": "2024-05-09T15:59:17.849713071Z", + "earliest_block_hash": "C34B7B0B82423554B844F444044D7D08A026D6E413E6F72848DB2F8C77ACE165", + "earliest_app_hash": "6B776065775471CEF46AC75DE09A4B869A0E0EB1D7725A04A342C0E46C16F472", + "earliest_block_height": "1", + "earliest_block_time": "2024-04-23T00:49:11.964127Z", + "catching_up": false + }, + "validator_info": { + "address": "0B46F33BA2FA5C2E2AD4C4C4E5ECE3F1CA03D195", + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "bA6GipHUijVuiYhv+4XymdePBsn8EeTqjGqNQrBGZ4I=" + }, + "voting_power": "0" + } + })).unwrap(); + status_response.node_info.network = mock_sequencer_chain_id.to_string().parse().unwrap(); let response = tendermint_rpc::response::Wrapper::new_with_id( Id::Num(1), - Some(partial_status_response), + Some(status_response), None, ); From f3c96ff2cead566880c9a033f30f26bd5e155e63 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Sat, 15 Jun 2024 11:23:54 -0500 Subject: [PATCH 14/23] use tendermint genesis, move validation to executor, other minor changes --- crates/astria-composer/src/composer.rs | 2 +- crates/astria-composer/src/executor/mod.rs | 44 ++++-- crates/astria-composer/src/executor/tests.rs | 135 +++++++++--------- .../tests/blackbox/helper/mock_sequencer.rs | 117 ++++++++------- 4 files changed, 159 insertions(+), 139 deletions(-) diff --git a/crates/astria-composer/src/composer.rs b/crates/astria-composer/src/composer.rs index 27c35b006..ac80de7ea 100644 --- a/crates/astria-composer/src/composer.rs +++ b/crates/astria-composer/src/composer.rs @@ -240,7 +240,7 @@ impl Composer { // run the collectors and executor spawn_geth_collectors(&mut geth_collectors, &mut geth_collector_tasks); - let _chain_id_result = executor.check_chain_ids().await.wrap_err("chain_id mismatch"); + // let _chain_id_result = executor.check_chain_ids().await.wrap_err("chain_id mismatch"); let executor_status = executor.subscribe().clone(); let mut executor_task = tokio::spawn(executor.run_until_stopped()); diff --git a/crates/astria-composer/src/executor/mod.rs b/crates/astria-composer/src/executor/mod.rs index 4733c1260..31525cffb 100644 --- a/crates/astria-composer/src/executor/mod.rs +++ b/crates/astria-composer/src/executor/mod.rs @@ -196,6 +196,10 @@ impl Executor { /// An error is returned if connecting to the sequencer fails. #[instrument(skip_all, fields(address = %self.address))] pub(super) async fn run_until_stopped(mut self) -> eyre::Result<()> { + let _chain_id_result = self + .ensure_configured_chain_id_matches_remote() + .await + .wrap_err("failed to validate chain_id")?; let mut submission_fut: Fuse> = Fuse::terminated(); let mut nonce = get_latest_nonce(self.sequencer_client.clone(), self.address) .await @@ -421,18 +425,36 @@ impl Executor { } // check for mismatched configured chain_id and sequencer client chain_id - pub(crate) async fn check_chain_ids(&self) -> eyre::Result<()> { - let client_response = self - .sequencer_client - .status() - .await - .wrap_err("failed to retrieve sequencer network status")?; - let client_chain_id = client_response.node_info.network.to_string(); - let configured_chain_id = self.sequencer_chain_id.clone(); + pub(crate) async fn ensure_configured_chain_id_matches_remote(&self) -> eyre::Result<()> { + let retry_config = tryhard::RetryFutureConfig::new(u32::MAX) + .exponential_backoff(Duration::from_millis(100)) + .max_delay(Duration::from_secs(20)) + .on_retry( + |attempt: u32, + next_delay: Option, + error: &sequencer_client::tendermint_rpc::Error| { + let wait_duration = next_delay + .map(humantime::format_duration) + .map(tracing::field::display); + warn!( + attempt, + wait_duration, + error = error as &dyn std::error::Error, + "attempt to fetch sequencer genesis info; retrying after backoff", + ); + futures::future::ready(()) + }, + ); + let client_genesis: tendermint::Genesis = + tryhard::retry_fn(|| self.sequencer_client.genesis()) + .with_config(retry_config) + .await + .wrap_err("failed to retrieve sequencer genesis after many attempts")?; ensure!( - configured_chain_id == client_chain_id, - "mismatch in configured chain_id: {configured_chain_id} and sequencer chain_id: \ - {client_chain_id}" + self.sequencer_chain_id == client_genesis.chain_id.as_str(), + "mismatch in configured chain_id: {0} and sequencer chain_id: {1}", + self.sequencer_chain_id, + client_genesis.chain_id.as_str() ); Ok(()) } diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index bcac3c267..ee8549bbf 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -1,5 +1,6 @@ use std::{ - io::Write, time::Duration + io::Write, + time::Duration, }; use astria_core::{ @@ -18,8 +19,19 @@ use prost::Message; use sequencer_client::SignedTransaction; use serde_json::json; use tempfile::NamedTempFile; +use tendermint::{ + consensus::{ + params::{ + AbciParams, + ValidatorParams, + }, + Params, + }, + Genesis, + Time, +}; use tendermint_rpc::{ - endpoint::{broadcast::tx_sync, status}, + endpoint::broadcast::tx_sync, request, response, Id, @@ -172,63 +184,50 @@ async fn mount_broadcast_tx_sync_seq_actions_mock(server: &MockServer) -> MockGu } /// Mounts a `CometBFT` status response with a specified mock sequencer chain id -async fn mount_cometbft_status_response( - server: &MockServer, - mock_sequencer_chain_id: &str, -) { - let mut status_response: status::Response = serde_json::from_value(json!({ - "node_info": { - "protocol_version": { - "p2p": "8", - "block": "11", - "app": "0" - }, - "id": "a1d3bbddb7800c6da2e64169fec281494e963ba3", - "listen_addr": "tcp://0.0.0.0:26656", - "network": "test", - "version": "0.38.6", - "channels": "40202122233038606100", - "moniker": "fullnode", - "other": { - "tx_index": "on", - "rpc_address": "tcp://0.0.0.0:26657" - } - }, - "sync_info": { - "latest_block_hash": "A4202E4E367712AC2A797860265A7EBEA8A3ACE513CB0105C2C9058449641202", - "latest_app_hash": "BCC9C9B82A49EC37AADA41D32B4FBECD2441563703955413195BDA2236775A68", - "latest_block_height": "452605", - "latest_block_time": "2024-05-09T15:59:17.849713071Z", - "earliest_block_hash": "C34B7B0B82423554B844F444044D7D08A026D6E413E6F72848DB2F8C77ACE165", - "earliest_app_hash": "6B776065775471CEF46AC75DE09A4B869A0E0EB1D7725A04A342C0E46C16F472", - "earliest_block_height": "1", - "earliest_block_time": "2024-04-23T00:49:11.964127Z", - "catching_up": false - }, - "validator_info": { - "address": "0B46F33BA2FA5C2E2AD4C4C4E5ECE3F1CA03D195", - "pub_key": { - "type": "tendermint/PubKeyEd25519", - "value": "bA6GipHUijVuiYhv+4XymdePBsn8EeTqjGqNQrBGZ4I=" - }, - "voting_power": "0" - } - })).unwrap(); - status_response.node_info.network = mock_sequencer_chain_id.to_string().parse().unwrap(); - - let response = tendermint_rpc::response::Wrapper::new_with_id( - Id::Num(1), - Some(status_response), - None, - ); - - Mock::given(body_partial_json(json!({"method": "status"}))) - .respond_with(ResponseTemplate::new(200).set_body_json(response)) - .up_to_n_times(1) - .expect(1..) - .named("CometBFT status") - .mount(server) - .await +async fn mount_genesis(server: &MockServer, mock_sequencer_chain_id: &str) { + Mock::given(body_partial_json( + json!({"jsonrpc": "2.0", "method": "genesis", "params": null}), + )) + .respond_with(ResponseTemplate::new(200).set_body_json( + tendermint_rpc::response::Wrapper::new_with_id( + tendermint_rpc::Id::uuid_v4(), + Some( + tendermint_rpc::endpoint::genesis::Response:: { + genesis: Genesis { + genesis_time: Time::from_unix_timestamp(1, 1).unwrap(), + chain_id: mock_sequencer_chain_id.try_into().unwrap(), + initial_height: 1, + consensus_params: Params { + block: tendermint::block::Size { + max_bytes: 1024, + max_gas: 1024, + time_iota_ms: 1000, + }, + evidence: tendermint::evidence::Params { + max_age_num_blocks: 1000, + max_age_duration: tendermint::evidence::Duration( + Duration::from_secs(3600), + ), + max_bytes: 1_048_576, + }, + validator: ValidatorParams { + pub_key_types: vec![tendermint::public_key::Algorithm::Ed25519], + }, + version: None, + abci: AbciParams::default(), + }, + validators: vec![], + app_hash: tendermint::hash::AppHash::default(), + app_state: serde_json::Value::Null, + }, + }, + ), + None, + ), + )) + .expect(1..) + .mount(server) + .await; } /// Helper to wait for the executor to connect to the mock sequencer @@ -259,7 +258,7 @@ async fn full_bundle() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + mount_genesis(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -283,7 +282,7 @@ async fn full_bundle() { .await; let status = executor.subscribe(); - executor.check_chain_ids().await.unwrap(); + // executor.check_chain_ids().await.unwrap(); let _executor_task = tokio::spawn(executor.run_until_stopped()); // wait for sequencer to get the initial nonce request from sequencer wait_for_startup(status, nonce_guard).await.unwrap(); @@ -361,7 +360,7 @@ async fn bundle_triggered_by_block_timer() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + mount_genesis(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -385,7 +384,7 @@ async fn bundle_triggered_by_block_timer() { .await; let status = executor.subscribe(); - executor.check_chain_ids().await.unwrap(); + // executor.check_chain_ids().await.unwrap(); let _executor_task = tokio::spawn(executor.run_until_stopped()); // wait for sequencer to get the initial nonce request from sequencer @@ -456,7 +455,7 @@ async fn two_seq_actions_single_bundle() { // set up the executor, channel for writing seq actions, and the sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); - mount_cometbft_status_response(&sequencer, &cfg.sequencer_chain_id).await; + mount_genesis(&sequencer, &cfg.sequencer_chain_id).await; let (executor, executor_handle) = executor::Builder { sequencer_url: cfg.sequencer_url.clone(), sequencer_chain_id: cfg.sequencer_chain_id.clone(), @@ -480,7 +479,7 @@ async fn two_seq_actions_single_bundle() { .await; let status = executor.subscribe(); - executor.check_chain_ids().await.unwrap(); + // executor.check_chain_ids().await.unwrap(); let _executor_task = tokio::spawn(executor.run_until_stopped()); // wait for sequencer to get the initial nonce request from sequencer @@ -563,7 +562,7 @@ async fn should_exit_if_mismatch_sequencer_chain_id() { let shutdown_token = CancellationToken::new(); // mount a status response with an incorrect chain_id - mount_cometbft_status_response(&sequencer, "bad-chain-id").await; + mount_genesis(&sequencer, "bad-chain-id").await; // build the executor with the correct chain_id let (executor, _executor_handle) = executor::Builder { @@ -578,6 +577,6 @@ async fn should_exit_if_mismatch_sequencer_chain_id() { .build() .unwrap(); - //verify that the executor chain_id check results in an error - assert!(executor.check_chain_ids().await.is_err()); + // verify that the executor chain_id check results in an error + assert!(executor.run_until_stopped().await.is_err()); } diff --git a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs index 5d668fc0f..546fce21d 100644 --- a/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs +++ b/crates/astria-composer/tests/blackbox/helper/mock_sequencer.rs @@ -1,5 +1,18 @@ +use std::time::Duration; + use prost::Message; use serde_json::json; +use tendermint::{ + consensus::{ + params::{ + AbciParams, + ValidatorParams, + }, + Params, + }, + Genesis, + Time, +}; use tendermint_rpc::{ response, Id, @@ -14,7 +27,6 @@ use wiremock::{ MockServer, ResponseTemplate, }; -use tendermint_rpc::endpoint::status; pub async fn start() -> (MockServer, MockGuard) { use astria_core::generated::protocol::account::v1alpha1::NonceResponse; @@ -28,7 +40,7 @@ pub async fn start() -> (MockServer, MockGuard) { }, ) .await; - mount_cometbft_status_response(&server, "test-chain-1").await; + mount_genesis(&server, "test-chain-1").await; (server, startup_guard) } @@ -60,61 +72,48 @@ pub async fn mount_abci_query_mock( .await } -async fn mount_cometbft_status_response( - server: &MockServer, - mock_sequencer_chain_id: &str, -) { - let mut status_response: status::Response = serde_json::from_value(json!({ - "node_info": { - "protocol_version": { - "p2p": "8", - "block": "11", - "app": "0" - }, - "id": "a1d3bbddb7800c6da2e64169fec281494e963ba3", - "listen_addr": "tcp://0.0.0.0:26656", - "network": "test", - "version": "0.38.6", - "channels": "40202122233038606100", - "moniker": "fullnode", - "other": { - "tx_index": "on", - "rpc_address": "tcp://0.0.0.0:26657" - } - }, - "sync_info": { - "latest_block_hash": "A4202E4E367712AC2A797860265A7EBEA8A3ACE513CB0105C2C9058449641202", - "latest_app_hash": "BCC9C9B82A49EC37AADA41D32B4FBECD2441563703955413195BDA2236775A68", - "latest_block_height": "452605", - "latest_block_time": "2024-05-09T15:59:17.849713071Z", - "earliest_block_hash": "C34B7B0B82423554B844F444044D7D08A026D6E413E6F72848DB2F8C77ACE165", - "earliest_app_hash": "6B776065775471CEF46AC75DE09A4B869A0E0EB1D7725A04A342C0E46C16F472", - "earliest_block_height": "1", - "earliest_block_time": "2024-04-23T00:49:11.964127Z", - "catching_up": false - }, - "validator_info": { - "address": "0B46F33BA2FA5C2E2AD4C4C4E5ECE3F1CA03D195", - "pub_key": { - "type": "tendermint/PubKeyEd25519", - "value": "bA6GipHUijVuiYhv+4XymdePBsn8EeTqjGqNQrBGZ4I=" - }, - "voting_power": "0" - } - })).unwrap(); - status_response.node_info.network = mock_sequencer_chain_id.to_string().parse().unwrap(); - - let response = tendermint_rpc::response::Wrapper::new_with_id( - Id::Num(1), - Some(status_response), - None, - ); - - Mock::given(body_partial_json(json!({"method": "status"}))) - .respond_with(ResponseTemplate::new(200).set_body_json(response)) - .up_to_n_times(1) - .expect(1..) - .named("CometBFT status") - .mount(server) - .await +async fn mount_genesis(server: &MockServer, mock_sequencer_chain_id: &str) { + Mock::given(body_partial_json( + json!({"jsonrpc": "2.0", "method": "genesis", "params": null}), + )) + .respond_with(ResponseTemplate::new(200).set_body_json( + tendermint_rpc::response::Wrapper::new_with_id( + tendermint_rpc::Id::uuid_v4(), + Some( + tendermint_rpc::endpoint::genesis::Response:: { + genesis: Genesis { + genesis_time: Time::from_unix_timestamp(1, 1).unwrap(), + chain_id: mock_sequencer_chain_id.try_into().unwrap(), + initial_height: 1, + consensus_params: Params { + block: tendermint::block::Size { + max_bytes: 1024, + max_gas: 1024, + time_iota_ms: 1000, + }, + evidence: tendermint::evidence::Params { + max_age_num_blocks: 1000, + max_age_duration: tendermint::evidence::Duration( + Duration::from_secs(3600), + ), + max_bytes: 1_048_576, + }, + validator: ValidatorParams { + pub_key_types: vec![tendermint::public_key::Algorithm::Ed25519], + }, + version: None, + abci: AbciParams::default(), + }, + validators: vec![], + app_hash: tendermint::hash::AppHash::default(), + app_state: serde_json::Value::Null, + }, + }, + ), + None, + ), + )) + .expect(1..) + .mount(server) + .await; } From 24e4b17bb9a014ad82a07931974a98223c1749e0 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Sat, 15 Jun 2024 11:31:17 -0500 Subject: [PATCH 15/23] minor changes --- crates/astria-composer/src/composer.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/astria-composer/src/composer.rs b/crates/astria-composer/src/composer.rs index ac80de7ea..e22bba724 100644 --- a/crates/astria-composer/src/composer.rs +++ b/crates/astria-composer/src/composer.rs @@ -240,7 +240,6 @@ impl Composer { // run the collectors and executor spawn_geth_collectors(&mut geth_collectors, &mut geth_collector_tasks); - // let _chain_id_result = executor.check_chain_ids().await.wrap_err("chain_id mismatch"); let executor_status = executor.subscribe().clone(); let mut executor_task = tokio::spawn(executor.run_until_stopped()); From b8d148fe6b66bb7f67ddd0b6a8a92004ec7b876a Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Tue, 25 Jun 2024 18:23:34 -0500 Subject: [PATCH 16/23] minor changes --- .../astria-composer/src/executor/builder.rs | 1 - crates/astria-composer/src/executor/mod.rs | 22 +++++----- crates/astria-composer/src/executor/tests.rs | 43 ++++--------------- 3 files changed, 20 insertions(+), 46 deletions(-) diff --git a/crates/astria-composer/src/executor/builder.rs b/crates/astria-composer/src/executor/builder.rs index fcc357f69..bd3d997a4 100644 --- a/crates/astria-composer/src/executor/builder.rs +++ b/crates/astria-composer/src/executor/builder.rs @@ -48,7 +48,6 @@ impl Builder { } = self; let sequencer_client = sequencer_client::HttpClient::new(sequencer_url.as_str()) .wrap_err("failed constructing sequencer client")?; - let (status, _) = watch::channel(Status::new()); let sequencer_key = read_signing_key_from_file(&private_key_file).wrap_err_with(|| { diff --git a/crates/astria-composer/src/executor/mod.rs b/crates/astria-composer/src/executor/mod.rs index 31525cffb..312a41ca0 100644 --- a/crates/astria-composer/src/executor/mod.rs +++ b/crates/astria-composer/src/executor/mod.rs @@ -196,10 +196,16 @@ impl Executor { /// An error is returned if connecting to the sequencer fails. #[instrument(skip_all, fields(address = %self.address))] pub(super) async fn run_until_stopped(mut self) -> eyre::Result<()> { - let _chain_id_result = self - .ensure_configured_chain_id_matches_remote() + let remote_chain_id = self + .get_sequencer_chain_id() .await - .wrap_err("failed to validate chain_id")?; + .wrap_err("failed obtain sequencer chain_id")?; + ensure!( + self.sequencer_chain_id == remote_chain_id, + "mismatch in configured chain_id: config specifies {0}, but sequencer rpc is for {1}", + self.sequencer_chain_id, + remote_chain_id + ); let mut submission_fut: Fuse> = Fuse::terminated(); let mut nonce = get_latest_nonce(self.sequencer_client.clone(), self.address) .await @@ -425,7 +431,7 @@ impl Executor { } // check for mismatched configured chain_id and sequencer client chain_id - pub(crate) async fn ensure_configured_chain_id_matches_remote(&self) -> eyre::Result<()> { + pub(crate) async fn get_sequencer_chain_id(&self) -> eyre::Result { let retry_config = tryhard::RetryFutureConfig::new(u32::MAX) .exponential_backoff(Duration::from_millis(100)) .max_delay(Duration::from_secs(20)) @@ -450,13 +456,7 @@ impl Executor { .with_config(retry_config) .await .wrap_err("failed to retrieve sequencer genesis after many attempts")?; - ensure!( - self.sequencer_chain_id == client_genesis.chain_id.as_str(), - "mismatch in configured chain_id: {0} and sequencer chain_id: {1}", - self.sequencer_chain_id, - client_genesis.chain_id.as_str() - ); - Ok(()) + Ok(client_genesis.chain_id.to_string()) } } diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index ee8549bbf..780266dd0 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -108,11 +108,12 @@ async fn setup() -> (MockServer, Config, NamedTempFile) { } /// Mount a mock for the `abci_query` endpoint. -async fn mount_nonce_query_mock( - server: &MockServer, - query_path: &str, - response: impl Message, -) -> MockGuard { +async fn mount_default_nonce_query_mock(server: &MockServer) -> MockGuard { + let query_path = "accounts/nonce"; + let response = NonceResponse { + height: 0, + nonce: 0, + }; let expected_body = json!({ "method": "abci_query" }); @@ -271,15 +272,7 @@ async fn full_bundle() { .build() .unwrap(); - let nonce_guard = mount_nonce_query_mock( - &sequencer, - "accounts/nonce", - NonceResponse { - height: 0, - nonce: 0, - }, - ) - .await; + let nonce_guard = mount_default_nonce_query_mock(&sequencer).await; let status = executor.subscribe(); // executor.check_chain_ids().await.unwrap(); @@ -373,15 +366,7 @@ async fn bundle_triggered_by_block_timer() { .build() .unwrap(); - let nonce_guard = mount_nonce_query_mock( - &sequencer, - "accounts/nonce", - NonceResponse { - height: 0, - nonce: 0, - }, - ) - .await; + let nonce_guard = mount_default_nonce_query_mock(&sequencer).await; let status = executor.subscribe(); // executor.check_chain_ids().await.unwrap(); @@ -468,18 +453,8 @@ async fn two_seq_actions_single_bundle() { .build() .unwrap(); - let nonce_guard = mount_nonce_query_mock( - &sequencer, - "accounts/nonce", - NonceResponse { - height: 0, - nonce: 0, - }, - ) - .await; + let nonce_guard = mount_default_nonce_query_mock(&sequencer).await; let status = executor.subscribe(); - - // executor.check_chain_ids().await.unwrap(); let _executor_task = tokio::spawn(executor.run_until_stopped()); // wait for sequencer to get the initial nonce request from sequencer From be387afd9075572f9f8d297b7cfc798b185be112 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Tue, 25 Jun 2024 18:29:47 -0500 Subject: [PATCH 17/23] minor changes --- crates/astria-composer/src/executor/tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index 8cad905aa..e781de34f 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -542,6 +542,7 @@ async fn should_exit_if_mismatch_sequencer_chain_id() { // set up sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); + let metrics = Box::leak(Box::new(Metrics::new(cfg.parse_rollups().unwrap().keys()))); // mount a status response with an incorrect chain_id mount_genesis(&sequencer, "bad-chain-id").await; @@ -555,6 +556,7 @@ async fn should_exit_if_mismatch_sequencer_chain_id() { max_bytes_per_bundle: cfg.max_bytes_per_bundle, bundle_queue_capacity: cfg.bundle_queue_capacity, shutdown_token: shutdown_token.clone(), + metrics, } .build() .unwrap(); From 8523e04a021781b7c8d0f52af7eafc43c1802ff0 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Mon, 1 Jul 2024 12:27:44 -0500 Subject: [PATCH 18/23] Streamline chain_id mismatch implementation and testing --- .../astria-composer/src/executor/builder.rs | 2 +- crates/astria-composer/src/executor/mod.rs | 69 ++++++++++++++----- crates/astria-composer/src/executor/tests.rs | 39 ++++++++--- 3 files changed, 84 insertions(+), 26 deletions(-) diff --git a/crates/astria-composer/src/executor/builder.rs b/crates/astria-composer/src/executor/builder.rs index e4bc0f217..871a4f1b3 100644 --- a/crates/astria-composer/src/executor/builder.rs +++ b/crates/astria-composer/src/executor/builder.rs @@ -12,7 +12,7 @@ use astria_core::{ use astria_eyre::eyre::{ self, eyre, - Context, + WrapErr as _, }; use tokio::sync::watch; use tokio_util::sync::CancellationToken; diff --git a/crates/astria-composer/src/executor/mod.rs b/crates/astria-composer/src/executor/mod.rs index 98675e113..78e88b3ff 100644 --- a/crates/astria-composer/src/executor/mod.rs +++ b/crates/astria-composer/src/executor/mod.rs @@ -24,7 +24,6 @@ use astria_core::{ }; use astria_eyre::eyre::{ self, - ensure, eyre, WrapErr as _, }; @@ -52,8 +51,10 @@ use tendermint::crypto::Sha256; use tokio::{ select, sync::{ - mpsc, - mpsc::error::SendTimeoutError, + mpsc::{ + self, + error::SendTimeoutError, + }, watch, }, time::{ @@ -98,7 +99,19 @@ pub(crate) use builder::Builder; const BUNDLE_DRAINING_DURATION: Duration = Duration::from_secs(16); type StdError = dyn std::error::Error; - +#[derive(Debug, thiserror::Error)] +pub(crate) enum EnsureChainIdError { + // + #[error("failed to obtain sequencer chain ID")] + FailedToGetChainId, + #[error("failed to obtain sequencer genesis")] + FailedToGetGenesis, + #[error("expected chain ID `{expected}`, but received `{actual}`")] + WrongChainId { + expected: String, + actual: tendermint::chain::Id, + }, +} /// The `Executor` interfaces with the sequencer. It handles account nonces, transaction signing, /// and transaction submission. /// The `Executor` receives `Vec` from the bundling logic, packages them with a nonce into @@ -203,15 +216,16 @@ impl Executor { /// An error is returned if connecting to the sequencer fails. #[instrument(skip_all, fields(address = %self.address))] pub(super) async fn run_until_stopped(mut self) -> eyre::Result<()> { - let remote_chain_id = self - .get_sequencer_chain_id() - .await - .wrap_err("failed obtain sequencer chain_id")?; - ensure!( - self.sequencer_chain_id == remote_chain_id, - "mismatch in configured chain_id: config specifies {0}, but sequencer rpc is for {1}", - self.sequencer_chain_id, - remote_chain_id + select!( + biased; + () = self.shutdown_token.cancelled() => { + info!("received shutdown signal while running initialization routines; exiting"); + return Ok(()); + } + + res = self.pre_run_checks() => { + res?; + } ); let mut submission_fut: Fuse> = Fuse::terminated(); let mut nonce = get_latest_nonce(self.sequencer_client.clone(), self.address, self.metrics) @@ -432,8 +446,29 @@ impl Executor { reason.map(|_| ()) } - // check for mismatched configured chain_id and sequencer client chain_id - pub(crate) async fn get_sequencer_chain_id(&self) -> eyre::Result { + /// Performs initialization checks prior to running the executor + async fn pre_run_checks(&self) -> eyre::Result<()> { + self.ensure_chain_id_is_correct().await?; + Ok(()) + } + + /// Performs check to ensure the configured chain ID matches the remote chain ID + pub(crate) async fn ensure_chain_id_is_correct(&self) -> Result<(), EnsureChainIdError> { + let remote_chain_id = self + .get_sequencer_chain_id() + .await + .map_err(|_| EnsureChainIdError::FailedToGetChainId)?; + if remote_chain_id.as_str() != self.sequencer_chain_id { + return Err(EnsureChainIdError::WrongChainId { + expected: self.sequencer_chain_id.clone(), + actual: remote_chain_id, + }); + } + Ok(()) + } + + /// Fetch chain id from the sequencer client + async fn get_sequencer_chain_id(&self) -> eyre::Result { let retry_config = tryhard::RetryFutureConfig::new(u32::MAX) .exponential_backoff(Duration::from_millis(100)) .max_delay(Duration::from_secs(20)) @@ -457,8 +492,8 @@ impl Executor { tryhard::retry_fn(|| self.sequencer_client.genesis()) .with_config(retry_config) .await - .wrap_err("failed to retrieve sequencer genesis after many attempts")?; - Ok(client_genesis.chain_id.to_string()) + .map_err(|_| EnsureChainIdError::FailedToGetGenesis)?; + Ok(client_genesis.chain_id) } } diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index d16ea4bce..50e6bed4b 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -54,6 +54,7 @@ use wiremock::{ use crate::{ executor, + executor::EnsureChainIdError, metrics::Metrics, test_utils::sequence_action_of_max_size, Config, @@ -194,7 +195,7 @@ async fn mount_broadcast_tx_sync_seq_actions_mock(server: &MockServer) -> MockGu .await } -/// Mounts a `CometBFT` status response with a specified mock sequencer chain id +/// Mounts genesis file with specified sequencer chain ID async fn mount_genesis(server: &MockServer, mock_sequencer_chain_id: &str) { Mock::given(body_partial_json( json!({"jsonrpc": "2.0", "method": "genesis", "params": null}), @@ -288,7 +289,6 @@ async fn full_bundle() { let nonce_guard = mount_default_nonce_query_mock(&sequencer).await; let status = executor.subscribe(); - // executor.check_chain_ids().await.unwrap(); let _executor_task = tokio::spawn(executor.run_until_stopped()); // wait for sequencer to get the initial nonce request from sequencer wait_for_startup(status, nonce_guard).await.unwrap(); @@ -380,7 +380,6 @@ async fn bundle_triggered_by_block_timer() { let nonce_guard = mount_default_nonce_query_mock(&sequencer).await; let status = executor.subscribe(); - // executor.check_chain_ids().await.unwrap(); let _executor_task = tokio::spawn(executor.run_until_stopped()); // wait for sequencer to get the initial nonce request from sequencer @@ -540,10 +539,12 @@ async fn two_seq_actions_single_bundle() { } } -/// Test to check that executor's configured sequencer chain id and sequencer's actual chain id -/// match +/// Test to check that executor's chain ID check is properly checked against the sequencer's chain +/// ID #[tokio::test] -async fn should_exit_if_mismatch_sequencer_chain_id() { +async fn chain_id_mismatch_returns_error() { + use tendermint::chain::Id; + // set up sequencer mock let (sequencer, cfg, _keyfile) = setup().await; let shutdown_token = CancellationToken::new(); @@ -567,6 +568,28 @@ async fn should_exit_if_mismatch_sequencer_chain_id() { .build() .unwrap(); - // verify that the executor chain_id check results in an error - assert!(executor.run_until_stopped().await.is_err()); + let err = executor.run_until_stopped().await.expect_err( + "should exit with an error when reading a bad chain ID, but exited with success", + ); + let mut found = false; + for cause in err.chain() { + if let Some(err) = cause.downcast_ref::() { + match err { + EnsureChainIdError::WrongChainId { + expected, + actual, + } => { + assert_eq!(*expected, cfg.sequencer_chain_id); + assert_eq!(*actual, Id::try_from("bad-chain-id".to_string()).unwrap()); + found = true; + break; + } + other => panic!("expected `EnsureChainIdError::WrongChainId`, but got `{other}`"), + } + } + } + assert!( + found, + "expected `EnsureChainIdError::WrongChainId` in error chain, but it was not found" + ); } From f5c9fd454be1dd3a95d5a968b569fcc96011a8c7 Mon Sep 17 00:00:00 2001 From: eoroshiba <57536879+eoroshiba@users.noreply.github.com> Date: Mon, 1 Jul 2024 12:33:09 -0500 Subject: [PATCH 19/23] Suggested change from @SuperFluffy Co-authored-by: Richard Janis Goldschmidt --- crates/astria-composer/src/executor/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/astria-composer/src/executor/mod.rs b/crates/astria-composer/src/executor/mod.rs index 78e88b3ff..dbd48a8b3 100644 --- a/crates/astria-composer/src/executor/mod.rs +++ b/crates/astria-composer/src/executor/mod.rs @@ -42,7 +42,7 @@ use prost::Message as _; use sequencer_client::{ tendermint_rpc::{ endpoint::broadcast::tx_sync, - Client, + Client as _, }, Address, SequencerClientExt as _, From 03d14dcd44a4735ba938216dc8b488e2c074f4e8 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Mon, 1 Jul 2024 13:08:45 -0500 Subject: [PATCH 20/23] Add helper function for asserting chain ID error --- crates/astria-composer/src/executor/tests.rs | 55 +++++++++++++++----- 1 file changed, 41 insertions(+), 14 deletions(-) diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index 50e6bed4b..d9290ef7b 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -118,6 +118,24 @@ async fn setup() -> (MockServer, Config, NamedTempFile) { (server, cfg, keyfile) } +/// Assert that given error is of correct type and contains the expected chain IDs. +fn assert_chain_id_err( + err: &EnsureChainIdError, + configured_expected: &str, + configured_actual: tendermint::chain::Id, +) { + match err { + EnsureChainIdError::WrongChainId { + expected, + actual, + } => { + assert_eq!(*expected, configured_expected); + assert_eq!(*actual, configured_actual); + } + other => panic!("expected `EnsureChainIdError::WrongChainId`, but got `{other}`"), + } +} + /// Mount a mock for the `abci_query` endpoint. async fn mount_default_nonce_query_mock(server: &MockServer) -> MockGuard { let query_path = "accounts/nonce"; @@ -568,26 +586,35 @@ async fn chain_id_mismatch_returns_error() { .build() .unwrap(); - let err = executor.run_until_stopped().await.expect_err( + // ensure that the chain id check function fails + let chain_id_check_err = executor + .ensure_chain_id_is_correct() + .await + .expect_err("executor::ensure_chain_id_is_correct() should return an error"); + assert_chain_id_err( + &chain_id_check_err, + &cfg.sequencer_chain_id, + Id::try_from("bad-chain-id".to_string()).unwrap(), + ); + + // ensure that executor run_until_stopped() will correctly propogate error + let run_err = executor.run_until_stopped().await.expect_err( "should exit with an error when reading a bad chain ID, but exited with success", ); let mut found = false; - for cause in err.chain() { + for cause in run_err.chain() { if let Some(err) = cause.downcast_ref::() { - match err { - EnsureChainIdError::WrongChainId { - expected, - actual, - } => { - assert_eq!(*expected, cfg.sequencer_chain_id); - assert_eq!(*actual, Id::try_from("bad-chain-id".to_string()).unwrap()); - found = true; - break; - } - other => panic!("expected `EnsureChainIdError::WrongChainId`, but got `{other}`"), - } + assert_chain_id_err( + err, + &cfg.sequencer_chain_id, + Id::try_from("bad-chain-id".to_string()).unwrap(), + ); + found = true; + break; } } + + // ensure that the error chain contains the expected error assert!( found, "expected `EnsureChainIdError::WrongChainId` in error chain, but it was not found" From 33ae83d700b25b3ae17bad4d7444bedd2957fd74 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Tue, 2 Jul 2024 11:08:34 -0500 Subject: [PATCH 21/23] minor improvements requested by @superfluffy --- crates/astria-composer/src/executor/mod.rs | 18 +++++++-------- crates/astria-composer/src/executor/tests.rs | 24 ++++++-------------- 2 files changed, 15 insertions(+), 27 deletions(-) diff --git a/crates/astria-composer/src/executor/mod.rs b/crates/astria-composer/src/executor/mod.rs index dbd48a8b3..c0e60240f 100644 --- a/crates/astria-composer/src/executor/mod.rs +++ b/crates/astria-composer/src/executor/mod.rs @@ -101,11 +101,8 @@ const BUNDLE_DRAINING_DURATION: Duration = Duration::from_secs(16); type StdError = dyn std::error::Error; #[derive(Debug, thiserror::Error)] pub(crate) enum EnsureChainIdError { - // - #[error("failed to obtain sequencer chain ID")] - FailedToGetChainId, - #[error("failed to obtain sequencer genesis")] - FailedToGetGenesis, + #[error("failed to obtain sequencer chain ID after multiple retries")] + GetChainId(#[source] sequencer_client::tendermint_rpc::Error), #[error("expected chain ID `{expected}`, but received `{actual}`")] WrongChainId { expected: String, @@ -224,7 +221,7 @@ impl Executor { } res = self.pre_run_checks() => { - res?; + res.wrap_err("required pre-run checks failed")?; } ); let mut submission_fut: Fuse> = Fuse::terminated(); @@ -457,7 +454,7 @@ impl Executor { let remote_chain_id = self .get_sequencer_chain_id() .await - .map_err(|_| EnsureChainIdError::FailedToGetChainId)?; + .map_err(EnsureChainIdError::GetChainId)?; if remote_chain_id.as_str() != self.sequencer_chain_id { return Err(EnsureChainIdError::WrongChainId { expected: self.sequencer_chain_id.clone(), @@ -468,7 +465,9 @@ impl Executor { } /// Fetch chain id from the sequencer client - async fn get_sequencer_chain_id(&self) -> eyre::Result { + async fn get_sequencer_chain_id( + &self, + ) -> Result { let retry_config = tryhard::RetryFutureConfig::new(u32::MAX) .exponential_backoff(Duration::from_millis(100)) .max_delay(Duration::from_secs(20)) @@ -491,8 +490,7 @@ impl Executor { let client_genesis: tendermint::Genesis = tryhard::retry_fn(|| self.sequencer_client.genesis()) .with_config(retry_config) - .await - .map_err(|_| EnsureChainIdError::FailedToGetGenesis)?; + .await?; Ok(client_genesis.chain_id) } } diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index d9290ef7b..d3579341d 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -119,10 +119,11 @@ async fn setup() -> (MockServer, Config, NamedTempFile) { } /// Assert that given error is of correct type and contains the expected chain IDs. +#[track_caller] fn assert_chain_id_err( err: &EnsureChainIdError, configured_expected: &str, - configured_actual: tendermint::chain::Id, + configured_actual: &tendermint::chain::Id, ) { match err { EnsureChainIdError::WrongChainId { @@ -130,7 +131,7 @@ fn assert_chain_id_err( actual, } => { assert_eq!(*expected, configured_expected); - assert_eq!(*actual, configured_actual); + assert_eq!(*actual, *configured_actual); } other => panic!("expected `EnsureChainIdError::WrongChainId`, but got `{other}`"), } @@ -586,28 +587,17 @@ async fn chain_id_mismatch_returns_error() { .build() .unwrap(); - // ensure that the chain id check function fails - let chain_id_check_err = executor - .ensure_chain_id_is_correct() - .await - .expect_err("executor::ensure_chain_id_is_correct() should return an error"); - assert_chain_id_err( - &chain_id_check_err, - &cfg.sequencer_chain_id, - Id::try_from("bad-chain-id".to_string()).unwrap(), - ); - - // ensure that executor run_until_stopped() will correctly propogate error - let run_err = executor.run_until_stopped().await.expect_err( + // ensure that run_until_stopped returns WrongChainId error + let err = executor.run_until_stopped().await.expect_err( "should exit with an error when reading a bad chain ID, but exited with success", ); let mut found = false; - for cause in run_err.chain() { + for cause in err.chain() { if let Some(err) = cause.downcast_ref::() { assert_chain_id_err( err, &cfg.sequencer_chain_id, - Id::try_from("bad-chain-id".to_string()).unwrap(), + &Id::try_from("bad-chain-id".to_string()).unwrap(), ); found = true; break; From 4d2ebb7d90f56abbd35bd7a78dcdc30f6e462e90 Mon Sep 17 00:00:00 2001 From: eoroshiba Date: Tue, 2 Jul 2024 19:15:32 -0500 Subject: [PATCH 22/23] minor update for clippy --- crates/astria-composer/src/executor/tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index d3579341d..4831d4bff 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -133,7 +133,9 @@ fn assert_chain_id_err( assert_eq!(*expected, configured_expected); assert_eq!(*actual, *configured_actual); } - other => panic!("expected `EnsureChainIdError::WrongChainId`, but got `{other}`"), + other @ EnsureChainIdError::GetChainId(_) => { + panic!("expected `EnsureChainIdError::WrongChainId`, but got '{other}'") + } } } From 0a931f552e5730560478d5df6851444f620519be Mon Sep 17 00:00:00 2001 From: eoroshiba <57536879+eoroshiba@users.noreply.github.com> Date: Wed, 3 Jul 2024 08:33:29 -0500 Subject: [PATCH 23/23] @superfluffy suggestion Co-authored-by: Richard Janis Goldschmidt --- crates/astria-composer/src/executor/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/astria-composer/src/executor/tests.rs b/crates/astria-composer/src/executor/tests.rs index 4831d4bff..463cddfd1 100644 --- a/crates/astria-composer/src/executor/tests.rs +++ b/crates/astria-composer/src/executor/tests.rs @@ -134,7 +134,7 @@ fn assert_chain_id_err( assert_eq!(*actual, *configured_actual); } other @ EnsureChainIdError::GetChainId(_) => { - panic!("expected `EnsureChainIdError::WrongChainId`, but got '{other}'") + panic!("expected `EnsureChainIdError::WrongChainId`, but got '{other:?}'") } } }