Skip to content

Conversation

@bordalix
Copy link
Contributor

@bordalix bordalix commented Jun 24, 2025

Creates new method on Onchain explorer that allows to subscribe to transactions for a given address:

    watchAddress(
        address: string,
        eventCallback: (txs: ExplorerTransaction[]) => void
    ): Promise<void>;

@altafan please review

Update: implements new Wallet method notifyIncomingFunds

    notifyIncomingFunds(
        eventCallback: (
            coins: Coin[] | VirtualCoin[],
            stopFunc: () => void
        ) => void
    ): Promise<void>;

Summary by CodeRabbit

  • New Features

    • Introduced real-time and polling-based notifications for incoming Bitcoin funds, supporting both onchain and offchain addresses.
    • Added helper functions to wait for incoming funds and receive notifications via callbacks.
    • Exposed new types and utility functions for handling incoming funds.
  • Documentation

    • Updated the README with a new section demonstrating how to receive Bitcoin and handle incoming funds notifications.
  • Tests

    • Added comprehensive end-to-end tests for incoming funds notifications and waiting mechanisms.
    • Introduced a mock WebSocket class for improved test coverage.
  • Style

    • Standardized string delimiters and formatting in the test configuration file.
  • Chores

    • Updated Node.js versions in CI and documentation workflows to version 22.

@bordalix bordalix requested a review from altafan June 24, 2025 14:09
@altafan altafan changed the title new notifyIncomingFunds method on onchain provider new watchAddress method on onchain provider Jun 25, 2025
@bordalix bordalix requested review from altafan and louisinger June 26, 2025 17:27
Adds new stopFunc() in callback for notifyIncomingFunds
New tests on the WebSocket
Copy link
Contributor

@Kukks Kukks left a comment

Choose a reason for hiding this comment

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

How hard would it be to refactor this to not be exclusively focused on incoming, but also outgoing?

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 1, 2025

Warning

Rate limit exceeded

@louisinger has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 21 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 7d58f16 and 5866d81.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • src/index.ts (5 hunks)
  • vitest.config.ts (1 hunks)

Walkthrough

The changes introduce a mechanism for wallets to receive notifications about incoming Bitcoin funds, both onchain and offchain. This includes new public APIs for subscribing to and awaiting incoming funds, updates to the provider interface to support address watching, and new end-to-end tests for these features. Documentation and test utilities were updated accordingly.

Changes

File(s) Change Summary
README.md Added documentation for receiving Bitcoin, including usage of new APIs for notifications and awaiting incoming funds.
src/index.ts Exported waitForIncomingFunds function and IncomingFunds type to the public API.
src/providers/onchain.ts Changed ExplorerTransaction.vout.value type, added watchAddresses method to OnchainProvider and its implementation in EsploraProvider, introduced WebSocket and polling for address monitoring, and added related types and type guards.
src/wallet/wallet.ts Added notifyIncomingFunds method and IncomingFunds type to Wallet, plus exported waitForIncomingFunds helper.
test/e2e/ark.test.ts Added end-to-end tests for offchain and onchain incoming fund notifications and waiting mechanisms; skipped one existing test.
test/e2e/utils.ts Changed TestArkWallet.wallet type, removed unused import, and added faucetOnchain utility function.
test/esplora.test.ts Added a MockWebSocket class for simulating WebSocket behavior in tests.
vitest.config.ts Reformatted file for consistent string delimiters and indentation; no logic changes.
.github/workflows/ci.yml Updated Node.js version from 20 to 22 in CI workflow.
.github/workflows/tsdoc.yml Updated Node.js version from 20 to 22 in TSDoc deployment workflow.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Wallet
    participant OnchainProvider
    participant IndexerProvider

    User->>Wallet: notifyIncomingFunds(callback)
    Wallet->>OnchainProvider: watchAddresses([boardingAddress], callback)
    OnchainProvider-->>Wallet: callback({type: "utxo", coins})
    Wallet->>IndexerProvider: subscribeForScripts([offchainScript])
    IndexerProvider-->>Wallet: callback({type: "vtxo", vtxos})
    Wallet-->>User: callback(IncomingFunds)
    User->>Wallet: stop() (to unsubscribe)
Loading
sequenceDiagram
    participant User
    participant Wallet

    User->>Wallet: waitForIncomingFunds()
    Wallet->>Wallet: notifyIncomingFunds(internalCallback)
    Wallet-->>User: Promise resolves with IncomingFunds (on first notification)
Loading

Possibly related PRs

  • Remove onchain wallet from Wallet, add OnchainWallet class #102: This PR restructures the wallet by moving onchain functionality to a separate OnchainWallet class, simplifying the wallet interface. It is related at the class level but focuses on different aspects compared to the current PR which enhances incoming funds handling.

Suggested reviewers

  • bordalix
  • altafan
✨ Finishing Touches
  • 📝 Generate Docstrings

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

@bordalix
Copy link
Contributor Author

bordalix commented Jul 1, 2025

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 1, 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.

@bordalix
Copy link
Contributor Author

bordalix commented Jul 1, 2025

@coderabbitai full review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 1, 2025

✅ Actions performed

Full review triggered.

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: 5

♻️ Duplicate comments (1)
package.json (1)

66-66: Consider using built-in WebSocket types instead of external dependency.

Based on past review feedback, the team decided to use the built-in WebSocket class (available since Node 21) to avoid external dependencies and polyfill requirements. The addition of @types/ws suggests the codebase might still be using the external ws library instead of the built-in WebSocket API.

Verify if the codebase is using the built-in WebSocket or external ws library:

#!/bin/bash
# Search for WebSocket usage in the codebase
echo "=== Searching for 'ws' import statements ==="
rg "import.*ws" --type ts

echo "=== Searching for WebSocket usage ==="
rg "new WebSocket\(" --type ts -A 2

echo "=== Searching for 'ws' package usage ==="
rg "require\(['\"]ws['\"]" --type ts
🧹 Nitpick comments (4)
test/e2e/utils.ts (1)

48-51: LGTM! Clear and consistent implementation.

The function follows the same pattern as faucetOffchain and correctly handles the satoshi-to-BTC conversion for the nigiri faucet command.

Consider adding a brief comment explaining the amount conversion logic:

 export function faucetOnchain(address: string, amount: number): void {
+    // Convert to BTC if amount is in satoshis (> 999)
     const btc = amount > 999 ? amount / 100_000_000 : amount;
     execSync(`nigiri faucet ${address} ${btc}`);
 }
test/e2e/ark.test.ts (1)

623-658: Review test implementation - offchain notification test.

