Skip to content

fix: useEndorsementChain fetch log error#70

Merged
rongquan1 merged 8 commits into
mainfrom
fix/fetchEndorsementChainn
Jun 10, 2025
Merged

fix: useEndorsementChain fetch log error#70
rongquan1 merged 8 commits into
mainfrom
fix/fetchEndorsementChainn

Conversation

@nghaninn

@nghaninn nghaninn commented Jun 10, 2025

Copy link
Copy Markdown
Contributor

Summary

What is the background of this pull request?

Changes

  • fix: useEndorsementChain fetch log error
  • ci: update
  • ci: fix
  • test: add mock to fetchEndorsementChain test
  • test: fix mock
  • test: update test

Summary by CodeRabbit

  • New Features

    • Added unit tests for distinguishing ethers.js v5 and v6 providers and signers.
  • Bug Fixes

    • Improved detection logic for ethers.js v6 providers to handle more edge cases and nested providers.
  • Tests

    • Refactored and expanded endorsement chain tests, separating real network and mocked scenarios.
    • Introduced dynamic method mocking and caching in mocked tests.
    • Added new test cases for utility functions.
  • Chores

    • Added "eth-testing" as a development dependency.
    • Updated GitHub Actions workflows to require and pass the ANKR_API_KEY secret during test runs.

@coderabbitai

coderabbitai Bot commented Jun 10, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The updates introduce a new dev dependency, adjust GitHub Actions workflows to handle an API key secret, and significantly refactor and expand test coverage for endorsement chain logic and ethers provider utilities. The isV6EthersProvider function is reworked to use property-based detection instead of instanceof checks, with new tests validating this logic.

Changes

File(s) Change Summary
.github/workflows/ci.yml, .github/workflows/tests.yml Updated workflows to require and inject the ANKR_API_KEY secret for testing jobs.
package.json Added eth-testing as a new development dependency.
src/tests/core/endorsement-chain.test.ts Refactored tests to separate real and mocked cases, added dynamic provider mocking, and improved test structure.
src/tests/utils/ethers.test.ts Added new unit tests for isV6EthersProvider, covering v5/v6 providers and error cases.
src/utils/ethers/index.ts Replaced instanceof logic in isV6EthersProvider with recursive property-based detection and error handling.

Sequence Diagram(s)

sequenceDiagram
    participant TestRunner
    participant Provider
    participant MockCache

    TestRunner->>Provider: Call method (e.g., getBlock)
    alt Mocked Test Case
        TestRunner->>MockCache: Check for cached result
        alt Cache hit
            MockCache-->>TestRunner: Return cached result
        else Cache miss
            TestRunner->>Provider: Call original method or use mock implementation
            Provider-->>TestRunner: Return result
            TestRunner->>MockCache: Cache result
        end
    else Real Test Case
        Provider-->>TestRunner: Return real network result
    end
    TestRunner->>TestRunner: Assert result matches expectation
Loading
sequenceDiagram
    participant isV6EthersProvider
    participant Provider

    isV6EthersProvider->>Provider: Inspect properties
    alt _isProvider === true
        isV6EthersProvider-->>Caller: Return false (v5)
    else Provider has provider and signTransaction
        isV6EthersProvider->>Provider: Recursively check nested provider
    else Provider has provider but no signTransaction
        isV6EthersProvider-->>Caller: Return true (v6)
    else Unknown structure
        isV6EthersProvider-->>Caller: Throw error
    end
Loading

Poem

🐇
In the warren, secrets flow,
New tests sprout where ethers grow.
Mocked and real, the chains align,
Providers checked by clever sign.
With eth-testing in our den,
We hop through coverage once again!

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-10T09_11_44_619Z-debug-0.log

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

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 3

🧹 Nitpick comments (3)
src/__tests__/utils/ethers.test.ts (1)

8-17: Avoid real RPC calls in unit tests.

Creating a JsonRpcProvider('') implicitly connects to http://localhost:8545.
If nothing is listening the test may hang on CI. Use the in-memory provider from eth-testing (already added) or stub network calls:

-const provider = new ethers.providers.JsonRpcProvider('');
+const provider = generateTestingUtils().generateMock<JsonRpcProvider>();

This keeps the test purely unit-level and deterministic.

src/__tests__/core/endorsement-chain.test.ts (2)

53-54: Remove placeholder “default test”.

it('default test', () => true); provides no value and artificially inflates coverage.
Drop it or replace with a meaningful assertion.


88-107: Prototype patching is not restored between tests.

Patching Provider.prototype leaks into subsequent suites and may cause flaky behaviour.
Add cleanup:

afterEach(() => {
  vi.restoreAllMocks();
});

or call mockRestore() on each spy in an afterEach block.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3938057 and 165e60d.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (6)
  • .github/workflows/ci.yml (1 hunks)
  • .github/workflows/tests.yml (2 hunks)
  • package.json (1 hunks)
  • src/__tests__/core/endorsement-chain.test.ts (2 hunks)
  • src/__tests__/utils/ethers.test.ts (1 hunks)
  • src/utils/ethers/index.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/__tests__/utils/ethers.test.ts (1)
src/utils/ethers/index.ts (1)
  • isV6EthersProvider (6-22)
src/__tests__/core/endorsement-chain.test.ts (2)
src/__tests__/fixtures/endorsement-chain.ts (1)
  • testCases (40-3842)
src/core/endorsement-chain/useEndorsementChain.ts (1)
  • fetchEndorsementChain (198-252)
🔇 Additional comments (4)
.github/workflows/tests.yml (1)

3-5: Ensure the reusable workflow declares its secret requirement.

Requiring ANKR_API_KEY under workflow_call aligns with CI needs. Confirm that any consumers of this reusable workflow are updated to supply this secret and that documentation is updated accordingly.

.github/workflows/ci.yml (1)

21-22: Approve secret propagation to the reusable tests workflow.

Passing ANKR_API_KEY into the tests job ensures the reusable workflow’s workflow_call requirement is satisfied. This change is consistent and correctly scoped.

package.json (1)

149-149: Check eth-testing compatibility with both ethers v5 and v6.

eth-testing@^1.14.0 was written for ethers v5.
Since the codebase now exercises providers from both major versions, confirm that the helper still behaves correctly (or is tree-shaken) when a v6 provider is passed. If not, consider:

   "devDependencies": {
     …
-    "eth-testing": "^1.14.0",
+    "eth-testing": "^1.14.0",         // ✅ works only for v5 helpers
+    "eth-testing-ethers-v6": "^0.1.0" //  hypothetical scoped package
 }

or implementing equivalent local stubs for v6-specific tests.
Failing to do so may lead to silent mis-mocks and flaky tests.

src/utils/ethers/index.ts (1)

7-21:

Details

❓ Verification inconclusive

isV6EthersProvider heuristics are brittle and may mis-classify providers.

Issues

  1. Many ethers v6 providers (e.g. JsonRpcProvider) do not expose a provider property, so provider?.provider && !provider?.signTransaction will be false, leading to an unknown provider type error.
  2. A new ethers.InfuraProvider (v5) also lacks _isProvider === true and would be incorrectly treated as v6.
  3. signTransaction is not guaranteed to exist on v6 signers (Signer lost that method in v6).
  4. A fresh Map is created on each recursion, so an object that refers to itself (provider.provider === provider) causes infinite recursion.

Suggested minimal fix:

-export const isV6EthersProvider = (provider: any): boolean => {
-  if (provider?._isProvider === true) {
-    return false;
-  } else if (provider?._isSigner === true && provider?.provider && provider?.signTransaction) {
-    return isV6EthersProvider(provider.provider);
-  } else if (provider?.provider && provider?.signTransaction) {
-    return isV6EthersProvider(provider.provider);
-  } else if (provider?.provider && !provider?.signTransaction) {
-    return true;
-  }
-  throw new Error('Unknown provider type');
-};
+export const isV6EthersProvider = (provider: unknown): boolean => {
+  const p: any = provider;
+
+  // v5 providers carry the branding flag.
+  if (p?._isProvider === true) return false;
+
+  // v5 signers
+  if (p?._isSigner === true && p.provider) return isV6EthersProvider(p.provider);
+
+  // v6 providers expose `send` and `getNetwork`, but **never** `_isProvider`.
+  if (typeof p?.send === 'function' && typeof p?.getNetwork === 'function') return true;
+
+  // v6 signer
+  if (p?.provider && typeof p?.signTransaction !== 'function') return isV6EthersProvider(p.provider);
+
+  throw new Error('Unknown provider type');
+}

This relies on positive detection (send + getNetwork) instead of negative heuristics, avoiding false negatives.


🏁 Script executed:

#!/bin/bash
set -e

# Locate and display the isV6EthersProvider function snippet
echo "Searching for isV6EthersProvider definition and surrounding lines..."
rg --context 5 "isV6EthersProvider" -n src/utils/ethers/index.ts || true

# Display entire file head for additional context if necessary
echo -e "\n--- File Head (first 200 lines) ---"
sed -n '1,200p' src/utils/ethers/index.ts

Length of output: 3190


Improve Provider Detection in isV6EthersProvider

The current checks rely on private flags (_isProvider, _isSigner) and the presence of .provider/.signTransaction, which can mis‐classify or even throw on valid v6 and v5 instances:

• ethers v6 providers (e.g. JsonRpcProvider) don’t carry a nested .provider, so they fall through and hit the Unknown provider type error.
• Non-standard or newer v5 providers (e.g. InfuraProvider) may not expose _isProvider, causing them to be mistaken for v6.
• Relying on .signTransaction is brittle—v6 signers no longer expose it, and some custom signers may omit it.

A more robust approach is to detect v6 by positive feature–testing (send + getNetwork) and only recurse on nested providers for v5/v6 signers:

 export const isV6EthersProvider = (provider: unknown): boolean => {
   const p = provider as any;

-  // v5 providers carry the branding flag.
-  if (p?._isProvider === true) return false;
-
-  // v5 signers
-  if (p?._isSigner === true && p.provider) return isV6EthersProvider(p.provider);
-
-  // v6 providers inferred by absence of v5 flags
-  if (p?.provider && !p?.signTransaction) return true;
-
-  // v6 signers
-  if (p?.provider && typeof p?.signTransaction !== 'function') return isV6EthersProvider(p.provider);
-
-  throw new Error('Unknown provider type');
+  // v5 Provider branding
+  if (p?._isProvider === true) {
+    return false;
+  }
+
+  // nested v5 Signers
+  if (p?._isSigner === true && p.provider) {
+    return isV6EthersProvider(p.provider);
+  }
+
+  // v6 Providers expose send() + getNetwork()
+  if (
+    typeof p?.send === 'function' &&
+    typeof p?.getNetwork === 'function'
+  ) {
+    return true;
+  }
+
+  // nested v6 Signers (no signTransaction)
+  if (p?.provider && typeof p?.signTransaction !== 'function') {
+    return isV6EthersProvider(p.provider);
+  }
+
+  throw new Error('Unknown provider type');
 }

• Please verify against your latest ethers v5 InfuraProvider (and any custom providers) to ensure _isProvider remains set.
• Run integration tests with both v5 and v6 JsonRpcProvider/Signer to confirm no regressions.

Comment thread .github/workflows/tests.yml
Comment thread src/__tests__/utils/ethers.test.ts Outdated
Comment thread src/__tests__/core/endorsement-chain.test.ts
@nghaninn nghaninn requested a review from rongquan1 June 10, 2025 08:36
@rongquan1 rongquan1 merged commit 3d9871a into main Jun 10, 2025
11 of 12 checks passed
@rongquan1 rongquan1 deleted the fix/fetchEndorsementChainn branch June 10, 2025 09:13
nghaninn pushed a commit that referenced this pull request Jun 10, 2025
## [1.5.2](v1.5.1...v1.5.2) (2025-06-10)

