provider-websocket.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.WebSocketProvider = void 0;
  4. const ws_js_1 = require("./ws.js"); /*-browser*/
  5. const provider_socket_js_1 = require("./provider-socket.js");
  6. /**
  7. * A JSON-RPC provider which is backed by a WebSocket.
  8. *
  9. * WebSockets are often preferred because they retain a live connection
  10. * to a server, which permits more instant access to events.
  11. *
  12. * However, this incurs higher server infrasturture costs, so additional
  13. * resources may be required to host your own WebSocket nodes and many
  14. * third-party services charge additional fees for WebSocket endpoints.
  15. */
  16. class WebSocketProvider extends provider_socket_js_1.SocketProvider {
  17. #connect;
  18. #websocket;
  19. get websocket() {
  20. if (this.#websocket == null) {
  21. throw new Error("websocket closed");
  22. }
  23. return this.#websocket;
  24. }
  25. constructor(url, network, options) {
  26. super(network, options);
  27. if (typeof (url) === "string") {
  28. this.#connect = () => { return new ws_js_1.WebSocket(url); };
  29. this.#websocket = this.#connect();
  30. }
  31. else if (typeof (url) === "function") {
  32. this.#connect = url;
  33. this.#websocket = url();
  34. }
  35. else {
  36. this.#connect = null;
  37. this.#websocket = url;
  38. }
  39. this.websocket.onopen = async () => {
  40. try {
  41. await this._start();
  42. this.resume();
  43. }
  44. catch (error) {
  45. console.log("failed to start WebsocketProvider", error);
  46. // @TODO: now what? Attempt reconnect?
  47. }
  48. };
  49. this.websocket.onmessage = (message) => {
  50. this._processMessage(message.data);
  51. };
  52. /*
  53. this.websocket.onclose = (event) => {
  54. // @TODO: What event.code should we reconnect on?
  55. const reconnect = false;
  56. if (reconnect) {
  57. this.pause(true);
  58. if (this.#connect) {
  59. this.#websocket = this.#connect();
  60. this.#websocket.onopen = ...
  61. // @TODO: this requires the super class to rebroadcast; move it there
  62. }
  63. this._reconnect();
  64. }
  65. };
  66. */
  67. }
  68. async _write(message) {
  69. this.websocket.send(message);
  70. }
  71. async destroy() {
  72. if (this.#websocket != null) {
  73. this.#websocket.close();
  74. this.#websocket = null;
  75. }
  76. super.destroy();
  77. }
  78. }
  79. exports.WebSocketProvider = WebSocketProvider;
  80. //# sourceMappingURL=provider-websocket.js.map