Skip to content

Conversation

@r0wdy1
Copy link
Collaborator

@r0wdy1 r0wdy1 commented Jun 30, 2025

This PR implements logic for indexing cross chain transactions from zetachain nodes.

  • The indexer synchronizes cctx both from the head (realtime_fetch) and tail (historical sync).
  • It also fetches and stores status updates and relations between crosschain transactions
  • cctxs are served either as a list with short information, paging and filtering or individually with related entities
  • new cctxs imported by realtime fetcher also are broadcasted via websocket to subscribers to /ws/cctxs
  • new status update in regards of a particular transaction are served via websocket to subscribers to /ws/cctxs/{index}
  • synchronization status is stored and can be queried using HTTP request

Summary by CodeRabbit

  • New Features

    • Zetachain CCTX service: gRPC + REST endpoints for CCTX, tokens, health & sync stats; background indexer (realtime/historical/status updates/token sync); WebSocket topics; RPC client and DB integration; TypeScript types package; CLI to check envs.
  • Documentation

    • Service README, OpenAPI/Swagger spec, proto HTTP mappings, example config added.
  • Chores

    • CI workflow, multi-stage Docker images (server & migration), migration toolchain, SQL utilities, helper scripts.
  • Tests

    • Extensive unit & integration tests for indexer, DB, token sync/pagination, APIs, migrations, and token icon syncing.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 30, 2025

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Walkthrough

Adds a new zetachain-cctx workspace with five crates (entity, logic, migration, proto, server). Introduces SeaORM entity models and active enums, 14 migrations and migration tooling, SQL query artifacts, a ZetachainCctxDatabase implementation, and an async Indexer with RPC client. Adds gRPC/protobuf schemas, HTTP mappings and Swagger, Actix+Tonic server wiring, services (health, stats, cctx, token), Channel/WebSocket channel handler, multi-stage Dockerfiles and migration scripts, a TypeScript types package, example config and justfile, many unit/integration tests, and a GitHub Actions CI workflow.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~150 minutes

Possibly related PRs

Poem

I nibble at migrations by moonlight,
I hop through enums and SQL tight.
Streams hum, tokens brighten the trail,
Jobs queue, retries wag their tail.
A little rabbit ships the night 🐇✨

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch zetachain-cctx

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@r0wdy1 r0wdy1 changed the title Zetachain cctx (feat) zetachain cross chain transactions Jul 9, 2025
@r0wdy1 r0wdy1 marked this pull request as ready for review July 23, 2025 08:56
@r0wdy1 r0wdy1 added the feat New feature label Jul 24, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 30

🧹 Nitpick comments (71)
zetachain-cctx/zetachain-cctx-logic/src/lib.rs (1)

1-6: Restrict public surface; consider using pub(crate) or private modules

All six modules are exposed with pub mod …. Unless these modules are intended to be consumed by external crates, keep the API surface minimal by making them mod … (private) or pub(crate) mod ….
This avoids locking you into a public contract too early and leaves freedom to refactor internals without breaking semver.

-pub mod indexer;
-pub mod settings;
-pub mod client;
-pub mod models;
-pub mod database;
-pub mod events;
+pub(crate) mod indexer;
+pub(crate) mod settings;
+pub(crate) mod client;
+pub(crate) mod models;
+pub(crate) mod database;
+pub(crate) mod events;

If external crates really need selective access, re-export only the required items instead of entire modules:

mod indexer;
pub use indexer::{Indexer, SyncProgress}; // exposed types only

This keeps the public API intentional and maintainable.

zetachain-cctx/zetachain-cctx-server/src/check-envs.rs (1)

11-16: Hard-coded paths limit reusability

"README.md" and "config/testnet.toml" are resolved relative to the current working directory.
When the binary is executed from a Docker image or different CWD, these files may not exist, breaking the CLI.

Expose them as optional CLI flags with sensible defaults, or resolve them via crate_dir!() at compile-time:

-        "README.md",
-        "config/testnet.toml",
+        concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"),
+        concat!(env!("CARGO_MANIFEST_DIR"), "/config/testnet.toml"),

This keeps paths valid regardless of runtime location.

zetachain-cctx/types/package.json (1)

9-10: Review the protoc command complexity and TypeScript compilation configuration.

The compile:proto script has a very long protoc command that could be difficult to maintain. Additionally, the compile:ts script uses tsc with only the --declaration flag, which may not produce the expected output structure.

Consider:

  1. Breaking the protoc command into multiple lines for readability
  2. Adding a proper tsconfig.json file instead of inline tsc options
  3. Verifying the output paths match the expected package structure
  "scripts": {
    "build": "npm run compile:proto && npm run compile:ts",
-    "compile:proto": "mkdir -p ./dist && protoc --plugin=./node_modules/.bin/protoc-gen-ts_proto --ts_proto_opt=snakeToCamel=false --ts_proto_opt=exportCommonSymbols=false --ts_proto_opt=stringEnums=true --ts_proto_opt=onlyTypes=true --ts_proto_opt=emitImportedFiles=false --proto_path=../ --proto_path=../../proto/ --ts_proto_out=./dist ../zetachain-cctx-proto/proto/v1/zetachain-cctx.proto",
-    "compile:ts": "tsc --declaration ./dist/zetachain-cctx-proto/proto/v1/zetachain-cctx.ts"
+    "compile:proto": "mkdir -p ./dist && protoc \\\n      --plugin=./node_modules/.bin/protoc-gen-ts_proto \\\n      --ts_proto_opt=snakeToCamel=false \\\n      --ts_proto_opt=exportCommonSymbols=false \\\n      --ts_proto_opt=stringEnums=true \\\n      --ts_proto_opt=onlyTypes=true \\\n      --ts_proto_opt=emitImportedFiles=false \\\n      --proto_path=../ \\\n      --proto_path=../../proto/ \\\n      --ts_proto_out=./dist \\\n      ../zetachain-cctx-proto/proto/v1/zetachain-cctx.proto",
+    "compile:ts": "tsc"
  },

Also add a tsconfig.json:

{
  "compilerOptions": {
    "target": "es2018",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./dist"
  },
  "include": ["./dist/**/*.ts"]
}
zetachain-cctx/zetachain-cctx-logic/Cargo.toml (2)

23-40: Clean up commented dependencies and consider organization.

There are several commented-out dependencies that appear to be unused. Consider removing them to keep the manifest clean, or add a comment explaining if they're planned for future use.

-## Uncomment this if needed
-#ethabi = "18.0"
-#ethers-core = "2.0.0"
 futures = { workspace = true }
-#hex = "0.4"
-#keccak-hash = "0.10.0"
-#lazy_static = "1"
-#mismatch = "1.0"
-#prometheus = "0.13"
 reqwest = { workspace = true }
-#semver = "1.0"
 serde = { workspace = true }
 governor.workspace = true
 serde_json = "1.0"
-#thiserror = "1.0"
 tokio = { workspace = true }
-#tonic = { version = "0.8", features = ["tls-roots"] }
-#tracing-subscriber = { version = "0.3", features = ["env-filter"]}
 base64 = { workspace = true }
 chrono = { workspace = true }
 async-stream = { workspace = true }
 zetachain-cctx-proto = { path = "../zetachain-cctx-proto" }

46-51: Review the dev-dependencies formatting and features.

The blockscout-service-launcher dependency has unusual formatting with empty lines in the features array.

 blockscout-service-launcher = { workspace = true, features = [
-
     "test-database",
     "database-1",
-
 ] }
zetachain-cctx/zetachain-cctx-logic/tests/helpers/mod.rs (1)

40-127: Consider consolidating duplicate test helpers

The dummy_cross_chain_tx function is duplicated across multiple test files with slight variations. Consider creating a shared test utilities module to reduce duplication and improve maintainability.

Would you like me to help create a shared test utilities crate that can be used across all test modules?

zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (1)

142-145: Field names use mixed casing – pick one style

receiver_chainId and lastUpdate_timestamp mix camel- and snake-case.

-  int64 receiver_chainId = 2;
+  int64 receiver_chain_id = 2;

-  int64 lastUpdate_timestamp = 3;
+  int64 last_update_timestamp = 3;

Consistent snake_case improves readability and keeps generated struct fields uniform.

Also applies to: 178-180

zetachain-cctx/zetachain-cctx-entity/Cargo.toml (1)

10-13: Enable serde/derive to avoid downstream surprises

If entity structs derive Serialize/Deserialize, add the feature explicitly:

-serde = { workspace = true }
+serde = { workspace = true, features = ["derive"] }

Prevents “cannot find derive macro” errors when the workspace root disables default features.

zetachain-cctx/js_ws_client/index.js (1)

12-16: Consider re-enabling ping functionality.

The commented ping code could be useful for keeping connections alive and detecting disconnections early.

If you want to keep connections alive, consider re-enabling the ping with proper connection state checks:

setInterval(() => {
    if (connected && ws.readyState === WebSocket.OPEN) {
        ws.send("ping");
    }
}, 30000); // Ping every 30 seconds instead of 1 second
zetachain-cctx/js_ws_client/package.json (1)

1-15: Complete the package metadata & harden scripts

description, author, and repository fields are empty, and the test script is a stub. This makes the package less consumable and CI‐unfriendly.

   "description": "",
+  "repository": {
+    "type": "git",
+    "url": "https://github.com/<org>/zetachain-cctx.git",
+    "directory": "zetachain-cctx/js_ws_client"
+  },
+  "author": "Zetachain Team",
   "main": "index.js",
   "scripts": {
-    "test": "echo \"Error: no test specified\" && exit 1",
+    "test": "node --test",
     "start": "node index.js"
   },

(Adjust URLs/author as appropriate.)
Small change, big payoff for discoverability and automated tooling.

zetachain-cctx/zetachain-cctx-server/src/services/mod.rs (1)

1-5: Export services consistently

Only HealthService is re-exported; cctx, stats, and token must be pub used from callers or referenced by fully-qualified paths, leading to an inconsistent public surface.

-pub mod cctx;
-pub mod stats;
-pub mod token;
-pub use health::HealthService;
+pub mod cctx;
+pub mod stats;
+pub mod token;
+
+pub use {
+    health::HealthService,
+    cctx::CctxService,
+    stats::StatsService,
+    token::TokenInfoService,
+};

Exporting the concrete service types keeps server::services::* ergonomically symmetrical.

zetachain-cctx/Cargo.toml (1)

11-42: Dependency versions are over-pinned

Most workspace deps lock exact patch versions (0.12.3, 0.3.6, …). That freezes the entire workspace to today’s crates-io state and inhibits cargo update security fixes.

Consider using caret ranges except where a known breaking change exists:

-prost = "0.13.5"
+prost = "0.13"

Likewise for sea-orm*, tonic*, etc.
Cargo.lock preserves reproducibility; semver ranges restore flexibility.

tac-operation-lifecycle/docker-compose.yml (2)

25-26: Fix newline & trailing space lint errors

YAMLlint flags both issues. Add a terminating newline and remove the stray space.

 volumes:
   postgres_data:
+

3-13: Consider externalising configuration & adding healthchecks

Hard-coding config/testnet.toml inside the container limits deployment flexibility.
Also, the app service lacks a healthcheck, so orchestrators cannot detect a stuck indexer.

  app:
    image: zetachain-cctx-server:latest
    environment:
      - ZETACHAIN_CCTX__CONFIG=${ZETACHAIN_CCTX_CONFIG:-/etc/cctx/config.toml}
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8050/health"]
      interval: 30s
      timeout: 3s
      retries: 3

Externalised config & a simple HTTP health probe make the stack production-ready.

zetachain-cctx/zetachain-cctx-server/src/main.rs (2)

10-10: Consider more graceful error handling for configuration loading.

Using expect() will cause the application to panic if configuration fails to load. Consider using proper error propagation instead.

-    let settings = Settings::build().expect("failed to read config");
+    let settings = Settings::build()?;

13-16: Simplify Arc wrapping syntax.

The Arc wrapping can be simplified for better readability.

-    let db = Arc::new(
-        db_connection
-    );
+    let db = Arc::new(db_connection);
zetachain-cctx/zetachain-cctx-server/src/services/health.rs (1)

8-18: Consider implementing actual health checks.

The current implementation always returns Serving status without performing any actual health checks. For a production service, you might want to verify database connectivity or other critical dependencies.

 #[async_trait::async_trait]
 impl Health for HealthService {
     async fn check(
         &self,
-        _request: tonic::Request<HealthCheckRequest>,
+        request: tonic::Request<HealthCheckRequest>,
     ) -> Result<tonic::Response<HealthCheckResponse>, tonic::Status> {
+        // TODO: Add actual health checks (database connectivity, etc.)
         Ok(tonic::Response::new(HealthCheckResponse {
             status: health_check_response::ServingStatus::Serving.into(),
         }))
     }
 }
zetachain-cctx/zetachain-cctx-logic/tests/test_filters.rs (3)

13-23: Consider extracting tracing initialization to a helper function.

The tracing initialization logic is repeated across test files and could be extracted to reduce duplication.

Consider adding a helper function in the helpers module:

pub fn init_test_tracing() {
    if std::env::var("TEST_TRACING").unwrap_or_default() == "true" {
        init_logs(
            "tests",
            &blockscout_service_launcher::tracing::TracingSettings {
                enabled: true,
                ..Default::default()
            },
            &blockscout_service_launcher::tracing::JaegerSettings::default(),
        )
        .unwrap();
    }
}

39-50: Consider using Filters::default() with field updates for better maintainability.

The manual filter construction is verbose and error-prone. Consider using the default implementation with specific field updates.

-    let cctxs = database.list_cctxs(10, 0, Filters {
-        status_reduced: vec!["Pending".to_string()],
-        sender_address: vec!["0x1234567890123456789012345678901234567890".to_string()],
-        receiver_address: vec![],
-        asset: vec![],
-        coin_type: vec![],
-        source_chain_id: vec![],
-        target_chain_id: vec![],
-        start_timestamp: None,
-        end_timestamp: None,
-        token_symbol: vec![],
-    }).await.unwrap();
+    let cctxs = database.list_cctxs(10, 0, Filters {
+        status_reduced: vec!["Pending".to_string()],
+        sender_address: vec!["0x1234567890123456789012345678901234567890".to_string()],
+        ..Default::default()
+    }).await.unwrap();

54-65: Apply the same simplification to the second filter usage.

-    let cctxs = database.list_cctxs(10, 0, Filters {
-        status_reduced: vec!["Pending".to_string(),"Success".to_string()],
-        sender_address: vec![],
-        receiver_address: vec![],
-        asset: vec![],
-        coin_type: vec![],
-        source_chain_id: vec![],
-        target_chain_id: vec![],
-        start_timestamp: None,
-        end_timestamp: None,
-        token_symbol: vec![],
-    }).await.unwrap();
+    let cctxs = database.list_cctxs(10, 0, Filters {
+        status_reduced: vec!["Pending".to_string(), "Success".to_string()],
+        ..Default::default()
+    }).await.unwrap();
tac-operation-lifecycle/.env (1)

20-20: Remove unnecessary quotes from empty AUTH_TOKEN.

Empty string values don't need quotes in environment files.

-TAC_OPERATION_LIFECYCLE__RPC__AUTH_TOKEN=""
+TAC_OPERATION_LIFECYCLE__RPC__AUTH_TOKEN=
zetachain-cctx/zetachain-cctx-proto/proto/v1/api_config_http.yaml (1)

1-27: Clean up YAML formatting issues.

The API configuration structure is correct, but there are several formatting issues that should be addressed.

 http:
   rules:
-    
+
     - selector: blockscout.zetachainCctx.v1.CctxInfo.GetCctxInfo
       get: /api/v1/CctxInfo:get
-    
+
     - selector: blockscout.zetachainCctx.v1.CctxInfo.ListCctxs
       get: /api/v1/CctxInfo:list
-    
+
     #################### Health ####################

     - selector: blockscout.zetachainCctx.v1.Health.Check
       get: /health

     #################### Stats ####################

     - selector: blockscout.zetachainCctx.v1.Stats.GetSyncProgress
-      get: /api/v1/Stats:getSyncProgress  
+      get: /api/v1/Stats:getSyncProgress

     #################### Token Info ####################

     - selector: blockscout.zetachainCctx.v1.TokenInfo.GetTokenInfo
       get: /api/v1/TokenInfo:get
-
zetachain-cctx/zetachain-cctx-server/src/services/stats.rs (1)

3-6: Remove empty import and clean up imports.

There's an incomplete import statement that should be removed.

Apply this diff to clean up the imports:

-use crate::proto::{
-    stats_server::Stats,
-   
-};
+use crate::proto::stats_server::Stats;
zetachain-cctx/zetachain-cctx-migration/src/lib.rs (1)

3-6: Consider using actual timestamps in migration names.

The migration files use placeholder timestamps (20220101) rather than actual creation dates. While functional, using actual timestamps improves traceability and helps understand the migration chronology.

Consider renaming migrations to reflect their actual creation dates for better maintainability and historical tracking.

zetachain-cctx/zetachain-cctx-logic/tests/batch_insert.rs (2)

6-6: Rename constant to reflect its actual purpose.

The constant name BAD_CCTX is misleading since it contains valid test data, not malformed data.

-const BAD_CCTX: &str = r#"
+const TEST_CCTX_WITH_OUTBOUND_PARAMS: &str = r#"

99-136: Test logic is correct but could benefit from better organization.

The test properly verifies batch insertion and relationship integrity. However, consider organizing imports at the top of the function and adding consistent formatting.

Move the imports to the top of the test function and add consistent spacing:

 #[tokio::test]
 async fn test_batch_insert(){
-
-use migration::sea_orm::{EntityTrait, QueryFilter,ColumnTrait};
-use zetachain_cctx_entity::{cross_chain_tx,outbound_params};
-
- let response: PagedCCTXResponse = serde_json::from_str(BAD_CCTX).expect("Failed to parse JSON");
+    use migration::sea_orm::{EntityTrait, QueryFilter, ColumnTrait};
+    use zetachain_cctx_entity::{cross_chain_tx, outbound_params};
+
+    let response: PagedCCTXResponse = serde_json::from_str(TEST_CCTX_WITH_OUTBOUND_PARAMS).expect("Failed to parse JSON");
zetachain-cctx/zetachain-cctx-entity/src/token.rs (1)

14-14: Consider using appropriate numeric type for foreign_chain_id.

Using String for foreign_chain_id may impact query performance and type safety. Consider using a numeric type if chain IDs are always numeric.

Based on the retrieved learning about chain_id type changes being deferred to maintain focus, this optimization could be addressed in a future PR if needed.

zetachain-cctx/config/example.toml (1)

18-29: Validate indexer configuration values for production readiness.

Some configuration values may need adjustment for production environments:

  • historical_batch_size = 1 is very conservative and might be too slow
  • realtime_threshold = 10000 (10s) might be too long for real-time use cases
  • restart_interval = 1000 (1s) might be too aggressive for restart attempts

Consider documenting the rationale for these values or providing production-oriented alternatives in comments.

zetachain-cctx/zetachain-cctx-proto/proto/v1/stats.proto (1)

16-21: Add field documentation and consider field types.

The response fields lack documentation, and all numeric fields use int64 which may be unnecessarily large for some counts.

Consider adding documentation and reviewing field types:

 message GetSyncProgressResponse {
-  int64 historic_watermark_timestamp = 1;
-  int64 pending_status_updates_count = 2;
-  int64 pending_cctxs_count = 3;
-  int64 realtime_gaps_count = 4;
+  // Timestamp of the historic watermark in Unix seconds
+  int64 historic_watermark_timestamp = 1;
+  // Number of pending status updates
+  int32 pending_status_updates_count = 2;
+  // Number of pending cross-chain transactions
+  int32 pending_cctxs_count = 3;
+  // Number of realtime gaps detected
+  int32 realtime_gaps_count = 4;
zetachain-cctx/justfile (1)

29-30: Improve test database cleanup and error handling.

The test-with-db command uses - prefix to ignore errors but doesn't ensure proper cleanup on failure.

Consider adding explicit cleanup:

 test-with-db *args:
-    -just db-port="{{test-db-port}}" db-name="" docker-name="{{docker-name}}-test" start-postgres
-    just db-port="{{test-db-port}}" db-name=""                                    test {{args}}
+    -just db-port="{{test-db-port}}" db-name="" docker-name="{{docker-name}}-test" start-postgres
+    just db-port="{{test-db-port}}" db-name="" test {{args}}; \
+    just docker-name="{{docker-name}}-test" stop-postgres
zetachain-cctx/zetachain-cctx-entity/src/watermark.rs (1)

22-23: Consider adding documentation for the empty Relation enum.

While no relationships are currently defined, adding a comment explaining why would be helpful for future maintainers.

 #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
-pub enum Relation {}
+pub enum Relation {
+    // No foreign key relationships defined for watermark table
+}
zetachain-cctx/README.md (1)

1-86: Address markdown formatting issues for better readability.

The static analysis tool identified several markdown formatting inconsistencies that should be addressed for better documentation quality.

Key issues to fix:

  • Use consistent heading styles (setext vs atx)
  • Fix unordered list indentation (use 2 spaces instead of 4)
  • Remove trailing punctuation from headings
  • Fix spacing in emphasis markers
  • Remove unused anchor references

Consider running a markdown formatter to automatically fix these issues.

zetachain-cctx/Dockerfile.local (1)

18-22: Consider making the protoc-gen-openapiv2 version configurable.

The version v2.16.2 is hard-coded. Consider using a build argument to make this configurable for easier maintenance and updates.

+ARG PROTOC_GEN_OPENAPIV2_VERSION=v2.16.2
 # Install protoc-gen-openapiv2 plugin from grpc-gateway (using compatible version)
-RUN go install github.com/grpc-ecosystem/grpc-gateway/v2/[email protected]
+RUN go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2@${PROTOC_GEN_OPENAPIV2_VERSION}
zetachain-cctx/zetachain-cctx-logic/src/settings.rs (1)

37-49: Consider adding documentation for time units and value ranges.

Some configuration values use different time units (milliseconds vs. raw numbers) and have very large defaults (e.g., failed_cctxs_polling_interval: 1_000_000 = ~16.7 minutes). Consider adding documentation comments to clarify:

  1. Time units for each interval field
  2. Reasonable ranges for batch sizes and thresholds
  3. The rationale for large default intervals
+/// Configuration for the CCTX indexer
 #[derive(Debug, Clone, Deserialize, PartialEq, Eq, Serialize)]
 #[serde(deny_unknown_fields)]
 pub struct IndexerSettings {
+   /// Enable/disable the indexer
    pub enabled: bool,
+   /// Number of concurrent processing tasks
    pub concurrency: u32,
+   /// Historical sync polling interval (milliseconds)
    pub polling_interval: u64,
+   /// Realtime polling interval (milliseconds)
    pub realtime_polling_interval: u64,
    // ... add similar docs for other fields
zetachain-cctx/docker-compose.yaml (1)

52-52: Fix formatting issues flagged by static analysis.

The file has trailing spaces and is missing a newline at the end.

  caddy_net:
-    driver: bridge  
+    driver: bridge
+
zetachain-cctx/zetachain-cctx-proto/build.rs (1)

49-53: Consider dynamic proto file discovery.

The proto files are hardcoded in the compile call. For better maintainability, consider dynamically discovering proto files from the proto directory.

+    let proto_files: Vec<_> = std::fs::read_dir("proto/v1")?
+        .filter_map(|entry| entry.ok())
+        .filter(|entry| {
+            entry.path().extension()
+                .and_then(|ext| ext.to_str())
+                .map(|ext| ext == "proto")
+                .unwrap_or(false)
+        })
+        .map(|entry| entry.path())
+        .collect();
+
     compile(
-        &["proto/v1/zetachain-cctx.proto", "proto/v1/health.proto", "proto/v1/stats.proto"],
+        &proto_files,
         &["proto"],
         gens,
     )?;
zetachain-cctx/zetachain-cctx-server/src/settings.rs (1)

36-50: Simplify WebSocketSettings default implementation.

The default_websocket_enabled() and default_websocket_settings() functions are redundant. You can simplify this by using serde's built-in default handling.

 #[derive(Debug, Clone, Deserialize, PartialEq, Eq, Serialize)]
 #[serde(deny_unknown_fields)]
 pub struct WebSocketSettings {
-    #[serde(default = "default_websocket_enabled")]
+    #[serde(default)]
     pub enabled: bool,
 }

 impl Default for WebSocketSettings {
     fn default() -> Self {
         Self {
-            enabled: default_websocket_enabled(),
+            enabled: true,
         }
     }
 }

-fn default_websocket_enabled() -> bool {
-    true
-}
-
-fn default_websocket_settings() -> WebSocketSettings {
-    WebSocketSettings::default()
-}

And update the Settings struct:

-    #[serde(default = "default_websocket_settings")]
+    #[serde(default)]
     pub websocket: WebSocketSettings,
zetachain-cctx/zetachain-cctx-entity/src/inbound_params.rs (1)

16-26: Consider the use of String types for numeric fields.

Fields like sender_chain_id, amount, observed_external_height, ballot_index, and finalized_zeta_height are using String types. While this may be intentional for handling large numbers or maintaining compatibility with external APIs, consider documenting why these numeric values are stored as strings.

zetachain-cctx/zetachain-cctx-logic/tests/historical_sync.rs (3)

78-78: Remove duplicate comment.

This comment is a duplicate of the one at line 67.

-    // Mock third page response when pagination.key == "THIRD_PAGE"
+    // Mock end response when pagination.key == "end"

27-246: Consider breaking down this test into smaller, more focused tests.

This test function is quite long (200+ lines) and tests multiple aspects of historical synchronization. Consider splitting it into smaller, more focused test functions for better maintainability and clarity.

For example:

  • test_historical_sync_pagination - Test pagination handling
  • test_historical_sync_entity_creation - Test entity creation and relationships
  • test_historical_sync_watermark_update - Test watermark updates

This would make the tests easier to understand and maintain.


139-139: Add semicolon for consistency.

While Rust allows omitting the semicolon for the last expression, adding it improves consistency.

-    let broadcaster = Arc::new(NoOpBroadcaster{})
+    let broadcaster = Arc::new(NoOpBroadcaster{});
zetachain-cctx/zetachain-cctx-server/tests/token_api.rs (2)

1-13: Clean up duplicate imports and remove extra semicolon.

The imports section has some organization issues that should be cleaned up.

-use zetachain_cctx_proto::blockscout::zetachain_cctx::v1::TokenInfoResponse
-;
+use zetachain_cctx_proto::blockscout::zetachain_cctx::v1::TokenInfoResponse;

-use sea_orm::{PaginatorTrait,QueryFilter, ColumnTrait};

The imports from sea_orm on line 13 are already included in line 6, so this line can be removed entirely.


62-67: Remove unnecessary empty lines.

     // Test successful token retrieval
-    
-
     let token_info: TokenInfoResponse = test_server::send_get_request(&server, &format!("/api/v1/TokenInfo:get?asset={}", asset)).await;
-    
-
zetachain-cctx/zetachain-cctx-logic/tests/level_data_gap.rs (2)

32-40: Consider using entity models instead of raw SQL for test data setup.

While raw SQL works for test setup, using the entity models would be more maintainable and type-safe. The hardcoded timestamps could also make tests brittle.

Example using entity models:

// Instead of raw SQL, consider:
let cross_chain_tx = cross_chain_tx::ActiveModel {
    creator: ActiveValue::Set("zeta18pksjzclks34qkqyaahf2rakss80mnusju77cm".to_string()),
    index: ActiveValue::Set("0x7f70bf83ed66c8029d8b2fce9ca95a81d053243537d0ea694de5a9c8e7d42f31".to_string()),
    // ... other fields
};
cross_chain_tx::Entity::insert(cross_chain_tx).exec(db.client().as_ref()).await.unwrap();

201-201: Add newline at end of file.

     assert_eq!(cctx_count, 7);
 }
+
zetachain-cctx/zetachain-cctx-entity/src/cross_chain_tx.rs (1)

81-81: Add newline at end of file.

 impl ActiveModelBehavior for ActiveModel {}
+
zetachain-cctx/zetachain-cctx-logic/tests/token_sync.rs (2)

266-351: Consider extracting mock setup to reduce duplication.

The mock setup for token pagination endpoints could be extracted to a helper function to improve readability and reduce duplication across tests.

Example helper:

async fn setup_token_pagination_mocks(mock_server: &MockServer, pages: Vec<TokenPageData>) {
    for (index, page_data) in pages.iter().enumerate() {
        let mut mock = Mock::given(method("GET"))
            .and(path("/fungible/foreign_coins"))
            .and(query_param("pagination.limit", "100"));
        
        if let Some(key) = &page_data.pagination_key {
            mock = mock.and(query_param("pagination.key", key));
        }
        
        mock.respond_with(ResponseTemplate::new(200).set_body_json(
            dummy_token_response(&page_data.tokens, page_data.next_key.as_deref())
        ))
        .mount(mock_server)
        .await;
    }
}

442-442: Add newline at end of file.

     assert_eq!(page3_token.name, "Page 3 Token 1");
 }
+
zetachain-cctx/zetachain-cctx-server/tests/list_cctxs_test.rs (3)

31-37: Remove unnecessary empty lines in the iterator chain.

The iterator chain has unnecessary empty lines that break the flow.

    let dummy_cctxs: Vec<CrossChainTx> = vec!["test_list_cctxs_endpoint_1"]
        .iter()
-        .map(|x| 
-            crate::helpers::dummy_cross_chain_tx(x, "PendingOutbound")
-        )
-        
+        .map(|x| crate::helpers::dummy_cross_chain_tx(x, "PendingOutbound"))
        .collect();

85-95: Improve iterator chain formatting for better readability.

The iterator chain has inconsistent indentation and could be more readable.

    let dummy_cctxs: Vec<CrossChainTx> = vec!["test_list_cctxs_with_status_filter_1", "test_list_cctxs_with_status_filter_2"]
-    .iter()
-    .map(|x| 
-        crate::helpers::dummy_cross_chain_tx(x, "OutboundMined")
-    )
-    .chain(vec!["test_list_cctxs_with_status_filter_3", "test_list_cctxs_with_status_filter_4", "test_list_cctxs_with_status_filter_5"]
-    .iter()
-    .map(|x| 
-        crate::helpers::dummy_cross_chain_tx(x, "PendingOutbound")
-    ))
-    .collect();
+        .iter()
+        .map(|x| crate::helpers::dummy_cross_chain_tx(x, "OutboundMined"))
+        .chain(
+            vec!["test_list_cctxs_with_status_filter_3", "test_list_cctxs_with_status_filter_4", "test_list_cctxs_with_status_filter_5"]
+                .iter()
+                .map(|x| crate::helpers::dummy_cross_chain_tx(x, "PendingOutbound"))
+        )
+        .collect();

161-161: Fix typo in comment.

-    //if TEST_TRACING is true, then initi
+    //if TEST_TRACING is true, then init
zetachain-cctx/zetachain-cctx-server/src/services/cctx.rs (2)

47-56: Consider logging parse failures for better debugging.

Multiple numeric fields use parse().unwrap_or(0) which silently converts parse failures to 0. This could hide data quality issues.

Consider adding debug logging when parse fails:

sender_chain_id: entity.inbound.sender_chain_id.parse()
    .unwrap_or_else(|e| {
        tracing::debug!("Failed to parse sender_chain_id '{}': {}", entity.inbound.sender_chain_id, e);
        0
    }),

213-221: Use pattern matching for cleaner code.

-        if complete_cctx.is_none() {
-            return Err(Status::not_found("CCTX not found"));
-        }
-
-        let entity = complete_cctx.unwrap();
-
-        let cctx =
-            transform_complete_cctx_to_cross_chain_tx(entity).map_err(|e| Status::internal(e))?;
+        let entity = complete_cctx
+            .ok_or_else(|| Status::not_found("CCTX not found"))?;
+
+        let cctx =
+            transform_complete_cctx_to_cross_chain_tx(entity).map_err(|e| Status::internal(e))?;
zetachain-cctx/zetachain-cctx-entity/src/sea_orm_active_enums.rs (1)

38-41: Consider standardizing enum string value casing across the schema.

The enum string values use inconsistent casing conventions - ConfirmationMode and InboundStatus use uppercase while other enums use PascalCase. Since this is a generated file, consider updating the database schema or code generation configuration to use a consistent casing convention across all enums.

Also applies to: 46-53

zetachain-cctx/zetachain-cctx-server/tests/indexer_tests.rs (2)

135-135: Add space before struct initialization braces for consistency.

-        Arc::new(NoOpBroadcaster{}),
+        Arc::new(NoOpBroadcaster {}),

Also applies to: 291-291


451-453: Remove unnecessary empty lines.

These empty lines don't add clarity and can be removed for more compact code.

Also applies to: 502-503, 507-508

zetachain-cctx/zetachain-cctx-server/src/websocket.rs (3)

95-97: Reduce excessive logging in production code.

Multiple consecutive log statements for a single subscription action can impact performance and clutter logs.

 SubscriptionType::NewCctxs => {
     self.new_cctx_subscribers.push(msg.client_id);
-    tracing::info!("New CCTX subscriber: {:?} added to new_cctx_subscribers", msg.client_id);
-    tracing::info!("new_cctx_subscribers: {:?}", self.new_cctx_subscribers);
+    tracing::debug!("New CCTX subscriber added: {}", msg.client_id);
 }

152-165: Reduce verbose logging in broadcast handler.

The broadcast handler has excessive logging that exposes internal state and could impact performance under load.

 WebSocketEvent::NewCctxImported { cctxs } => {
-    tracing::info!("Broadcasting new CCTX imports: {:?}", cctxs.iter().map(|cctx| cctx.index.clone()).collect::<Vec<String>>());
+    tracing::debug!("Broadcasting {} new CCTX imports", cctxs.len());
     for &client_id in &self.new_cctx_subscribers {
-        tracing::info!("Searching for client: {:?}", client_id);
         if let Some((_, recipient)) = self.clients.get(&client_id) {
-            tracing::info!("Found client: {:?}", client_id);
             let _ = recipient.try_send(WebSocketMessage {
                 content: event_json.clone(),
             });
-        } else {
-            tracing::info!("Client not found: {:?}", client_id);
         }
     }
-    tracing::debug!("Broadcasted new CCTX imports {:?} to {} subscribers", cctxs.iter().map(|cctx| cctx.index.clone()).collect::<Vec<String>>(), self.new_cctx_subscribers.len());
+    tracing::debug!("Broadcasted to {} subscribers", self.new_cctx_subscribers.len());
 }

238-256: Remove redundant unused methods.

These methods duplicate the functionality already provided by the EventBroadcaster trait implementation below. Having both creates confusion about which API to use.

Remove these redundant methods since the EventBroadcaster trait implementation provides the same functionality and is the one actually used by the indexer.

zetachain-cctx/zetachain-cctx-logic/src/indexer.rs (2)

45-47: Simplify error handling by using anyhow's context methods.

The current error handling pattern with nested map_err and format! can be simplified.

-    let fetched_cctx = client.fetch_cctx(&cctx.index).await.map_err(|e| anyhow::anyhow!(format!("Failed to fetch cctx: {}", e)))?;
-    database.update_cctx_status(cctx.id, fetched_cctx).await.map_err(|e| anyhow::anyhow!(format!("Failed to update cctx status: {}", e)))?;
+    let fetched_cctx = client.fetch_cctx(&cctx.index).await
+        .context("Failed to fetch cctx")?;
+    database.update_cctx_status(cctx.id, fetched_cctx).await
+        .context("Failed to update cctx status")?;

Apply similar changes to lines 120-121, 136, and 146.

Also applies to: 120-121, 136-136, 146-146


184-186: Move helper function to improve code organization.

The prio_left helper function interrupts the flow of the main implementation. Consider moving it to where it's used or to the top of the file with other utility functions.

Move this function inside the run method where it's used, as a closure:

-fn prio_left(_: &mut ()) -> PollNext {
-    PollNext::Left
-}

 pub async fn run(&self) -> anyhow::Result<()> {
     // ... existing code ...
+    let prio_left = |_: &mut ()| PollNext::Left;
     let combined_stream = select_with_strategy(historical_stream, failed_cctx_stream, prio_left);
zetachain-cctx/zetachain-cctx-logic/src/models.rs (1)

20-44: Inconsistent casing between enum variant and string representation.

The enum variant is named ERC20 (all caps) while the string match uses "Erc20" (mixed case). This inconsistency could lead to confusion. Consider aligning the naming convention.

Either rename the enum variant to match the string representation:

 pub enum CoinType {
     Zeta,
     Gas,
-    ERC20,
+    Erc20,
     Cmd,
     NoAssetCall,
 }

Or update all string representations to use consistent casing throughout the codebase.

zetachain-cctx/zetachain-cctx-logic/src/database.rs (5)

274-349: Consider wrapping initialization operations in a transaction.

The setup operations modify multiple tables (watermarks and cross_chain_tx). While each operation is unlikely to fail, wrapping them in a transaction would ensure atomicity and prevent partial initialization states.

 pub async fn setup_db(&self) -> anyhow::Result<()> {
     tracing::debug!("checking if historical watermark exists");
+    let tx = self.db.begin().await?;
 
     //insert historical watermarks if there are no watermarks for historical type
     let historical_watermark = watermark::Entity::find()
         .filter(watermark::Column::Kind.eq(Kind::Historical))
-        .one(self.db.as_ref())
+        .one(&tx)
         .await?;

Then commit the transaction at the end of the function.


544-903: Consider breaking down this large function into smaller, focused helper functions.

This 359-line function handles multiple responsibilities. Breaking it into smaller functions would improve maintainability and testability.

Consider extracting helper functions like:

  • prepare_cctx_models(cctxs: &Vec<CrossChainTx>, job_id: Uuid) -> Result<Vec<ActiveModel>>
  • prepare_status_models(cctx_id: i32, status: &CctxStatus) -> Result<ActiveModel>
  • prepare_inbound_models(cctx_id: i32, inbound: &InboundParams) -> Result<ActiveModel>
  • insert_child_entities(models: ChildModels, tx: &DatabaseTransaction) -> Result<()>

This would make the main function more readable and each helper function independently testable.


1478-1535: Consider using named columns or a query builder to avoid fragile positional indices.

The current implementation uses positional indices (0-45) which is error-prone and difficult to maintain. Any change to the SELECT statement requires updating all index positions.

Consider using SeaORM's query builder with proper joins, or at minimum, create constants for the column positions:

const CCTX_ID_POS: usize = 0;
const CCTX_CREATOR_POS: usize = 1;
// ... etc

Or better yet, use SeaORM's find() with proper relations to avoid raw SQL entirely.


1931-2191: Ensure proper database indices exist for query performance.

The list_cctxs query performs complex joins and filters. Ensure indices exist on:

  • cross_chain_tx.id (likely primary key)
  • cctx_status.cross_chain_tx_id
  • inbound_params.cross_chain_tx_id
  • outbound_params.cross_chain_tx_id
  • cctx_status.created_timestamp (for ordering)
  • Any columns used in WHERE clauses

1-2246: Consider splitting this large file into smaller, focused modules.

At 2246 lines, this file is quite large and handles many different aspects of database operations. Consider organizing it into modules like:

  • watermark.rs - watermark-related operations
  • cctx_import.rs - CCTX import and batch operations
  • cctx_query.rs - CCTX querying and filtering
  • cctx_status.rs - status update operations
  • token.rs - token synchronization

This would improve maintainability and make the codebase easier to navigate.

zetachain-cctx/zetachain-cctx-server/tests/helpers/mod.rs (4)

14-17: Remove misleading comment.

The comment mentions "Initialize tracing for all tests that use this helper" but this function only handles database initialization, not tracing.

-    // Initialize tracing for all tests that use this helper
     let db_name = format!("{db_prefix}_{test_name}");

21-31: Consider improving error handling and preventing double initialization.

The function uses unwrap() which could provide unhelpful error messages in tests. Additionally, multiple calls to this function might cause tracing initialization conflicts.

Consider this improvement:

 pub async fn init_tests_logs() {
+    static TRACING_INIT: std::sync::Once = std::sync::Once::new();
+    TRACING_INIT.call_once(|| {
         blockscout_service_launcher::tracing::init_logs(
             "tests",
             &blockscout_service_launcher::tracing::TracingSettings {
                 enabled: true,
                 ..Default::default()
             },
             &blockscout_service_launcher::tracing::JaegerSettings::default(),
         )
-        .unwrap();
+        .expect("Failed to initialize tracing for tests");
+    });
 }

44-44: Remove commented code.

The commented init_tracing() call should be removed if it's not needed, or uncommented with proper explanation if it is.

-    // init_tracing();

62-149: Comprehensive test data generator - consider modularity.

The function creates realistic and comprehensive test data. Consider breaking it into smaller helper functions if it grows further, but the current implementation serves its testing purpose well.

If this function grows more complex, consider extracting helper functions like:

  • dummy_cctx_status(status: &str) -> CctxStatus
  • dummy_inbound_params(index: &str) -> InboundParams
  • dummy_outbound_params(index: &str, suffix: &str) -> OutboundParams
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 332a892 and 79f6ec0.

⛔ Files ignored due to path filters (2)
  • zetachain-cctx/Cargo.lock is excluded by !**/*.lock
  • zetachain-cctx/js_ws_client/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (79)
  • tac-operation-lifecycle/.env (1 hunks)
  • tac-operation-lifecycle/docker-compose.yml (1 hunks)
  • tac-operation-lifecycle/tac-operation-lifecycle-server/.config.env (1 hunks)
  • tac-operation-lifecycle/tac-operation-lifecycle-server/.env (1 hunks)
  • zetachain-cctx/.github/workflows/zetachain-cctx.yml (1 hunks)
  • zetachain-cctx/Cargo.toml (1 hunks)
  • zetachain-cctx/Dockerfile (1 hunks)
  • zetachain-cctx/Dockerfile.local (1 hunks)
  • zetachain-cctx/README.md (1 hunks)
  • zetachain-cctx/config/example.toml (1 hunks)
  • zetachain-cctx/docker-compose.yaml (1 hunks)
  • zetachain-cctx/js_ws_client/index.js (1 hunks)
  • zetachain-cctx/js_ws_client/package.json (1 hunks)
  • zetachain-cctx/justfile (1 hunks)
  • zetachain-cctx/types/.gitignore (1 hunks)
  • zetachain-cctx/types/.npmignore (1 hunks)
  • zetachain-cctx/types/package.json (1 hunks)
  • zetachain-cctx/zetachain-cctx-entity/Cargo.toml (1 hunks)
  • zetachain-cctx/zetachain-cctx-entity/src/cctx_status.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-entity/src/cross_chain_tx.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-entity/src/enum_conversions.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-entity/src/inbound_params.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-entity/src/lib.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-entity/src/outbound_params.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-entity/src/prelude.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-entity/src/revert_options.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-entity/src/sea_orm_active_enums.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-entity/src/token.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-entity/src/watermark.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/Cargo.toml (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/client.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/database.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/events.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/indexer.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/lib.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/models.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/settings.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/batch_insert.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/helpers/mod.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/historical_sync.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/level_data_gap.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/mod.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/test_filters.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/token_sync.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/traverse_tree.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-migration/Cargo.toml (1 hunks)
  • zetachain-cctx/zetachain-cctx-migration/src/lib.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-migration/src/m20220101_000001_create_table.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-migration/src/m20220101_000002_add_foreign_key_indexes.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-migration/src/m20220101_000003_create_token_table.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-migration/src/m20220101_000004_add_inbound_params_composite_unique.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-migration/src/main.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/Cargo.toml (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/build.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/proto/v1/api_config_http.yaml (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/proto/v1/health.proto (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/proto/v1/stats.proto (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/src/lib.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/Cargo.toml (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/check-envs.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/lib.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/main.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/proto.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/server.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/services/cctx.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/services/health.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/services/mod.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/services/stats.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/services/token.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/settings.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/websocket.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/tests/helpers/mod.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/tests/indexer_tests.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/tests/list_cctxs_test.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/tests/mod.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/tests/startup_works.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/tests/token_api.rs (1 hunks)
🧰 Additional context used
🧠 Learnings (35)
📓 Common learnings
Learnt from: rimrakhimov
PR: blockscout/blockscout-rs#1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.
Learnt from: bragov4ik
PR: blockscout/blockscout-rs#1226
File: stats/stats-server/src/update_service.rs:110-119
Timestamp: 2025-02-04T10:10:46.118Z
Learning: Graceful shutdown mechanisms for services in blockscout-rs are being implemented in dedicated PRs (#1128, #1129) using TaskTracker, JoinSet, and CancellationToken, rather than being handled individually in each service.
zetachain-cctx/zetachain-cctx-server/src/proto.rs (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/Cargo.toml (1)

Learnt from: bragov4ik
PR: #1137
File: stats/stats/Cargo.toml:17-17
Timestamp: 2024-12-10T16:24:23.028Z
Learning: When a dependency like trait-variant is correctly defined under [workspace.dependencies] in the root Cargo.toml, it should not be flagged as improperly defined in workspace crates.

zetachain-cctx/zetachain-cctx-server/tests/startup_works.rs (2)

Learnt from: bragov4ik
PR: #1226
File: stats/stats-server/tests/it/mock_blockscout_simple/stats_full.rs:0-0
Timestamp: 2025-02-04T10:08:27.299Z
Learning: In stats-server tests, waiting for server initialization requires not just checking server health but also ensuring all chart values have been calculated and initialized.

Learnt from: bragov4ik
PR: #1226
File: stats/stats-server/src/update_service.rs:110-119
Timestamp: 2025-02-04T10:10:46.118Z
Learning: Graceful shutdown mechanisms for services in blockscout-rs are being implemented in dedicated PRs (#1128, #1129) using TaskTracker, JoinSet, and CancellationToken, rather than being handled individually in each service.

zetachain-cctx/zetachain-cctx-logic/tests/batch_insert.rs (3)

Learnt from: bragov4ik
PR: #1147
File: stats/stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs:76-98
Timestamp: 2024-12-11T15:25:33.248Z
Learning: In the ClearAllAndPassStep::batch_update_values_step_with function in stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs, it's acceptable to perform the clear and insert operations separately without wrapping them in a transaction, as inconsistency is acceptable in this context, and the insert step is very unlikely to fail unless the service is down.

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

zetachain-cctx/zetachain-cctx-server/src/services/health.rs (1)

Learnt from: bragov4ik
PR: #1226
File: stats/stats-server/src/update_service.rs:110-119
Timestamp: 2025-02-04T10:10:46.118Z
Learning: Graceful shutdown mechanisms for services in blockscout-rs are being implemented in dedicated PRs (#1128, #1129) using TaskTracker, JoinSet, and CancellationToken, rather than being handled individually in each service.

zetachain-cctx/zetachain-cctx-logic/tests/test_filters.rs (1)

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

zetachain-cctx/zetachain-cctx-entity/src/token.rs (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/zetachain-cctx-server/src/services/stats.rs (2)

Learnt from: bragov4ik
PR: #1226
File: stats/stats-server/src/update_service.rs:110-119
Timestamp: 2025-02-04T10:10:46.118Z
Learning: Graceful shutdown mechanisms for services in blockscout-rs are being implemented in dedicated PRs (#1128, #1129) using TaskTracker, JoinSet, and CancellationToken, rather than being handled individually in each service.

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

zetachain-cctx/zetachain-cctx-entity/src/revert_options.rs (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/zetachain-cctx-migration/src/m20220101_000004_add_inbound_params_composite_unique.rs (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/zetachain-cctx-migration/src/m20220101_000002_add_foreign_key_indexes.rs (2)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

zetachain-cctx/zetachain-cctx-logic/Cargo.toml (1)

Learnt from: bragov4ik
PR: #1137
File: stats/stats/Cargo.toml:17-17
Timestamp: 2024-12-10T16:24:23.028Z
Learning: When a dependency like trait-variant is correctly defined under [workspace.dependencies] in the root Cargo.toml, it should not be flagged as improperly defined in workspace crates.

zetachain-cctx/zetachain-cctx-entity/src/cctx_status.rs (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/zetachain-cctx-migration/src/m20220101_000003_create_token_table.rs (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/zetachain-cctx-server/src/services/token.rs (1)

Learnt from: bragov4ik
PR: #1226
File: stats/stats-server/src/update_service.rs:110-119
Timestamp: 2025-02-04T10:10:46.118Z
Learning: Graceful shutdown mechanisms for services in blockscout-rs are being implemented in dedicated PRs (#1128, #1129) using TaskTracker, JoinSet, and CancellationToken, rather than being handled individually in each service.

zetachain-cctx/zetachain-cctx-logic/tests/historical_sync.rs (2)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: bragov4ik
PR: #1147
File: stats/stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs:76-98
Timestamp: 2024-12-11T15:25:33.248Z
Learning: In the ClearAllAndPassStep::batch_update_values_step_with function in stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs, it's acceptable to perform the clear and insert operations separately without wrapping them in a transaction, as inconsistency is acceptable in this context, and the insert step is very unlikely to fail unless the service is down.

zetachain-cctx/zetachain-cctx-logic/tests/level_data_gap.rs (5)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: bragov4ik
PR: #1147
File: stats/stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs:76-98
Timestamp: 2024-12-11T15:25:33.248Z
Learning: In the ClearAllAndPassStep::batch_update_values_step_with function in stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs, it's acceptable to perform the clear and insert operations separately without wrapping them in a transaction, as inconsistency is acceptable in this context, and the insert step is very unlikely to fail unless the service is down.

Learnt from: bragov4ik
PR: #1191
File: stats/stats/src/charts/counters/total_operational_txns.rs:77-78
Timestamp: 2025-01-16T13:06:57.738Z
Learning: In stats/stats/src/charts/counters/total_operational_txns.rs, the test value "44" for total operational transactions is calculated as 57 (total transactions) minus 13 (total blocks).

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:98-108
Timestamp: 2025-01-22T09:57:55.036Z
Learning: In eth-bytecode-db's alliance_db.rs, when determining if a contract match is "full" via extract_match_type, only the creation metadata match is considered, even for complete matches. This is a deliberate design choice to prioritize creation match over runtime match.

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

zetachain-cctx/zetachain-cctx-logic/tests/helpers/mod.rs (2)

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

Learnt from: rimrakhimov
PR: #1134
File: eth-bytecode-db/verifier-alliance-database/src/internal.rs:270-273
Timestamp: 2024-12-12T16:19:10.540Z
Learning: In eth-bytecode-db/verifier-alliance-database/src/types.rs, the RetrieveContractDeployment struct guarantees that at least one of transaction_hash or runtime_code is always Some, enforced by its constructors. This invariant ensures that functions using this struct can safely assume one of these fields is present without additional checks.

zetachain-cctx/zetachain-cctx-logic/tests/token_sync.rs (1)

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

zetachain-cctx/zetachain-cctx-entity/src/outbound_params.rs (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/zetachain-cctx-server/tests/list_cctxs_test.rs (3)

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

Learnt from: bragov4ik
PR: #1191
File: stats/stats/src/charts/counters/total_operational_txns.rs:77-78
Timestamp: 2025-01-16T13:06:57.738Z
Learning: In stats/stats/src/charts/counters/total_operational_txns.rs, the test value "44" for total operational transactions is calculated as 57 (total transactions) minus 13 (total blocks).

Learnt from: bragov4ik
PR: #1226
File: stats/stats-server/src/update_service.rs:110-119
Timestamp: 2025-02-04T10:10:46.118Z
Learning: Graceful shutdown mechanisms for services in blockscout-rs are being implemented in dedicated PRs (#1128, #1129) using TaskTracker, JoinSet, and CancellationToken, rather than being handled individually in each service.

zetachain-cctx/zetachain-cctx-logic/tests/traverse_tree.rs (3)

Learnt from: bragov4ik
PR: #1147
File: stats/stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs:76-98
Timestamp: 2024-12-11T15:25:33.248Z
Learning: In the ClearAllAndPassStep::batch_update_values_step_with function in stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs, it's acceptable to perform the clear and insert operations separately without wrapping them in a transaction, as inconsistency is acceptable in this context, and the insert step is very unlikely to fail unless the service is down.

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

Learnt from: sevenzing
PR: #1147
File: stats/stats/src/charts/db_interaction/write.rs:59-65
Timestamp: 2024-12-12T07:52:29.072Z
Learning: In Rust, when a function takes a ConnectionTrait as an argument (e.g., in clear_all_chart_data function in stats/stats/src/charts/db_interaction/write.rs), it's not possible to begin a transaction within that function since the connection could be either a DatabaseConnection or a TransactionConnection. Additionally, if a transaction performs only one SQL statement, it's unnecessary to begin a transaction.

zetachain-cctx/zetachain-cctx-server/tests/helpers/mod.rs (1)

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

zetachain-cctx/zetachain-cctx-entity/src/cross_chain_tx.rs (2)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

zetachain-cctx/zetachain-cctx-entity/src/sea_orm_active_enums.rs (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/zetachain-cctx-entity/src/inbound_params.rs (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/zetachain-cctx-entity/src/enum_conversions.rs (3)

Learnt from: rimrakhimov
PR: #1294
File: smart-contract-verifier/smart-contract-verifier-server/src/types/batch_verification.rs:67-89
Timestamp: 2025-03-24T13:46:28.400Z
Learning: In the smart-contract-verifier library, artifacts from verification_common::verifier_alliance are designed with the contract that they must always be serializable to JSON. The types implement From for Value with .expect() to enforce this contract, making additional error handling for JSON serialization unnecessary. Serialization failure would indicate a programming error rather than a runtime condition.

Learnt from: sevenzing
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:77-78
Timestamp: 2024-12-11T09:00:43.057Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, within the TotalTxnsEstimation struct's estimate method, using u64::try_from(n).unwrap_or(0) will not cause a panic because unwrap_or handles the error by returning 0.

Learnt from: bragov4ik
PR: #1154
File: stats/stats/src/charts/lines/new_operational_txns.rs:71-71
Timestamp: 2024-12-13T15:52:06.550Z
Learning: In stats/stats/src/charts/lines/new_operational_txns.rs, the variable data from zip_same_timespan is of type EitherOrBoth<i64, i64> and not Option, so methods like unwrap_or are not applicable.

zetachain-cctx/zetachain-cctx-server/tests/indexer_tests.rs (2)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: bragov4ik
PR: #1191
File: stats/stats/src/charts/counters/total_operational_txns.rs:77-78
Timestamp: 2025-01-16T13:06:57.738Z
Learning: In stats/stats/src/charts/counters/total_operational_txns.rs, the test value "44" for total operational transactions is calculated as 57 (total transactions) minus 13 (total blocks).

zetachain-cctx/zetachain-cctx-proto/src/lib.rs (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/zetachain-cctx-logic/src/models.rs (2)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: rimrakhimov
PR: #1294
File: smart-contract-verifier/smart-contract-verifier-server/src/types/batch_verification.rs:67-89
Timestamp: 2025-03-24T13:46:28.400Z
Learning: In the smart-contract-verifier library, artifacts from verification_common::verifier_alliance are designed with the contract that they must always be serializable to JSON. The types implement From for Value with .expect() to enforce this contract, making additional error handling for JSON serialization unnecessary. Serialization failure would indicate a programming error rather than a runtime condition.

zetachain-cctx/zetachain-cctx-migration/src/m20220101_000001_create_table.rs (2)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: sevenzing
PR: #1147
File: stats/stats/src/charts/db_interaction/write.rs:59-65
Timestamp: 2024-12-12T07:52:29.072Z
Learning: In Rust, when a function takes a ConnectionTrait as an argument (e.g., in clear_all_chart_data function in stats/stats/src/charts/db_interaction/write.rs), it's not possible to begin a transaction within that function since the connection could be either a DatabaseConnection or a TransactionConnection. Additionally, if a transaction performs only one SQL statement, it's unnecessary to begin a transaction.

zetachain-cctx/zetachain-cctx-server/tests/token_api.rs (1)

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

zetachain-cctx/zetachain-cctx-server/src/services/cctx.rs (1)

Learnt from: bragov4ik
PR: #1226
File: stats/stats-server/src/update_service.rs:110-119
Timestamp: 2025-02-04T10:10:46.118Z
Learning: Graceful shutdown mechanisms for services in blockscout-rs are being implemented in dedicated PRs (#1128, #1129) using TaskTracker, JoinSet, and CancellationToken, rather than being handled individually in each service.

zetachain-cctx/zetachain-cctx-logic/src/database.rs (5)

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

Learnt from: sevenzing
PR: #1147
File: stats/stats/src/charts/db_interaction/write.rs:59-65
Timestamp: 2024-12-12T07:52:29.072Z
Learning: In Rust, when a function takes a ConnectionTrait as an argument (e.g., in clear_all_chart_data function in stats/stats/src/charts/db_interaction/write.rs), it's not possible to begin a transaction within that function since the connection could be either a DatabaseConnection or a TransactionConnection. Additionally, if a transaction performs only one SQL statement, it's unnecessary to begin a transaction.

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: rimrakhimov
PR: #1134
File: eth-bytecode-db/verifier-alliance-database/src/internal.rs:270-273
Timestamp: 2024-12-12T16:19:10.540Z
Learning: In eth-bytecode-db/verifier-alliance-database/src/types.rs, the RetrieveContractDeployment struct guarantees that at least one of transaction_hash or runtime_code is always Some, enforced by its constructors. This invariant ensures that functions using this struct can safely assume one of these fields is present without additional checks.

Learnt from: bragov4ik
PR: #1147
File: stats/stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs:76-98
Timestamp: 2024-12-11T15:25:33.248Z
Learning: In the ClearAllAndPassStep::batch_update_values_step_with function in stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs, it's acceptable to perform the clear and insert operations separately without wrapping them in a transaction, as inconsistency is acceptable in this context, and the insert step is very unlikely to fail unless the service is down.

🧬 Code Graph Analysis (12)
zetachain-cctx/zetachain-cctx-logic/tests/test_filters.rs (3)
zetachain-cctx/zetachain-cctx-logic/src/models.rs (1)
  • default (213-226)
zetachain-cctx/zetachain-cctx-logic/tests/helpers/mod.rs (2)
  • init_db (11-15)
  • dummy_cross_chain_tx (40-127)
zetachain-cctx/zetachain-cctx-server/tests/helpers/mod.rs (2)
  • init_db (14-18)
  • dummy_cross_chain_tx (62-149)
zetachain-cctx/zetachain-cctx-entity/src/token.rs (1)
zetachain-cctx/zetachain-cctx-server/src/services/cctx.rs (1)
  • entity (106-145)
zetachain-cctx/zetachain-cctx-server/src/check-envs.rs (1)
libs/env-collector/src/types.rs (1)
  • blacklist (34-37)
zetachain-cctx/zetachain-cctx-entity/src/revert_options.rs (6)
zetachain-cctx/zetachain-cctx-server/src/services/cctx.rs (1)
  • entity (106-145)
zetachain-cctx/zetachain-cctx-entity/src/enum_conversions.rs (6)
  • from (58-67)
  • from (77-83)
  • from (97-104)
  • from (126-131)
  • from (150-158)
  • from (180-185)
zetachain-cctx/zetachain-cctx-entity/src/cross_chain_tx.rs (4)
  • to (57-59)
  • to (63-65)
  • to (69-71)
  • to (75-77)
zetachain-cctx/zetachain-cctx-entity/src/inbound_params.rs (1)
  • to (46-48)
zetachain-cctx/zetachain-cctx-entity/src/cctx_status.rs (1)
  • to (39-41)
zetachain-cctx/zetachain-cctx-entity/src/outbound_params.rs (1)
  • to (48-50)
zetachain-cctx/zetachain-cctx-logic/src/events.rs (1)
zetachain-cctx/zetachain-cctx-server/src/websocket.rs (4)
  • broadcast_cctx_update (240-247)
  • broadcast_cctx_update (260-270)
  • broadcast_new_cctxs (251-255)
  • broadcast_new_cctxs (272-276)
zetachain-cctx/zetachain-cctx-server/src/settings.rs (3)
zetachain-cctx/zetachain-cctx-logic/src/client.rs (1)
  • default (199-206)
zetachain-cctx/zetachain-cctx-logic/src/settings.rs (1)
  • default (33-50)
zetachain-cctx/zetachain-cctx-server/src/websocket.rs (1)
  • default (67-73)
zetachain-cctx/zetachain-cctx-logic/tests/historical_sync.rs (4)
zetachain-cctx/zetachain-cctx-logic/src/client.rs (5)
  • serde_json (119-119)
  • serde_json (149-149)
  • serde_json (180-180)
  • new (28-38)
  • default (199-206)
zetachain-cctx/zetachain-cctx-logic/tests/helpers/mod.rs (5)
  • init_tests_logs (28-38)
  • init_db (11-15)
  • dummy_cctx_with_pagination_response (149-167)
  • empty_cctx_response (18-26)
  • dummy_cross_chain_tx (40-127)
zetachain-cctx/zetachain-cctx-logic/src/database.rs (6)
  • db (991-1005)
  • db (1031-1043)
  • db (1076-1090)
  • new (57-59)
  • cctx (1276-1278)
  • cctx (1286-1286)
zetachain-cctx/zetachain-cctx-logic/src/indexer.rs (1)
  • new (188-200)
zetachain-cctx/zetachain-cctx-logic/tests/helpers/mod.rs (2)
zetachain-cctx/zetachain-cctx-logic/tests/traverse_tree.rs (3)
  • TestDbGuard (19-19)
  • init_db (17-20)
  • dummy_cross_chain_tx (24-88)
zetachain-cctx/zetachain-cctx-server/tests/helpers/mod.rs (8)
  • TestDbGuard (17-17)
  • init_db (14-18)
  • init_tests_logs (21-31)
  • dummy_cross_chain_tx (62-149)
  • indices (154-160)
  • indices (172-178)
  • dummy_cctx_with_pagination_response (171-189)
  • empty_response (192-200)
zetachain-cctx/zetachain-cctx-entity/src/cross_chain_tx.rs (6)
zetachain-cctx/zetachain-cctx-server/src/services/cctx.rs (1)
  • entity (106-145)
zetachain-cctx/zetachain-cctx-entity/src/enum_conversions.rs (6)
  • from (58-67)
  • from (77-83)
  • from (97-104)
  • from (126-131)
  • from (150-158)
  • from (180-185)
zetachain-cctx/zetachain-cctx-entity/src/inbound_params.rs (1)
  • to (46-48)
zetachain-cctx/zetachain-cctx-entity/src/cctx_status.rs (1)
  • to (39-41)
zetachain-cctx/zetachain-cctx-entity/src/revert_options.rs (1)
  • to (33-35)
zetachain-cctx/zetachain-cctx-entity/src/outbound_params.rs (1)
  • to (48-50)
zetachain-cctx/zetachain-cctx-entity/src/enum_conversions.rs (1)
zetachain-cctx/zetachain-cctx-logic/src/models.rs (4)
  • fmt (47-55)
  • try_from (32-43)
  • try_from (60-68)
  • try_from (271-299)
zetachain-cctx/zetachain-cctx-proto/src/lib.rs (1)
libs/blockscout-client/crate/tests/it_works.rs (1)
  • blockscout (125-127)
zetachain-cctx/zetachain-cctx-logic/src/models.rs (1)
zetachain-cctx/zetachain-cctx-entity/src/enum_conversions.rs (8)
  • try_from (8-15)
  • try_from (21-27)
  • try_from (33-43)
  • try_from (109-117)
  • try_from (136-142)
  • try_from (163-172)
  • try_from (189-195)
  • try_from (200-208)
🪛 dotenv-linter (3.3.0)
tac-operation-lifecycle/.env

[warning] 8-8: [DuplicatedKey] The TAC_OPERATION_LIFECYCLE__DATABASE__CONNECT_OPTIONS__MAX_CONNECTIONS key is duplicated


[warning] 8-8: [UnorderedKey] The TAC_OPERATION_LIFECYCLE__DATABASE__CONNECT_OPTIONS__MAX_CONNECTIONS key should go before the TAC_OPERATION_LIFECYCLE__DATABASE__CONNECT_OPTIONS__MAX_CONNECTIONS key


[warning] 16-16: [UnorderedKey] The TAC_OPERATION_LIFECYCLE__INDEXER__CONCURRENCY key should go before the TAC_OPERATION_LIFECYCLE__INDEXER__POLLING_INTERVAL key


[warning] 20-20: [QuoteCharacter] The value has quote characters (', ")


[warning] 27-27: [UnorderedKey] The TAC_OPERATION_LIFECYCLE__SERVER__HTTP__CORS__ALLOWED_METHODS key should go before the TAC_OPERATION_LIFECYCLE__SERVER__HTTP__CORS__ALLOWED_ORIGIN key


[warning] 27-27: [ValueWithoutQuotes] This value needs to be surrounded in quotes


[warning] 28-28: [UnorderedKey] The TAC_OPERATION_LIFECYCLE__SERVER__HTTP__CORS__ALLOWED_CREDENTIALS key should go before the TAC_OPERATION_LIFECYCLE__SERVER__HTTP__CORS__ALLOWED_METHODS key

🪛 YAMLlint (1.37.1)
tac-operation-lifecycle/docker-compose.yml

[error] 26-26: no new line character at the end of file

(new-line-at-end-of-file)


[error] 26-26: trailing spaces

(trailing-spaces)

zetachain-cctx/zetachain-cctx-proto/proto/v1/api_config_http.yaml

[error] 6-6: trailing spaces

(trailing-spaces)


[error] 9-9: trailing spaces

(trailing-spaces)


[error] 12-12: trailing spaces

(trailing-spaces)


[error] 21-21: trailing spaces

(trailing-spaces)


[warning] 27-27: too many blank lines (1 > 0)

(empty-lines)

zetachain-cctx/docker-compose.yaml

[error] 52-52: no new line character at the end of file

(new-line-at-end-of-file)


[error] 52-52: trailing spaces

(trailing-spaces)

zetachain-cctx/.github/workflows/zetachain-cctx.yml

[error] 90-90: trailing spaces

(trailing-spaces)


[error] 92-92: trailing spaces

(trailing-spaces)


[error] 93-93: no new line character at the end of file

(new-line-at-end-of-file)

🪛 Gitleaks (8.27.2)
zetachain-cctx/zetachain-cctx-logic/tests/batch_insert.rs

93-93: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

zetachain-cctx/zetachain-cctx-logic/tests/token_sync.rs

203-203: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


219-219: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🪛 markdownlint-cli2 (0.17.2)
zetachain-cctx/README.md

4-4: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


5-5: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


5-5: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


29-29: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


29-29: Spaces inside emphasis markers

(MD037, no-space-in-emphasis)


29-29: Spaces inside emphasis markers

(MD037, no-space-in-emphasis)


30-30: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


32-32: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


35-35: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


36-36: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


38-38: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


40-40: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


42-42: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


48-48: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


50-50: Link and image reference definitions should be needed
Unused link or image reference definition: "anchor"

(MD053, link-image-reference-definitions)


86-86: Link and image reference definitions should be needed
Duplicate link or image reference definition: "anchor"

(MD053, link-image-reference-definitions)

🪛 Buf (1.55.1)
zetachain-cctx/zetachain-cctx-proto/proto/v1/stats.proto

3-3: Files with package "blockscout.zetachainCctx.v1" must be within a directory "blockscout/zetachainCctx/v1" relative to root but were in directory "zetachain-cctx/zetachain-cctx-proto/proto/v1".

(PACKAGE_DIRECTORY_MATCH)

zetachain-cctx/zetachain-cctx-proto/proto/v1/health.proto

3-3: Files with package "blockscout.zetachainCctx.v1" must be within a directory "blockscout/zetachainCctx/v1" relative to root but were in directory "zetachain-cctx/zetachain-cctx-proto/proto/v1".

(PACKAGE_DIRECTORY_MATCH)

zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto

3-3: Files with package "blockscout.zetachainCctx.v1" must be within a directory "blockscout/zetachainCctx/v1" relative to root but were in directory "zetachain-cctx/zetachain-cctx-proto/proto/v1".

(PACKAGE_DIRECTORY_MATCH)

🪛 Checkov (3.2.334)
zetachain-cctx/.github/workflows/zetachain-cctx.yml

[MEDIUM] 63-64: Basic Auth Credentials

(CKV_SECRET_4)

zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml

[HIGH] 1-573: Ensure that security requirement defined in securityDefinitions - version 2.0 files

(CKV_OPENAPI_6)


[HIGH] 1-573: Ensure that the global security field has rules defined

(CKV_OPENAPI_4)


[HIGH] 1-573: Ensure that security operations is not empty.

(CKV_OPENAPI_5)


[MEDIUM] 186-191: Ensure that arrays have a maximum number of items

(CKV_OPENAPI_21)


[HIGH] 1-573: Ensure that securityDefinitions is defined and not empty - version 2.0 files

(CKV_OPENAPI_1)

🔇 Additional comments (64)
zetachain-cctx/zetachain-cctx-server/src/check-envs.rs (1)

7-18: No action required: run_env_collector_cli returns ()

The run_env_collector_cli function in libs/env-collector/src/lib.rs is declared without a -> Result<…>, so it already returns unit. There’s no Result to propagate, and the suggested refactor isn’t applicable.

zetachain-cctx/types/.npmignore (1)

1-1: LGTM! Standard npm package exclusion.

The .npmignore correctly excludes node_modules from the published package, following standard npm practices.

zetachain-cctx/types/.gitignore (1)

1-1: LGTM! Correctly ignores generated files.

The .gitignore appropriately excludes the /dist directory containing generated TypeScript files from version control.

zetachain-cctx/zetachain-cctx-migration/src/m20220101_000004_add_inbound_params_composite_unique.rs (1)

40-45: LGTM! Proper enum definition for migration identifiers.

The InboundParams enum correctly defines the table and column identifiers needed for the migration.

zetachain-cctx/zetachain-cctx-logic/Cargo.toml (1)

15-21: LGTM! Appropriate SeaORM feature selection.

The SeaORM features are correctly configured for PostgreSQL usage with tokio runtime and necessary macros.

zetachain-cctx/zetachain-cctx-proto/proto/v1/health.proto (1)

42-63: Health check implementation looks good

The basic health check service is sufficient for initial implementation. The Watch method can be added later if streaming health status becomes a requirement.

zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml (1)

1-14: Verify if API authentication is required

The Swagger specification doesn't include any security definitions. Please verify if this API requires authentication and if it should be documented in the OpenAPI spec.

If authentication is handled by an API gateway or at a different layer, consider adding a comment in the Swagger file to document this decision.

zetachain-cctx/zetachain-cctx-migration/src/m20220101_000001_create_table.rs (1)

97-176: Well-designed schema with proper constraints

The cross_chain_txs table with self-referential foreign keys for tree structure is well implemented. The use of SET NULL for delete actions on parent/root relationships ensures data integrity while allowing flexible tree operations.

zetachain-cctx/zetachain-cctx-server/tests/mod.rs (1)

1-2: No issues – helpers module inclusion looks good

The blanket mod helpers; keeps test utilities centralised. 👍

tac-operation-lifecycle/tac-operation-lifecycle-server/.env (1)

1-1: Confirm relative path works in all deployment targets

TAC_OPERATION_LIFECYCLE__CONFIG=tac-operation-lifecycle-server/config.yaml is relative.
If the service is started with a different working directory (e.g. via Docker WORKDIR /app), the file may not resolve. Consider an absolute path or ${PWD}/… in container images.

zetachain-cctx/zetachain-cctx-logic/tests/mod.rs (1)

1-1: Helpers module inclusion acknowledged

Keeps test code DRY; no action needed.

zetachain-cctx/zetachain-cctx-server/src/proto.rs (1)

1-1: LGTM: Clean protobuf re-export pattern.

The wildcard re-export provides a clean abstraction layer for accessing generated protobuf types throughout the server crate.

tac-operation-lifecycle/tac-operation-lifecycle-server/.config.env (2)

4-5: LGTM: Reasonable concurrency and rate limiting settings.

The indexer concurrency (5) and request rate limit (1/second) provide a good balance between performance and resource usage.


2-3: Check boolean value quoting in .config.env

The CREATE_DATABASE and RUN_MIGRATIONS fields are currently wrapped in quotes, yielding the literal strings "true". Many parsers expect bare booleans (true/false) and will fail to convert quoted values.

Please update the .config.env entries as follows:

• Remove quotes around the boolean values

-TAC_OPERATION_LIFECYCLE__DATABASE__CREATE_DATABASE="true"
-TAC_OPERATION_LIFECYCLE__DATABASE__RUN_MIGRATIONS="true"
+TAC_OPERATION_LIFECYCLE__DATABASE__CREATE_DATABASE=true
+TAC_OPERATION_LIFECYCLE__DATABASE__RUN_MIGRATIONS=true

Verify that your configuration loader (e.g. the config crate’s environment source) correctly parses unquoted booleans.

zetachain-cctx/zetachain-cctx-migration/src/main.rs (1)

1-6: LGTM: Standard SeaORM migration CLI setup.

The implementation correctly follows SeaORM migration patterns with appropriate async runtime setup.

zetachain-cctx/zetachain-cctx-server/src/lib.rs (1)

1-9: LGTM: Well-structured module organization.

The module declarations and public API re-exports follow Rust best practices, providing a clean and focused interface for the server crate.

zetachain-cctx/zetachain-cctx-migration/Cargo.toml (1)

11-22: Verify mixed async runtimes & SeaORM feature set

async-std is enabled with tokio1 compatibility, while sea-orm-migration is compiled with the runtime-tokio-rustls feature only.
This hybrid can silently pull both runtimes, increase binary size, and create “two Tokio reactors” bugs when code inside the migration crate spawns tasks.

If you intend to execute migrations exclusively from the CLI, consider aligning:

-async-std = { version = "1", features = ["attributes", "tokio1"] }
+tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }

and drop async-std (or flip SeaORM to the runtime-async-std-native-tls feature).

Please double-check build output before merging.

zetachain-cctx/zetachain-cctx-entity/src/prelude.rs (1)

1-9: LGTM! Generated entity prelude follows SeaORM conventions.

The prelude module correctly re-exports all entity types, providing a convenient single import point for the SeaORM entities. The structure is standard and appropriate for generated code.

zetachain-cctx/zetachain-cctx-proto/src/lib.rs (1)

1-11: LGTM! Standard protobuf code generation pattern.

The module structure and generated code inclusion follows standard Rust protobuf practices. The clippy suppression is appropriate for generated code that may not follow all linting rules.

zetachain-cctx/zetachain-cctx-proto/Cargo.toml (1)

1-18: LGTM! Well-structured proto crate configuration.

The Cargo.toml follows Rust conventions with appropriate dependencies for gRPC/HTTP services and protobuf code generation. The use of workspace dependencies ensures version consistency across the monorepo.

zetachain-cctx/zetachain-cctx-server/tests/startup_works.rs (1)

11-36: LGTM! Clean integration test following established patterns.

The test properly verifies server startup functionality with appropriate database initialization and helper usage. The ignore attribute is correctly applied for database-dependent tests, consistent with other blockscout-rs integration tests.

zetachain-cctx/zetachain-cctx-entity/src/lib.rs (1)

1-13: LGTM! Standard SeaORM entity aggregator.

This generated code properly aggregates the domain entities needed for cross-chain transaction indexing. The module structure follows SeaORM conventions with a prelude and comprehensive entity coverage.

zetachain-cctx/zetachain-cctx-server/src/services/stats.rs (1)

28-28: Verify historical_watermark_timestamp timezone conversion

The call

historic_watermark_timestamp: sync_progress
    .historical_watermark_timestamp
    .and_utc()
    .timestamp(),

interprets the database value as a timezone-naive (local) timestamp and forces it into UTC. Please double-check that:

  • Your DB column historical_watermark_timestamp is stored as a local‐time TIMESTAMP WITHOUT TIME ZONE (so “treat as UTC” is correct),
  • or it’s actually a TIMESTAMPTZ (UTC) value—in which case you can drop .and_utc() and call .timestamp() on the existing DateTime<Utc> directly.

Review these spots in the codebase:
• server/src/services/stats.rs (line 28)
• logic/src/database.rs (lines ~1441–1469) where historical_watermark is mapped → historical_watermark_timestamp

zetachain-cctx/Dockerfile (1)

1-34: Well-structured multi-stage Dockerfile following best practices.

The Dockerfile effectively uses cargo chef for dependency caching, creates a non-root user for security, and maintains a minimal runtime image. The multi-stage approach optimizes both build time and final image size.

zetachain-cctx/zetachain-cctx-migration/src/lib.rs (1)

8-20: Migration orchestrator implementation looks correct.

The Migrator properly implements MigratorTrait and returns migrations in the correct sequential order. The structure follows SeaORM conventions.

zetachain-cctx/zetachain-cctx-logic/tests/batch_insert.rs (1)

93-93: Static analysis false positive - this is test pagination data.

The static analysis tool flagged this as a potential API key, but this is actually a base64-encoded pagination token from the test JSON data, not a sensitive credential.

The next_key field contains pagination data, not an API key. This is a false positive from the static analysis tool.

zetachain-cctx/zetachain-cctx-entity/src/token.rs (2)

26-27: Please verify Token entity foreign key relationships

The empty Relation enum in zetachain-cctx-entity/src/token.rs indicates no FK relationships are defined for the Token entity. We weren’t able to locate any references to token_id in other entities via automated search, so please double-check manually:

• Confirm whether other tables (e.g., cross-chain transactions) should reference Token via a foreign key.
• If such references exist, add the corresponding variants to the Relation enum (and update migrations/schema).
• Otherwise, document that Token is currently standalone with no FKs.


19-21: String-Based Fields for gas_limit and liquidity_cap Are by Design

We’ve confirmed that both gas_limit and liquidity_cap are consistently represented as String in:

zetachain-cctx-entity/src/token.rs (Entity model)
• API client models (Serde JSON fields)
• Service layer (.parse().unwrap_or(0) into u64)
• Logic layer (passed through ActiveValue::Set(token.gas_limit))

No usage of non-numeric values was found, and all sample values fall well within standard integer ranges. Since these fields are never used in database-side numeric queries or aggregations, storing them as strings avoids cross-layer type mismatches.

If you later need to filter or aggregate by these values in SQL, you could migrate to a numeric column type (e.g., NUMERIC/BigDecimal in SeaORM). Otherwise, no change is required here.

zetachain-cctx/zetachain-cctx-entity/src/watermark.rs (1)

1-25: Entity model looks well-designed for watermark tracking.

The watermark entity model is well-structured with appropriate fields for tracking processing state, retry logic, and temporal bounds. The use of custom enums for Kind and ProcessingStatus provides type safety.

zetachain-cctx/README.md (1)

48-85: Comprehensive environment variables documentation.

The environment variables table is thorough and well-structured, providing clear guidance for configuration. The distinction between required and optional variables is helpful.

zetachain-cctx/zetachain-cctx-entity/src/revert_options.rs (2)

5-18: LGTM! Well-structured SeaORM entity definition.

The entity model follows SeaORM conventions properly with appropriate field types, constraints, and nullable annotations. The unique constraint on cross_chain_tx_id correctly enforces the one-to-one relationship with the parent entity.


22-30: Proper foreign key relationship configuration.

The belongs_to relationship is correctly configured with cascade delete behavior, ensuring referential integrity when parent records are removed.

zetachain-cctx/zetachain-cctx-logic/tests/traverse_tree.rs (1)

90-209: Well-structured integration test with proper transaction handling.

The test correctly:

  • Sets up a temporary database with proper migrations
  • Uses transactions appropriately for batch operations
  • Creates a realistic hierarchical data structure
  • Verifies that the tree traversal logic updates relationships correctly
  • Uses proper assertions to validate the expected behavior
zetachain-cctx/zetachain-cctx-logic/src/settings.rs (1)

25-29: Robust default concurrency calculation.

The function properly handles the case where available_parallelism() fails by falling back to 1. This is a good defensive programming practice.

zetachain-cctx/zetachain-cctx-server/src/services/token.rs (2)

14-18: Clean service constructor following dependency injection pattern.

The constructor properly takes an Arc<ZetachainCctxDatabase> for thread-safe shared access, which is appropriate for a gRPC service that may handle concurrent requests.


22-51: Well-implemented gRPC service method with proper error handling.

The method implementation correctly:

  • Validates input parameters (empty asset check)
  • Uses proper error mapping with appropriate gRPC status codes
  • Includes tracing instrumentation for observability
  • Handles both database errors and not-found cases appropriately

The error messages are informative and the status codes follow gRPC conventions.

zetachain-cctx/zetachain-cctx-entity/src/cctx_status.rs (3)

6-24: Well-structured entity model with comprehensive error tracking.

The entity model is well-designed with appropriate constraints and relationships. The multiple error message fields (error_message, error_message_revert, error_message_abort) provide comprehensive error tracking for different scenarios.


28-36: Properly configured foreign key relationship.

The foreign key relationship to cross_chain_tx is well-configured with cascade delete behavior, which ensures data integrity when parent records are removed.


17-19: CctxStatus timestamp types are intentionally different
created_timestamp is an epoch‐seconds field (i64) carried through the service/API as a string and parsed back to i64 for storage, whereas last_update_timestamp records the precise update time as a DateTime<Utc>. This distinction reflects their different roles (original submission time vs. DB update time) and is handled consistently across entity, logic, server, tests, and the Proto definitions—no changes required.

zetachain-cctx/zetachain-cctx-migration/src/m20220101_000002_add_foreign_key_indexes.rs (3)

10-23: Excellent composite unique index for data integrity.

The composite unique index on (cross_chain_tx_id, receiver, receiver_chain_id) effectively prevents duplicate outbound parameters for the same transaction-receiver combination, ensuring data integrity.


36-86: Well-optimized foreign key indexes for performance.

The foreign key indexes on cross_chain_tx_id columns across multiple tables (cctx_status, inbound_params, outbound_params, revert_options) will significantly improve join performance for related entity queries. The index on cross_chain_tx.index field also supports efficient lookups.


91-159: Proper migration rollback implementation.

The down method correctly reverses all changes by dropping indexes in the appropriate order, ensuring clean migration rollbacks.

zetachain-cctx/zetachain-cctx-migration/src/m20220101_000003_create_token_table.rs (3)

9-50: Comprehensive token table schema with proper constraints.

The token table schema is well-designed with appropriate data types, constraints, and defaults. The unique constraint on zrc20_contract_address prevents duplicate contract registrations, and the enum for coin_type ensures data consistency.


52-72: Strategic indexing for optimal query performance.

The indexes on asset and foreign_chain_id are well-chosen for the expected query patterns. These will support efficient token lookups by asset identifier and filtering by chain.


32-32: Proper enum definition for coin types.

The inline enum definition with variants ["Zeta", "Gas", "Erc20", "Cmd", "NoAssetCall"] provides type safety and ensures only valid coin types can be stored.

zetachain-cctx/zetachain-cctx-server/Cargo.toml (4)

6-14: Clear binary target definitions.

The two binary targets are well-defined: the main server application and a utility for environment variable checking. This separation of concerns is a good practice.


16-35: Comprehensive and well-organized dependencies.

The dependency selection covers all necessary functionality with appropriate feature flags. The use of workspace dependencies where available promotes consistency across the project.


42-49: Well-structured test dependencies.

The dev dependencies provide comprehensive testing support with utilities for assertions, HTTP testing, and database testing. The inclusion of the entity crate in dev-dependencies supports integration testing.


17-17: env-collector@26eed65 audit – no known security issues found
We’ve checked the public blockscout/blockscout-rs repo (last updated June 2025) and found no documented vulnerabilities or advisories against the env-collector crate at revision 26eed65. It appears in the public commit history, and neither RustSec nor GitHub’s advisory database list any issues for this hash.

• Location to confirm:

  • zetachain-cctx/zetachain-cctx-server/Cargo.toml (line 17)

Action: No changes required. Continue to monitor the upstream repo and RustSec/GitHub Advisories for future updates.

zetachain-cctx/zetachain-cctx-entity/src/inbound_params.rs (1)

1-51: LGTM! Generated entity model is well-structured.

The SeaORM entity model is properly configured with appropriate relations and cascade delete behavior. The use of custom enums for type safety is a good practice.

zetachain-cctx/zetachain-cctx-server/tests/token_api.rs (1)

76-201: Well-structured comprehensive test for token database operations.

This test thoroughly covers token synchronization scenarios including insertion, querying, and updates. The verification of no duplicate entries on update is particularly valuable.

zetachain-cctx/zetachain-cctx-entity/src/outbound_params.rs (1)

1-54: Auto-generated SeaORM entity looks correct.

This entity definition is auto-generated by sea-orm-codegen and properly defines the outbound_params table structure with appropriate relations.

zetachain-cctx/zetachain-cctx-entity/src/cross_chain_tx.rs (1)

1-81: Auto-generated entity with proper hierarchical relations.

This entity correctly defines the cross_chain_tx table with self-referential relations for parent/child hierarchy. The relations to other entities are properly configured.

zetachain-cctx/zetachain-cctx-logic/tests/token_sync.rs (1)

23-57: Well-designed helper function for token response mocking.

The dummy_token_response function provides a clean way to generate test token data with pagination support.

zetachain-cctx/zetachain-cctx-server/tests/list_cctxs_test.rs (1)

259-369: Well-structured test for status reduction logic.

The test comprehensively covers the status reduction mapping with clear data organization and proper assertions.

zetachain-cctx/zetachain-cctx-server/src/services/cctx.rs (1)

187-197: Good pagination implementation.

The pagination logic correctly requests one extra item to detect if there are more pages and properly calculates the next page parameters.

zetachain-cctx/zetachain-cctx-logic/src/models.rs (1)

275-282: Good defensive programming for coin type parsing.

The implementation handles both "ERC20" and "Erc20" cases, which provides flexibility when dealing with potentially inconsistent external data sources.

zetachain-cctx/zetachain-cctx-logic/src/database.rs (3)

36-44: Good defensive string sanitization.

The function properly handles PostgreSQL's UTF-8 encoding requirements by removing null bytes and replacing invalid sequences. This prevents potential database errors.


969-1008: Excellent implementation of concurrent job processing with exponential backoff.

The use of FOR UPDATE SKIP LOCKED ensures proper concurrent access, and the exponential backoff using POWER(2, retries_number) provides intelligent retry spacing. The atomic update prevents race conditions.


1995-2007: Excellent SQL injection prevention with parameterized queries.

The dynamic query building correctly uses parameterized queries with proper array handling, preventing SQL injection vulnerabilities. The parameter counting approach ensures correct parameter binding.

zetachain-cctx/zetachain-cctx-server/tests/helpers/mod.rs (4)

1-12: LGTM! Well-organized imports.

The imports are appropriately structured and cover all the necessary dependencies for the test helper functionality.


34-59: Well-designed server initialization helper.

The function provides good flexibility through the settings_setup closure parameter and properly integrates with the test server infrastructure.


171-189: LGTM! Consistent pagination response structure.

The pagination response structure matches the expected API format and is consistent with the empty_response function.


192-200: LGTM! Proper empty response structure.

The empty response correctly represents the end state with an empty array and "end" next_key.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

♻️ Duplicate comments (2)
zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (2)

51-76: Enum values must be UPPER_SNAKE_CASE to satisfy proto-lint tools

CoinType, CctxStatus, and CctxStatusReduced still use mixed-case identifiers (Zeta, PendingInbound, …). Proto style (and Buf) requires UPPER_SNAKE_CASE.

-enum CoinType {
-  Zeta = 0;
-  Gas = 1;
-  Erc20 = 2;
-  Cmd = 3;
-  NoAssetCall = 4;
+enum CoinType {
+  COIN_TYPE_ZETA          = 0;
+  COIN_TYPE_GAS           = 1;
+  COIN_TYPE_ERC20         = 2;
+  COIN_TYPE_CMD           = 3;
+  COIN_TYPE_NO_ASSET_CALL = 4;
 }

Apply the same pattern to the other enums in this file.


3-3: Fix Buf PACKAGE_DIRECTORY_MATCH error – package does not match directory

blockscout.zetachainCctx.v1 implies the file should live under blockscout/zetachainCctx/v1/….
Either move the file or update the package declaration to match the current path.

-package blockscout.zetachainCctx.v1;
+package zetachain_cctx.v1;
🧹 Nitpick comments (4)
zetachain-cctx/zetachain-cctx-server/src/settings.rs (2)

60-62: Document the time unit for restart_interval.

The value 10000 for restart_interval likely represents milliseconds (10 seconds), but this should be documented for clarity.

Consider adding a comment to clarify the time unit:

 fn default_restart_interval() -> u64 {
+    // 10 seconds in milliseconds
     10000
 }

68-92: LGTM! Well-implemented constructor with minor formatting issue.

The constructor logic is correct and properly initializes all settings. However, there are some unnecessary blank lines in the parameter list.

Consider cleaning up the formatting:

 pub fn default(
-    
     database_url: String,
-    
 ) -> Self {
zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (1)

179-181: Inconsistent field casing: lastUpdate_timestamp

Stick to a single style (snake_case). Recommend:

-  int64 lastUpdate_timestamp = 3;
+  int64 last_update_timestamp = 3;
zetachain-cctx/zetachain-cctx-logic/src/database.rs (1)

970-1008: Well-implemented failure retry mechanism.

The exponential backoff strategy and atomic locking are properly implemented. Consider making the batch size (currently hardcoded to 100) configurable for different deployment scenarios.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 79f6ec0 and cc82aac.

📒 Files selected for processing (9)
  • zetachain-cctx/.gitignore (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/database.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/settings.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/test_filters.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/server.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/services/cctx.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/settings.rs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • zetachain-cctx/.gitignore
🚧 Files skipped from review as they are similar to previous changes (4)
  • zetachain-cctx/zetachain-cctx-logic/tests/test_filters.rs
  • zetachain-cctx/zetachain-cctx-logic/src/settings.rs
  • zetachain-cctx/zetachain-cctx-server/src/services/cctx.rs
  • zetachain-cctx/zetachain-cctx-server/src/server.rs
🧰 Additional context used
🪛 Buf (1.55.1)
zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto

3-3: Files with package "blockscout.zetachainCctx.v1" must be within a directory "blockscout/zetachainCctx/v1" relative to root but were in directory "zetachain-cctx/zetachain-cctx-proto/proto/v1".

(PACKAGE_DIRECTORY_MATCH)

🪛 Checkov (3.2.334)
zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml

[HIGH] 1-573: Ensure that security requirement defined in securityDefinitions - version 2.0 files

(CKV_OPENAPI_6)


[HIGH] 1-573: Ensure that the global security field has rules defined

(CKV_OPENAPI_4)


[HIGH] 1-573: Ensure that security operations is not empty.

(CKV_OPENAPI_5)


[MEDIUM] 186-191: Ensure that arrays have a maximum number of items

(CKV_OPENAPI_21)


[HIGH] 1-573: Ensure that securityDefinitions is defined and not empty - version 2.0 files

(CKV_OPENAPI_1)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Unit, doc and integration tests
🔇 Additional comments (9)
zetachain-cctx/zetachain-cctx-server/src/settings.rs (4)

1-7: LGTM! Well-organized imports.

The imports are appropriately structured and bring in all necessary dependencies for configuration management.


33-38: LGTM! Clean struct definition.

The WebSocketSettings struct is well-defined with appropriate serde attributes and custom default function.


40-46: LGTM! Consistent Default implementation.

The Default implementation correctly uses the same default function as the serde attribute, ensuring consistency.


64-66: LGTM! Correct trait implementation.

The ConfigSettings implementation with the appropriate service name is correct.

zetachain-cctx/zetachain-cctx-logic/src/database.rs (5)

35-44: LGTM! Proper sanitization for PostgreSQL.

The function correctly handles the PostgreSQL constraint against null bytes in UTF-8 strings.


1217-1432: Well-implemented related CCTX import with proper tree structure management.

The function correctly handles:

  • Tree relationships (root_id, parent_id, depth)
  • Idempotent insertions with ON CONFLICT DO NOTHING
  • String sanitization for all text fields
  • Transactional consistency

194-272: Excellent tree traversal implementation with proper BFS algorithm.

The level-by-level traversal ensures correct depth assignment and efficiently updates all descendants. The distinction between mined (final) and non-mined (may have future children) CCTXs is properly handled.


2209-2243: Proper token synchronization with comprehensive conflict handling.

The implementation correctly handles token updates using the zrc20_contract_address as the unique identifier and updates all relevant fields on conflict.


274-349: Audit concurrent setup safety and unlock logic

A couple of areas need your attention in setup_db (lines 274–349):

  • Potential race condition in the check-then-insert of historical and token watermarks (lines 274–314). If two instances run this concurrently, both may observe “no watermark” and attempt insertion.
    Suggestion: enforce a DB-level UNIQUE constraint on watermark.kind or use SeaORM’s on_conflict/INSERT … ON CONFLICT DO NOTHING to avoid duplicate records under load.

  • Unconditional unlocking of all locked CCTXs (lines 279–285) and watermarks (lines 339–346). This will clear any in-flight locks, potentially disrupting active indexing processes.
    Suggestion: narrow the unlock to only stale or orphaned locks (e.g., based on timestamp or owner), or verify that global unlock is safe in your operational model.

Please confirm the presence (or absence) of a unique constraint on watermark.kind in your schema and review whether force-unlocking every record aligns with your indexer’s locking guarantees.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (7)
zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml (1)

1-14: Add mandatory securityDefinitions and global security block

Swagger 2.0 specs without an explicit security scheme violate CKV_OPENAPI_1/4/5/6 and will block CI/production deploys. Re-add an API-key or OAuth2 definition and reference it globally (same recommendation was given earlier).
Example patch:

 consumes:
   - application/json
 produces:
   - application/json
+securityDefinitions:
+  ApiKeyAuth:
+    type: apiKey
+    in: header
+    name: Authorization
+security:
+  - ApiKeyAuth: []
zetachain-cctx/zetachain-cctx-logic/src/database.rs (3)

542-902: Consider refactoring this large function for better maintainability.

While the implementation is correct and handles all edge cases properly (sanitization, conflict resolution, batch operations), the function is quite large at ~360 lines. Consider splitting it into smaller functions:

  1. Separate the model preparation logic
  2. Extract the protobuf response construction
  3. Create helper functions for each entity type insertion

This would improve readability and testability while maintaining the same transactional guarantees.


1475-1928: Refactor to reduce fragility from hardcoded column indices.

The extensive use of hardcoded column indices (0-45) makes this code extremely fragile and error-prone. Any change to the SELECT statement order would require updating all index references.

Consider:

  1. Using SeaORM's query builder with proper type mapping
  2. Creating a struct to map the raw query results
  3. At minimum, use column aliases and a mapping structure to avoid magic numbers

The current implementation is a maintenance hazard despite being functionally correct.


1930-2213: Fix potential panic and clarify pagination logic.

Issues found:

  1. Potential panic at line 2131: min().unwrap_or(0) - if rows is empty, this could panic. Use unwrap_or_default() or handle the None case explicitly.

  2. Unusual pagination: The query fetches limit * 2 rows but only returns limit items. This seems inefficient and the purpose is unclear.

  3. SQL building: Consider using a query builder pattern or extracting the filter building logic to improve readability.

-        let next_page_key = truncated.clone().map(|row| row.try_get_by_index(15).unwrap()).min().unwrap_or(0) as i64
+        let next_page_key = truncated.clone()
+            .filter_map(|row| row.try_get_by_index::<i64>(15).ok())
+            .min()
+            .unwrap_or(0);
zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (3)

3-3: Package declaration still mismatched with file path – Buf will error out

The file lives under proto/v1/, but the declared package starts with blockscout… which implies a blockscout/zetachainCctx/v1/ directory. Buf’s PACKAGE_DIRECTORY_MATCH rule will keep failing until either the file is moved or the package is changed.

-package blockscout.zetachainCctx.v1;
+package zetachain_cctx.v1;

(then regenerate all stubs).


57-63: CoinType enum casing unchanged from last review

Values are still Zeta, Gas, etc. Proto conventions require UPPER_SNAKE_CASE with an enum-name prefix to avoid global collisions.

-enum CoinType {
-  Zeta = 0;
-  Gas = 1;
-  Erc20 = 2;
-  Cmd = 3;
-  NoAssetCall = 4;
+enum CoinType {
+  COIN_TYPE_ZETA          = 0;
+  COIN_TYPE_GAS           = 1;
+  COIN_TYPE_ERC20         = 2;
+  COIN_TYPE_CMD           = 3;
+  COIN_TYPE_NO_ASSET_CALL = 4;
 }

Apply the same treatment to CctxStatus, CctxStatusReduced, ConfirmationMode, etc., to silence buf-lint and generate idiomatic code.


147-152: Field receiver_chainId violates proto snake_case – breaks generated code style

Rename to receiver_chain_id (and regenerate stubs + update callers).

-  int64 receiver_chainId = 2;
+  int64 receiver_chain_id = 2;
🧹 Nitpick comments (2)
zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml (1)

47-52: limit query parameter should be integer, not string

OpenAPI treats query primitives literally. Declaring a numeric value as a string with format: int64 hinders validator & client generator tooling.

-        - name: limit
-          in: query
-          required: false
-          type: string
-          format: int64
+        - name: limit
+          in: query
+          required: false
+          type: integer
+          format: int64
zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (1)

185-187: Mixed-case field names (lastUpdate_timestamp, isAbortRefunded) slip through

Stay consistent: all field identifiers should be snake_case. Consider:

-  int64 lastUpdate_timestamp = 3;
-  bool isAbortRefunded = 4;
+  int64 last_update_timestamp = 3;
+  bool is_abort_refunded     = 4;

Fixing now avoids ugly conversions in every generated language later on.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cc82aac and 4510716.

📒 Files selected for processing (5)
  • zetachain-cctx/zetachain-cctx-logic/src/database.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/test_filters.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/services/cctx.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • zetachain-cctx/zetachain-cctx-logic/tests/test_filters.rs
  • zetachain-cctx/zetachain-cctx-server/src/services/cctx.rs
🧰 Additional context used
🪛 Checkov (3.2.334)
zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml

[HIGH] 1-589: Ensure that security requirement defined in securityDefinitions - version 2.0 files

(CKV_OPENAPI_6)


[HIGH] 1-589: Ensure that the global security field has rules defined

(CKV_OPENAPI_4)


[HIGH] 1-589: Ensure that security operations is not empty.

(CKV_OPENAPI_5)


[MEDIUM] 194-199: Ensure that arrays have a maximum number of items

(CKV_OPENAPI_21)


[HIGH] 1-589: Ensure that securityDefinitions is defined and not empty - version 2.0 files

(CKV_OPENAPI_1)

🪛 Buf (1.55.1)
zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto

3-3: Files with package "blockscout.zetachainCctx.v1" must be within a directory "blockscout/zetachainCctx/v1" relative to root but were in directory "zetachain-cctx/zetachain-cctx-proto/proto/v1".

(PACKAGE_DIRECTORY_MATCH)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Unit, doc and integration tests
🔇 Additional comments (13)
zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml (1)

15-36: Colon in path segment may break tooling

Paths like /api/v1/CctxInfo:get are accepted by grpc-gateway but many OpenAPI parsers (e.g., Swagger-UI, OpenAPI-Generator) treat colon as an invalid path character. Consider changing to /api/v1/CctxInfo/get or /api/v1/cctxinfo and mapping via an x-grpc-method vendor extension instead.

zetachain-cctx/zetachain-cctx-logic/src/database.rs (12)

1-32: Good architectural foundation.

The structure is well-organized with appropriate use of Arc<DatabaseConnection> for thread-safe database access and comprehensive imports for the required functionality.


34-43: Critical security function correctly implemented.

The sanitization properly handles PostgreSQL UTF-8 encoding restrictions by removing null bytes and replacing invalid UTF-8 sequences. This prevents potential database insertion errors and security issues.


45-53: Clean status reduction logic.

The pattern matching provides clear mapping from detailed CCTX status to simplified status categories for API responses.


273-348: Solid database initialization logic.

The method properly handles startup initialization by creating required watermarks and cleaning up any locked records from previous runs. Good use of proper timestamps and comprehensive error handling.


193-271: Well-implemented tree traversal algorithm.

The method correctly handles complex CCTX relationship management with proper transaction usage, breadth-first traversal, and depth tracking. The logic for importing new CCTXs and updating hierarchical relationships is sound.


1136-1215: Proper status update handling.

The method correctly manages status updates across related entities with appropriate transaction usage and error handling. The unlock logic at the end ensures proper processing flow.


968-1007: Excellent concurrent processing pattern.

The method implements a robust failed CCTX recovery system with exponential backoff, atomic lock-and-update operations, and proper concurrency handling via FOR UPDATE SKIP LOCKED. The exponential backoff prevents overwhelming the system with rapid retries.


2215-2249: Efficient token synchronization implementation.

The method properly handles batch token insertion with conflict resolution, updating relevant columns when duplicates are encountered. Good performance optimization with empty collection check.


904-966: Consistent lock management patterns.

The watermark and CCTX locking methods follow consistent patterns with proper status transitions, timestamp updates, and audit trails via job IDs. Good use of instrumentation for observability.


1216-1431: Comprehensive CCTX import implementation.

The method properly handles importing complete CCTX structures with all related entities, appropriate conflict resolution, and proper hierarchy management. Good use of string sanitization and error handling throughout.


1433-1473: Useful sync progress monitoring.

The method provides comprehensive sync status information by querying relevant entities and counting pending operations. Good error handling for missing watermarks and clear progress metrics.


2250-2267: Clean utility method for token lookup.

The get_token_by_asset method provides a straightforward token lookup with proper error handling and optional return type handling.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
zetachain-cctx/README.md (1)

54-66: Environment-variable prefix still contains the extra “C”.

The typo ZETACHAIN_CCCTX__… persists across all variables in this block.
Replace CCCTX with CCTX to keep naming consistent with the codebase.

-| `ZETACHAIN_CCCTX__DATABASE__CONNECT__URL`
+| `ZETACHAIN_CCTX__DATABASE__CONNECT__URL`
# …repeat for every variable beginning with ZETACHAIN_CCCTX__
🧹 Nitpick comments (3)
zetachain-cctx/.gitignore (1)

1-2: Consider keeping a committed, sanitized template and exclude only local overrides

Blanket-ignoring the entire config/dev/* tree and docker-compose.yml prevents any version-controlled example configuration or compose file from living next to the codebase, which hurts onboarding and reproducibility.
Common pattern:

config/dev/*
+!config/dev/README.md          # keep docs
+!config/dev/*.sample.*         # keep redacted samples

docker-compose.yml
+!docker-compose.sample.yml     # keep a template

This way, sensitive or machine-specific files stay out of Git, while developers still get a ready-to-copy starting point.
Please verify whether a template (or docs) should be committed and refine the ignore rules accordingly.

zetachain-cctx/README.md (2)

50-88: Duplicate link reference anchors at lines 50 and 88.

Housing two identical [anchor]: <> definitions is redundant and triggers MD053.
Remove one of them (the trailing instance is safest to drop).


1-5: Mixed heading styles (Setext vs ATX) flagging MD003/MD026.

Line 1/2 uses Setext (===) while subsequent headings switch to ##/###.
Standardise on one style—preferably ATX for all—to silence the linter and keep the document uniform.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4510716 and 12c9ab1.

📒 Files selected for processing (4)
  • zetachain-cctx/.gitignore (1 hunks)
  • zetachain-cctx/README.md (1 hunks)
  • zetachain-cctx/config/example.toml (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/check-envs.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • zetachain-cctx/zetachain-cctx-server/src/check-envs.rs
  • zetachain-cctx/config/example.toml
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
zetachain-cctx/README.md

4-4: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


5-5: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


5-5: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


29-29: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


29-29: Spaces inside emphasis markers

(MD037, no-space-in-emphasis)


29-29: Spaces inside emphasis markers

(MD037, no-space-in-emphasis)


30-30: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


32-32: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


35-35: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


36-36: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


38-38: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


40-40: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


42-42: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


48-48: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


50-50: Link and image reference definitions should be needed
Unused link or image reference definition: "anchor"

(MD053, link-image-reference-definitions)


88-88: Link and image reference definitions should be needed
Duplicate link or image reference definition: "anchor"

(MD053, link-image-reference-definitions)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Unit, doc and integration tests

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
zetachain-cctx/README.md (1)

54-54: Previous typo fixed – variable name now correct

The earlier extra ‘C’ in ZETACHAIN_CCTX__DATABASE__CONNECT__URL has been removed. ✅

🧹 Nitpick comments (5)
zetachain-cctx/README.md (5)

4-5: Unify heading style to silence markdown-lint warnings

markdownlint is flagging mixed heading styles (setext for the title vs. atx everywhere else).
Pick one convention (preferably atx for consistency) and rewrite the level-2 headings accordingly.

-## Indexer architecture
+## Indexer architecture

Replicate for the other level-2/3 headings that currently use ### ….
This is purely cosmetic but keeps automated docs checks green.


28-31: Fix bullet-list indentation – renders incorrectly on GitHub

The inner bullets under “Realtime-fetch handler” are indented with four spaces instead of two, violating MD007 and causing odd rendering:

-*  Realtime-fetch handler
-    * Periodically calls …
-    * Inserts new cctxs …
+* Realtime-fetch handler
+  * Periodically calls …
+  * Inserts new cctxs …

Apply the same two-space indentation rule to nested lists in the rest of the file.


50-88: Remove duplicate [anchor] reference definitions

The reference link [anchor] is defined twice (lines 50 and 88), triggering MD053 and potentially confusing Markdown processors.

-[anchor]: <> (anchors.envs.start)-[anchor]: <> (anchors.envs.end)

Keep only one definition or delete both if no longer needed.


52-54: Clean up table header – invisible zero-width chars hamper copy/paste

Req&#x200B;uir&#x200B;ed contains zero-width spaces to force column width. This impairs readability and makes copying the word tricky.

-| Variable | Req&#x200B;uir&#x200B;ed | Description | Default value |
+| Variable | Required | Description | Default value |

If column width is a concern, rely on normal spaces or let Markdown render naturally.


67-69: Consider pluralising REQUEST_PER_SECOND

Environment variable ZETACHAIN_CCTX__RPC__REQUEST_PER_SECOND suggests a rate; plural (REQUESTS_PER_SECOND) is more idiomatic and aligns with common wording (“requests per second”).

Renaming now avoids future confusion but requires a coordinated config change.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 12c9ab1 and ee9cfe2.

📒 Files selected for processing (2)
  • zetachain-cctx/README.md (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/check-envs.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • zetachain-cctx/zetachain-cctx-server/src/check-envs.rs
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
zetachain-cctx/README.md

4-4: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


5-5: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


5-5: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


29-29: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


29-29: Spaces inside emphasis markers

(MD037, no-space-in-emphasis)


29-29: Spaces inside emphasis markers

(MD037, no-space-in-emphasis)


30-30: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


32-32: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


35-35: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


36-36: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


38-38: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


40-40: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


42-42: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


48-48: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)


50-50: Link and image reference definitions should be needed
Unused link or image reference definition: "anchor"

(MD053, link-image-reference-definitions)


88-88: Link and image reference definitions should be needed
Duplicate link or image reference definition: "anchor"

(MD053, link-image-reference-definitions)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Unit, doc and integration tests

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (5)
zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (4)

3-3: Package directory mismatch needs resolution

The package name conflicts with the file directory structure, causing Buf validation to fail.


51-54: Enum values must follow proto conventions

The Direction enum values need to be in UPPER_SNAKE_CASE format as required by proto style guidelines.


58-83: Proto enum values require UPPER_SNAKE_CASE format

All enum values in CoinType, CctxStatus, and CctxStatusReduced violate proto naming conventions.


150-150: Field name violates proto style conventions

The field receiver_chainId uses mixed casing which should be snake_case.

zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml (1)

1-14: Missing security definitions prevent production deployment

The Swagger specification lacks required security schemes that are essential for production APIs.

🧹 Nitpick comments (3)
zetachain-cctx/zetachain-cctx-proto/proto/v1/api_config_http.yaml (2)

6-6: Remove trailing whitespace

Multiple lines contain trailing spaces that should be removed for clean formatting.

Apply this diff to remove trailing spaces:

-    
+    
-    
+    
-    
+    
-      get: /api/v1/Stats:getSyncProgress  
+      get: /api/v1/Stats:getSyncProgress

Also applies to: 9-9, 12-12, 21-21


31-31: Remove extra blank line

The file ends with an unnecessary blank line.

-
zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml (1)

207-211: Consider array size constraints for API stability

The details array in googlerpcStatus lacks maximum item constraints, which could lead to unbounded response sizes.

Add a reasonable maximum items constraint:

       details:
         type: array
+        maxItems: 10
         items:
           type: object
           $ref: '#/definitions/protobufAny'
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bcf4cc8 and 97df0c8.

📒 Files selected for processing (5)
  • zetachain-cctx/zetachain-cctx-logic/src/database.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/proto/v1/api_config_http.yaml (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/services/token.rs (1 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: rimrakhimov
PR: blockscout/blockscout-rs#1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.
zetachain-cctx/zetachain-cctx-server/src/services/token.rs (1)

Learnt from: bragov4ik
PR: #1226
File: stats/stats-server/src/update_service.rs:110-119
Timestamp: 2025-02-04T10:10:46.118Z
Learning: Graceful shutdown mechanisms for services in blockscout-rs are being implemented in dedicated PRs (#1128, #1129) using TaskTracker, JoinSet, and CancellationToken, rather than being handled individually in each service.

zetachain-cctx/zetachain-cctx-logic/src/database.rs (5)

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

Learnt from: sevenzing
PR: #1147
File: stats/stats/src/charts/db_interaction/write.rs:59-65
Timestamp: 2024-12-12T07:52:29.072Z
Learning: In Rust, when a function takes a ConnectionTrait as an argument (e.g., in clear_all_chart_data function in stats/stats/src/charts/db_interaction/write.rs), it's not possible to begin a transaction within that function since the connection could be either a DatabaseConnection or a TransactionConnection. Additionally, if a transaction performs only one SQL statement, it's unnecessary to begin a transaction.

Learnt from: bragov4ik
PR: #1147
File: stats/stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs:76-98
Timestamp: 2024-12-11T15:25:33.248Z
Learning: In the ClearAllAndPassStep::batch_update_values_step_with function in stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs, it's acceptable to perform the clear and insert operations separately without wrapping them in a transaction, as inconsistency is acceptable in this context, and the insert step is very unlikely to fail unless the service is down.

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:98-108
Timestamp: 2025-01-22T09:57:55.036Z
Learning: In eth-bytecode-db's alliance_db.rs, when determining if a contract match is "full" via extract_match_type, only the creation metadata match is considered, even for complete matches. This is a deliberate design choice to prioritize creation match over runtime match.

zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (2)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

🧬 Code Graph Analysis (1)
zetachain-cctx/zetachain-cctx-server/src/services/token.rs (3)
zetachain-cctx/zetachain-cctx-server/src/services/cctx.rs (1)
  • new (19-21)
zetachain-cctx/zetachain-cctx-logic/src/database.rs (5)
  • new (56-58)
  • db (990-1004)
  • db (1030-1042)
  • db (1075-1089)
  • list_tokens (2268-2278)
zetachain-cctx/zetachain-cctx-server/src/services/stats.rs (1)
  • new (18-20)
🪛 Checkov (3.2.334)
zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml

[HIGH] 1-611: Ensure that security requirement defined in securityDefinitions - version 2.0 files

(CKV_OPENAPI_6)


[HIGH] 1-611: Ensure that the global security field has rules defined

(CKV_OPENAPI_4)


[HIGH] 1-611: Ensure that security operations is not empty.

(CKV_OPENAPI_5)


[MEDIUM] 208-213: Ensure that arrays have a maximum number of items

(CKV_OPENAPI_21)


[HIGH] 1-611: Ensure that securityDefinitions is defined and not empty - version 2.0 files

(CKV_OPENAPI_1)

🪛 Buf (1.55.1)
zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto

3-3: Files with package "blockscout.zetachainCctx.v1" must be within a directory "blockscout/zetachainCctx/v1" relative to root but were in directory "zetachain-cctx/zetachain-cctx-proto/proto/v1".

(PACKAGE_DIRECTORY_MATCH)

🪛 YAMLlint (1.37.1)
zetachain-cctx/zetachain-cctx-proto/proto/v1/api_config_http.yaml

[error] 6-6: trailing spaces

(trailing-spaces)


[error] 9-9: trailing spaces

(trailing-spaces)


[error] 12-12: trailing spaces

(trailing-spaces)


[error] 21-21: trailing spaces

(trailing-spaces)


[warning] 30-30: too many blank lines (1 > 0)

(empty-lines)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Unit, doc and integration tests
🔇 Additional comments (17)
zetachain-cctx/zetachain-cctx-logic/src/database.rs (14)

1-32: Well-structured imports and database wrapper.

The imports are comprehensive and properly organized. Using Arc<DatabaseConnection> is the correct approach for thread-safe database access across the application.


34-43: Good sanitization implementation for PostgreSQL compatibility.

The string sanitization correctly addresses PostgreSQL's UTF-8 encoding constraints by removing null bytes and handling invalid UTF-8 sequences.


45-53: Clean status categorization logic.

The status reduction function appropriately groups detailed statuses into broader categories for better user experience. The pattern matching is clear and comprehensive.


273-348: Robust database initialization and recovery logic.

The setup function properly handles initialization by:

  • Creating required watermarks if missing
  • Unlocking any records left in locked state from previous runs
  • Using appropriate base64 encoding for initial pointers

This ensures clean startup and recovery from unexpected shutdowns.


193-271: Well-implemented hierarchical relationship management.

The tree traversal function correctly:

  • Maintains transactional consistency for relationship updates
  • Uses breadth-first traversal to properly update depths
  • Handles both direct and indirect descendants
  • Makes appropriate decisions about when to mark transactions as processed

The implementation is sophisticated and handles the complex hierarchical nature of CCTX relationships well.


968-1007: Good retry strategy with exponential backoff.

The failed CCTX query implements:

  • Exponential backoff using POWER(2, retries_number) for retry intervals
  • Proper concurrency control with SELECT FOR UPDATE pattern
  • Batch processing to avoid overwhelming the system

This approach prevents thundering herd problems and provides reasonable retry intervals.


1136-1215: Well-coordinated multi-table update with proper transaction handling.

The CCTX status update function correctly:

  • Updates related outbound parameters and status within a single transaction
  • Handles timestamp parsing with appropriate error handling
  • Unlocks the CCTX after successful update
  • Maintains data consistency across related tables

1216-1431: Comprehensive related CCTX import with proper data handling.

The import function excellently handles:

  • Complete entity graph insertion with referential integrity
  • String sanitization for database compatibility
  • Conflict resolution using appropriate ON CONFLICT strategies
  • Optional field handling (e.g., empty hash detection)
  • Transaction consistency across multiple related tables

This ensures robust import of complex hierarchical CCTX data.


2215-2249: Efficient token synchronization with comprehensive conflict resolution.

The token sync function properly:

  • Handles batch operations for efficiency
  • Updates all relevant token fields on conflict
  • Provides appropriate logging for monitoring
  • Uses exec_with_returning_many for getting inserted records

This ensures token metadata stays synchronized with the external source.


2251-2278: Clean and straightforward token query implementations.

The token query functions are well-implemented with:

  • Proper Option handling for nullable results
  • Consistent mapping to domain models
  • Clear and readable logic

351-370: Comprehensive watermark management with good instrumentation.

The watermark operations provide:

  • Complete lifecycle management (lock, unlock, done, move)
  • Proper timestamp tracking for coordination
  • Good tracing instrumentation for debugging
  • Appropriate transaction handling for consistency

This enables robust distributed processing coordination.

Also applies to: 904-951


407-445: Well-structured realtime import logic with proper validation.

The function correctly handles:

  • Realtime threshold validation to avoid processing stale data
  • Existence checks to prevent duplicate processing
  • Atomic operations using transactions
  • Clear early returns for different processing scenarios

This ensures efficient and accurate realtime data processing.


469-510: Sophisticated gap detection for complete data coverage.

The realtime processing function implements:

  • Upper and lower boundary validation to detect coverage gaps
  • Automatic watermark creation for continued processing of gaps
  • Clear logging for gap detection scenarios
  • Proper transaction handling for atomicity

This ensures no transactions are missed during realtime synchronization.


1433-1473: Comprehensive sync progress monitoring with multi-entity aggregation.

The sync progress function provides valuable operational visibility by:

  • Aggregating status from watermarks, pending updates, and realtime gaps
  • Providing meaningful metrics for monitoring dashboards
  • Handling edge cases like missing watermarks appropriately
  • Returning complete synchronization state information

This enables effective monitoring of the indexing system's health.

zetachain-cctx/zetachain-cctx-server/src/services/token.rs (3)

10-18: Well-structured service implementation

The service follows consistent patterns with proper dependency injection using Arc<ZetachainCctxDatabase>.


22-51: Robust error handling and validation

The get_token_info method includes proper input validation, error logging, and appropriate gRPC status code mapping.


53-68: Clean implementation with consistent error handling

The list_tokens method follows the same error handling patterns and properly transforms database results to proto messages.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 97df0c8 and 6bcd9b1.

📒 Files selected for processing (5)
  • zetachain-cctx/zetachain-cctx-logic/src/database.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/models.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/test_filters.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/tests/list_cctxs_test.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/tests/token_api.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • zetachain-cctx/zetachain-cctx-logic/tests/test_filters.rs
  • zetachain-cctx/zetachain-cctx-server/tests/token_api.rs
  • zetachain-cctx/zetachain-cctx-server/tests/list_cctxs_test.rs
  • zetachain-cctx/zetachain-cctx-logic/src/database.rs
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: rimrakhimov
PR: blockscout/blockscout-rs#1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.
zetachain-cctx/zetachain-cctx-logic/src/models.rs (2)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: rimrakhimov
PR: #1294
File: smart-contract-verifier/smart-contract-verifier-server/src/types/batch_verification.rs:67-89
Timestamp: 2025-03-24T13:46:28.400Z
Learning: In the smart-contract-verifier library, artifacts from verification_common::verifier_alliance are designed with the contract that they must always be serializable to JSON. The types implement From for Value with .expect() to enforce this contract, making additional error handling for JSON serialization unnecessary. Serialization failure would indicate a programming error rather than a runtime condition.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Unit, doc and integration tests
🔇 Additional comments (4)
zetachain-cctx/zetachain-cctx-logic/src/models.rs (4)

1-18: LGTM!

The imports are well-organized and the basic response structures follow good practices with appropriate serde annotations for API compatibility.


71-227: LGTM!

The CCTX data structures are well-designed with appropriate use of serde annotations for API compatibility and proper handling of optional fields. The Default implementation for Filters is clean and follows Rust conventions.


229-252: LGTM!

The sync progress tracking and related structures are well-defined with appropriate types. Good separation between external API models and internal processing models.


254-307: LGTM!

The token models and conversion logic are well-implemented with proper error handling, appropriate use of SeaORM ActiveValue types, and automatic timestamp management. The conversion correctly handles the CoinType to DbCoinType transformation with proper error propagation.

pub enum CoinType {
Zeta,
Gas,
ERC20,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix case inconsistency in ERC20 variant.

There's a case mismatch between the enum variant ERC20 and its string representations. The enum uses ERC20 but both the Display implementation and TryFrom<String> use "Erc20".

Choose one consistent casing. If the external API expects "Erc20", apply this diff:

-    ERC20,
+    Erc20,

Or if "ERC20" is preferred, update the string handling:

-            "Erc20" => CoinType::ERC20,
+            "ERC20" => CoinType::ERC20,
-            CoinType::ERC20 => write!(f, "Erc20"),
+            CoinType::ERC20 => write!(f, "ERC20"),

Also applies to: 36-36, 51-51

🤖 Prompt for AI Agents
In zetachain-cctx/zetachain-cctx-logic/src/models.rs at lines 24, 36, and 51,
there is a case inconsistency between the enum variant ERC20 and its string
representations in Display and TryFrom<String> implementations. To fix this,
choose a consistent casing for ERC20 across the enum variant and all string
handling code. Update the Display implementation and TryFrom<String> match arms
to use the exact same casing as the enum variant, either "ERC20" or "Erc20",
ensuring all references match perfectly.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (12)
zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml (2)

1-14: Missing security definitions blocks production deployment

The Swagger specification lacks any security scheme declaration, which is required for production use. Without securityDefinitions and security fields, the API is exposed without authentication.


438-440: Field naming inconsistency: receiver_chainId should be receiver_chain_id

The field uses mixed casing which violates the snake_case convention used throughout the API.

zetachain-cctx/zetachain-cctx-logic/src/database.rs (3)

542-902: Large function should be refactored for maintainability

The batch_insert_transactions function spans ~360 lines, making it difficult to maintain and test. Consider extracting helper functions for model preparation and response construction.


1475-1928: Hardcoded column indices make code extremely fragile

Using indices 0-45 for SQL result columns is error-prone. Any change to the SELECT statement requires updating all indices. Consider using a struct to map results or SeaORM's query builder.


2140-2147: Fix potential panic and clarify pagination logic

Two issues:

  1. Lines 2143/2145 could panic if truncated is empty
  2. Fetching limit * 2 rows (line 2134) but only returning limit items is inefficient
-        let next_page_key = {
-            if direction == Direction::Asc {
-                truncated.clone().map(|row| row.try_get_by_index(15).unwrap()).max().unwrap_or(0) as i64
-            } else {
-                truncated.clone().map(|row| row.try_get_by_index(15).unwrap()).min().unwrap_or(0) as i64
-            }
-        };
+        let next_page_key = if next_page_items_len > 0 {
+            if direction == Direction::Asc {
+                truncated.clone()
+                    .filter_map(|row| row.try_get_by_index::<i64>(15).ok())
+                    .max()
+                    .unwrap_or(0)
+            } else {
+                truncated.clone()
+                    .filter_map(|row| row.try_get_by_index::<i64>(15).ok())
+                    .min()
+                    .unwrap_or(0)
+            }
+        } else {
+            0
+        };
zetachain-cctx/zetachain-cctx-logic/src/client.rs (2)

57-64: Retry logic only covers rate limiter timeout, not HTTP request failures.

The current implementation only retries when waiting for the rate limiter times out, but doesn't retry the actual HTTP request if it fails. Consider adding retry logic for transient HTTP errors.


99-99: URL parsing could panic on invalid configuration.

Using unwrap() on URL parsing could cause panic if the configured URL is invalid.

Also applies to: 130-130, 181-181

zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (5)

3-3: Fix Buf package-directory mismatch

Buf fails with PACKAGE_DIRECTORY_MATCH because the package blockscout.zetachainCctx.v1 requires the file to live under blockscout/zetachainCctx/v1/….


60-63: Enum Direction values must be UPPER_SNAKE_CASE and prefixed

Proto-style and most linters expect ASC / DESC (or DIRECTION_ASC/DIRECTION_DESC) – current camel-case identifiers will fail buf-lint and generate awkward Rust/Go names.


67-92: Normalise enum value casing to satisfy proto-lint tools

Enum values should be UPPER_SNAKE_CASE by convention (and required by most linters).


159-159: Field receiver_chainId violates proto-style (mixed casing)

Field names must be snake_case. Mixed-case names break generated-code conventions.


195-196: Inconsistent field naming conventions

These fields use inconsistent casing patterns that violate proto style guidelines.

🧹 Nitpick comments (5)
zetachain-cctx/zetachain-cctx-migration/src/lib.rs (1)

3-7: Consider migration date consistency.

The migration naming follows a good pattern, but there's a date inconsistency. The first four migrations use 20220101 while the last uses 20240101. If this migration was added in 2024, the date is appropriate. However, ensure migration dates reflect actual creation time for better maintainability and avoid confusion.

zetachain-cctx/zetachain-cctx-proto/proto/v1/api_config_http.yaml (1)

6-21: Remove trailing spaces for consistency

YAMLlint detected trailing spaces on lines 6, 9, 12, and 21.

   rules:
-    
+
     - selector: blockscout.zetachainCctx.v1.CctxInfo.GetCctxInfo
       get: /api/v1/CctxInfo:get
-    
+
     - selector: blockscout.zetachainCctx.v1.CctxInfo.ListCctxs
       get: /api/v1/CctxInfo:list
-    
+
     #################### Health ####################

     - selector: blockscout.zetachainCctx.v1.Stats.GetSyncProgress
-      get: /api/v1/Stats:getSyncProgress  
+      get: /api/v1/Stats:getSyncProgress
zetachain-cctx/zetachain-cctx-logic/tests/token_icon_sync.rs (1)

94-101: Consider using more reliable synchronization for test timing.

The current approach with fixed timeouts (300ms/400ms) could be flaky in CI environments under load. Consider using a more deterministic approach such as polling the database until the expected state is reached or using a test fixture that allows explicit control over indexer execution cycles.

zetachain-cctx/zetachain-cctx-server/src/services/token.rs (1)

54-70: Consider implementing pagination for list_tokens.

The current implementation loads all tokens at once, which could cause performance issues with large datasets. The ListTokensRequest message might support pagination parameters that should be utilized.

-    async fn list_tokens(&self, _request: Request<ListTokensRequest>) -> Result<Response<TokensResponse>, Status> {
-        let tokens = self.db.list_tokens().await.map_err(|e| {
+    async fn list_tokens(&self, request: Request<ListTokensRequest>) -> Result<Response<TokensResponse>, Status> {
+        // TODO: Extract pagination parameters from request if available
+        let req = request.into_inner();
+        let tokens = self.db.list_tokens().await.map_err(|e| {
zetachain-cctx/zetachain-cctx-logic/tests/list_tokens.rs (1)

13-32: Well-structured test data setup.

The loop creates comprehensive token records with realistic test data. The use of the loop index to generate unique values for each token is effective for testing.

Consider adding a comment explaining the test data pattern for better readability:

+    // Insert dummy tokens with unique attributes based on index
     for i in 0..3 {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6bcd9b1 and 5ff66ec.

📒 Files selected for processing (15)
  • zetachain-cctx/zetachain-cctx-entity/src/token.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/client.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/database.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/indexer.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/src/models.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/list_tokens.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/test_filters.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-logic/tests/token_icon_sync.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-migration/src/lib.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-migration/src/m20240101_000005_add_icon_url_to_token.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/proto/v1/api_config_http.yaml (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (1 hunks)
  • zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/src/services/token.rs (1 hunks)
  • zetachain-cctx/zetachain-cctx-server/tests/token_api.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • zetachain-cctx/zetachain-cctx-entity/src/token.rs
  • zetachain-cctx/zetachain-cctx-server/tests/token_api.rs
  • zetachain-cctx/zetachain-cctx-logic/tests/test_filters.rs
  • zetachain-cctx/zetachain-cctx-logic/src/models.rs
  • zetachain-cctx/zetachain-cctx-logic/src/indexer.rs
🧰 Additional context used
🧠 Learnings (9)
📓 Common learnings
Learnt from: rimrakhimov
PR: blockscout/blockscout-rs#1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.
zetachain-cctx/zetachain-cctx-migration/src/m20240101_000005_add_icon_url_to_token.rs (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/zetachain-cctx-server/src/services/token.rs (1)

Learnt from: bragov4ik
PR: #1226
File: stats/stats-server/src/update_service.rs:110-119
Timestamp: 2025-02-04T10:10:46.118Z
Learning: Graceful shutdown mechanisms for services in blockscout-rs are being implemented in dedicated PRs (#1128, #1129) using TaskTracker, JoinSet, and CancellationToken, rather than being handled individually in each service.

zetachain-cctx/zetachain-cctx-logic/tests/token_icon_sync.rs (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/zetachain-cctx-logic/src/client.rs (2)

Learnt from: bragov4ik
PR: #1226
File: stats/stats-server/src/update_service.rs:175-178
Timestamp: 2025-02-04T10:09:47.440Z
Learning: Retry mechanisms should only be suggested for operations that can fail transiently (e.g., network calls, external services). They should not be used for programming invariant checks or validation of internal logic, as retrying with the same inputs would yield the same results.

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

zetachain-cctx/zetachain-cctx-logic/tests/list_tokens.rs (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml (1)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto (2)

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

zetachain-cctx/zetachain-cctx-logic/src/database.rs (6)

Learnt from: bragov4ik
PR: #1144
File: stats/stats/src/charts/counters/total_txns.rs:28-54
Timestamp: 2024-12-11T09:29:58.857Z
Learning: In stats/stats/src/charts/counters/total_txns.rs, attempting to combine the two database queries into one can result in code that doesn't compile and is more verbose. In future reviews, avoid suggesting this optimization for this context.

Learnt from: sevenzing
PR: #1147
File: stats/stats/src/charts/db_interaction/write.rs:59-65
Timestamp: 2024-12-12T07:52:29.072Z
Learning: In Rust, when a function takes a ConnectionTrait as an argument (e.g., in clear_all_chart_data function in stats/stats/src/charts/db_interaction/write.rs), it's not possible to begin a transaction within that function since the connection could be either a DatabaseConnection or a TransactionConnection. Additionally, if a transaction performs only one SQL statement, it's unnecessary to begin a transaction.

Learnt from: rimrakhimov
PR: #1134
File: eth-bytecode-db/verifier-alliance-database/src/internal.rs:270-273
Timestamp: 2024-12-12T16:19:10.540Z
Learning: In eth-bytecode-db/verifier-alliance-database/src/types.rs, the RetrieveContractDeployment struct guarantees that at least one of transaction_hash or runtime_code is always Some, enforced by its constructors. This invariant ensures that functions using this struct can safely assume one of these fields is present without additional checks.

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:9-12
Timestamp: 2025-01-22T09:56:00.917Z
Learning: The chain_id parameter type change from i64 to u128 in eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs was deferred to a future PR to maintain focus on the verifier_alliance schema v1 integration.

Learnt from: bragov4ik
PR: #1147
File: stats/stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs:76-98
Timestamp: 2024-12-11T15:25:33.248Z
Learning: In the ClearAllAndPassStep::batch_update_values_step_with function in stats/src/data_source/kinds/local_db/parameters/update/batching/parameters/mod.rs, it's acceptable to perform the clear and insert operations separately without wrapping them in a transaction, as inconsistency is acceptable in this context, and the insert step is very unlikely to fail unless the service is down.

Learnt from: rimrakhimov
PR: #1202
File: eth-bytecode-db/eth-bytecode-db/src/search/alliance_db.rs:98-108
Timestamp: 2025-01-22T09:57:55.036Z
Learning: In eth-bytecode-db's alliance_db.rs, when determining if a contract match is "full" via extract_match_type, only the creation metadata match is considered, even for complete matches. This is a deliberate design choice to prioritize creation match over runtime match.

🪛 Checkov (3.2.334)
zetachain-cctx/zetachain-cctx-proto/swagger/v1/zetachain-cctx.swagger.yaml

[HIGH] 1-614: Ensure that security requirement defined in securityDefinitions - version 2.0 files

(CKV_OPENAPI_6)


[HIGH] 1-614: Ensure that the global security field has rules defined

(CKV_OPENAPI_4)


[HIGH] 1-614: Ensure that security operations is not empty.

(CKV_OPENAPI_5)


[MEDIUM] 209-214: Ensure that arrays have a maximum number of items

(CKV_OPENAPI_21)


[HIGH] 1-614: Ensure that securityDefinitions is defined and not empty - version 2.0 files

(CKV_OPENAPI_1)

🪛 Buf (1.55.1)
zetachain-cctx/zetachain-cctx-proto/proto/v1/zetachain-cctx.proto

3-3: Files with package "blockscout.zetachainCctx.v1" must be within a directory "blockscout/zetachainCctx/v1" relative to root but were in directory "zetachain-cctx/zetachain-cctx-proto/proto/v1".

(PACKAGE_DIRECTORY_MATCH)

🪛 YAMLlint (1.37.1)
zetachain-cctx/zetachain-cctx-proto/proto/v1/api_config_http.yaml

[error] 6-6: trailing spaces

(trailing-spaces)


[error] 9-9: trailing spaces

(trailing-spaces)


[error] 12-12: trailing spaces

(trailing-spaces)


[error] 21-21: trailing spaces

(trailing-spaces)

🔇 Additional comments (7)
zetachain-cctx/zetachain-cctx-migration/src/lib.rs (3)

1-2: LGTM: Standard SeaORM migration re-export pattern.

The re-export of the SeaORM migration prelude is correct and follows standard conventions for migration modules.


9-10: LGTM: Standard migrator struct declaration.

The Migrator struct follows SeaORM conventions correctly.


11-22: LGTM: Correct MigratorTrait implementation.

The async trait implementation is correct and follows SeaORM patterns. The migration order is chronological and consistent with the module declarations.

zetachain-cctx/zetachain-cctx-migration/src/m20240101_000005_add_icon_url_to_token.rs (1)

1-39: Migration implementation looks good!

The migration properly adds a nullable icon_url column with rollback support.

zetachain-cctx/zetachain-cctx-logic/tests/list_tokens.rs (3)

1-6: LGTM!

The imports are well-organized and include all necessary dependencies for the integration test.


8-9: LGTM!

The test function definition follows proper async testing conventions with a clear, descriptive name.


10-11: LGTM!

The test setup properly initializes an isolated test database and obtains a connection for operations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feat New feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants