Skip to content

Improve ApiError variants#861

Merged
3alpha merged 4 commits intomainfrom
improve-apierror-variants
Sep 24, 2025
Merged

Improve ApiError variants#861
3alpha merged 4 commits intomainfrom
improve-apierror-variants

Conversation

@3alpha
Copy link
Copy Markdown
Collaborator

@3alpha 3alpha commented Sep 24, 2025

Usage related changes

Better UX when Errors are printed out

Development related changes

Small change in ApiError enum, resolves #850.

Checklist:

  • Checked out the contribution guidelines
  • Applied formatting - ./scripts/format.sh
  • No linter errors - ./scripts/clippy_check.sh
  • No unused dependencies - ./scripts/check_unused_deps.sh
  • No spelling errors - ./scripts/check_spelling.sh
  • Performed code self-review
  • Rebased to the latest commit of the target branch (or merged it into my branch)
    • Once you make the PR reviewable, please avoid force-pushing
  • Updated the docs if needed - ./website/README.md
  • Linked the issues resolvable by this PR - linking info
  • Updated the tests if needed; all passing - execution info

Summary by CodeRabbit

  • Bug Fixes
    • Improved error messages for invalid addresses across relevant endpoints.
  • Refactor
    • Simplified token address handling to reduce unnecessary failures and streamline balance/mint flows.
    • Removed an unused public constant from the types package to reduce API surface.
  • Tests
    • Added coverage to ensure address construction behaves consistently.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Sep 24, 2025

Walkthrough

