Skip to content

fix(billing): refactor billing signing client#1771

Merged
baktun14 merged 4 commits intomainfrom
fix/account-null
Aug 4, 2025
Merged

fix(billing): refactor billing signing client#1771
baktun14 merged 4 commits intomainfrom
fix/account-null

Conversation

@baktun14
Copy link
Contributor

@baktun14 baktun14 commented Aug 3, 2025

#1752

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Improved performance and consistency by introducing caching for account address and account information during transaction signing and execution.
    • Added a new method to execute transaction batches with enhanced handling.
    • Enhanced error handling and logging for transaction batch execution.
  • Bug Fixes

    • Reduced redundant blockchain calls by centralizing account data management.
  • Other Improvements

    • Minor updates to fee estimation and transaction simulation for reliability.

@baktun14 baktun14 marked this pull request as ready for review August 3, 2025 22:19
@baktun14 baktun14 requested a review from a team as a code owner August 3, 2025 22:19
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 3, 2025

Walkthrough

The BatchSigningClientService now implements caching and promise-based lazy initialization for the wallet's first address and account info, including address, account number, and sequence. It replaces direct fetching with concurrency-safe cache retrieval, updates sequence handling, and refines transaction execution and error handling to leverage cached data and the DataLoader.

Changes

Cohort / File(s) Change Summary
BatchSigningClientService Caching & Transaction Execution Refactor
apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.ts
Added caching and promise-based lazy initialization for wallet address and account info; extended ShortAccountInfo with address; replaced updateAccountInfo with cache management methods; updated transaction signing, simulation, and error handling to use cached data and DataLoader; added public executeTx method.
BatchSigningClientService Test Enhancements
apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.spec.ts
Added tests verifying caching behavior, concurrency control, error handling, and sequence increment logic for cached first address and account info retrieval methods; ensured proper cache clearing and error propagation under concurrent and failure scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant BatchSigningClientService
    participant BlockchainClient

    Client->>BatchSigningClientService: executeTx(messages, options)
    BatchSigningClientService->>BatchSigningClientService: getCachedFirstAddress()
    alt Cache miss
        BatchSigningClientService->>BlockchainClient: fetchFirstAddress()
        BlockchainClient-->>BatchSigningClientService: address
        BatchSigningClientService->>BatchSigningClientService: cache address
    end
    BatchSigningClientService->>BatchSigningClientService: getCachedAccountInfo()
    alt Cache miss
        BatchSigningClientService->>BlockchainClient: fetchAccountInfo(address)
        BlockchainClient-->>BatchSigningClientService: accountInfo
        BatchSigningClientService->>BatchSigningClientService: cache accountInfo
    end
    BatchSigningClientService->>BlockchainClient: signAndBroadcast(messages, accountInfo)
    BlockchainClient-->>BatchSigningClientService: txResult
    BatchSigningClientService->>BatchSigningClientService: incrementSequence()
    BatchSigningClientService-->>Client: txResult
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

In the warren, cache is king,
No more fetching every thing!
Addresses stored, sequences tracked,
On every hop, the code’s more packed.
With bouncy paws, I sign and send,
Efficient now, from end to end!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 191667c and f7fbe9d.

📒 Files selected for processing (1)
  • apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.spec.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.spec.ts
⏰ 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). (2)
  • GitHub Check: validate / validate-app
  • GitHub Check: test-build
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/account-null

🪧 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.
  • 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.

Support

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

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 generate unit tests to generate unit tests for 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
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

🧹 Nitpick comments (1)
apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.ts (1)

129-131: Consider also clearing the cached address for consistency.

While the current implementation is correct, consider clearing both caches together to ensure complete cache invalidation:

   private clearCachedAccountInfo(): void {
     this.cachedAccountInfo = undefined;
+    this.cachedFirstAddress = undefined;
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7de2437 and 733587e.

📒 Files selected for processing (1)
  • apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.ts (7 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/general.mdc)

Never use type any or cast to type any. Always define the proper TypeScript types.

Files:

  • apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.ts
**/*.{js,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/general.mdc)

**/*.{js,ts,tsx}: Never use deprecated methods from libraries.
Don't add unnecessary comments to the code

Files:

  • apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.ts
⏰ 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). (2)
  • GitHub Check: validate / validate-app
  • GitHub Check: test-build
