Skip to content

feat(pubkey-manager): add pubkey watch function similar to balance watch#178

Merged
CharlVS merged 8 commits intodevfrom
feat/pubkey-watcher
Aug 12, 2025
Merged

feat(pubkey-manager): add pubkey watch function similar to balance watch#178
CharlVS merged 8 commits intodevfrom
feat/pubkey-watcher

Conversation

@takenagain
Copy link
Copy Markdown
Contributor

@takenagain takenagain commented Aug 8, 2025

Introduces a Pubkey watch function similar to the one in BalanceManager to address the comment in #3049.

Adds fake_async as a direct dev dependency for unit testing.

Summary by CodeRabbit

  • New Features

    • Introduced a reactive and cached public key management system with streaming updates and improved lifecycle handling.
    • Added the ability to retrieve cached public keys instantly and pre-cache them for faster access.
    • Updated the asset page to subscribe continuously to public key updates with reactive UI state management.
    • Enhanced resource cleanup and state reset when switching wallets.
  • Bug Fixes

    • Improved consistency and reliability of public key management when the user context changes.
  • Tests

    • Added a comprehensive test suite covering public key management scenarios, streaming behavior, error handling, and cache updates.
  • Chores

    • Added the fake_async package as a development dependency.

@takenagain takenagain self-assigned this Aug 8, 2025
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Aug 8, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces a major refactor of the PubkeyManager class, adding a new interface, reactive streaming APIs, caching, and lifecycle management tied to authentication state. It also adds comprehensive tests for the new behaviors, introduces a new dev dependency, and includes a minor formatting change in an unrelated file.

Changes

Cohort / File(s) Change Summary
PubkeyManager Refactor & Interface
packages/komodo_defi_sdk/lib/src/pubkeys/pubkey_manager.dart
Refactored PubkeyManager to implement a new IPubkeyManager interface. Added streaming API (watchPubkeys), internal caching, authentication state awareness, and improved resource cleanup. Introduced new public methods for cache access and pre-caching. Enhanced lifecycle and error handling throughout.
PubkeyManager Test Suite
packages/komodo_defi_sdk/test/pubkeys/pubkey_manager_test.dart
Added comprehensive tests for PubkeyManager, covering pubkey retrieval, streaming, cache behaviors, error handling, user authentication changes, and resource cleanup. Utilizes mocks and fake async for time-dependent and asynchronous behaviors.
Dev Dependency Addition
packages/komodo_defi_sdk/pubspec.yaml
Added fake_async as a new dev dependency for testing asynchronous code.
Asset Page Stream Subscription Update
packages/komodo_defi_sdk/example/lib/screens/asset_page.dart
Replaced one-time pubkey fetch with continuous subscription to pubkey streams, updating UI reactively. Added subscription management and refactored refresh logic to use pre-cache method.
Formatting Change
packages/komodo_defi_sdk/lib/src/balances/balance_manager.dart
Inserted a single blank line after the dart:async import; no functional code changes.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant PubkeyManager
    participant ApiClient
    participant AuthState

    Client->>PubkeyManager: watchPubkeys(asset)
    alt Cached pubkeys available
        PubkeyManager-->>Client: Emit cached pubkeys
    end
    loop Every 30 seconds
        PubkeyManager->>ApiClient: Fetch latest pubkeys for asset
        ApiClient-->>PubkeyManager: Return pubkeys
        PubkeyManager-->>Client: Emit updated pubkeys
    end
    AuthState-->>PubkeyManager: On wallet change
    PubkeyManager-->>Client: Reset cache, cancel watchers
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

Suggested labels

codex

Suggested reviewers

  • CharlVS

Poem

A bunny hopped through lines of code,
Streaming keys in a reactive mode.
With caches fresh and tests anew,
It watched for changes, swift and true.
Now pubkeys flow and bugs take flight—
The warren’s safe, the future bright!
🐇✨

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/pubkey-watcher

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.

@takenagain takenagain requested a review from Copilot August 8, 2025 15:28

This comment was marked as outdated.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Aug 8, 2025

Visit the preview URL for this PR (updated for commit f678d1b):

https://komodo-defi-sdk--pr178-feat-pubkey-watcher-cwknam3g.web.app

(expires Tue, 19 Aug 2025 12:16:42 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: 7f9f5ac39928f333b6e8fcefb7138575e24ed347

@takenagain takenagain requested a review from Copilot August 8, 2025 16:41
@takenagain
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Aug 8, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

This comment was marked as outdated.

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

♻️ Duplicate comments (2)
packages/komodo_defi_sdk/lib/src/pubkeys/pubkey_manager.dart (2)

70-79: Same activation-result check needed for createNewPubkey.

Discarding the ActivationResult risks attempting address creation on an inactive asset – likely to fail. Apply the guard here too.


83-93: Ditto for createNewPubkeyStream.

Stream should early-error if activation doesn’t succeed; otherwise consumers see an empty stream.

🧹 Nitpick comments (1)
packages/komodo_defi_sdk/lib/src/pubkeys/pubkey_manager.dart (1)

197-214: Silent catch hides useful diagnostics.

Swallowing all exceptions without at least a debugPrint makes production debugging painful.

- } catch (_) {
-   // Swallow transient errors; continue with last known state
+ } catch (e, st) {
+   debugPrint('watchPubkeys polling error for ${asset.id.name}: $e\n$st');

Even a low-level log is preferable to complete silence.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 62b919f and 841bcea.

📒 Files selected for processing (4)
  • packages/komodo_defi_sdk/lib/src/balances/balance_manager.dart (1 hunks)
  • packages/komodo_defi_sdk/lib/src/pubkeys/pubkey_manager.dart (4 hunks)
  • packages/komodo_defi_sdk/pubspec.yaml (1 hunks)
  • packages/komodo_defi_sdk/test/pubkeys/pubkey_manager_test.dart (1 hunks)
⏰ 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: build_and_preview_sdk_example_preview
  • GitHub Check: build_and_preview_playground_preview
🔇 Additional comments (3)
packages/komodo_defi_sdk/lib/src/balances/balance_manager.dart (1)

2-2: No functional change – looks good.
The added blank line keeps import grouping tidy without altering behaviour.

packages/komodo_defi_sdk/pubspec.yaml (1)

48-49: Dev-dependency addition approved, but double-check transitive impact.

fake_async is appropriate for the new tests; just ensure no version-range conflicts with the SDK (³.7) or with other packages at resolution time.

packages/komodo_defi_sdk/test/pubkeys/pubkey_manager_test.dart (1)

214-248: Nice use of fake_async – test clearly asserts the 30 s poll.
Coverage is thorough and readable.

@takenagain takenagain requested a review from Copilot August 8, 2025 17:35
@takenagain
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Aug 8, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR adds a reactive watchPubkeys function to the PubkeyManager class, providing streaming updates for public keys similar to the existing balance watching functionality. This addresses the need for real-time pubkey monitoring in wallet applications.

  • Introduces streaming pubkey watching with periodic updates and caching functionality
  • Adds proper lifecycle management for authentication state changes and resource cleanup
  • Updates the example app to demonstrate the new streaming pubkey functionality

Reviewed Changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
packages/komodo_defi_sdk/lib/src/pubkeys/pubkey_manager.dart Core implementation of streaming pubkey watching with caching, auth handling, and dispose pattern
packages/komodo_defi_sdk/test/pubkeys/pubkey_manager_test.dart Comprehensive test suite covering streaming behavior, auth changes, error handling, and edge cases
packages/komodo_defi_sdk/pubspec.yaml Adds fake_async dependency for testing time-dependent behavior
packages/komodo_defi_sdk/example/lib/screens/asset_page.dart Updates example to use streaming pubkey watching instead of one-time fetch
packages/komodo_defi_sdk/lib/src/balances/balance_manager.dart Minor formatting change adding blank line

@takenagain takenagain marked this pull request as ready for review August 8, 2025 17:37
@takenagain takenagain requested a review from CharlVS August 8, 2025 17:37
cursor[bot]

This comment was marked as outdated.

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

♻️ Duplicate comments (1)
packages/komodo_defi_sdk/test/pubkeys/pubkey_manager_test.dart (1)

246-247: Await subscription cancellation in tests
Using unawaited(sub.cancel()) may let the stream keep running after the test finishes, causing flakiness.
Simply await sub.cancel(); as previously suggested.

🧹 Nitpick comments (3)
packages/komodo_defi_sdk/lib/src/pubkeys/pubkey_manager.dart (2)

61-62: Make polling interval injectable

Hard-coding the 30 s value makes unit-tests depend on fake-time tricks and prevents product owners from tuning network load.
Pass a Duration pollingInterval (defaulting to 30 s) to the constructor or to watchPubkeys.


298-307: Skip restart when nobody is listening

Inside _resetState() you restart watchers for every non-closed controller, even if it currently has zero listeners (!controller.hasListener).
Check hasListener to avoid spinning idle polling tasks.

packages/komodo_defi_sdk/example/lib/screens/asset_page.dart (1)

82-86: Avoid mutating the cached list in place

_pubkeys?.keys.add(newPubkey); mutates the existing list that may be shared with other widgets or caches, breaking value equality and change-detection.

Create a new instance instead:

- _pubkeys?.keys.add(newPubkey);
+ if (_pubkeys != null) {
+   _pubkeys = _pubkeys!.copyWith(
+     keys: [..._pubkeys!.keys, newPubkey],
+   );
+ }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 841bcea and b440c24.

📒 Files selected for processing (3)
  • packages/komodo_defi_sdk/example/lib/screens/asset_page.dart (4 hunks)
  • packages/komodo_defi_sdk/lib/src/pubkeys/pubkey_manager.dart (4 hunks)
  • packages/komodo_defi_sdk/test/pubkeys/pubkey_manager_test.dart (1 hunks)
⏰ 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: build_and_preview_sdk_example_preview
  • GitHub Check: build_and_preview_playground_preview

cursor[bot]

This comment was marked as outdated.

Copy link
Copy Markdown
Collaborator

@CharlVS CharlVS left a comment

Choose a reason for hiding this comment

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

Thank you for your contributions.

Comment on lines +33 to +34
/// Pre-caches pubkeys for an asset to warm the cache and notify listeners
Future<void> preCachePubkeys(Asset asset);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit: "precache" is one word, so the name should be precachePubkeys

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.

Done in 9499bd8 for PubkeyManager and f678d1b for BalanceManager

Comment on lines +318 to +336
if (_isDisposed) return;
_isDisposed = true;

await _authSubscription?.cancel();
_authSubscription = null;

for (final subscription in _activeWatchers.values) {
await subscription.cancel();
}
_activeWatchers.clear();

for (final controller in _pubkeysControllers.values) {
await controller.close();
}
_pubkeysControllers.clear();

_pubkeysCache.clear();
_watchedAssets.clear();
_currentWalletId = null;
Copy link
Copy Markdown
Collaborator

@CharlVS CharlVS Aug 11, 2025

Choose a reason for hiding this comment

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

Improve the error handling to make it more resilient to errors being thrown early in the function. If it won't cause potential race conditions, consider putting all async operations into a Future.await([...]) since it lets all futures run and also runs them concurrently.

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.

Done in 9499bd8 for PubkeyManager and f678d1b for BalanceManager

Comment on lines +27 to +28
/// Streamed version of [createNewPubkey]
Stream<NewAddressState> createNewPubkeyStream(Asset asset);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit: createNewPubkeyStream may be unclear since (without reading comments for additional context) it suggests its function is to create a stream for new pubkeys.

In line with the convention to add watch- for creating streamed versions of methods, it can be named watchCreateNewPubkey

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.

Done in 9499bd8

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Is there a specific reason you opted to make the methods require the Asset type instead of assetId? Some of the behaviour may depend on the Asset's properties, but since this is a publicly exposed SDK method, it places a significant responsibility on projects consuming the SDK, as they must retain a reference to the entire Asset across all states to use these methods.

Also, it may cause unexpected behaviour if we're using the Asset values passed since the consuming app could instantiate their own Asset object to alter the method's behaviour.

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.

To align with the behaviour of existing PubkeyManager methods in terms of performing automatic activation of assets. The Asset type is required for activation using SharedActivationCoordinator.

Copy link
Copy Markdown
Collaborator

@CharlVS CharlVS left a comment

Choose a reason for hiding this comment

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

Great yield and awesome thinking

@CharlVS CharlVS merged commit d5b5c38 into dev Aug 12, 2025
6 of 8 checks passed
@CharlVS CharlVS deleted the feat/pubkey-watcher branch August 12, 2025 17:07
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.

3 participants