# @electrum-cash/web-socket

> @electrum-cash/web-socket implements the ElectrumSocket interface using web sockets.

Latest version **4.0.3** (published 2026-09-16) · MIT license · 0 weekly downloads

## Install

```sh
npm install @electrum-cash/web-socket
pnpm add @electrum-cash/web-socket
yarn add @electrum-cash/web-socket
bun add @electrum-cash/web-socket
```

## Health

**Score 70/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; recently updated; high maintenance score; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 4.0.3 |
| Published | 2026-09-16 |
| First published | 2024-10-11 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM |
| Dependencies | 8 |
| Unpacked size | 55 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Jonathan Silverblood |
| Maintainers | monsterbitar |
| Keywords | electrum, bitcoin, bitcoin cash |

## Links

- npm: https://www.npmjs.com/package/@electrum-cash/web-socket
- Repository: https://gitlab.com/electrum-cash/web-socket
- Homepage: https://gitlab.com/electrum-cash/web-socket#readme
- Issues: https://gitlab.com/electrum-cash/web-socket/issues
- npm.io page: https://npm.io/package/@electrum-cash/web-socket

## Dependencies (8)

- [ws](https://npm.io/package/ws.md) ^8.13.0
- [@types/ws](https://npm.io/package/@types/ws.md) ^8.5.5
- [async-mutex](https://npm.io/package/async-mutex.md) ^0.5.0
- [eventemitter3](https://npm.io/package/eventemitter3.md) ^5.0.1
- [lossless-json](https://npm.io/package/lossless-json.md) ^4.0.1
- [@electrum-cash/socket](https://npm.io/package/@electrum-cash/socket.md) ^4.0.0
- [@electrum-cash/debug-logs](https://npm.io/package/@electrum-cash/debug-logs.md) ^1.0.0
- [@monsterbitar/isomorphic-ws](https://npm.io/package/@monsterbitar/isomorphic-ws.md) ^5.3.0

## Recent versions

- 4.0.3 (latest) — 2026-09-16
- 4.0.2-development.16509686236 (development) — 2026-09-15
- 4.0.2 — 2026-09-15
- 4.0.1 — 2026-09-13
- 4.0.1-development.16470117584 — 2026-09-13
- 4.0.0-development.13005454293 — 2026-02-05
- 4.0.0-development.13005283199 — 2026-02-05
- 4.0.0-development.13004898146 — 2026-02-05
- 4.0.0-development.13003410370 — 2026-02-05
- 4.0.0-development.13002798518 — 2026-02-05
- 4.0.0-development.13000747253 — 2026-02-05
- 4.0.0-development.13000345946 — 2026-02-05
- 4.0.0-development.12998368427 — 2026-02-05
- 4.0.0-development.12998123950 — 2026-02-05
- 4.0.0-development.12997687390 — 2026-02-05
- … 28 more at https://npm.io/package/@electrum-cash/web-socket/versions

## README

# Electrum-Cash Web Socket

This package provides a configurable `ElectrumSocket` that works in both NodeJS and browser settings, with consistent behavior across various environments by default.

## Features

the `ElectrumSocket` is a wrapper for a `WebSocket` with the following added features:

- Has promise-based and idempotent interfaces.
- Uses the `debug` package for configurable logging levels.
- Initial connections time out rather than linger in a stalled state.
- Can automatically suspend to save battery based on browser visibility and connectivity.

## Usage

### Imports

Before using this package, you need to import it:

```ts
import { ElectrumWebSocket } from '@electrum-cash/web-socket';
```

To properly handle all possible errors, also import the custom error types:

```ts
import type {
	SocketInternalError,
	SocketTimeoutError,
	SocketConnectionError,
	SocketWriteError,
} from '@electrum-cash/web-socket`;
```

### Creating an ElectrumWebSocket

First, create an instance of the socket with:

```ts
// Create the web socket with default behavior.
const socket = new ElectrumWebSocket('hostNameOrIPNumber');
```

Alternatively, you can configure the socket behavior by providing one or more options:

```ts
// Optionally configure socket behavior with one or more of the ElectrumSocketOptions properties.
const options =
{
	enforceConsistentBrowserBehavior: false,
}

// Create the web socket with customized behavior.
const socket = new ElectrumWebSocket('hostNameOrIPNumber', options);
```

### Connecting to the host

After you have created an ElectrumWebSocket, you can connect with the host:

```ts
await socket.connect();
```

### Disconnecting from a host

When you no longer need the ElectrumWebSocket, you can disconnect from the host:

```ts
await socket.disconnect();
```

### Sending messages

While connected, you can send messages with:

```ts
await socket.write('YourTextMessageHere');
```

### Receiving messages

To receive messages from the socket, listen to the `data` emitted events.

```ts
// Set up handler for incoming data.
const onSocketData = async function(data: string)
{
	console.log(data);
}

// Register handler for incoming data.
socket.addEventListener('data', onSocketData);
```

### Managing connection

The socket also emits `connected` and `disconnected` event over its lifetime:

```ts
// Signal indicating that the socket has connected.
socket.addEventListener('connected', onSocketConnected);

// Signal indicating that the socket has disconnected.
socket.addEventListener('disconnected', onSocketDisconnected);
```

### Handling errors

When connecting the socket, you might get a promise rejection containing an error:

```ts
try
{
	await socket.connect();
}
catch (error)
{
	// Internal errors are bugs in the implementation, simply log and move on.
	if(error instanceof SocketInternalError)
	{
		console.error(error);
	}

	// Timeout during connection could be network or host problems, try again later?
	if(error instanceof SocketTimeoutError)
	{
		// Code to try again later
	}

	// Connection errors range from being something you can handle, to things outside of your control.
	if(error instanceof SocketConnectionError)
	{
		// Inspect error.message for more details, or just log, like this:
		console.error(error);
	}
}
```

When writing to the socket, you might get a promise rejection containing an error:

```ts
try
{
	await socket.write('message');
}
catch (error)
{
	// Internal errors are bugs in the implementation, simply log and move on.
	if(error instanceof SocketInternalError)
	{
		console.error(error);
	}

	// Write errors means the data was not sent, so maybe try again later?
	if(error instanceof SocketWriteError)
	{
		// Code to try again later
	}
}
```

## Change Log

### v4.0

#### Safety

- The following calls are now idempotent: `connect()`, `disconnect()`, `write()`.
- The following calls now return a promise that resolves or reject when the action is completed: `connect()`, `disconnect()`.
- The following calls are now safe to use concurrently: `connect()`, `disconnect()`, `write()`.
- There is now four new custom errors: `SocketInternalError`, `SocketTimeoutError`, `SocketConnectionError` and `SocketWriteError`
- Event listeners are now assigned in only one place, and ensured not to create duplicates.
- Added edge-case and error handling tests.
- Added @throws to all calls that can throw.

#### Features

- There is now four new utility functions to return current state: `isConnecting()`, `isConnected()`, `isDisconnecting` and `isDisconnected`.
- Self-signed certificates are now allowed when `enforceBrowserConsistency` is set to `false`, and running in a non-browser environment.

#### Cleanups

- removed `error` events as these are now handled with promise rejections.
- removed support for sending `Uint8Array`s, as the electrum protocol only sends strings.

### v1.2

- Handle browser visibilty and connectivity events consistently.
- Added basic happy-path tests.

### v1.1

- Changed library bundler to tsdown

### v1.0

- Initial release

---
_Source: https://npm.io/package/@electrum-cash/web-socket · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
