Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getBalance implementation #12

Merged
merged 3 commits into from
Feb 6, 2025
Merged

getBalance implementation #12

merged 3 commits into from
Feb 6, 2025

Conversation

Dodecahedr0x
Copy link
Contributor

@Dodecahedr0x Dodecahedr0x commented Feb 5, 2025

Uses getAccountInfo to potentially reuse the account fetching logic

Summary by CodeRabbit

  • New Features

    • Enhanced balance retrieval capability with improved asynchronous handling in the primary account interface.
    • Marked several RPC methods as completed, indicating full support for getMinimumBalanceForRentExemption, getBalance, and requestAirdrop.
  • Refactor

    • Reorganized account methods for improved clarity in querying operations, including updates to the get_block_commitment method.
  • Chores

    • Removed the previous implementation of the get_block_commitment method to streamline the interface.

Copy link

coderabbitai bot commented Feb 5, 2025

Walkthrough

The changes refactor the RPC interface by removing the existing get_block_commitment method from the AccountsData trait and adding a new version of the same method, which is now unimplemented but retains its signature. Additionally, the get_balance method in the Minimal RPC trait has been updated to support asynchronous operations, changing its return type to BoxFuture<Result<RpcResponse<u64>>>. The README.md file has been updated to reflect the completion status of several RPC methods.

Changes

File Path Change Summary
crates/core/src/rpc/accounts_data.rs - Removed the existing get_block_commitment method from the AccountsData trait.
- Added a new get_block_commitment method with the same signature, marked as unimplemented, and positioned after get_multiple_accounts.
- Added #[rpc(meta, name = "getBlockCommitment")] attribute.
crates/core/src/rpc/minimal.rs - Updated the get_balance method signature in the Minimal RPC trait to return BoxFuture<Result<RpcResponse<u64>>>.
- Renamed parameter config to _config.
- Altered the implementation to incorporate asynchronous error handling and response construction.
README.md - Marked getMinimumBalanceForRentExemption, getBalance, and requestAirdrop methods as completed in the "RPC Support" section.

Possibly related PRs

  • feat: introduce accounts_data trait #6: The changes in the main PR directly modify the get_block_commitment method within the AccountsData trait, which is also defined in the retrieved PR, indicating a strong connection between the two.

Suggested reviewers

  • lgalabru

Poem

I'm the rabbit coding under moonlight,
Hopping through traits and methods just right.
New blocks committed with a swift little hop,
While balances change, and old methods stop.
In lines of code where futures take flight,
I munch on carrots, celebrating change tonight!
🐇✨

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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 (1)
crates/core/src/rpc/accounts_data.rs (1)

144-165: Consider optimizing the balance retrieval implementation.

The current implementation has several areas for improvement:

  1. Error handling could be more specific rather than using map_or(0, |account| account.lamports)
  2. RpcAccountInfoConfig::default() creates an unnecessary allocation
  3. Fetching full account data when only lamports are needed may impact performance

Consider this optimized implementation:

     fn get_balance(
         &self,
         meta: Self::Metadata,
         pubkey_str: String,
         _config: Option<RpcContextConfig>,
     ) -> BoxFuture<Result<RpcResponse<u64>>> {
         let absolute_slot = match meta.get_state() {
             Ok(s) => s.epoch_info.absolute_slot,
             Err(e) => return Box::pin(future::err(e.into())),
         };
-        let account =
-            self.get_account_info(meta, pubkey_str, Some(RpcAccountInfoConfig::default()));
+        let pubkey = match verify_pubkey(&pubkey_str) {
+            Ok(pk) => pk,
+            Err(e) => return Box::pin(future::err(e)),
+        };
+        
+        let state_reader = match meta.get_state() {
+            Ok(res) => res,
+            Err(e) => return Box::pin(future::err(e.into())),
+        };
+        
+        let lamports = state_reader.svm.get_account(&pubkey)
+            .map(|acc| acc.lamports)
+            .unwrap_or(0);
+        
+        let rpc_client = state_reader.rpc_client.clone();
+        drop(state_reader);

         Box::pin(async move {
-            let lamports = account.await?.value.map_or(0, |account| account.lamports);
+            let lamports = if lamports == 0 {
+                // Only fetch from RPC if not found locally
+                rpc_client.get_account(&pubkey).await
+                    .map(|acc| acc.lamports)
+                    .unwrap_or(0)
+            } else {
+                lamports
+            };

             Ok(RpcResponse {
                 context: RpcResponseContext::new(absolute_slot),
                 value: lamports,
             })
         })
     }

