Skip to content

feat: add GetBlockHeightTransactions grpc method#7081

Merged
SWvheerden merged 9 commits intotari-project:developmentfrom
Krakaw:krakaw-add-grpc-tx-method
May 22, 2025
Merged

feat: add GetBlockHeightTransactions grpc method#7081
SWvheerden merged 9 commits intotari-project:developmentfrom
Krakaw:krakaw-add-grpc-tx-method

Conversation

@Krakaw
Copy link
Copy Markdown
Contributor

@Krakaw Krakaw commented May 21, 2025

Description

Added a non-streaming block transactions grpc method

Motivation and Context

We needed a non-streaming block transactions grpc method

How Has This Been Tested?

Tested locally

3.0.0-pre.2
{
  transactions: [
    {
      tx_id: '13779150612046258454',
      source_address: <Buffer 02 03 a6 90 c4 93 b5 f3 0b 5a f6 cd 25 84 14 7b 1e 38 29 5d 33 0a 26 97 5c 05 06 49 a2 9f 37 28 70 4e 9e 94 3c 42 48 09 f5 78 78 57 c6 1b a5 45 1e 33 ... 17 more bytes>,
      dest_address: <Buffer 02 01 36 a6 6d 82 88 af 3d b1 5d 26 c7 2a 01 8a 00 67 cd 1d de b8 34 a4 2b f8 ba b7 1d ab a6 fe 7f 68 e8 72 a6 e7 9e b7 37 4d cd c7 7d 71 3a 51 7c 9f ... 17 more bytes>,
      status: 'TRANSACTION_STATUS_MINED_UNCONFIRMED',
      direction: 'TRANSACTION_DIRECTION_INBOUND',
      amount: '10000000',
      fee: '700',
      is_cancelled: false,
      excess_sig: <Buffer b0 47 14 a2 be 79 8b 7e d4 16 6f 4d e1 aa 08 92 1d 23 4f 36 68 2f 4a 0f 33 c2 17 10 84 55 67 0c>,
      timestamp: '1747855605',
      payment_id: <Buffer 03 80 96 98 00 00 00 00 00 00 00 00 05 80 02 03 a6 90 c4 93 b5 f3 0b 5a f6 cd 25 84 14 7b 1e 38 29 5d 33 0a 26 97 5c 05 06 49 a2 9f 37 28 70 4e 9e 94 ... 39 more bytes>,
      mined_in_block_height: '1550'
    }
  ]
}

What process can a PR reviewer use to test or verify this change?

Request a block your wallet has gotten transactions on, they should appear in the result.

Breaking Changes

  • None
  • Requires data directory on base node to be deleted
  • Requires hard fork
  • Other - Please specify

Summary by CodeRabbit

  • New Features

    • Added the ability to retrieve all wallet transactions mined at a specific block height via a new gRPC method.
    • Node.js client now supports calling the new method to fetch transactions by block height.
  • Documentation

    • Enhanced documentation for the new gRPC method, including usage examples and detailed parameter descriptions.
  • Style

    • Minor comment formatting improvements for consistency.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented May 21, 2025

Walkthrough

A new gRPC method, GetBlockHeightTransactions, was introduced to the wallet service API, enabling clients to query all wallet transactions mined at a specific block height. The method is defined in the protocol buffer, implemented server-side in Rust, and exposed to Node.js clients, with updated documentation and example usage.

Changes

File(s) Change Summary
applications/minotari_app_grpc/proto/wallet.proto Added the GetBlockHeightTransactions RPC to the Wallet service, along with new request and response messages. Enhanced documentation for the new method, provided example usage, and made minor formatting corrections to comments.
applications/minotari_console_wallet/src/grpc/wallet_grpc_server.rs Implemented the new get_block_height_transactions async method in the WalletGrpcServer, integrating it into the Wallet trait implementation. The method queries completed transactions at a given block height and returns them in the response, with appropriate logging and error handling.
clients/nodejs/wallet_grpc_client/index.js Registered the new "GetBlockHeightTransactions" method in the RPC client, updated the example usage to demonstrate calling this method.

Sequence Diagram(s)

