Skip to content

Conversation

jzsfkzm
Copy link
Contributor

@jzsfkzm jzsfkzm commented Aug 27, 2025

closes #1841

Summary by CodeRabbit

  • New Features

    • Zero-amount balance reservations are allowed and now return 0.
  • Bug Fixes

    • Negative reservation requests now produce a clear "Invalid amount" error instead of "Insufficient balance".
    • Reservations for positive amounts now reserve up to the available balance and return the reserved amount.
  • Tests

    • Added tests covering zero and negative reservation cases and updated coverage for clarified behavior.

@jzsfkzm jzsfkzm requested a review from a team as a code owner August 27, 2025 10:06
Copy link

coderabbitai bot commented Aug 27, 2025

Walkthrough

Updates CachedBalance.reserveSufficientAmount to validate inputs: negative amounts now throw "Invalid amount"; zero returns 0. Positive amounts reserve up to available balance via Math.min, decrementing the cached value. Unit tests split zero and negative cases.

Changes

Cohort / File(s) Summary
Service logic: cached balance reservation
apps/api/src/deployment/services/cached-balance/cached-balance.service.ts
Added input validation: negative desiredAmount throws "Invalid amount"; zero returns 0. Refactored reservation to compute reservedAmount = Math.min(desiredAmount, this.value), decrement internal balance, and return the reserved amount.
Unit tests for reservation behavior
apps/api/src/deployment/services/cached-balance/cached-balance.service.spec.ts
Split combined test into two: one asserting reserveSufficientAmount(0) returns 0; another asserting reserveSufficientAmount(-100) throws "Invalid amount". Existing over-reservation tests unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant CB as CachedBalance

  Caller->>CB: reserveSufficientAmount(desiredAmount)
  alt desiredAmount < 0
    CB-->>Caller: throw Error("Invalid amount")
  else desiredAmount == 0
    CB-->>Caller: return 0
  else desiredAmount > 0
    CB->>CB: reserved = Math.min(desiredAmount, value)
    CB->>CB: value -= reserved
    CB-->>Caller: return reserved
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Assessment against linked issues

Objective Addressed Explanation
Fix CachedBalance throwing "Insufficient balance" during top-up flow when amount should not cause an error (#1841)

Poem

I nibbled numbers, found a sneaky zero,
It hopped right through without a woe or furrow.
Negatives shooed with a firm little thump,
Reserves now settle—no more clumsy bump.
I wiggle my ears and tap my foot—huzzah! 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 56fe101 and 347c02b.

📒 Files selected for processing (2)
  • apps/api/src/deployment/services/cached-balance/cached-balance.service.spec.ts (1 hunks)
  • apps/api/src/deployment/services/cached-balance/cached-balance.service.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/api/src/deployment/services/cached-balance/cached-balance.service.spec.ts
  • apps/api/src/deployment/services/cached-balance/cached-balance.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
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • 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.
  • 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 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/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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 (5)
apps/api/src/deployment/services/cached-balance/cached-balance.service.ts (2)

9-11: Good validation; add non-finite guard + explicit zero fast-path

Covers negatives. Consider rejecting NaN/Infinity and explicitly returning early for zero to make intent unambiguous.

   public reserveSufficientAmount(desiredAmount: number) {
-    if (desiredAmount < 0) {
+    if (!Number.isFinite(desiredAmount)) {
+      throw new Error(`Invalid amount: ${desiredAmount}`);
+    }
+    if (desiredAmount < 0) {
       throw new Error(`Invalid amount: ${desiredAmount}`);
     }
+    if (desiredAmount === 0) {
+      return 0;
+    }

26-36: Unbounded address cache could grow indefinitely

If many distinct addresses are touched, Map may retain entries for the process lifetime. Consider TTL/LRU eviction or an explicit invalidate API (e.g., after successful top-up).

apps/api/src/deployment/services/cached-balance/cached-balance.service.spec.ts (3)

67-72: Zero-amount case covered—nice

Test captures the new contract. Optionally, add a follow-up reserve to assert balance remains untouched by zero reservation.

   const amount = balance.reserveSufficientAmount(0);
   expect(amount).toBe(0);
+  const next = balance.reserveSufficientAmount(1000);
+  expect(next).toBe(1000);

74-78: Negative amount case aligned with new error

Prefer regex match to avoid coupling to full message text.

-expect(() => balance.reserveSufficientAmount(-100)).toThrow("Invalid amount");
+expect(() => balance.reserveSufficientAmount(-100)).toThrow(/Invalid amount/);

10-16: Refactor tests to repository guidelines (setup function + jest-mock-extended, no shared state)

Current tests use beforeEach and manual jest.fn mocks. The repo guidelines require a setup() at the bottom of the root describe, no shared state, and using jest-mock-extended.

Example rewrite sketch (key parts only):

import { mockDeep } from "jest-mock-extended";

describe(CachedBalanceService.name, () => {
  describe("get", () => {
    it("should fetch and cache balance for new address", async () => {
      const { service, balancesService, address } = setup({ deploymentLimit: 1000 });
      // ...
    });

    // other its...
    
    function setup({ deploymentLimit = 1000 }: { deploymentLimit?: number }) {
      const balancesService = mockDeep<BalancesService>();
      balancesService.getFreshLimits.mockResolvedValue({
        deployment: deploymentLimit,
        fee: 100
      });

      const service = new CachedBalanceService(balancesService);
      const address = createAkashAddress();
      return { service, balancesService, address };
    }
  });
});

Additionally, for consistency you can update other string-based toThrow usages (e.g., Line 57) to regex: /Insufficient balance/.

Also applies to: 22-27

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e4ab7c9 and 56fe101.

📒 Files selected for processing (2)
  • apps/api/src/deployment/services/cached-balance/cached-balance.service.spec.ts (1 hunks)
  • apps/api/src/deployment/services/cached-balance/cached-balance.service.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/deployment/services/cached-balance/cached-balance.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/deployment/services/cached-balance/cached-balance.service.spec.ts
  • apps/api/src/deployment/services/cached-balance/cached-balance.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/deployment/services/cached-balance/cached-balance.service.spec.ts
  • apps/api/src/deployment/services/cached-balance/cached-balance.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 (2)
apps/api/src/deployment/services/cached-balance/cached-balance.service.ts (2)

13-15: Insufficient-at-zero behavior is consistent with tests

Throwing only when balance is exactly 0 preserves prior semantics while allowing partial reservation otherwise. LGTM.


17-20: Reserve-up-to logic looks correct

Math.min with in-place decrement prevents negatives and returns the actual reserved amount. LGTM.

@jzsfkzm jzsfkzm force-pushed the bugfixes/1841-reserve-zero branch from 56fe101 to 347c02b Compare August 27, 2025 13:12

public reserveSufficientAmount(desiredAmount: number) {
const value = Math.min(desiredAmount, this.value);
if (desiredAmount < 0) {
Copy link
Contributor

Choose a reason for hiding this comment

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

We should investigate a little further as to why there are negative amounts. It seems to be coming from this

return Math.floor(deployment.blockRate * (averageBlockCountInAnHour * this.config.get("AUTO_TOP_UP_DEPLOYMENT_INTERVAL_IN_H")));

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@baktun14 ok, let's put this PR aside while we check logs, I added a few lines of logging in this other PR. I suppose problem is with deployment.blockRate, as the other two factors of that product are constants.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

My change in this PR is not about negative values though, just made the change so 0 won't throw an error any more.

@jzsfkzm jzsfkzm marked this pull request as draft August 27, 2025 23:08
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.

Deployment top up error
2 participants