🔇 Additional comments (8)
apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.ts (8)

18-22: LGTM! Good addition to the interface.

Adding the address field to ShortAccountInfo improves data cohesion by keeping all account-related information together.


44-46: LGTM! Well-structured cache properties.

The optional private properties for caching address and account info are appropriately typed and encapsulated.


66-68: LGTM! Clean implementation of pending transaction check.

The getter provides a clear interface to check for pending transactions using the existing semaphore.


70-76: LGTM! Clean transaction execution with proper error handling.

The method correctly uses the DataLoader for batching and includes appropriate error handling with a clear error message.


123-127: LGTM! Safe sequence increment with proper null check.

The method correctly checks for cached account info before incrementing and is protected by the semaphore during batch execution.


146-148: LGTM! Proper cache invalidation on sequence mismatch.

The implementation correctly clears the cached account info when a sequence mismatch occurs and uses the appropriate getter for logging the address.


167-180: LGTM! Efficient use of cached account info.

The implementation properly uses cached account information for signing transactions and correctly increments the sequence after each sign operation. The safe navigation for the granter property prevents potential runtime errors.


218-220: LGTM! Consistent use of address caching.

The simulate method now properly uses the cached address, maintaining consistency with the caching approach throughout the service.

stalniy
stalniy previously approved these changes Aug 4, 2025
Copy link
Contributor

@stalniy stalniy left a comment

Choose a reason for hiding this comment

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

Nice! short an clean, I like it 👍

@codecov
Copy link

codecov bot commented Aug 4, 2025

Codecov Report

❌ Patch coverage is 96.07843% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 42.23%. Comparing base (9b05a7c) to head (f7fbe9d).
⚠️ Report is 2 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
...tch-signing-client/batch-signing-client.service.ts 96.07% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1771      +/-   ##
==========================================
- Coverage   42.45%   42.23%   -0.23%     
==========================================
  Files         934      929       -5     
  Lines       26273    26131     -142     
  Branches     6990     6981       -9     
==========================================
- Hits        11154    11036     -118     
+ Misses      13952    13928      -24     
  Partials     1167     1167              
Flag Coverage Δ *Carryforward flag
api 81.11% <96.07%> (+0.05%) ⬆️
deploy-web 20.95% <ø> (ø) Carriedforward from 191667c
log-collector ?
notifications 87.25% <ø> (ø) Carriedforward from 191667c
provider-console 80.95% <ø> (ø) Carriedforward from 191667c
provider-proxy 84.75% <ø> (ø) Carriedforward from 191667c

*This pull request uses carry forward flags. Click here to find out more.

Files with missing lines Coverage Δ
...tch-signing-client/batch-signing-client.service.ts 90.90% <96.07%> (+2.24%) ⬆️

... and 6 files with indirect coverage changes

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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 4a60d7a and 191667c.

📒 Files selected for processing (1)
  • apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.spec.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/no-jest-mock.mdc)

Don't use jest.mock() to mock dependencies in test files. Instead, use jest-mock-extended to create mocks and pass mocks as dependencies to the service under test.

**/*.spec.{ts,tsx}: Use setup function instead of beforeEach in test files
setup function must be at the bottom of the root describe block in test files
setup function creates an object under test and returns it
setup function should accept a single parameter with inline type definition
Don't use shared state in setup function
Don't specify return type of setup function

Files:

  • apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.spec.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/general.mdc)

Never use type any or cast to type any. Always define the proper TypeScript types.

Files:

  • apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.spec.ts
**/*.{js,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/general.mdc)

