# Socket

## 📖 Socket Module

The `socket` module in the **ono-web** package provides a **WebSocket client** to subscribe and listen to real-time updates from the ONO core node network.

***

### 📦 Importing

To use the socket module, import it as follows:

```javascript
const OnoSocketClient = require('ono-web').socket;
```

***

### 🚀 Class: `OnoSocketClient`

The `OnoSocketClient` class allows you to **connect**, **subscribe to events**, and **receive real-time updates** from the ONO blockchain network.

***

### 🔨 Constructor

#### `new OnoSocketClient(coreHost?)`

Creates a new instance of the socket client.\
If no `coreHost` is provided, it defaults to `ws://core.ono.gg`.

#### 📥 Parameters

| Name       | Type   | Required | Description                                                          |
| ---------- | ------ | -------- | -------------------------------------------------------------------- |
| `coreHost` | string | Optional | Custom ONO core node WebSocket address (e.g., `ws://127.0.0.1:5001`) |

#### 📝 Example

```javascript
const client = new OnoSocketClient(); // Uses default ws://core.ono.gg
const client = new OnoSocketClient('http://127.0.0.1:5001'); // Custom address
```

***

### 📡 Methods

#### 1. `subscribe(handler, errorHandler)`

Connects to the WebSocket server and subscribes to real-time blockchain updates (like new blocks, transactions, etc.).

#### 📥 Parameters

| Name           | Type     | Description                                                                 |
| -------------- | -------- | --------------------------------------------------------------------------- |
| `handler`      | function | Callback that handles incoming messages. Receives `(message, socketClient)` |
| `errorHandler` | function | Callback to handle JSON parsing or connection errors. Receives `(error)`    |

#### ✅ Behavior

* Establishes a WebSocket connection.
* Automatically manages connection open/close state.
* Calls `handler` when a message is received.
* Calls `errorHandler` if there’s an error processing a message.

#### 📝 Example

```javascript
const client = new OnoSocketClient();

client.subscribe(
    (message, socket) => {
        console.log('Received message:', message);
    },
    (error) => {
        console.error('Socket error:', error);
    }
);
```

***

#### 2. `setCoreHost(address)`

Changes the WebSocket core host **after initialization**, allowing reconnection to a different node.

#### 📥 Parameters

| Name      | Type   | Description                                                         |
| --------- | ------ | ------------------------------------------------------------------- |
| `address` | string | New WebSocket address for core node (e.g., `http://127.0.0.1:5001`) |

#### 📝 Example

```javascript
client.setCoreHost('http://127.0.0.1:5001');
```

***

#### 3. `disconnect()`

Gracefully closes the WebSocket connection and unsubscribes from updates.

#### 📝 Example

```javascript
client.disconnect();
```

***

### 📚 Usage Example (Full Flow)

```javascript
const OnoSocketClient = require('ono-web').socket;

// Initialize client
const client = new OnoSocketClient('http://127.0.0.1:5001');

// Subscribe to blockchain events
client.subscribe(
    (message, socket) => {
        console.log('New update:', message);
    },
    (error) => {
        console.error('Failed to handle message:', error);
    }
);

// After some time, disconnect if needed
setTimeout(() => {
    client.disconnect();
    console.log('Disconnected from ONO core node.');
}, 60000); // Disconnect after 1 minute
```

***

### ⚙️ Internal Mechanics

* Each client instance gets a **unique `node-id`** using UUID, passed as query parameter for identification:\
  `ws://core.ono.gg?node-id=generated-uuid`
* Automatically manages:
  * Connection opening
  * Re-subscription protection
  * Message parsing and error handling

***

### 🚨 Notes

* Make sure your core node allows external WebSocket connections if using a remote or custom host.
* Handle sensitive events securely when working with `/secure` WebSocket updates.
* Always manage `disconnect()` properly to avoid memory leaks or dangling connections.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://berinis-organization.gitbook.io/ono/integration/socket.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