This optimization:

  1. Avoids fetching full account data when only lamports are needed
  2. Provides clearer error handling
  3. Reduces unnecessary allocations
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ae005a8 and 96ecfc1.

📒 Files selected for processing (2)
  • crates/core/src/rpc/accounts_data.rs (4 hunks)
  • crates/core/src/rpc/minimal.rs (0 hunks)
💤 Files with no reviewable changes (1)
  • crates/core/src/rpc/minimal.rs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: run_cargo_checks
  • GitHub Check: build
🔇 Additional comments (2)
crates/core/src/rpc/accounts_data.rs (2)

12-12: LGTM!

The addition of RpcContextConfig import is appropriate for the new balance retrieval functionality.


33-39: LGTM!

The get_balance trait method is well-defined with appropriate parameters and return type. The use of RpcContextConfig allows for future extensibility.

@@ -23,14 +23,6 @@ use solana_sdk::{
pub trait Minimal {
type Metadata;

#[rpc(meta, name = "getBalance")]
fn get_balance(
Copy link
Member

Choose a reason for hiding this comment

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

The shape of these traits are coming from the canonical implementation.
I personally don't necessarily agree with the way they've been designed, but I think staying consistent with the canonical design would help us maintaining this set of methods.
Could we please keep the get_balance implementation in the Minimal trait?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sure, I wasn't aware of the canonical design and did that because I wanted to reuse the implementation from accounts data. Ideally there should be a trait implemented by the run loop that fetches and updates local accounts if they are missing but I was facing ownership issues.

Could you point me to the official design please?

Copy link

@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 (1)
README.md (1)

59-63: Fix markdown list indentation.

The list items have inconsistent indentation. They should be indented by 4 spaces to match the parent list's style.

-        - [x] getMinimumBalanceForRentExemption
-        - [x] getBalance
         - [ ] simulateTransaction
         - [ ] getTransaction
-        - [x] requestAirdrop
+    - [x] getMinimumBalanceForRentExemption
+    - [x] getBalance
     - [ ] simulateTransaction
     - [ ] getTransaction
+    - [x] requestAirdrop
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

59-59: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)


60-60: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)


61-61: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)


62-62: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)


63-63: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 96ecfc1 and 0980c44.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • crates/core/src/rpc/accounts_data.rs (1 hunks)
  • crates/core/src/rpc/minimal.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/core/src/rpc/accounts_data.rs
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
README.md

59-59: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)


60-60: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)


61-61: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)


62-62: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)


63-63: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: run_cargo_checks
🔇 Additional comments (2)
crates/core/src/rpc/minimal.rs (2)

27-32: LGTM! The async conversion looks good.

The change to return BoxFuture is appropriate for potentially long-running operations like account fetching.

Consider documenting why the config parameter is currently unused:

-        _config: Option<RpcContextConfig>,
+        _config: Option<RpcContextConfig>, // TODO: implement commitment level support
✅ Verification successful

Async conversion and parameter documentation are appropriately handled.

  • The conversion to a BoxFuture is suitable for long-running operations.
  • The underscore prefix on _config correctly indicates that the parameter is currently unused.
  • As suggested, adding a comment (e.g., // TODO: implement commitment level support) to explain why _config is unused would improve clarity.

97-146: Verify error handling in account fetching logic.

The account fetching logic might silently ignore RPC errors by using .ok(). Consider propagating these errors for better error handling.

-                if let Some(fetched_account) = rpc_client.get_account(&pubkey).await.ok() {
+                match rpc_client.get_account(&pubkey).await {
+                    Ok(fetched_account) => {
                         let mut state_reader = meta.get_state_mut()?;
                         state_reader
                             .svm
                             .set_account(pubkey, fetched_account.clone())
                             .map_err(|err| {
                                 Error::invalid_params(format!(
                                     "failed to save fetched account {pubkey:?}: {err:?}"
                                 ))
                             })?;
 
                         Some(fetched_account)
-                } else {
+                    }
+                    Err(err) => {
+                        return Err(Error::invalid_params(format!(
+                            "failed to fetch account {pubkey:?}: {err:?}"
+                        )));
+                    }
+                }

Copy link
Member

@lgalabru lgalabru left a comment

Choose a reason for hiding this comment

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

Love it! Thank you @Dodecahedr0x!!

@lgalabru lgalabru merged commit 54fe993 into main Feb 6, 2025
3 checks passed
@lgalabru lgalabru deleted the feat/getBalance branch February 6, 2025 19:23
Dodecahedr0x added a commit that referenced this pull request Feb 8, 2025
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.

2 participants