Fix/memory leaks and connection monitor #961
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Critical Bug Fixes and Utility Packages
Summary
This PR addresses three critical production bugs and introduces two utility packages to improve reliability and maintainability across the web3-react ecosystem.
Critical Bug Fixes
1. WalletConnect v1 ChainId Parsing Bug
Impact: All WalletConnect v1 connections fail with NaN chainId values, breaking the entire connection flow.
Root Cause:
The
parseInt()function inpackages/walletconnect/src/index.ts(line 14) was called without the radix parameter:Solution:
Created a standardized
parseChainId()utility in the new@web3-react/utilspackage that properly handles hex strings, decimal strings, and numeric inputs with comprehensive validation.2. Memory Leaks in Event Listeners
Impact: Memory accumulates indefinitely when users switch between connectors in long-running applications.
Files Affected:
packages/metamask/src/index.tspackages/coinbase-wallet/src/index.tspackages/eip1193/src/index.tsRoot Cause:
Connectors registered event listeners on provider connect/disconnect/chainChanged/accountsChanged events but never removed them during connector deactivation.
Solution:
Added
deactivate()methods to all affected connectors that properly remove event listeners and reset state:3. setTimeout Memory Leaks in Network Provider Selection
Impact: Timeout handlers are never cleared in the
getBestProvider()function, causing memory leaks and potential unexpected behavior.File:
packages/network/src/utils.tsRoot Cause:
The function created multiple
setTimeoutcalls for provider health checks but never stored or cleared the timeout IDs.Solution:
Track all timeout IDs and clear them when the fastest provider responds or when all providers fail:
New Packages
1. @web3-react/utils - Standardized Validation Utilities
Purpose: Provide consistent validation and parsing utilities to prevent bugs across all connectors.
Exports:
parseChainId(chainId: string | number): number- Safe chainId parsing with validation for NaN, negative values, and values exceeding MAX_SAFE_INTEGERvalidateAccounts(accounts: unknown): string[]- Validates accounts array is non-empty before usegetFirstAccount(accounts: string[] | undefined): string | undefined- Safe first account retrievalformatChainIdToHex(chainId: number): string- Converts chainId to hex format for RPC callsKNOWN_CHAINS- Metadata object containing information for 15+ blockchain networksisKnownChain(chainId: number): boolean- Check if chainId is in known chainsgetChainInfo(chainId: number)- Retrieve metadata for a specific chainBenefits:
2. @web3-react/connection-monitor - Connection Health Monitoring
Purpose: Detect and recover from stale connections that appear connected but are unresponsive.
Features:
eth_chainIdRPC callsAPI:
Use Case:
Applications can now detect when a wallet connection has silently failed (network issues, wallet crashed, etc.) and automatically attempt reconnection or notify users.
3. @web3-react/request-queue - Priority Request Queue
Purpose: Serialize critical wallet operations to prevent race conditions and concurrent wallet UI conflicts.
Features:
eth_requestAccountsandwallet_switchEthereumChainBenefits:
Testing
@web3-react/utilspackage@web3-react/connection-monitorhookBackward Compatibility
This PR is 100% backward compatible. No breaking changes were introduced.
deactivate()methods are optional additionsMigration Path
Optional: Adopt Standardized Utilities
Connectors can migrate to use the shared utilities:
Optional: Add Connection Monitoring
Applications can add health monitoring:
Files Changed
Bug Fixes
packages/metamask/src/index.ts- Added event listener cleanuppackages/coinbase-wallet/src/index.ts- Added event listener cleanuppackages/eip1193/src/index.ts- Added event listener cleanup and deactivate methodpackages/network/src/utils.ts- Added timeout cleanup in getBestProvidertsconfig.json- Added esModuleInterop for proper module importsNew Packages
packages/utils/- New standardized utilities packagepackages/connection-monitor/- New health monitoring packagepackages/request-queue/- New request queue packageDocumentation
@web3-react/utils@web3-react/connection-monitor@web3-react/request-queueChecklist
Additional Notes
The WalletConnect chainId parsing bug is particularly severe as it causes complete connection failure. This issue was not addressed by any existing open PRs and represents a critical production bug.
The memory leak fixes prevent resource exhaustion in long-running applications where users frequently switch between wallets or networks.
The new utility packages provide optional enhancements that improve reliability and developer experience without requiring any changes to existing code.