sequenceDiagram
    participant NodeJS_Client as Node.js Client
    participant gRPC_Server as WalletGrpcServer (Rust)
    participant Wallet_Service as Wallet Service
    NodeJS_Client->>gRPC_Server: GetBlockHeightTransactions(block_height)
    gRPC_Server->>Wallet_Service: get_completed_transactions(block_height)
    Wallet_Service-->>gRPC_Server: List<Transaction>
    gRPC_Server-->>NodeJS_Client: GetBlockHeightTransactionsResponse(transactions)
Loading

Possibly related PRs

  • feat: add block height to query #7033: Extends existing GetCompletedTransactions RPC and backend to support filtering by block height, related to querying transactions by block height but via a different RPC endpoint.

Suggested reviewers

  • SWvheerden

Poem

In the warren, deep and bright,
Rabbits code with all their might.
Now you’ll find with just one call,
Transactions mined, block height and all!
From Rust to Node, the data flows,
Through gRPC, the magic grows.
🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 30th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a5b2334 and 0b85db2.

📒 Files selected for processing (2)
  • applications/minotari_console_wallet/src/grpc/wallet_grpc_server.rs (2 hunks)
  • clients/nodejs/wallet_grpc_client/index.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • clients/nodejs/wallet_grpc_client/index.js
  • applications/minotari_console_wallet/src/grpc/wallet_grpc_server.rs
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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
Copy Markdown
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

🧹 Nitpick comments (2)
clients/nodejs/wallet_grpc_client/index.js (2)

7-8: Remove debug console.log statement.

This debug statement prints the path to the proto file on every import, which is unnecessary in production code.

-const path = require("path");
-console.log(path.join(__dirname, "../../../applications/minotari_app_grpc/proto/wallet.proto"));
+const path = require("path");

94-100: Convert example code to proper test or documentation.

This self-executing function appears to be test/example code. Such code would be better placed in a separate test file or converted to a commented example.

-
-(async () => {
-    const a = Client.connect('localhost:18183');
-    const {version} = await a.getVersion();
-    console.log(version);
-    const resp = await a.GetBlockHeightTransactions({block_height: 1550});
-    console.log(resp);
-})()
+
+// Example usage:
+// (async () => {
+//     const a = Client.connect('localhost:18183');
+//     const {version} = await a.getVersion();
+//     console.log(version);
+//     const resp = await a.GetBlockHeightTransactions({block_height: 1550});
+//     console.log(resp);
+// })()
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 7ab4d16 and b07a354.

⛔ Files ignored due to path filters (1)
  • clients/nodejs/wallet_grpc_client/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • applications/minotari_app_grpc/proto/wallet.proto (5 hunks)
  • applications/minotari_console_wallet/src/grpc/wallet_grpc_server.rs (2 hunks)
  • clients/nodejs/wallet_grpc_client/index.js (3 hunks)
🔇 Additional comments (5)
applications/minotari_app_grpc/proto/wallet.proto (2)

387-435: Well-structured RPC documentation.

The documentation for the new GetBlockHeightTransactions RPC method is comprehensive and follows the established pattern in the file. It clearly explains the purpose, request parameters, restrictions, and includes a practical JavaScript example with sample response.


1407-1416: Clean message definitions.

The message definitions for GetBlockHeightTransactionsRequest and GetBlockHeightTransactionsResponse are appropriately structured and maintain consistency with the existing protocol definitions.

clients/nodejs/wallet_grpc_client/index.js (1)

53-53: LGTM - Appropriate function registration.

The new GetBlockHeightTransactions method is correctly added to the functions array.

applications/minotari_console_wallet/src/grpc/wallet_grpc_server.rs (2)

89-90: LGTM - Properly imported new message types.

The new request and response message types are correctly imported.


1032-1054: Clean and efficient transaction mapping.

The transaction mapping logic is well-implemented, correctly extracting and converting all the necessary fields from the transaction objects to their protocol buffer representation.