The PR reorders ERC20 address constants in starknet-devnet-core. In starknet-devnet-types, it removes PREFIX_INVOKE and adds unchecked constructors: PatriciaKey::new_unchecked and ContractAddress::new_unchecked. In starknet-devnet-server, it replaces get_erc20_address (Result-returning) with get_erc20_fee_unit_address (direct value), updates callers in read/write endpoints, and adjusts error handling. ApiError removes GeneralError, renames InvalidValueError to InvalidAddress, and updates mappings accordingly. Balance and mint paths now use direct ERC20 address construction without fallible conversion. Unit tests validate ContractAddress::new vs new_unchecked for ETH/STRK addresses.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Out of Scope Changes Check ⚠️ Warning The PR contains edits that appear unrelated to the linked issue, notably the removal of the public constant PREFIX_INVOKE and the repositioning of ERC20 address constants in constants.rs, which are not documented in the description and could change the public API surface or break external callers. Either remove or explicitly document these constant changes and, if they are intentional breaking changes, split them into a separate PR with rationale, compatibility notes, and updated references/tests before merging this error-variant-focused change.
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Improve ApiError variants" is concise, single-sentence, and accurately reflects the primary change in the PR (refactoring ApiError variants and related error handling), making it clear to reviewers and maintainers.
Linked Issues Check ✅ Passed The changes address the objectives in [#850]: GeneralError was removed and InvalidValueError was replaced with a more specific InvalidAddress variant, get_erc20_address was made non-fallible by introducing get_erc20_fee_unit_address and unchecked constructors in the types crate, and api_error_to_rpc_error/is_forwardable_to_origin were updated accordingly, with tests added to validate the new constructors.
Description Check ✅ Passed The PR description follows the repository template by providing "Usage related changes" and "Development related changes", references issue #850, and includes a completed checklist with formatting/lint/tests noted, so it gives sufficient context for reviewers.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch improve-apierror-variants

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.

@3alpha 3alpha requested a review from FabijanC September 24, 2025 07:53
@3alpha
Copy link
Copy Markdown
Collaborator Author

3alpha commented Sep 24, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Sep 24, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@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

🧹 Nitpick comments (4)
crates/starknet-devnet-types/src/patricia_key.rs (1)

22-23: Guard the unchecked constructor with a debug assertion and add a safety note.

Helps catch accidental out-of-range uses in dev builds and documents the invariant.

 impl PatriciaKey {
@@
-        Ok(Self(felt))
+        Ok(Self(felt))
     }
 
-    pub(crate) fn new_unchecked(felt: Felt) -> Self {
-        Self(felt)
+    /// Constructs without range checks.
+    /// Safety: `felt` must be in [0x0, PATRICIA_KEY_UPPER_BOUND).
+    pub(crate) fn new_unchecked(felt: Felt) -> Self {
+        debug_assert!(
+            Felt::from_hex_unchecked(PATRICIA_KEY_UPPER_BOUND) >= felt,
+            "PatriciaKey out of range"
+        );
+        Self(felt)
     }

Also applies to: 25-26

crates/starknet-devnet-types/src/rpc/contract_address.rs (1)

20-22: Document the unchecked constructor.

Clarify caller responsibility to maintain invariants.

-    pub fn new_unchecked(felt: Felt) -> Self {
+    /// Constructs a ContractAddress without range checks.
+    /// Safety: `felt` must satisfy PatriciaKey bounds.
+    pub fn new_unchecked(felt: Felt) -> Self {
         Self(PatriciaKey::new_unchecked(felt))
     }
crates/starknet-devnet-server/src/api/error.rs (1)

87-89: Confirm UX choice for InvalidAddress message.

Mapping returns only the inner msg (without the "Invalid address:" prefix). If intentional for cleaner client messages, keep as is; otherwise switch to error_message for consistency with other variants.

Would you like a small unit test asserting the RPC mapping for InvalidAddress? I can add one similar to existing tests.

Also applies to: 287-291

crates/starknet-devnet-server/src/api/account_helpers.rs (1)

60-65: Good switch to non-fallible ERC20 helper and validating tests.

  • Helper now clearly reflects deterministic mapping of FeeUnit -> ERC20 address.
  • Tests ensure constants remain in range for both checked/unchecked paths.

Optional: add doc comment on get_erc20_fee_unit_address noting it relies on canonical, compile-time constants.

Also applies to: 72-76, 80-105

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d7cf606 and 04e2b7f.

📒 Files selected for processing (8)
  • crates/starknet-devnet-core/src/constants.rs (1 hunks)
  • crates/starknet-devnet-server/src/api/account_helpers.rs (1 hunks)
  • crates/starknet-devnet-server/src/api/endpoints.rs (3 hunks)
  • crates/starknet-devnet-server/src/api/error.rs (4 hunks)
  • crates/starknet-devnet-server/src/api/write_endpoints.rs (2 hunks)
  • crates/starknet-devnet-types/src/constants.rs (0 hunks)
  • crates/starknet-devnet-types/src/patricia_key.rs (1 hunks)
  • crates/starknet-devnet-types/src/rpc/contract_address.rs (1 hunks)
💤 Files with no reviewable changes (1)
  • crates/starknet-devnet-types/src/constants.rs
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: FabijanC
PR: 0xSpaceShard/starknet-devnet#799
File: crates/starknet-devnet-core/src/starknet/mod.rs:240-246
Timestamp: 2025-06-16T07:35:24.725Z
Learning: In the Starknet devnet codebase, `get_class_hash_at` has different behaviors at different layers: at the internal state level (blockifier), it returns `Ok(ClassHash(Felt::ZERO))` for undeployed addresses, while at the RPC layer, this gets converted to `Err(Error::ContractNotFound)`. When checking if a contract is deployed at the internal state level, use `is_ok_and(|h| h.0 == Felt::ZERO)` to detect undeployed addresses.
📚 Learning: 2025-06-16T07:35:24.725Z
Learnt from: FabijanC
PR: 0xSpaceShard/starknet-devnet#799
File: crates/starknet-devnet-core/src/starknet/mod.rs:240-246
Timestamp: 2025-06-16T07:35:24.725Z
Learning: In the Starknet devnet codebase, `get_class_hash_at` has different behaviors at different layers: at the internal state level (blockifier), it returns `Ok(ClassHash(Felt::ZERO))` for undeployed addresses, while at the RPC layer, this gets converted to `Err(Error::ContractNotFound)`. When checking if a contract is deployed at the internal state level, use `is_ok_and(|h| h.0 == Felt::ZERO)` to detect undeployed addresses.

Applied to files:

  • crates/starknet-devnet-types/src/rpc/contract_address.rs
  • crates/starknet-devnet-core/src/constants.rs
🔇 Additional comments (4)
crates/starknet-devnet-core/src/constants.rs (1)

34-35: LGTM on constant reordering.

No functional change; consistent with intent to group ERC20 symbols.

Also applies to: 43-44

crates/starknet-devnet-server/src/api/write_endpoints.rs (1)

20-21: Mint path simplification looks good.

Using a non-fallible ERC20 address for known fee units removes unnecessary error plumbing.

Also applies to: 313-314

crates/starknet-devnet-server/src/api/error.rs (1)

302-302: Forwardability classification is appropriate.

Keeping InvalidAddress non-forwardable aligns with local validation semantics.

Also applies to: 330-331

crates/starknet-devnet-server/src/api/endpoints.rs (1)

22-24: Address parsing and ERC20 helper updates look correct.

  • Properly maps parse errors to InvalidAddress.
  • Uses the non-fallible ERC20 address helper.
  • Error propagation for get_balance stays intact.

Also applies to: 680-684, 692-693

@3alpha 3alpha merged commit 8524f8b into main Sep 24, 2025
2 checks passed
@3alpha 3alpha deleted the improve-apierror-variants branch September 24, 2025 10:18
@3alpha 3alpha added enhancement New feature or request maintenance and removed enhancement New feature or request labels Oct 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Too generic error variants

2 participants