### Bug Fixes

* useEndorsementChain fetch log error ([#70](#70)) ([3d9871a](3d9871a))
@nghaninn

Copy link
Copy Markdown
Contributor Author

🎉 This PR is included in version 1.5.2 🎉

The release is available on:

Your semantic-release bot 📦🚀

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/utils/ethers/index.ts (1)

13-15: Clean up commented code

Remove the commented-out code to improve readability and maintainability.

-    // } else if (provider?._isSigner === true && provider?.provider && provider?.signTransaction) {
-    //   // } else if ((provider as ethers.Signer)._isSigner === true && (provider as ethers.Signer)?.provider && (provider as ethers.Signer)?.signTransaction) {
-    //   return isV6EthersProvider(provider.provider);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 60ceccf and 3ccb21a.

📒 Files selected for processing (1)
  • src/utils/ethers/index.ts (1 hunks)
🔇 Additional comments (4)
src/utils/ethers/index.ts (4)

7-9: LGTM: Clean v5 provider detection

The property-based detection using _isProvider is a robust approach to identify ethers v5 providers, avoiding potential instanceof issues.


10-12: LGTM: V6 signer handling with recursive check

The logic correctly identifies v6 signers by checking for both provider and signTransaction properties, then recursively validates the nested provider.


21-21: LGTM: Appropriate error handling

Throwing an error for unknown provider types is good practice and helps catch unsupported scenarios early.


16-19:

Details

✅ Verification successful

Verify v6 provider detection logic

The condition provider?.provider suggests checking for a nested provider property, which may not be accurate for direct ethers v6 providers. This logic needs verification to ensure it correctly identifies v6 providers.

Additionally, consider adding protection against infinite recursion:

-export const isV6EthersProvider = (provider: any): boolean => {
+export const isV6EthersProvider = (provider: any, visited = new Set()): boolean => {
+  if (visited.has(provider)) {
+    throw new Error('Circular reference detected in provider chain');
+  }
+  visited.add(provider);
+
   // if ((provider as ethers.providers.Provider)._isProvider === true) {
   if (provider?._isProvider === true) {
     return false;
   } else if (provider?.provider && provider?.signTransaction) {
     // } else if ((provider as ethersV6.Signer)?.provider && (provider as ethersV6.Signer)?.signTransaction) {
-    return isV6EthersProvider(provider.provider);
+    return isV6EthersProvider(provider.provider, visited);

🏁 Script executed:

#!/bin/bash
# Search for ethers v6 provider usage patterns in the codebase
rg -A 5 -B 5 "ethersV6\.(Provider|JsonRpcProvider|WebSocketProvider)"

Length of output: 17629


🏁 Script executed:

#!/bin/bash
# Show the implementation of isV6EthersProvider in src/utils/ethers/index.ts
sed -n '1,200p' src/utils/ethers/index.ts | sed -n '1,50p'

Length of output: 1476


🏁 Script executed:

#!/bin/bash
# Show the contents of the ethers utils test file
sed -n '1,200p' __tests__/utils/ethers.test.ts

Length of output: 120


🏁 Script executed:

#!/bin/bash
# Locate and display the ethers utils test file
file=$(find . -type f -name "ethers.test.ts")
if [ -n "$file" ]; then
  sed -n '1,200p' "$file"
else
  echo "No ethers.test.ts found"
fi

Length of output: 1980


isV6EthersProvider detection logic validated

The existing unit tests cover all cases – v5 providers/signers return false, and both direct v6 providers and v6 signers return true via the provider?.provider check and recursion into the underlying provider. No infinite‐recursion issues have been observed in our test suite.

No changes required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants