Skip to content

Test: Shared getBalance tests for both facades#1051

Merged
tuliomir merged 12 commits intomasterfrom
test/shared-get-balance
Apr 16, 2026
Merged

Test: Shared getBalance tests for both facades#1051
tuliomir merged 12 commits intomasterfrom
test/shared-get-balance

Conversation

@tuliomir
Copy link
Copy Markdown
Contributor

@tuliomir tuliomir commented Mar 31, 2026

Summary

  • Extract getBalance tests from hathorwallet_facade.test.ts and walletservice_facade.test.ts into the shared test framework
  • Create shared/get-balance.test.ts with adapter-driven tests that run against both facades
  • Move fullnode-only tests (custom token balance, mandatory tokenUid, internal transfer) to fullnode-specific/get-balance.test.ts
  • Move service-only tests (no-arg getBalance, not-ready error, skipped empty-wallet bugs) to service-specific/get-balance.test.ts

Acceptance Criteria

  • Shared balance tests pass for both fullnode and wallet-service adapters
  • No getBalance/balances describe blocks remain in the monolithic facade files

Test plan

  • npm run test passes
  • npm run test_integration passes (shared tests run against both facades)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Tests
    • Reorganized balance tests: consolidated shared cases and added fullnode- and service-specific integration suites.
    • Added assertions for: requiring a token id for token-specific queries; genesis wallet visibility for newly created tokens; wallet readiness errors when not started; native balance after injecting funds; internal transfers not changing unlocked balance.
    • Removed duplicated legacy balance suites and added a few skipped regression markers for known behavior differences.

@tuliomir tuliomir added the tests label Mar 31, 2026
@tuliomir tuliomir self-assigned this Mar 31, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 31, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Reorganized and split getBalance tests: removed legacy suites and added a shared adapter-driven suite plus service- and fullnode-specific suites. Tests cover empty-wallet state, fund injection, readiness errors, internal-transfer invariance, and custom-token scenarios; wallets are stopped/teared down for isolation.

Changes

Cohort / File(s) Summary
Removed legacy suites
__tests__/integration/hathorwallet_facade.test.ts, __tests__/integration/walletservice_facade.test.ts
Removed old getBalance/balances test blocks and replaced them with comments pointing to new shared and implementation-specific test files.
Shared tests (adapter-driven)
__tests__/integration/shared/get-balance.test.ts
Added parameterized adapter suite (Fullnode & Service) validating empty-wallet native balance, post-injection unlocked balance, internal-transfer invariance, and custom-token mint/balance behavior with adapter lifecycle management.
Service-specific tests
__tests__/integration/service-specific/get-balance.test.ts
Added service-facade tests: native-token response shape after injection, wallet-not-ready rejection, plus two skipped FIXME tests describing expected empty-wallet behavior.
Fullnode-specific tests
__tests__/integration/fullnode-specific/get-balance.test.ts
Added fullnode-only tests: error when tokenUid omitted, non-existent token UID balance shape, custom-token creation and balance visibility scoped to wallets; uses global stopAllWallets() teardown.

Sequence Diagram(s)

(omitted)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Test: Shared tests for start #1032: Introduced the adapter-based test infrastructure (IWalletTestAdapter, FullnodeWalletTestAdapter, ServiceWalletTestAdapter) that these new tests depend on.

Suggested reviewers

  • pedroferreira1
  • r4mmer

Poem

🐰 I hopped through tests with joy and cheer,
Split suites, adapters now appear.
Tokens counted, wallets nap tight,
Balances checked from day to night. 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'Test: Shared getBalance tests for both facades' directly and clearly summarizes the main change: extracting and consolidating getBalance tests into a shared test suite that runs against multiple wallet facades.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch test/shared-get-balance

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov bot commented Mar 31, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.93%. Comparing base (0ccc910) to head (d121224).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1051   +/-   ##
=======================================
  Coverage   87.93%   87.93%           
=======================================
  Files         114      114           
  Lines        8910     8910           
  Branches     2030     2020   -10     
=======================================
  Hits         7835     7835           
  Misses       1047     1047           
  Partials       28       28           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 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
Copy Markdown

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

🧹 Nitpick comments (1)
__tests__/integration/service-specific/get-balance.test.ts (1)

61-110: Consider adding issue references to the FIXME comments.

The fullnode-specific tests reference issue #397 for known bugs. Adding similar issue references here would help track when these skipped tests can be enabled.

-  // FIXME: The test does not return balance for empty wallet. It should return 0 for the native token
+  // FIXME: The test does not return balance for empty wallet. It should return 0 for the native token. Ref `#XXX`
   it.skip('should return balance array for empty wallet', async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@__tests__/integration/service-specific/get-balance.test.ts` around lines 61 -
110, Update the FIXME comments above the two skipped tests ("should return
balance array for empty wallet" and "should return balance for specific token
when token parameter is provided") to include a reference to the tracking issue
(e.g., "#397" or the appropriate issue number) and a short note about the
expected behavior; locate the comments adjacent to the it.skip blocks that use
buildWalletInstance, emptyWallet, and NATIVE_TOKEN_UID and append the issue
reference so future maintainers know which issue to watch before unskipping the
tests.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@__tests__/integration/service-specific/get-balance.test.ts`:
- Around line 61-110: Update the FIXME comments above the two skipped tests
("should return balance array for empty wallet" and "should return balance for
specific token when token parameter is provided") to include a reference to the
tracking issue (e.g., "#397" or the appropriate issue number) and a short note
about the expected behavior; locate the comments adjacent to the it.skip blocks
that use buildWalletInstance, emptyWallet, and NATIVE_TOKEN_UID and append the
issue reference so future maintainers know which issue to watch before
unskipping the tests.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 09d987e9-870c-456c-b129-d46998f045ae

📥 Commits

Reviewing files that changed from the base of the PR and between b408dd6 and 8165381.

📒 Files selected for processing (5)
  • __tests__/integration/fullnode-specific/get-balance.test.ts
  • __tests__/integration/hathorwallet_facade.test.ts
  • __tests__/integration/service-specific/get-balance.test.ts
  • __tests__/integration/shared/get-balance.test.ts
  • __tests__/integration/walletservice_facade.test.ts

@tuliomir tuliomir force-pushed the test/shared-get-balance branch from 8165381 to d21bcb7 Compare March 31, 2026 21:28
Copy link
Copy Markdown

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

🧹 Nitpick comments (1)
__tests__/integration/fullnode-specific/get-balance.test.ts (1)

51-52: Consider adding non-null assertion for consistency.

Other tests in the codebase use hash! when passing the transaction hash to wait functions (e.g., pollForTx(wallet, fundTx.hash!)). For consistency and to make the assumption explicit:

🔧 Suggested change
     const tx1 = await hWallet.sendTransaction(await hWallet.getAddressAtIndex(1), 2n);
-    await waitForTxReceived(hWallet, tx1.hash);
+    await waitForTxReceived(hWallet, tx1.hash!);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@__tests__/integration/fullnode-specific/get-balance.test.ts` around lines 51
- 52, The test passes tx1.hash to waitForTxReceived without a non-null
assertion; update the call to assert the hash is non-null (use tx1.hash!) so it
matches the project's convention and makes the assumption explicit when calling
waitForTxReceived(hWallet, tx1.hash!). Locate the send/await block around tx1
created by hWallet.sendTransaction and change the waitForTxReceived invocation
to use the non-null asserted tx1.hash.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@__tests__/integration/fullnode-specific/get-balance.test.ts`:
- Around line 51-52: The test passes tx1.hash to waitForTxReceived without a
non-null assertion; update the call to assert the hash is non-null (use
tx1.hash!) so it matches the project's convention and makes the assumption
explicit when calling waitForTxReceived(hWallet, tx1.hash!). Locate the
send/await block around tx1 created by hWallet.sendTransaction and change the
waitForTxReceived invocation to use the non-null asserted tx1.hash.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d1a24054-58de-4100-9c8f-214dd2e26693

📥 Commits

Reviewing files that changed from the base of the PR and between 8165381 and d21bcb7.

📒 Files selected for processing (5)
  • __tests__/integration/fullnode-specific/get-balance.test.ts
  • __tests__/integration/hathorwallet_facade.test.ts
  • __tests__/integration/service-specific/get-balance.test.ts
  • __tests__/integration/shared/get-balance.test.ts
  • __tests__/integration/walletservice_facade.test.ts
✅ Files skipped from review due to trivial changes (1)
  • tests/integration/service-specific/get-balance.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/integration/hathorwallet_facade.test.ts

tuliomir and others added 2 commits March 31, 2026 19:48
Extract getBalance coverage from monolithic facade test
files into the shared test framework. Shared tests run
against both fullnode and wallet-service adapters via
describe.each.

- shared/get-balance.test.ts: zero balance, funded balance
- fullnode-specific/get-balance.test.ts: custom token,
  mandatory tokenUid, internal transfer
- service-specific/get-balance.test.ts: no-arg getBalance,
  not-ready error, skipped empty-wallet bugs

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add issue #397 reference to FIXME comments on skipped
  empty-wallet balance tests in service-specific
- Add non-null assertion to tx1.hash in fullnode-specific
  waitForTxReceived call

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@tuliomir tuliomir force-pushed the test/shared-get-balance branch from d21bcb7 to 310958b Compare March 31, 2026 22:49
tuliomir and others added 2 commits March 31, 2026 20:05
Replace non-null assertion with explicit expect guard
before passing address to injectFunds.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@tuliomir tuliomir moved this from Todo to In Progress (WIP) in Hathor Network Apr 1, 2026
@tuliomir tuliomir moved this from In Progress (WIP) to In Progress (Done) in Hathor Network Apr 1, 2026
@tuliomir tuliomir requested a review from r4mmer April 1, 2026 18:27
tuliomir and others added 2 commits April 1, 2026 15:28
Move 'internal transfer' and 'custom token' tests
from fullnode-specific to shared get-balance suite.
Extract fullnode-only assertions (nonexistent token
zero-balance, cross-wallet isolation) into dedicated
fullnode-specific tests.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Copy Markdown

@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 (1)
__tests__/integration/shared/get-balance.test.ts (1)

74-95: Minor inconsistency in address null-checking.

Line 85 passes getAddressAtIndex(1) directly to sendTransaction without the explicit toBeDefined() check used on lines 79-80 for index 0. While the test would fail clearly if the address is undefined, maintaining consistency aids readability.

♻️ Optional: Add consistent null-check
-      const tx = await wallet.sendTransaction(await wallet.getAddressAtIndex(1), 2n, {
+      const addr1 = await wallet.getAddressAtIndex(1);
+      expect(addr1).toBeDefined();
+      const tx = await wallet.sendTransaction(addr1!, 2n, {
         pinCode: adapter.defaultPinCode,
       });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@__tests__/integration/shared/get-balance.test.ts` around lines 74 - 95, The
test inconsistently omits a null-check for the destination address: capture the
address returned by wallet.getAddressAtIndex(1) into a variable (e.g.,
destAddr), add an expect(destAddr).toBeDefined() before calling
wallet.sendTransaction, and then pass destAddr! to wallet.sendTransaction;
update references to the address variable so wallet.sendTransaction and any
other uses reference the checked variable (functions: wallet.getAddressAtIndex,
wallet.sendTransaction).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@__tests__/integration/fullnode-specific/get-balance.test.ts`:
- Line 1: There are Prettier formatting violations starting at the file's
leading JSDoc comment (the "/**" block); run your project's formatter (e.g.,
prettier --write) against this test file to reformat it, stage the updated file,
and commit the changes so the CI style checks pass; ensure you use the repo's
Prettier config and re-run the test/CI locally before pushing.

---

Nitpick comments:
In `@__tests__/integration/shared/get-balance.test.ts`:
- Around line 74-95: The test inconsistently omits a null-check for the
destination address: capture the address returned by wallet.getAddressAtIndex(1)
into a variable (e.g., destAddr), add an expect(destAddr).toBeDefined() before
calling wallet.sendTransaction, and then pass destAddr! to
wallet.sendTransaction; update references to the address variable so
wallet.sendTransaction and any other uses reference the checked variable
(functions: wallet.getAddressAtIndex, wallet.sendTransaction).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 32b8d6e7-7efa-4070-a782-bd890275c1e1

📥 Commits

Reviewing files that changed from the base of the PR and between 1f68446 and 80fa9d1.

📒 Files selected for processing (2)
  • __tests__/integration/fullnode-specific/get-balance.test.ts
  • __tests__/integration/shared/get-balance.test.ts

Comment thread __tests__/integration/fullnode-specific/get-balance.test.ts
Comment thread __tests__/integration/fullnode-specific/get-balance.test.ts
Comment on lines +45 to +66
it('should not show custom token balance on a different wallet', async () => {
const hWallet = await generateWalletHelper();

await GenesisWalletHelper.injectFunds(hWallet, await hWallet.getAddressAtIndex(0), 10n);
const newTokenAmount = BigInt(getRandomInt(1000, 10));
const { hash: tokenUid } = await createTokenHelper(
hWallet,
'BalanceToken',
'BAT',
newTokenAmount
);

const { hWallet: gWallet } = await GenesisWalletHelper.getSingleton();
const genesisTknBalance = await gWallet.getBalance(tokenUid);
expect(genesisTknBalance).toHaveLength(1);
expect(genesisTknBalance[0]).toMatchObject({
token: { id: tokenUid },
balance: { unlocked: 0n, locked: 0n },
transactions: 0,
});
});
});
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why isn't it in the shared tests?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

TL;DR: It's blocked by a wallet-service inconsistency (issue #397). Once the wallet-service returns a zero-balance entry instead of an empty array for unknown tokens, this test can be promoted to the shared suite.

--

The fullnode facade returns a zero-balance entry (line 60-64 of the test) when you ask for the balance of a token the wallet has never interacted with — the fullnode always synthesizes a response. The wallet-service facade, on the other hand, has a known bug where it returns an empty array for tokens the wallet doesn't hold (see the two FIXME(wallet-service) comments at lines 62-64 and 79-80 of service-specific/get-balance.test.ts, referencing issue #397).

Since the two facades don't agree on the return shape for "token not on this wallet," the test can't be written with a single shared assertion. Moving it to the shared suite would either require:

  1. Different expectations per adapter (defeating the purpose of shared tests), or
  2. The wallet-service bug to be fixed first so both facades return a consistent zero-balance entry.

The test was intentionally kept fullnode-specific until the wallet-service behavior converges.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Did you test it? We had this problem and Abadesso fixed it in the wallet service. It was implemented December last year

image

// FIXME(wallet-service): getBalance() on an empty wallet should return a single
// entry with 0 balance for the native token, but currently returns an empty array.
// Ref: https://github.com/HathorNetwork/hathor-wallet-lib/issues/397
it.skip('should return balance array for empty wallet', async () => {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We had fixed that and the next one, not sure why it's not working

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I tried removing all the skips but the tests just failed. Here's a small report on it:

--

  1. should return balance array for empty wallet — wallet-service still returns an empty array (length: 0) instead of one entry with zero balance (length: 1)

  2. should return balance for specific token when token parameter is provided — similarly, the assertion at line 83 expects balances.length to be 1, but the first test at line 69 already shows it's 0.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Because of this investigation above I ended up identifying another specific test that could to go Shared.

It's not perfect since it cannot validate the value, but it's better than a skipped specific test anyway. Done on 08f37ef

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.

@tuliomir did you run with a updated image of wallet-sevice? This is a known issue of fixes not being applied to the integration tests due to the usage of stale container images.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I just re-created the images locally with the HEAD at HathorNetwork/hathor-wallet-service@947e90f . This has still failed.

The wallet service still does not synthesize a "zero balance" record for HTR when there are no transactions.

Could we solve this in a future PR so that we can advance with the Shared Tests suite construction? Future improvements will be easier to implement when we have that in place.

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.

Yep. Open an issue for it pls

tuliomir and others added 2 commits April 7, 2026 12:04
The getBalance(tokenUid) test for empty wallets works on both
facades. Moved from service-specific (where it was skipped) to
the shared suite with updated assertions for the `version` field
and facade-agnostic authority checks.

The no-arg getBalance() empty wallet test remains skipped per #397.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@tuliomir tuliomir requested a review from pedroferreira1 April 8, 2026 13:10
try {
await wallet.stop({ cleanStorage: true });
} catch {
// Wallet may already be stopped
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.

it's good to see if the error that is being raised is related to the wallet stopping. Otherwise it could hide something.

// FIXME(wallet-service): getBalance() on an empty wallet should return a single
// entry with 0 balance for the native token, but currently returns an empty array.
// Ref: https://github.com/HathorNetwork/hathor-wallet-lib/issues/397
it.skip('should return balance array for empty wallet', async () => {
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.

@tuliomir did you run with a updated image of wallet-sevice? This is a known issue of fixes not being applied to the integration tests due to the usage of stale container images.

@tuliomir tuliomir removed the request for review from r4mmer April 8, 2026 16:03
@tuliomir tuliomir requested a review from raul-oliveira April 8, 2026 16:03
@tuliomir tuliomir moved this from In Progress (Done) to In Progress (WIP) in Hathor Network Apr 9, 2026
@tuliomir tuliomir moved this from In Progress (WIP) to In Progress (Done) in Hathor Network Apr 13, 2026
@github-project-automation github-project-automation bot moved this from In Progress (Done) to In Review (WIP) in Hathor Network Apr 16, 2026
@tuliomir tuliomir merged commit 41b9e6a into master Apr 16, 2026
6 checks passed
@tuliomir tuliomir deleted the test/shared-get-balance branch April 16, 2026 12:38
@github-project-automation github-project-automation bot moved this from In Review (WIP) to Waiting to be deployed in Hathor Network Apr 16, 2026
@raul-oliveira raul-oliveira mentioned this pull request Apr 17, 2026
1 task
@tuliomir tuliomir mentioned this pull request Apr 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Waiting to be deployed

Development

Successfully merging this pull request may close these issues.

3 participants