Skip to content

fix(alert): properly calculates deployment escrow balance#1545

Merged
ygrishajev merged 1 commit intomainfrom
feature/alert
Jun 24, 2025
Merged

fix(alert): properly calculates deployment escrow balance#1545
ygrishajev merged 1 commit intomainfrom
feature/alert

Conversation

@ygrishajev
Copy link
Contributor

@ygrishajev ygrishajev commented Jun 24, 2025

Summary by CodeRabbit

  • New Features

    • Deployment balance calculations now incorporate lease pricing and blockchain height for more accurate results.
    • Notifications system enhanced to include lease data in balance alerts.
  • Bug Fixes

    • Improved handling of closed deployments in balance calculations.
  • Tests

    • Enhanced tests to cover lease data integration and updated balance expectations.
    • Test utilities updated to support new data structures and parameters.
  • Chores

    • Updated type exports to improve type accessibility across modules.

@ygrishajev ygrishajev requested a review from a team as a code owner June 24, 2025 16:11
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 24, 2025

Walkthrough

Lease pricing is now integrated into deployment balance calculations. The DeploymentService and its tests were updated to inject and use LeaseHttpService, and the balance logic now considers lease price per block and escrow settlement time. Supporting types and test seeders were adjusted to handle new fields and behaviors, with provider configuration updated accordingly.

Changes

File(s) Change Summary
.../providers/http-sdk.provider.ts Added LeaseHttpService to providers with configuration for base URL.
.../services/deployment-balance-alerts/deployment-balance-alerts.service.ts Modified getDeploymentBalance calls to include current block height as an argument.
.../services/deployment/deployment.service.ts Injected LeaseHttpService, added lease-based logic to getDeploymentBalance, updated method signature, added getPricePerBlock.
.../services/deployment/deployment.service.spec.ts Updated tests to mock and verify lease data, adjusted expectations, and included new argument for block height.
.../test/functional/balance-alert.spec.ts Mocked lease API responses, updated expected alert balance, and included settlement timestamp in test data.
.../test/seeders/deployment-balance-response.seeder.ts Extended seeder to accept and include optional settledAt timestamp in generated responses.
.../lease/lease-http.service.ts Exported RestAkashLeaseListResponse type for external use.

Sequence Diagram(s)

sequenceDiagram
  participant AlertService
  participant DeploymentService
  participant DeploymentHttpService
  participant LeaseHttpService

  AlertService->>DeploymentService: processSingleAlert(owner, dseq, block.height)
  DeploymentService->>DeploymentHttpService: getDeploymentInfo(owner, dseq)
  DeploymentService->>LeaseHttpService: list(owner, dseq)
  DeploymentService->>DeploymentService: getPricePerBlock(leases)
  DeploymentService->>DeploymentService: calculateBalance(escrow, pricePerBlock, settledAt, block.height)
  DeploymentService-->>AlertService: return balance
Loading

Suggested reviewers

  • baktun14
  • stalniy

Poem

In fields of code where leases grow,
A rabbit hops where balances flow.
With blocks and prices now entwined,
Escrow and leases are combined.
The numbers crunch, alerts arise—
Another hop, another prize!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-24T16_19_32_549Z-debug-0.log

✨ 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.

@codecov
Copy link

codecov bot commented Jun 24, 2025

Codecov Report

Attention: Patch coverage is 91.30435% with 2 lines in your changes missing coverage. Please review.

Project coverage is 40.59%. Comparing base (d0176c0) to head (b1ec54b).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...es/alert/services/deployment/deployment.service.ts 90.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1545      +/-   ##
==========================================
+ Coverage   40.57%   40.59%   +0.02%     
==========================================
  Files         872      872              
  Lines       21217    21228      +11     
  Branches     3864     3870       +6     
==========================================
+ Hits         8608     8618      +10     
- Misses      11881    12289     +408     
+ Partials      728      321     -407     
Flag Coverage Δ *Carryforward flag
api 71.33% <ø> (ø)
deploy-web 18.89% <ø> (ø)
notifications 87.90% <91.30%> (+0.02%) ⬆️
provider-proxy 82.13% <ø> (ø) Carriedforward from d0176c0

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

Files with missing lines Coverage Δ
...s/src/modules/alert/providers/http-sdk.provider.ts 100.00% <100.00%> (ø)
...alance-alerts/deployment-balance-alerts.service.ts 95.91% <100.00%> (ø)
...es/alert/services/deployment/deployment.service.ts 90.69% <90.00%> (-0.22%) ⬇️

... and 136 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 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: 3

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d0176c0 and 1c861f2.

📒 Files selected for processing (7)
  • apps/notifications/src/modules/alert/providers/http-sdk.provider.ts (2 hunks)
  • apps/notifications/src/modules/alert/services/deployment-balance-alerts/deployment-balance-alerts.service.ts (1 hunks)
  • apps/notifications/src/modules/alert/services/deployment/deployment.service.spec.ts (5 hunks)
  • apps/notifications/src/modules/alert/services/deployment/deployment.service.ts (3 hunks)
  • apps/notifications/test/functional/balance-alert.spec.ts (3 hunks)
  • apps/notifications/test/seeders/deployment-balance-response.seeder.ts (2 hunks)
  • packages/http-sdk/src/lease/lease-http.service.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.spec.{ts,tsx}`: Use a `setup` function instead of `beforeEach` for test setup. The `setup` function must be at the bottom of the root `describe` block, create and return the ...

**/*.spec.{ts,tsx}: Use a setup function instead of beforeEach for test setup. The setup function must be at the bottom of the root describe block, create and return the object under test, accept a single parameter with inline type definition, avoid shared state, and should not specify a return type.

  • apps/notifications/test/functional/balance-alert.spec.ts
  • apps/notifications/src/modules/alert/services/deployment/deployment.service.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: test-api-build
  • GitHub Check: validate-api
  • GitHub Check: validate-notifications
  • GitHub Check: test-deploy-web-build
  • GitHub Check: validate-deploy-web
  • GitHub Check: Validate local packages
🔇 Additional comments (16)
packages/http-sdk/src/lease/lease-http.service.ts (1)

5-5: LGTM! Proper type export for cross-module usage.

Exporting the type enables type-safe usage of lease response data in other modules, which aligns with the integration of lease pricing into deployment balance calculations.

apps/notifications/test/seeders/deployment-balance-response.seeder.ts (1)

8-8: LGTM! Proper seeder extension for escrow settlement timing.

The addition of the settledAt parameter with appropriate default value generation and optional typing correctly supports the enhanced deployment balance calculation logic.

Also applies to: 14-14, 28-29

apps/notifications/src/modules/alert/services/deployment-balance-alerts/deployment-balance-alerts.service.ts (1)

54-54: LGTM! Correctly passes block height for time-based balance calculation.

The addition of block.height as a parameter enables the deployment service to calculate balance based on elapsed time since escrow settlement, which is essential for the lease pricing integration.

apps/notifications/src/modules/alert/providers/http-sdk.provider.ts (1)

1-1: LGTM! Proper provider setup for LeaseHttpService.

The addition follows the established pattern for HTTP service providers, correctly injecting ConfigService and using the same API endpoint configuration.

Also applies to: 16-23

apps/notifications/test/functional/balance-alert.spec.ts (1)

78-80: LGTM! Comprehensive test coverage for lease-integrated balance calculation.

The test properly mocks lease data and validates the enhanced balance calculation. The expected value of 700000 correctly reflects the calculation: initial balance (800000) minus cost for elapsed blocks (100 blocks × 1000 per block = 100000).

Also applies to: 82-92, 107-113, 127-127

apps/notifications/src/modules/alert/services/deployment/deployment.service.spec.ts (6)

1-2: LGTM: Proper imports for lease functionality

The imports correctly include the new LeaseHttpService and RestAkashLeaseListResponse type needed for the updated functionality.


17-18: LGTM: Test setup updated for new functionality

The test description and setup correctly reflect the addition of lease pricing calculations and the new block height parameter.


27-34: LGTM: Mock data properly updated

The escrow balance and funds amounts have been increased to accommodate the new calculation logic, and the settled_at field has been correctly added.


38-48: LGTM: Lease service mock properly configured

The mock correctly returns lease data with price information needed for the balance calculation.


49-51: LGTM: Method call and assertion updated correctly

The method call now includes the required block height parameter, and the expected balance (700000) matches the calculation logic: (400000 + 400000) / 1000 - (1000 - 900) = 700 blocks * 1000 = 700000.


91-104: LGTM: Setup function follows coding guidelines

The setup function correctly follows the coding guidelines by:

  • Being placed at the bottom of the root describe block
  • Creating and returning the object under test
  • Avoiding shared state
  • Not specifying a return type
apps/notifications/src/modules/alert/services/deployment/deployment.service.ts (5)

1-1: LGTM: Import statement updated correctly

The import statement properly includes the new LeaseHttpService dependency.


22-23: LGTM: Type definition updated

The DeploymentInfo type correctly includes the new settled_at field needed for escrow settlement calculations.


30-30: LGTM: Service dependency injection

The LeaseHttpService is properly injected into the constructor.


36-36: LGTM: Method signature updated

The method signature correctly adds the block parameter needed for balance calculations.


38-38: LGTM: Concurrent data fetching

Using Promise.all for concurrent fetching of deployment info and price per block is an efficient approach.

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 1c861f2 and b1ec54b.

📒 Files selected for processing (7)
  • apps/notifications/src/modules/alert/providers/http-sdk.provider.ts (2 hunks)
  • apps/notifications/src/modules/alert/services/deployment-balance-alerts/deployment-balance-alerts.service.ts (1 hunks)
  • apps/notifications/src/modules/alert/services/deployment/deployment.service.spec.ts (5 hunks)
  • apps/notifications/src/modules/alert/services/deployment/deployment.service.ts (3 hunks)
  • apps/notifications/test/functional/balance-alert.spec.ts (3 hunks)
  • apps/notifications/test/seeders/deployment-balance-response.seeder.ts (2 hunks)
  • packages/http-sdk/src/lease/lease-http.service.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • packages/http-sdk/src/lease/lease-http.service.ts
  • apps/notifications/test/seeders/deployment-balance-response.seeder.ts
  • apps/notifications/test/functional/balance-alert.spec.ts
  • apps/notifications/src/modules/alert/providers/http-sdk.provider.ts
  • apps/notifications/src/modules/alert/services/deployment-balance-alerts/deployment-balance-alerts.service.ts
  • apps/notifications/src/modules/alert/services/deployment/deployment.service.ts
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.spec.{ts,tsx}`: Use a `setup` function instead of `beforeEach` for test setup. The `setup` function must be at the bottom of the root `describe` block, create and return the ...

**/*.spec.{ts,tsx}: Use a setup function instead of beforeEach for test setup. The setup function must be at the bottom of the root describe block, create and return the object under test, accept a single parameter with inline type definition, avoid shared state, and should not specify a return type.

  • apps/notifications/src/modules/alert/services/deployment/deployment.service.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: validate-notifications
  • GitHub Check: validate-api
  • GitHub Check: test-api-build
  • GitHub Check: validate-deploy-web
  • GitHub Check: test-deploy-web-build
  • GitHub Check: Validate local packages
🔇 Additional comments (6)
apps/notifications/src/modules/alert/services/deployment/deployment.service.spec.ts (6)

1-2: LGTM - Import statements properly updated for lease integration.

The new imports for DeploymentInfo, RestAkashLeaseListResponse, and LeaseHttpService are correctly added to support the lease pricing integration functionality.


17-18: Test description and setup appropriately updated.

The test description now accurately reflects the "calculated escrow balance" functionality, and the setup destructuring includes the new dependencies (leaseHttpService and CURRENT_HEIGHT) needed for lease pricing calculations.


38-48: Lease mock data structure looks correct.

The mock leaseHttpService.list response properly follows the RestAkashLeaseListResponse structure with lease price data needed for balance calculations.


49-51: Method signature and assertion updated correctly.

The getDeploymentBalance call now includes the CURRENT_HEIGHT parameter as expected, and the assertion reflects the new calculated balance including lease pricing.


76-78: Closed deployment test case properly maintained.

The test for closed deployments correctly includes the new lease service mock and height parameter while maintaining the existing error handling logic.


27-34: To locate and inspect the exact balance‐calculation logic, let’s pull in the service file and search around the key terms:

#!/bin/bash
# 1. Find the deployment.service.ts implementation
service_file=$(fd -g "deployment.service.ts" apps/notifications/src/modules/alert/services/deployment)
echo "Found service file at: $service_file"

# 2. Show the first 200 lines to locate relevant methods
echo "----- Top of $service_file -----"
sed -n '1,200p' "$service_file"

# 3. Search for balance/settle/current‐height references to spot the calculation block
echo "----- Scanning for balance calculation references -----"
rg -n "balance" -n "settle" -n "CURRENT_HEIGHT" -n "block" -n "price" "$service_file"

@ygrishajev ygrishajev merged commit 4ea20e4 into main Jun 24, 2025
29 checks passed
@ygrishajev ygrishajev deleted the feature/alert branch June 24, 2025 16:33
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