**/*.{js,ts,tsx}: Never use deprecated methods from libraries.
Don't add unnecessary comments to the code

Files:

  • apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.spec.ts
🧠 Learnings (4)
📓 Common learnings
Learnt from: baktun14
PR: akash-network/console#1725
File: apps/api/src/utils/constants.ts:5-5
Timestamp: 2025-07-24T17:00:52.361Z
Learning: In the Akash Network Console project, when cross-cutting concerns or broader refactoring issues are identified during PR review, the preferred approach is to create a separate GitHub issue to track the work rather than expanding the scope of the current PR. This maintains focus and allows for proper planning of architectural improvements.
📚 Learning: applies to **/*.spec.{ts,tsx} : don't use `jest.mock()` to mock dependencies in test files. instead,...
Learnt from: CR
PR: akash-network/console#0
File: .cursor/rules/no-jest-mock.mdc:0-0
Timestamp: 2025-07-21T08:24:24.269Z
Learning: Applies to **/*.spec.{ts,tsx} : Don't use `jest.mock()` to mock dependencies in test files. Instead, use `jest-mock-extended` to create mocks and pass mocks as dependencies to the service under test.

Applied to files:

  • apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.spec.ts
📚 Learning: the getprovidershosturibyattributes method in apps/api/src/provider/repositories/provider/provider.r...
Learnt from: stalniy
PR: akash-network/console#1436
File: apps/api/src/provider/repositories/provider/provider.repository.ts:79-90
Timestamp: 2025-06-08T03:07:13.871Z
Learning: The getProvidersHostUriByAttributes method in apps/api/src/provider/repositories/provider/provider.repository.ts already has comprehensive test coverage in provider.repository.spec.ts, including tests for complex HAVING clause logic with COUNT(*) FILTER (WHERE ...) syntax, signature conditions (anyOf/allOf), and glob pattern matching.

Applied to files:

  • apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.spec.ts
📚 Learning: applies to **/*.spec.{ts,tsx} : don't use shared state in `setup` function...
Learnt from: CR
PR: akash-network/console#0
File: .cursor/rules/setup-instead-of-before-each.mdc:0-0
Timestamp: 2025-07-21T08:25:07.474Z
Learning: Applies to **/*.spec.{ts,tsx} : Don't use shared state in `setup` function

Applied to files:

  • apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.spec.ts
⏰ 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). (2)
  • GitHub Check: validate / validate-app
  • GitHub Check: test-build
🔇 Additional comments (9)
apps/api/src/billing/lib/batch-signing-client/batch-signing-client.service.spec.ts (9)

31-48: LGTM! Well-structured concurrency test.

This test effectively validates that concurrent calls to getCachedFirstAddress() share the same underlying promise and prevent race conditions. The use of setTimeout to control promise resolution timing is appropriate for testing concurrent behavior.


50-61: LGTM! Clean caching validation test.

This test clearly demonstrates that the first address is cached after the initial call, preventing redundant wallet operations.


98-112: LGTM! Proper account info caching validation.

This test effectively verifies that account information is cached and reused on subsequent calls.


114-124: LGTM! Cache clearing functionality well-tested.

This test properly validates that the cache clearing mechanism works as expected, forcing fresh data retrieval.


126-139: LGTM! Sequence increment logic properly tested.

This test thoroughly validates the sequence increment functionality, ensuring correct transaction ordering behavior.


141-151: LGTM! Proper error handling and retry logic tested.

This test effectively validates that failed promise caches are cleared, allowing for proper retry behavior when address fetching fails.


153-163: LGTM! Account info error handling properly tested.

This test validates that account info fetching errors are handled correctly with proper cache clearing and retry behavior.


165-173: LGTM! Account not found scenario properly handled.

This test validates the specific case when an account doesn't exist, ensuring a descriptive error message is provided for better debugging.


175-229: LGTM! Setup function follows coding guidelines.

The setup function is properly positioned at the bottom of the describe block, uses jest-mock-extended for mocking as required, and maintains no shared state between tests.

@baktun14 baktun14 merged commit 5982d52 into main Aug 4, 2025
62 checks passed
@baktun14 baktun14 deleted the fix/account-null branch August 4, 2025 17:02
stalniy pushed a commit that referenced this pull request Nov 20, 2025
* fix(billing): refactor billing signing client

* fix(billing): race condition fix

* fix(billing): add tests

* fix(billing): pr fix
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

Comments