Comment on lines +1008 to +1058
async fn get_block_height_transactions(
&self,
request: Request<GetBlockHeightTransactionsRequest>,
) -> Result<Response<GetBlockHeightTransactionsResponse>, Status> {
let start = std::time::Instant::now();
trace!(
target: LOG_TARGET,
"GetBlockHeightTransactions: Incoming GRPC request"
);
let message = request.into_inner();
let block_height = message.block_height;

let mut transaction_service = self.get_transaction_service();
let transactions = transaction_service
.get_completed_transactions(None, None, Some(block_height))
.await
.map_err(|err| Status::not_found(format!("No transactions found at block height {}: {:?}", block_height, err)))?;
debug!(
target: LOG_TARGET,
"GetBlockHeightTransactions: Found {} transactions at block height {}",
transactions.len(),
block_height
);

let transactions = transactions
.iter()
.map(|txn| TransactionInfo {
tx_id: txn.tx_id.into(),
source_address: txn.source_address.to_vec(),
dest_address: txn.destination_address.to_vec(),
status: TransactionStatus::from(txn.status.clone()) as i32,
amount: txn.amount.into(),
is_cancelled: txn.cancelled.is_some(),
direction: TransactionDirection::from(txn.direction.clone()) as i32,
fee: txn.fee.into(),
timestamp: txn.timestamp.timestamp() as u64,
excess_sig: txn
.transaction
.first_kernel_excess_sig()
.unwrap_or(&Signature::default())
.get_signature()
.to_vec(),
payment_id: txn.payment_id.to_bytes(),
mined_in_block_height: txn.mined_height.unwrap_or(0),
})
.collect();

trace!(target: LOG_TARGET, "'get_block_height_transactions' completed in {:.2?}", start.elapsed());

Ok(Response::new(GetBlockHeightTransactionsResponse { transactions }))
}
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.

🛠️ Refactor suggestion

Consider returning an empty list instead of an error when no transactions are found.

The implementation correctly queries transactions at a specific block height, but returns a not_found error status if no transactions exist at that height. This differs from similar methods like get_completed_transactions, where an empty list would be a more appropriate response for a valid block height with no transactions.

Consider modifying line 1024 to handle the empty transaction case:

-        let transactions = transaction_service
-            .get_completed_transactions(None, None, Some(block_height))
-            .await
-            .map_err(|err| Status::not_found(format!("No transactions found at block height {}: {:?}", block_height, err)))?;
+        let transactions = match transaction_service
+            .get_completed_transactions(None, None, Some(block_height))
+            .await {
+                Ok(txns) => txns,
+                Err(err) => {
+                    debug!(
+                        target: LOG_TARGET,
+                        "No transactions found at block height {}: {:?}", block_height, err
+                    );
+                    vec![]
+                }
+            };

