ethers.js/lib.commonjs/providers/provider-websocket.js

80 lines
2.7 KiB
JavaScript
Raw Normal View History

2022-09-05 23:57:11 +03:00
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebSocketProvider = void 0;
const ws_js_1 = require("./ws.js"); /*-browser*/
const provider_socket_js_1 = require("./provider-socket.js");
2023-06-02 00:52:58 +03:00
/**
* A JSON-RPC provider which is backed by a WebSocket.
*
* WebSockets are often preferred because they retain a live connection
* to a server, which permits more instant access to events.
*
* However, this incurs higher server infrasturture costs, so additional
* resources may be required to host your own WebSocket nodes and many
* third-party services charge additional fees for WebSocket endpoints.
*/
2022-09-05 23:57:11 +03:00
class WebSocketProvider extends provider_socket_js_1.SocketProvider {
2022-10-01 08:34:06 +03:00
#connect;
2022-09-05 23:57:11 +03:00
#websocket;
2022-09-30 05:57:27 +03:00
get websocket() {
if (this.#websocket == null) {
throw new Error("websocket closed");
}
return this.#websocket;
}
2023-11-27 14:11:49 +03:00
constructor(url, network, options) {
super(network, options);
2022-09-05 23:57:11 +03:00
if (typeof (url) === "string") {
2022-10-01 08:34:06 +03:00
this.#connect = () => { return new ws_js_1.WebSocket(url); };
this.#websocket = this.#connect();
}
else if (typeof (url) === "function") {
this.#connect = url;
this.#websocket = url();
2022-09-05 23:57:11 +03:00
}
else {
2022-10-01 08:34:06 +03:00
this.#connect = null;
2022-09-05 23:57:11 +03:00
this.#websocket = url;
}
2022-09-27 10:45:27 +03:00
this.websocket.onopen = async () => {
try {
await this._start();
2022-10-01 08:34:06 +03:00
this.resume();
2022-09-27 10:45:27 +03:00
}
catch (error) {
console.log("failed to start WebsocketProvider", error);
// @TODO: now what? Attempt reconnect?
}
2022-09-05 23:57:11 +03:00
};
this.websocket.onmessage = (message) => {
this._processMessage(message.data);
};
2022-10-01 08:34:06 +03:00
/*
this.websocket.onclose = (event) => {
// @TODO: What event.code should we reconnect on?
const reconnect = false;
if (reconnect) {
this.pause(true);
if (this.#connect) {
this.#websocket = this.#connect();
this.#websocket.onopen = ...
// @TODO: this requires the super class to rebroadcast; move it there
}
this._reconnect();
}
};
*/
2022-09-05 23:57:11 +03:00
}
async _write(message) {
this.websocket.send(message);
}
2022-09-30 05:57:27 +03:00
async destroy() {
2022-12-31 00:35:04 +03:00
if (this.#websocket != null) {
this.#websocket.close();
this.#websocket = null;
2022-09-30 05:57:27 +03:00
}
2022-12-31 00:35:04 +03:00
super.destroy();
2022-09-30 05:57:27 +03:00
}
2022-09-05 23:57:11 +03:00
}
exports.WebSocketProvider = WebSocketProvider;
//# sourceMappingURL=provider-websocket.js.map