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

66 lines
2.1 KiB
JavaScript
Raw Normal View History

2022-09-05 23:57:11 +03:00
import { WebSocket as _WebSocket } from "./ws.js"; /*-browser*/
import { SocketProvider } from "./provider-socket.js";
export class WebSocketProvider extends 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;
}
2022-09-05 23:57:11 +03:00
constructor(url, network) {
super(network);
if (typeof (url) === "string") {
2022-10-01 08:34:06 +03:00
this.#connect = () => { return new _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
}
//# sourceMappingURL=provider-websocket.js.map