Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ This is a hosted version of [example](/example).
| [`@web3-react/types`](packages/types) | [![npm](https://img.shields.io/npm/v/@web3-react/types/beta.svg)](https://www.npmjs.com/package/@web3-react/types/v/beta) | [![minzip](https://img.shields.io/bundlephobia/minzip/@web3-react/types/beta.svg)](https://bundlephobia.com/result?p=@web3-react/types@beta) | |
| [`@web3-react/store`](packages/store) | [![npm](https://img.shields.io/npm/v/@web3-react/store/beta.svg)](https://www.npmjs.com/package/@web3-react/store/v/beta) | [![minzip](https://img.shields.io/bundlephobia/minzip/@web3-react/store/beta.svg)](https://bundlephobia.com/result?p=@web3-react/store@beta) | |
| [`@web3-react/core`](packages/core) | [![npm](https://img.shields.io/npm/v/@web3-react/core/beta.svg)](https://www.npmjs.com/package/@web3-react/core/v/beta) | [![minzip](https://img.shields.io/bundlephobia/minzip/@web3-react/core/beta.svg)](https://bundlephobia.com/result?p=@web3-react/core@beta) | |
| [`@web3-react/connection-monitor`](packages/connection-monitor) | 🆕 New | 🆕 New | Connection health monitoring & auto-recovery |
| **Connectors** | | | |
| [`@web3-react/eip1193`](packages/eip1193) | [![npm](https://img.shields.io/npm/v/@web3-react/eip1193/beta.svg)](https://www.npmjs.com/package/@web3-react/eip1193/v/beta) | [![minzip](https://img.shields.io/bundlephobia/minzip/@web3-react/eip1193/beta.svg)](https://bundlephobia.com/result?p=@web3-react/eip1193@beta) | [EIP-1193](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md) |
| [`@web3-react/empty`](packages/empty) | [![npm](https://img.shields.io/npm/v/@web3-react/empty/beta.svg)](https://www.npmjs.com/package/@web3-react/empty/v/beta) | [![minzip](https://img.shields.io/bundlephobia/minzip/@web3-react/empty/beta.svg)](https://bundlephobia.com/result?p=@web3-react/empty@beta) | |
Expand Down Expand Up @@ -42,7 +43,7 @@ In addition to compiling each package in watch mode, this will also spin up [/ex

## Publish

- `yarn lerna publish [--dist-tag] `
- `yarn lerna publish [--dist-tag]`

## Documentation

Expand Down
43 changes: 35 additions & 8 deletions packages/coinbase-wallet/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ export class CoinbaseWallet extends Connector {
return !!this.provider?.selectedAddress
}

// Store bound listener references for proper cleanup
private connectListener?: (connectInfo: ProviderConnectInfo) => void
private disconnectListener?: (error: ProviderRpcError) => void
private chainChangedListener?: (chainId: string) => void
private accountsChangedListener?: (accounts: string[]) => void

private async isomorphicInitialize(): Promise<void> {
if (this.eagerConnection) return

Expand All @@ -54,27 +60,34 @@ export class CoinbaseWallet extends Connector {
this.coinbaseWallet = new m.default(options)
this.provider = this.coinbaseWallet.makeWeb3Provider(url)

this.provider.on('connect', ({ chainId }: ProviderConnectInfo): void => {
// Create bound listener functions for proper cleanup
this.connectListener = ({ chainId }: ProviderConnectInfo): void => {
this.actions.update({ chainId: parseChainId(chainId) })
})
}

this.provider.on('disconnect', (error: ProviderRpcError): void => {
this.disconnectListener = (error: ProviderRpcError): void => {
this.actions.resetState()
this.onError?.(error)
})
}

this.provider.on('chainChanged', (chainId: string): void => {
this.chainChangedListener = (chainId: string): void => {
this.actions.update({ chainId: parseChainId(chainId) })
})
}

this.provider.on('accountsChanged', (accounts: string[]): void => {
this.accountsChangedListener = (accounts: string[]): void => {
if (accounts.length === 0) {
// handle this edge case by disconnecting
this.actions.resetState()
} else {
this.actions.update({ accounts })
}
})
}

// Register event listeners
this.provider.on('connect', this.connectListener)
this.provider.on('disconnect', this.disconnectListener)
this.provider.on('chainChanged', this.chainChangedListener)
this.provider.on('accountsChanged', this.accountsChangedListener)
}))
}

Expand Down Expand Up @@ -179,7 +192,21 @@ export class CoinbaseWallet extends Connector {

/** {@inheritdoc Connector.deactivate} */
public deactivate(): void {
// Remove all event listeners to prevent memory leaks
if (
this.provider &&
this.connectListener &&
this.disconnectListener &&
this.chainChangedListener &&
this.accountsChangedListener
) {
this.provider.removeListener('connect', this.connectListener)
this.provider.removeListener('disconnect', this.disconnectListener)
this.provider.removeListener('chainChanged', this.chainChangedListener)
this.provider.removeListener('accountsChanged', this.accountsChangedListener)
}
this.coinbaseWallet?.disconnect()
this.actions.resetState()
}

public async watchAsset({
Expand Down
86 changes: 86 additions & 0 deletions packages/connection-monitor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# @web3-react/connection-monitor

## Overview

A robust connection health monitoring system for web3-react connectors that provides:

- **Automatic health checks** - Periodic verification that providers are still responsive
- **Stale connection detection** - Identifies when a connection has gone bad without explicit disconnect
- **Request deduplication** - Prevents duplicate concurrent requests to the same method
- **Graceful degradation** - Automatic reconnection attempts with exponential backoff
- **Memory leak prevention** - Proper cleanup of timers and event listeners

## Installation

```bash
yarn add @web3-react/connection-monitor
```

## Usage

```typescript
import { useConnectionMonitor } from '@web3-react/connection-monitor'
import { useWeb3React } from '@web3-react/core'

function MyComponent() {
const { connector, provider } = useWeb3React()

const { isHealthy, lastChecked, reconnect } = useConnectionMonitor(connector, provider, {
checkInterval: 30000, // Check every 30 seconds
timeout: 5000, // 5 second timeout for health checks
maxRetries: 3, // Maximum reconnection attempts
onStale: () => console.warn('Connection went stale'),
onRecover: () => console.log('Connection recovered')
})

return (
<div>
<p>Connection: {isHealthy ? '✅ Healthy' : '❌ Unhealthy'}</p>
<p>Last checked: {lastChecked?.toLocaleTimeString()}</p>
{!isHealthy && <button onClick={reconnect}>Reconnect</button>}
</div>
)
}
```

## API

### `useConnectionMonitor(connector, provider, options)`

**Parameters:**

- `connector`: The web3-react connector to monitor
- `provider`: The provider instance (optional, will use connector.provider if not provided)
- `options`: Configuration options

**Options:**

- `checkInterval` (number): Milliseconds between health checks (default: 30000)
- `timeout` (number): Health check timeout in milliseconds (default: 5000)
- `maxRetries` (number): Maximum automatic reconnection attempts (default: 3)
- `enabled` (boolean): Enable/disable monitoring (default: true)
- `onStale` (callback): Called when connection becomes stale
- `onRecover` (callback): Called when connection recovers
- `onError` (callback): Called on health check errors

**Returns:**

- `isHealthy` (boolean): Current connection health status
- `lastChecked` (Date | null): Timestamp of last health check
- `consecutiveFailures` (number): Count of consecutive failed checks
- `reconnect` (function): Manual reconnection trigger
- `reset` (function): Reset failure counter

## How It Works

1. **Periodic Health Checks**: Sends `eth_chainId` requests to verify provider responsiveness
2. **Stale Detection**: Monitors for connections that appear active but don't respond
3. **Smart Recovery**: Exponential backoff for reconnection attempts
4. **Resource Cleanup**: Automatically cleans up timers when component unmounts

## Benefits

- Prevents user frustration from silent connection failures
- Reduces support tickets from "stuck" connections
- Improves overall application reliability
- Zero-config with sensible defaults
36 changes: 36 additions & 0 deletions packages/connection-monitor/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "@web3-react/connection-monitor",
"version": "1.0.0",
"description": "Connection health monitoring and automatic recovery for web3-react connectors",
"keywords": [
"web3",
"ethereum",
"react",
"hooks",
"connector",
"health-check",
"monitoring"
],
"repository": {
"type": "git",
"url": "https://github.com/Uniswap/web3-react.git",
"directory": "packages/connection-monitor"
},
"license": "GPL-3.0-or-later",
"author": "Uniswap",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "tsc",
"prepublish": "yarn build"
},
"peerDependencies": {
"@web3-react/types": "^8.0.0",
"react": ">=18"
},
"dependencies": {},
"devDependencies": {}
}
Loading