Skip to content

feat: external risk service - #1407

Open
Dodecahedr0x wants to merge 9 commits into
engine-integrationfrom
dode/external-risk-server
Open

feat: external risk service#1407
Dodecahedr0x wants to merge 9 commits into
engine-integrationfrom
dode/external-risk-server

Conversation

@Dodecahedr0x

@Dodecahedr0x Dodecahedr0x commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Summary

Relies on the query filtering service to get risk results, sharing the same cache to reduce API calls. Closes #1433

Breaking Changes

  • Yes — The config changes to point to the service

Summary by CodeRabbit

  • New Features

    • Risk checks now use a dedicated HTTP risk server.
    • Risk responses include server-provided risk status and assessment details.
    • Added configuration for the risk server URL and request timeout.
  • Bug Fixes

    • Improved handling of high- and low-risk address results.
    • Updated risk-check errors and configuration defaults for the new service.
    • Removed obsolete local caching and legacy risk-provider settings.

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The AML implementation now calls an external risk server through GET /risk?pubkey=.... Local Range API credentials, SQLite caching, deduplication, and score thresholds were removed. Configuration and defaults now use risk-server-url. Chainlink wiring no longer passes a ledger path. Unit and integration tests use the new server response format.

Assessment against linked issues:

Objective Addressed Explanation
Use an external service for AML risk checks [#1433]

Suggested reviewers: gabrielepicco

✨ Finishing Touches 💡 1
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch dode/external-risk-server
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch dode/external-risk-server

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.

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
putComment timed out

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@config.example.toml`:
- Around line 272-287: The full-coverage example config test is missing
assertions for the new Chainlink risk settings. Update
test_example_config_full_coverage in tests.rs to also verify
config.chainlink.risk.risk_server_url and config.chainlink.risk.request_timeout
alongside config.chainlink.risk.enabled, so the example file’s new values are
covered and any drift is caught. Use the existing
test_example_config_full_coverage and config.chainlink.risk fields to locate the
check.

In `@magicblock-aml/src/lib.rs`:
- Around line 43-57: `Risk::try_from_config` currently stores
`config.risk_server_url` without validation, so invalid or empty URLs only fail
later during requests. Add a parse/validation step in `try_from_config` before
constructing `Self`, and map failures to an appropriate `RiskError` so startup
fails fast. Keep the existing `Client::builder` setup and `base_url` assignment,
but ensure `RiskConfig::risk_server_url` is validated before trimming and
storing it.

In `@magicblock-chainlink/src/chainlink/errors.rs`:
- Around line 73-74: Rename the RangeRisk error variant to RiskCheckFailed in
the errors enum so it matches the new risk server naming. Update the enum
definition in the Errors/RiskError area and keep the existing #[error(...)]
message and #[from] conversion aligned with the new variant name, then fix any
references that still use RangeRisk across the Chainlink error handling code.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 1ead3eac-31fd-40bc-b762-990a70bf8305

📥 Commits

Reviewing files that changed from the base of the PR and between 4b70fd8 and 668bfd9.

⛔ Files ignored due to path filters (2)
  • Cargo.lock is excluded by !**/*.lock
  • test-integration/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (11)
  • config.example.toml
  • magicblock-aml/Cargo.toml
  • magicblock-aml/src/lib.rs
  • magicblock-api/src/magic_validator.rs
  • magicblock-chainlink/src/chainlink/errors.rs
  • magicblock-chainlink/src/chainlink/mod.rs
  • magicblock-config/src/config/chain.rs
  • magicblock-config/src/consts.rs
  • magicblock-config/src/tests.rs
  • test-integration/test-aml/src/lib.rs
  • test-integration/test-chainlink/tests/ix_aml_undelegation.rs
💤 Files with no reviewable changes (2)
  • magicblock-aml/Cargo.toml
  • magicblock-api/src/magic_validator.rs

Comment thread config.example.toml
Comment thread magicblock-aml/src/lib.rs
Comment thread magicblock-chainlink/src/chainlink/errors.rs Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
config.example.toml (1)

273-277: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Update stale documentation to match the new risk server architecture.

These comments still reference the deprecated "Range Risk API" and "Range API", which might cause confusion since the client and configuration have been updated to use a generic risk server.

📝 Proposed fix
-# Optional: Range Risk API validation for post-delegation actions signers
+# Optional: Risk server validation for post-delegation actions signers
 # ------------------------------------------------------------------------------
 # When enabled, all signers referenced by post-delegation actions are checked
-# against Range API before actions are allowed to execute.
+# against the risk server before actions are allowed to execute.
 [chainlink.risk]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@config.example.toml` around lines 273 - 277, Update the comments above the
[chainlink.risk] configuration section to replace the deprecated “Range Risk
API” and “Range API” terminology with the current generic risk server
terminology, while preserving the documented validation behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@config.example.toml`:
- Around line 273-277: Update the comments above the [chainlink.risk]
configuration section to replace the deprecated “Range Risk API” and “Range API”
terminology with the current generic risk server terminology, while preserving
the documented validation behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2110284f-dc0f-4102-8e7e-ffd82ab37cb6

📥 Commits

Reviewing files that changed from the base of the PR and between 668bfd9 and 07c49ef.

⛔ Files ignored due to path filters (2)
  • Cargo.lock is excluded by !**/*.lock
  • test-integration/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (8)
  • config.example.toml
  • magicblock-aml/src/lib.rs
  • magicblock-api/src/magic_validator.rs
  • magicblock-chainlink/src/chainlink/errors.rs
  • magicblock-chainlink/src/chainlink/mod.rs
  • magicblock-config/src/config/chain.rs
  • magicblock-config/src/consts.rs
  • magicblock-config/src/tests.rs

@Dodecahedr0x
Dodecahedr0x force-pushed the dode/external-risk-server branch from d84816f to 9e0810e Compare July 30, 2026 16:40
@Dodecahedr0x
Dodecahedr0x changed the base branch from master to engine-integration July 30, 2026 16:40
@Dodecahedr0x
Dodecahedr0x force-pushed the dode/external-risk-server branch from 9e0810e to 8bbce4c Compare August 4, 2026 15:34

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
bins/magicblock-validator/src/leader.rs (2)

474-476: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Wait for primary on-chain setup before admitting on-chain requests.

In ephemeral mode, spawn_primary_onchain_setup starts a detached task and returns immediately. Leader::start then starts UndelegationRequestService and IntentExecutionService before ensure_validator_funded_on_chain and ensure_magic_fee_vault_on_chain finish. Comments say transaction commits fail without a properly configured fee vault, so requests can fail after Leader::start reports success.

Store the setup task handle and await a readiness result, or add a cancellation token before spawn_primary_onchain_setup completes. Otherwise Leader::stop can return before the setup task is stopped, but the setup task may still submit transactions or call std::process::exit.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@bins/magicblock-validator/src/leader.rs` around lines 474 - 476, Update
Leader::start and spawn_primary_onchain_setup so ephemeral mode does not admit
on-chain requests until validator funding and the magic fee vault setup
completes successfully. Store and await the setup task’s readiness result before
starting UndelegationRequestService and IntentExecutionService, and retain a
cancellation/abort handle so Leader::stop waits for or stops the task before
returning, preventing background transaction submission or process exit.

177-189: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Make the Aperture runtime lifecycle observable to Leader.

.expect inside the spawned RPC thread turns a runtime Builder::build() error into an unobservable panic that can leave try_from_config returning a Leader without RPC. Thread cancellations at initialization and during stop detach before propagating join results; propagate runtime or join failures so the validator never starts with a failed RPC path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@bins/magicblock-validator/src/leader.rs` around lines 177 - 189, Update the
RPC thread lifecycle around rpc_handle, Leader::try_from_config, and
Leader::stop to propagate Builder::build failures as recoverable errors instead
of using expect inside the spawned thread. Ensure initialization and shutdown
join operations do not detach or discard thread cancellation/results, and
propagate runtime or join failures so try_from_config cannot return a Leader
without a functioning RPC path.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@magicblock-aml/src/lib.rs`:
- Around line 68-77: Limit request fan-out in check_addresses instead of passing
every address to try_join_all concurrently. Implement bounded concurrency or
batching for assess_address calls, preserving RiskResult error propagation and
result aggregation; alternatively use a bulk endpoint if available. If the limit
is intentionally fixed, define and document the maximum signer set, checker
concurrency, timeout behavior, and overload mitigation at the relevant
configuration/API boundary.
- Around line 50-65: The URL validation in try_from_config must prevent
unauthenticated transport for risk-decision calls: allow http:// only for
validated loopback hosts, require https:// for all other endpoints, and
configure the Client used by assess_address to reject redirects that cross
origins or downgrade from HTTPS. Preserve the existing invalid-configuration
error path and base_url normalization.

---

Outside diff comments:
In `@bins/magicblock-validator/src/leader.rs`:
- Around line 474-476: Update Leader::start and spawn_primary_onchain_setup so
ephemeral mode does not admit on-chain requests until validator funding and the
magic fee vault setup completes successfully. Store and await the setup task’s
readiness result before starting UndelegationRequestService and
IntentExecutionService, and retain a cancellation/abort handle so Leader::stop
waits for or stops the task before returning, preventing background transaction
submission or process exit.
- Around line 177-189: Update the RPC thread lifecycle around rpc_handle,
Leader::try_from_config, and Leader::stop to propagate Builder::build failures
as recoverable errors instead of using expect inside the spawned thread. Ensure
initialization and shutdown join operations do not detach or discard thread
cancellation/results, and propagate runtime or join failures so try_from_config
cannot return a Leader without a functioning RPC path.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: bf462edb-1d53-44fa-87d4-7cdd6640dc99

📥 Commits

Reviewing files that changed from the base of the PR and between 233217c and 4a3255f.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • bins/magicblock-validator/src/leader.rs
  • config.example.toml
  • magicblock-aml/Cargo.toml
  • magicblock-aml/src/lib.rs
  • magicblock-chainlink/src/chainlink/errors.rs
  • magicblock-chainlink/src/chainlink/mod.rs
  • magicblock-chainlink/tests/10_aml_undelegation.rs
  • magicblock-config/src/config/chain.rs
  • magicblock-config/src/consts.rs

Comment thread magicblock-aml/src/lib.rs
Comment thread magicblock-aml/src/lib.rs
@Dodecahedr0x
Dodecahedr0x force-pushed the dode/external-risk-server branch from 4d332ab to a7fdf3b Compare August 4, 2026 19:19

Dodecahedr0x commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Warning

This pull request is not mergeable via GitHub because a downstack PR is open. Once all requirements are satisfied, merge this PR as a stack on Graphite.
Learn more

This stack of pull requests is managed by Graphite. Learn more about stacking.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
magicblock-aml/src/lib.rs (1)

129-133: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Limit the decoded response body before deserialization.

Response::json buffers an unbounded body. One oversized response can exhaust validator memory. Concurrent address checks increase this risk.

Read at most a small configured limit before calling serde_json::from_slice. Enforce the limit on decoded bytes because compressed responses can bypass a Content-Length check.

As per coding guidelines, “Preserve critical-path performance; if degradation is unavoidable, report its reason, expected impact, and mitigation.” <coding_guidelines>

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@magicblock-aml/src/lib.rs` around lines 129 - 133, Replace the Response::json
call in the RiskAssessment request flow with bounded decoded-byte reading,
enforcing a small configured maximum after decompression before passing the
bytes to serde_json::from_slice. Preserve the existing error-for-status behavior
and propagate oversized-body or deserialization errors; document the unavoidable
buffering cost and mitigation if required by the project’s performance
guidelines.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@magicblock-aml/src/lib.rs`:
- Around line 45-64: Update validate_base_url to reject URLs containing query
strings or fragments before accepting the scheme, while preserving the existing
HTTP loopback restriction and HTTPS behavior. Add rejection coverage for both
query and fragment cases in the validation tests, including risk_server_url
inputs.

---

Outside diff comments:
In `@magicblock-aml/src/lib.rs`:
- Around line 129-133: Replace the Response::json call in the RiskAssessment
request flow with bounded decoded-byte reading, enforcing a small configured
maximum after decompression before passing the bytes to serde_json::from_slice.
Preserve the existing error-for-status behavior and propagate oversized-body or
deserialization errors; document the unavoidable buffering cost and mitigation
if required by the project’s performance guidelines.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: b938c122-11d4-42a6-bd96-f7257e301eca

📥 Commits

Reviewing files that changed from the base of the PR and between 4a3255f and 4d332ab.

⛔ Files ignored due to path filters (2)
  • Cargo.lock is excluded by !**/*.lock
  • test-integration/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • magicblock-aml/Cargo.toml
  • magicblock-aml/src/lib.rs

Comment thread magicblock-aml/src/lib.rs
@bmuddha
bmuddha changed the base branch from engine-integration to graphite-base/1407 August 4, 2026 19:51
@bmuddha
bmuddha force-pushed the dode/external-risk-server branch from a7fdf3b to 38b69b5 Compare August 4, 2026 19:57
@bmuddha
bmuddha force-pushed the dode/external-risk-server branch from f442f9a to c675855 Compare August 5, 2026 08:24
@bmuddha
bmuddha changed the base branch from dode/crank-refactor to engine-integration August 5, 2026 08:24
@Dodecahedr0x
Dodecahedr0x force-pushed the dode/external-risk-server branch 2 times, most recently from d741022 to a70bea9 Compare August 5, 2026 14:08
@bmuddha
bmuddha force-pushed the dode/external-risk-server branch 2 times, most recently from 5a60fd4 to c88d891 Compare August 5, 2026 18:32

@bmuddha bmuddha left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@bmuddha
bmuddha force-pushed the dode/external-risk-server branch 2 times, most recently from 3caebc4 to c60708a Compare August 7, 2026 18:36
@Dodecahedr0x
Dodecahedr0x force-pushed the dode/external-risk-server branch 2 times, most recently from b45f58b to c40cc22 Compare August 10, 2026 08:30
@bmuddha
bmuddha force-pushed the dode/external-risk-server branch from c40cc22 to dd316c3 Compare August 10, 2026 14:54
@Dodecahedr0x
Dodecahedr0x force-pushed the dode/external-risk-server branch 2 times, most recently from c40cc22 to 836e5f9 Compare August 11, 2026 07:47
@bmuddha
bmuddha force-pushed the dode/external-risk-server branch 2 times, most recently from 2e64b83 to 7eecffc Compare August 11, 2026 13:25
@bmuddha
bmuddha force-pushed the dode/external-risk-server branch from 7eecffc to 2292fcb Compare August 11, 2026 14:38
@Dodecahedr0x
Dodecahedr0x force-pushed the dode/external-risk-server branch from 2292fcb to 96375cd Compare August 11, 2026 22:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: use an external risk checking service

2 participants