The test structure is good, but consider these improvements for reliability:

 it(
     "should be notified of offchain incoming funds",
-    { timeout: 6000 },
+    { timeout: 10000 },
     async () => {
         const alice = await createTestWallet();
         const aliceAddress = (await alice.wallet.getAddress()).offchain;
         expect(aliceAddress).toBeDefined();

         let notified = false;
+        let stopNotification: (() => void) | undefined;
         const fundAmount = 10000;

         // set up the notification
-        alice.wallet.notifyIncomingFunds((coins) => {
+        alice.wallet.notifyIncomingFunds((coins, stopFunc) => {
             notified = true;
+            stopNotification = stopFunc;
             // ... rest of assertions
         });

         // wait for the notification to be set up
-        await new Promise((resolve) => setTimeout(resolve, 1000));
+        await new Promise((resolve) => setTimeout(resolve, 2000));

         // fund the offchain address using faucet
         faucetOffchain(aliceAddress!, fundAmount);

         // wait for the transaction to be processed
-        await new Promise((resolve) => setTimeout(resolve, 4000));
+        await new Promise((resolve) => setTimeout(resolve, 6000));
         expect(notified).toBeTruthy();
+
+        // Clean up notification
+        if (stopNotification) stopNotification();
     }
 );
src/providers/onchain.ts (1)

212-234: Optimize transaction comparison logic.

Using JSON.stringify for comparison is inefficient and can fail with circular references. Consider using a Set-based approach throughout.

Apply this diff to optimize the comparison:

-            // initial fetch to get existing transactions
-            const initialTxs = await getAllTxs();
+            // track known transactions using a Set
+            const knownTxKeys = new Set<string>();

             // we use block_time in key to also notify when a transaction is confirmed
             const txKey = (tx: ExplorerTransaction) =>
                 `${tx.txid}_${tx.status.block_time}`;

+            // initial fetch to populate known transactions
+            const initialTxs = await getAllTxs();
+            initialTxs.forEach(tx => knownTxKeys.add(txKey(tx)));

             // polling for new transactions
             const intervalId = setInterval(async () => {
                 // get current transactions
-                // we will compare with initialTxs to find new ones
                 const currentTxs = await getAllTxs();
+                const newTxs: ExplorerTransaction[] = [];

-                // if current transactions differ from initial, we have new transactions
-                if (JSON.stringify(currentTxs) !== JSON.stringify(initialTxs)) {
-                    // create a set of existing transactions to avoid duplicates
-                    const existingTxs = new Set(initialTxs.map(txKey));
-
-                    // filter out transactions that are already in initialTxs
-                    const newTxs = currentTxs.filter(
-                        (tx) => !existingTxs.has(txKey(tx))
-                    );
+                // check for new transactions
+                for (const tx of currentTxs) {
+                    const key = txKey(tx);
+                    if (!knownTxKeys.has(key)) {
+                        knownTxKeys.add(key);
+                        newTxs.push(tx);
+                    }
+                }

                     if (newTxs.length > 0) {
-                        initialTxs.push(...newTxs);
                         const stopFunc = () => clearInterval(intervalId);
                         callback(newTxs, stopFunc);
                     }
-                }
             }, pollingInterval);
README.md (1)

43-46: Fix template literal syntax in the example.

The console.log statement uses single quotes instead of backticks for template literals.

 wallet.notifyIncomingFunds((coins) => {
   const amount = coins.reduce((sum, a) => sum + a.value)
-  console.log('received ${coins.length} coins totalling ${amount} sats')
+  console.log(`received ${coins.length} coins totalling ${amount} sats`)
 })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3c79041 and 5502ed8.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (9)
  • README.md (5 hunks)
  • package.json (2 hunks)
  • src/providers/onchain.ts (3 hunks)
  • src/wallet/index.ts (1 hunks)
  • src/wallet/serviceWorker/wallet.ts (1 hunks)
  • src/wallet/wallet.ts (1 hunks)
  • test/e2e/ark.test.ts (3 hunks)
  • test/e2e/utils.ts (1 hunks)
  • test/esplora.test.ts (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/wallet/serviceWorker/wallet.ts (1)
Learnt from: louisinger
PR: arkade-os/ts-sdk#102
File: src/wallet/serviceWorker/worker.ts:381-385
Timestamp: 2025-07-01T07:27:31.768Z
Learning: In the Ark SDK, subdust UTXOs are included in the swept list, so the recoverable balance calculation in handleGetBalance correctly processes them when iterating through sweptVtxos and checking isSpendable.
🧬 Code Graph Analysis (2)
test/e2e/ark.test.ts (3)
test/e2e/utils.ts (3)
  • createTestWallet (26-40)
  • faucetOffchain (42-46)
  • faucetOnchain (48-51)
src/wallet/index.ts (2)
  • VirtualCoin (100-104)
  • Coin (95-98)
src/index.ts (2)
  • VirtualCoin (146-146)
  • Coin (132-132)
src/wallet/wallet.ts (3)
src/wallet/index.ts (2)
  • Coin (95-98)
  • VirtualCoin (100-104)
src/index.ts (3)
  • Coin (132-132)
  • VirtualCoin (146-146)
  • ArkAddress (84-84)
src/script/address.ts (1)
  • ArkAddress (6-55)
🪛 GitHub Check: test
test/e2e/ark.test.ts

[failure] 694-694: test/e2e/ark.test.ts > Wallet SDK Integration Tests > should be notified of onchain incoming funds
AssertionError: expected false to be truthy

  • Expected
  • Received
  • true
  • false

❯ test/e2e/ark.test.ts:694:30

src/providers/onchain.ts

[failure] 159-159: Unhandled error
ReferenceError: WebSocket is not defined
❯ EsploraProvider.watchAddresses src/providers/onchain.ts:159:20
❯ Wallet.notifyIncomingFunds src/wallet/wallet.ts:1032:34
❯ test/e2e/ark.test.ts:673:26
❯ processTicksAndRejections node:internal/process/task_queues:95:5
❯ node_modules/.pnpm/@vitest+runner@2.1.9/node_modules/@vitest/runner/dist/index.js:533:5
❯ runTest node_modules/.pnpm/@vitest+runner@2.1.9/node_modules/@vitest/runner/dist/index.js:1056:11
❯ runSuite node_modules/.pnpm/@vitest+runner@2.1.9/node_modules/@vitest/runner/dist/index.js:1205:15
❯ runSuite node_modules/.pnpm/@vitest+runner@2.1.9/node_modules/@vitest/runner/dist/index.js:1205:15
❯ runFiles node_modules/.pnpm/@vitest+runner@2.1.9/node_modules/@vitest/runner/dist/index.js:1262:5
❯ startTests node_modules/.pnpm/@vitest+runner@2.1.9/node_modules/@vitest/runner/dist/index.js:1271:3

This error originated in "test/e2e/ark.test.ts" test file. It doesn't mean the error was thrown inside the file itself, but while it was running.
The latest test that might've caused the error is "should be notified of onchain incoming funds". It might mean one of the following:

  • The error was thrown, while Vitest was running this test.
  • If the error occurred after the test had been completed, this was the last documented test before it was thrown.

[failure] 159-159: Unhandled error
ReferenceError: WebSocket is not defined
❯ EsploraProvider.watchAddresses src/providers/onchain.ts:159:20
❯ Wallet.notifyIncomingFunds src/wallet/wallet.ts:1032:34
❯ test/e2e/ark.test.ts:635:26
❯ processTicksAndRejections node:internal/process/task_queues:95:5
❯ node_modules/.pnpm/@vitest+runner@2.1.9/node_modules/@vitest/runner/dist/index.js:533:5
❯ runTest node_modules/.pnpm/@vitest+runner@2.1.9/node_modules/@vitest/runner/dist/index.js:1056:11
❯ runSuite node_modules/.pnpm/@vitest+runner@2.1.9/node_modules/@vitest/runner/dist/index.js:1205:15
❯ runSuite node_modules/.pnpm/@vitest+runner@2.1.9/node_modules/@vitest/runner/dist/index.js:1205:15
❯ runFiles node_modules/.pnpm/@vitest+runner@2.1.9/node_modules/@vitest/runner/dist/index.js:1262:5
❯ startTests node_modules/.pnpm/@vitest+runner@2.1.9/node_modules/@vitest/runner/dist/index.js:1271:3

This error originated in "test/e2e/ark.test.ts" test file. It doesn't mean the error was thrown inside the file itself, but while it was running.
The latest test that might've caused the error is "should be notified of offchain incoming funds". It might mean one of the following:

  • The error was thrown, while Vitest was running this test.
  • If the error occurred after the test had been completed, this was the last documented test before it was thrown.
🪛 GitHub Actions: CI
test/e2e/ark.test.ts

[error] 694-694: Test failure: 'Wallet SDK Integration Tests > should be notified of onchain incoming funds' failed with assertion error: expected false to be truthy.


[error] Unhandled ReferenceError: WebSocket is not defined during test run, causing potential false positive tests.

src/providers/onchain.ts

[error] 159-159: Unhandled rejection ReferenceError: WebSocket is not defined at EsploraProvider.watchAddresses.

🔇 Additional comments (5)
src/wallet/serviceWorker/wallet.ts (1)

31-33: LGTM! Clean exclusion of unsupported method.

The use of Omit<IWallet, "notifyIncomingFunds"> is a clean approach to exclude the notification method from ServiceWorkerWallet, which already handles notifications through IndexedDB and LiveQuery as discussed in past reviews.

src/wallet/index.ts (1)

171-177: LGTM! Well-designed method signature.

The method signature effectively addresses the discussed requirements:

  • Callback approach supports reactive UI updates
  • Union type Coin[] | VirtualCoin[] handles both onchain and offchain notifications
  • stopFunc parameter provides subscription control
  • Promise<void> return type indicates async setup completion
test/e2e/ark.test.ts (2)

1-1: Import statement looks good.

The addition of vi import and the test utilities aligns with the new test functionality.


23-26: LGTM! Appropriate imports for the new test functionality.

The import of faucet functions and coin types is necessary for the new notification tests.

test/esplora.test.ts (1)

1-315: Comprehensive test coverage for watchAddresses functionality!

The test suite thoroughly covers the WebSocket-based real-time transaction watching with proper mocking and edge case handling, including the fallback polling mechanism. Good use of Vitest's timer and mock utilities.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 1, 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
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

🧹 Nitpick comments (1)
src/providers/onchain.ts (1)

175-176: Consider more explicit WebSocket URL construction.

While the regex replacement works, a more explicit approach would improve code clarity and maintainability.

-        const wsUrl = this.baseUrl.replace(/^http(s)?:/, "ws$1:") + "/v1/ws";
+        const wsUrl = this.baseUrl.replace(/^https?:/, this.baseUrl.startsWith('https') ? 'wss:' : 'ws:') + "/v1/ws";

Alternatively, use URL constructor for more robust handling:

const url = new URL(this.baseUrl);
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = url.toString() + "/v1/ws";
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a3e9fad and df1a9ef.

📒 Files selected for processing (1)
  • src/providers/onchain.ts (3 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: louisinger
PR: arkade-os/ts-sdk#115
File: src/wallet/wallet.ts:821-822
Timestamp: 2025-07-07T17:02:26.687Z
Learning: In the Ark SDK, the Transaction.addOutputAddress() method from @scure/btc-signer already validates the output address format internally, so explicit validation before calling this method is redundant.
Learnt from: louisinger
PR: arkade-os/ts-sdk#102
File: src/wallet/serviceWorker/worker.ts:381-385
Timestamp: 2025-07-01T07:27:31.782Z
Learning: In the Ark SDK, subdust UTXOs are included in the swept list, so the recoverable balance calculation in handleGetBalance correctly processes them when iterating through sweptVtxos and checking isSpendable.
src/providers/onchain.ts (2)
Learnt from: louisinger
PR: arkade-os/ts-sdk#115
File: src/wallet/onchain.ts:180-187
Timestamp: 2025-07-07T17:02:12.316Z
Learning: In the OnchainWallet.bumpP2A method in src/wallet/onchain.ts, the return statement in the finally block is intentional. The method is designed to always return the transaction hex strings even if broadcasting fails, allowing callers to handle the transactions as needed.
Learnt from: bordalix
PR: arkade-os/ts-sdk#95
File: src/providers/onchain.ts:153-159
Timestamp: 2025-07-01T11:51:00.158Z
Learning: Node.js v22.4.0+ has stable WebSocket API support available as a global, contrary to older information suggesting WebSocket doesn't exist in Node.js environments.
🔇 Additional comments (4)
src/providers/onchain.ts (4)

16-16: Type change appropriately reflects API response format.

The change from bigint to string for the value field correctly aligns with JSON serialization requirements and the actual API response format.


24-52: Well-implemented type safety additions.

The isExplorerTransaction type guard and WebSocket interfaces provide excellent type safety for handling external API data and WebSocket messages.


178-212: Solid WebSocket event handling implementation.

The WebSocket event handlers are well-structured with proper error handling and message parsing. The filtering logic correctly validates transactions using the type guard.


262-268: Proper cleanup implementation.

The stop function correctly handles cleanup of both WebSocket connections and polling intervals with appropriate state checks.

louisinger and others added 4 commits July 10, 2025 09:00
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: louisinger <41042567+louisinger@users.noreply.github.com>
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 5169a44 and d62c2bd.

📒 Files selected for processing (1)
  • src/providers/onchain.ts (4 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: louisinger
PR: arkade-os/ts-sdk#115
File: src/wallet/wallet.ts:821-822
Timestamp: 2025-07-07T17:02:26.687Z
Learning: In the Ark SDK, the Transaction.addOutputAddress() method from @scure/btc-signer already validates the output address format internally, so explicit validation before calling this method is redundant.
Learnt from: louisinger
PR: arkade-os/ts-sdk#102
File: src/wallet/serviceWorker/worker.ts:381-385
Timestamp: 2025-07-01T07:27:31.782Z
Learning: In the Ark SDK, subdust UTXOs are included in the swept list, so the recoverable balance calculation in handleGetBalance correctly processes them when iterating through sweptVtxos and checking isSpendable.
src/providers/onchain.ts (2)
Learnt from: louisinger
PR: arkade-os/ts-sdk#115
File: src/wallet/onchain.ts:180-187
Timestamp: 2025-07-07T17:02:12.316Z
Learning: In the OnchainWallet.bumpP2A method in src/wallet/onchain.ts, the return statement in the finally block is intentional. The method is designed to always return the transaction hex strings even if broadcasting fails, allowing callers to handle the transactions as needed.
Learnt from: bordalix
PR: arkade-os/ts-sdk#95
File: src/providers/onchain.ts:153-159
Timestamp: 2025-07-01T11:51:00.158Z
Learning: Node.js v22.4.0+ has stable WebSocket API support available as a global, contrary to older information suggesting WebSocket doesn't exist in Node.js environments.
🧬 Code Graph Analysis (1)
src/providers/onchain.ts (1)
src/index.ts (1)
  • ExplorerTransaction (234-234)
🪛 Biome (1.9.4)
src/providers/onchain.ts

[error] 226-226: Expected an identifier, a string literal, a number literal, a private field name, or a computed name but instead found ')'.

Expected an identifier, a string literal, a number literal, a private field name, or a computed name here.

(parse)


[error] 228-228: expected a semicolon to end the class property, but found none

(parse)


[error] 233-233: expected a semicolon to end the class property, but found none

(parse)


[error] 233-233: Duplicate class member name "stopFunc"

(lint/suspicious/noDuplicateClassMembers)

🪛 GitHub Actions: CI
src/providers/onchain.ts

[error] 226-226: Prettier syntax error: Unexpected token at line 226. A constructor, method, accessor, or property was expected.

🔇 Additional comments (4)
src/providers/onchain.ts (4)

16-16: LGTM - Type change aligns with API response format.

The change from bigint to string for the value field correctly reflects the actual API response format from Esplora endpoints.


41-44: LGTM - Interface addition matches PR objectives.

The watchAddresses method signature correctly implements the required functionality to watch multiple addresses with a callback for transaction updates.


319-347: LGTM - Well-implemented type guards and interfaces.

The isExplorerTransaction type guard provides proper runtime validation, and the WebSocket interfaces clearly define the expected message format. The type checking aligns with the string value type for transaction outputs.


140-224: LGTM - Robust WebSocket implementation with proper fallback.

The implementation provides a solid foundation for real-time transaction monitoring with:

  • Proper WebSocket error handling and message processing
  • Efficient polling fallback mechanism with deduplication
  • Clean resource management with the stop function
  • Good error logging for debugging

The approach addresses the concerns raised in previous reviews about error handling and efficiency.

@louisinger louisinger changed the title new watchAddress method on onchain provider add Wallet.NotifyIncomingFunds method Jul 10, 2025
@louisinger
Copy link
Collaborator

Update

I've removed the websocket tests in esplora.test.ts because :

  1. we can assume built-in WebSocket is reliable
  2. it is tested in e2e tests
  3. we don't want testing variable in the interface

I've also added a type to the result of NotifyIncomingFunds callback in order to let the user knows if the notification is UTXOs or VTXOs.

@bordalix please review
@coderabbitai full review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 10, 2025

Tip

For best results, initiate chat on the files or code changes.

@louisinger Thank you for the updates and the clear explanation! The changes you've made are well-reasoned improvements.

Review Summary

Your updates address important concerns and enhance the implementation:

Excellent Design Decisions

  1. WebSocket Test Removal: Your reasoning is spot-on:

    • Built-in WebSocket reliability assumption is valid
    • E2E tests provide better integration coverage
    • Avoiding testing implementation details of external interfaces
  2. Discriminated Union Type: Adding the type field to IncomingFunds is a great UX improvement:

    type IncomingFunds = 
      | { type: "utxo"; coins: Coin[] }
      | { type: "vtxo"; vtxos: VirtualCoin[] }

    This makes it crystal clear to users whether they're receiving onchain UTXOs or offchain VTXOs.

🔍 Key Implementation Highlights

  • Robust Fallback Strategy: The watchAddresses method gracefully falls back to polling when WebSocket connections fail
  • Clean API Design: The notifyIncomingFunds method provides a simple callback interface with a stop function
  • Type Safety: The discriminated union prevents runtime confusion between coin types
  • Comprehensive Testing: E2E tests cover both onchain and offchain scenarios

💡 Minor Considerations

The implementation looks solid overall. The architectural decisions around WebSocket handling, type safety, and testing strategy are well-executed.

Full review triggered

The PR successfully adds the requested notification functionality while maintaining code quality and providing clear type distinctions for users.

@louisinger louisinger merged commit e60bfe0 into next-version Jul 10, 2025
2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jul 10, 2025
@louisinger louisinger deleted the utxo-listener branch July 10, 2025 11:30
louisinger added a commit that referenced this pull request Jul 11, 2025
* add arknote tests

* refactor arknote to v7

* make hrp a optional constructor variable

* refactor tests to test hrp

* update ci to work next-version branch

* add arknote integration test (#75)

* BIP322 Intents (#77)

* BIP322 intent

* also return message in the intents methods

* new round flow (#78)

setup test to target next-version branch

hotfix note in registerInputsForNextRound

fix signingSession.ts

* nit: better test instructions (#82)

* nit: better test instructions

* fix ci

* Intent registration (#80)

* new round flow

setup test to target next-version branch

hotfix note in registerInputsForNextRound

fix signingSession.ts

* use BIP0322 to register intent

* ArkNote implements ExtendedCoin

* allow all sighash types

* remove registerOutputsForNextRound API

* offchain transaction w/ checkpoints (#84)

* new round flow

setup test to target next-version branch

hotfix note in registerInputsForNextRound

fix signingSession.ts

* use BIP0322 to register intent

* implement checkpoints

* update examples

* fix register message

* fix tx history (#89)

* Support recoverable vtxos (#88)

* support recoverable vtxos

* update ci.yml

* fixes

* update e2e test

* Drop explorer for indexer (#83)

* drop explorer for indexer

* remove console.log

* fix on returned vtxos

* Update src/providers/ark.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: João Bordalo <bordalix@users.noreply.github.com>

* separates indexer to own provider

* private method createSubscription

* implements all methods on indexer provider

* remove console.logs

* fix build error

* add opts to indexer methods

* remove not needed export

* remove getRound() from ark provider

* cleanup ProtoTypes in ark provider

* fix export of RestIndexerProvider

* refactor indexer to use namespace

* adds type guards

* fixes

* new test

* Merge branch 'next-version' into drop_explorer_for_indexer

* remove console.log

* use paginationOptions

* more tests

* bug fix

* activate tx history test

* forfeit address

* make methods name lowercase

* update endpoints

* move indexer tests to indexer.test.ts

* update to latest APIs

* freeze test on commit deca5ef4699037dcc38a320e50478fc3eae957ec

* lint

* new util functions to create vtxos

* fixes with content-type

* new subscribeForScripts test

* fix tests

---------

Signed-off-by: João Bordalo <bordalix@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: louisinger <louis@vulpem.com>

* support for subdust vtxo in ark tx (#98)

* add checkpointTapLeafScript in VirtualTxInput (#101)

* Rework ark psbt fields (#105)

* rework ark psbt fields

* use constant as key.type

* fix decode

* TxGraph, new address and pub/sub (#100)

* add tx graph, remove tx tree class

* fix signingSession.ts and txGraph.ts

* new address encoding

* compatibilty with arkd next-version

* rename and move unilateral exit e2e test

* update examples

* update README.md

* update README.md

* add e2e test case

* update index.ts

* fixes indexer.go

* cleaning validation.go

* renaming tests

* Remove onchain wallet from `Wallet`, add `OnchainWallet` class (#102)

* add OnchainWallet class

* "send" --> "sendBitcoin"

* update WalletBalance

* fix src/index.ts

* fix ark.test.ts

* update README

* remove network from WalletConfig

* test on 783ba19512f0ddf87962a558576acc9389d0bd7e arkd

* fix serviceWorker/wallet.ts

* cleaning

* update WalletBalance

* get dust amount from server

* remove getAddressInfo

* getAddress & getBoardingAddress

* update README

* update tests

* update test/e2e/utils.ts

* Update to latest next-version arkd (#112)

* update to latest next-version arkd

* add more e2e indexer tests

* server.Dockerfile: test on next-version

* skip failing tests

* ServiceWorkerWallet implements Identity (#114)

* ServiceWorkerWallet implements Identity

* fix error message

* fix tests after arkd v0.7 (#118)

* Unilateral exit v7 (#115)

* add AnchorBumper interface and rework exit (renamed "unroll")

* unilareral exit v7

* update README

* Update src/wallet/wallet.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: louisinger <41042567+louisinger@users.noreply.github.com>

* Update src/wallet/wallet.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: louisinger <41042567+louisinger@users.noreply.github.com>

* fix selectcoins

* Revert "fix selectcoins"

This reverts commit 9a52311.

* cleaning coinselect.ts

* clean

* remove hardcoded 600 sats, add "forceChange" boolean in selectCoins

* handle undefined getFeeRate

* use blocks/tip endpoint

* Unroll namespace

* Update src/wallet/unroll.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: louisinger <41042567+louisinger@users.noreply.github.com>

* Update src/wallet/unroll.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: louisinger <41042567+louisinger@users.noreply.github.com>

* ark.test.ts: switch case

* add compleUnroll function, remove it from Wallet interface

---------

Signed-off-by: louisinger <41042567+louisinger@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* add Ramps class (#119)

* Update README.md

Signed-off-by: Marco Argentieri <3596602+tiero@users.noreply.github.com>

* Update to latest arkd,  renaming and TSDoc (#108)

* renaming

* remove unused imports

* update names, JSDocs

* update index.ts

* remove unused dev deps

* remove "lint-staged"

* add "arkade" keyword to pkg.json

* TSDoc

* add TSDoc generation

* add tsdoc.yml workflow

* remove upload

* use pnpm docs:build

* fix

* trigger TSDoc deploy on next-version and master push

* Update .github/workflows/tsdoc.yml

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: louisinger <41042567+louisinger@users.noreply.github.com>

* update to master (v0.7.0-rc2)

* update tsdoc.yml

* rename "chunk" to "node"

* rename InMemoryKey -> SingleKey

---------

Signed-off-by: louisinger <41042567+louisinger@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* tsdoc.yml: trigger on version tag

* update README.md

* add Wallet.NotifyIncomingFunds method (#95)

* new notifyIncomingFunds method on onchain provider

* track multi addresses

* ignore error

* new util function faucetOnchain()

* new wallet method notifyIncomingFunds()

* tests: make sure there was a notification

* Uses built in WebSocket instead of isomorphic-ws
Adds new stopFunc() in callback for notifyIncomingFunds
New tests on the WebSocket

* remove console.log

* polyfill WebSocket for github tests

* Update src/providers/onchain.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: João Bordalo <bordalix@users.noreply.github.com>

* new waitForIncomingFunds() func

* fix readme

* Update src/wallet/wallet.ts

Co-authored-by: louisinger <41042567+louisinger@users.noreply.github.com>
Signed-off-by: João Bordalo <bordalix@users.noreply.github.com>

* Update src/wallet/wallet.ts

Co-authored-by: louisinger <41042567+louisinger@users.noreply.github.com>
Signed-off-by: João Bordalo <bordalix@users.noreply.github.com>

* make waitForIncomingFunds a utils function

* Update src/providers/onchain.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: João Bordalo <bordalix@users.noreply.github.com>

* Update test/e2e/ark.test.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: João Bordalo <bordalix@users.noreply.github.com>

* update src/utils/waitForIncomingFunds.ts

* lint

* update readme

* Handle missing outputs gracefully instead of throwing errors

* Fix variable naming and incorrect property access.

* Improve WebSocket URL construction robustness

* fix test

* fix test

* refactor notifyIncomingFunds to return stopFunc

* refactor esplora tests

* Update README.md

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: João Bordalo <bordalix@users.noreply.github.com>

* Update src/utils/waitForIncomingFunds.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: João Bordalo <bordalix@users.noreply.github.com>

* Fix the infinite loop that prevents the method from returning

* fix docker files

* fix docker-compose.yml

* add VERSION to dockerfile

* skip "should redeem a note" test

* fix note test

* remove watchAddresses test

* remove "ws" devDeps

* remove testing purpose only interface parameter

* do not export unused types

* Update src/providers/onchain.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: louisinger <41042567+louisinger@users.noreply.github.com>

* remove setup-polyfill

* fix

* fallback to polling if WebSocket not available

* fix test

* fix test

* update README

* add SubscriptionResponse to index.ts exports

* remove MockWebSocket

* remove extra blanck line

* revert vitest.config.ts

---------

Signed-off-by: João Bordalo <bordalix@users.noreply.github.com>
Signed-off-by: louisinger <41042567+louisinger@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: louisinger <41042567+louisinger@users.noreply.github.com>
Co-authored-by: louisinger <louis@vulpem.com>

* add tsdoc comments (#120)

* handle FetchTimeout in new streaming functions

* remove duplicated code

* CI: run down to delete dev env

* freeze test on v0.7.0 tag

* update examples

* Dockerfiles: use tag to checkout v0.7.0

* remove useless docker env vars

* rename virtualTx -> arkTx

* fix capture ark logs in CI

* add sleep to indexer.test.ts

* arkade wallet  hotfix

---------

Signed-off-by: João Bordalo <bordalix@users.noreply.github.com>
Signed-off-by: louisinger <41042567+louisinger@users.noreply.github.com>
Signed-off-by: Marco Argentieri <3596602+tiero@users.noreply.github.com>
Co-authored-by: João Bordalo <bordalix@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Marco Argentieri <3596602+tiero@users.noreply.github.com>
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.

6 participants