This approach would return an empty list of transactions rather than an error when no transactions exist at the given block height, which is more consistent with typical API behavior for list endpoints.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async fn get_block_height_transactions(
&self,
request: Request<GetBlockHeightTransactionsRequest>,
) -> Result<Response<GetBlockHeightTransactionsResponse>, Status> {
let start = std::time::Instant::now();
trace!(
target: LOG_TARGET,
"GetBlockHeightTransactions: Incoming GRPC request"
);
let message = request.into_inner();
let block_height = message.block_height;
let mut transaction_service = self.get_transaction_service();
let transactions = transaction_service
.get_completed_transactions(None, None, Some(block_height))
.await
.map_err(|err| Status::not_found(format!("No transactions found at block height {}: {:?}", block_height, err)))?;
debug!(
target: LOG_TARGET,
"GetBlockHeightTransactions: Found {} transactions at block height {}",
transactions.len(),
block_height
);
let transactions = transactions
.iter()
.map(|txn| TransactionInfo {
tx_id: txn.tx_id.into(),
source_address: txn.source_address.to_vec(),
dest_address: txn.destination_address.to_vec(),
status: TransactionStatus::from(txn.status.clone()) as i32,
amount: txn.amount.into(),
is_cancelled: txn.cancelled.is_some(),
direction: TransactionDirection::from(txn.direction.clone()) as i32,
fee: txn.fee.into(),
timestamp: txn.timestamp.timestamp() as u64,
excess_sig: txn
.transaction
.first_kernel_excess_sig()
.unwrap_or(&Signature::default())
.get_signature()
.to_vec(),
payment_id: txn.payment_id.to_bytes(),
mined_in_block_height: txn.mined_height.unwrap_or(0),
})
.collect();
trace!(target: LOG_TARGET, "'get_block_height_transactions' completed in {:.2?}", start.elapsed());
Ok(Response::new(GetBlockHeightTransactionsResponse { transactions }))
}
async fn get_block_height_transactions(
&self,
request: Request<GetBlockHeightTransactionsRequest>,
) -> Result<Response<GetBlockHeightTransactionsResponse>, Status> {
let start = std::time::Instant::now();
trace!(
target: LOG_TARGET,
"GetBlockHeightTransactions: Incoming GRPC request"
);
let message = request.into_inner();
let block_height = message.block_height;
let mut transaction_service = self.get_transaction_service();
- let transactions = transaction_service
- .get_completed_transactions(None, None, Some(block_height))
- .await
- .map_err(|err| Status::not_found(format!("No transactions found at block height {}: {:?}", block_height, err)))?;
+ let transactions = match transaction_service
+ .get_completed_transactions(None, None, Some(block_height))
+ .await
+ {
+ Ok(txns) => txns,
+ Err(err) => {
+ debug!(
+ target: LOG_TARGET,
+ "No transactions found at block height {}: {:?}", block_height, err
+ );
+ vec![]
+ }
+ };
debug!(
target: LOG_TARGET,
"GetBlockHeightTransactions: Found {} transactions at block height {}",
transactions.len(),
block_height
);
let transactions = transactions
.iter()
.map(|txn| TransactionInfo {
tx_id: txn.tx_id.into(),
source_address: txn.source_address.to_vec(),
dest_address: txn.destination_address.to_vec(),
status: TransactionStatus::from(txn.status.clone()) as i32,
amount: txn.amount.into(),
is_cancelled: txn.cancelled.is_some(),
direction: TransactionDirection::from(txn.direction.clone()) as i32,
fee: txn.fee.into(),
timestamp: txn.timestamp.timestamp() as u64,
excess_sig: txn
.transaction
.first_kernel_excess_sig()
.unwrap_or(&Signature::default())
.get_signature()
.to_vec(),
payment_id: txn.payment_id.to_bytes(),
mined_in_block_height: txn.mined_height.unwrap_or(0),
})
.collect();
trace!(target: LOG_TARGET, "'get_block_height_transactions' completed in {:.2?}", start.elapsed());
Ok(Response::new(GetBlockHeightTransactionsResponse { transactions }))
}
🤖 Prompt for AI Agents
In applications/minotari_console_wallet/src/grpc/wallet_grpc_server.rs between
lines 1008 and 1058, the current code returns a not_found error if no
transactions are found at the specified block height. Instead, modify the code
around line 1024 to check if the returned transactions list is empty and, if so,
proceed without error by returning an empty list. This means removing the
map_err that converts empty results into an error and allowing the function to
return an empty transactions vector in the response, aligning with typical API
behavior for list endpoints.

SWvheerden
SWvheerden previously approved these changes May 22, 2025
@github-actions
Copy link
Copy Markdown

Test Results (CI)

    2 files     60 suites   35m 36s ⏱️
1 093 tests 1 089 ✅ 0 💤 4 ❌
2 182 runs  2 174 ✅ 0 💤 8 ❌

For more details on these failures, see this check.

Results for commit ba078e4.

@github-actions
Copy link
Copy Markdown

Test Results (Integration tests)

 2 files  + 2  11 suites  +11   1h 47m 56s ⏱️ + 1h 47m 56s
36 tests +36  29 ✅ +29  0 💤 ±0   7 ❌ + 7 
47 runs  +47  32 ✅ +32  0 💤 ±0  15 ❌ +15 

For more details on these failures, see this check.

Results for commit ba078e4. ± Comparison against base commit 7ab4d16.

@SWvheerden SWvheerden merged commit d8fa8f3 into tari-project:development May 22, 2025
12 of 15 checks passed
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