starknet 7.5.0 → 7.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -3843,6 +3843,18 @@ var RpcError = class extends LibraryError {
3843
3843
  return rpc_default[typeName] === this.code;
3844
3844
  }
3845
3845
  };
3846
+ var TimeoutError = class extends LibraryError {
3847
+ constructor(message) {
3848
+ super(message);
3849
+ this.name = "TimeoutError";
3850
+ }
3851
+ };
3852
+ var WebSocketNotConnectedError = class extends LibraryError {
3853
+ constructor(message) {
3854
+ super(message);
3855
+ this.name = "WebSocketNotConnectedError";
3856
+ }
3857
+ };
3846
3858
 
3847
3859
  // src/utils/eth.ts
3848
3860
  var eth_exports = {};
@@ -5330,6 +5342,31 @@ var RpcChannel2 = class {
5330
5342
  }
5331
5343
  };
5332
5344
 
5345
+ // src/utils/eventEmitter.ts
5346
+ var EventEmitter = class {
5347
+ listeners = {};
5348
+ on(event, listener) {
5349
+ if (!this.listeners[event]) {
5350
+ this.listeners[event] = [];
5351
+ }
5352
+ this.listeners[event].push(listener);
5353
+ }
5354
+ off(event, listener) {
5355
+ if (!this.listeners[event]) {
5356
+ return;
5357
+ }
5358
+ this.listeners[event] = this.listeners[event].filter((l) => l !== listener);
5359
+ }
5360
+ emit(event, data) {
5361
+ if (this.listeners[event]) {
5362
+ this.listeners[event].forEach((listener) => listener(data));
5363
+ }
5364
+ }
5365
+ clear() {
5366
+ this.listeners = {};
5367
+ }
5368
+ };
5369
+
5333
5370
  // src/utils/connect/ws.ts
5334
5371
  var ws_default = typeof WebSocket !== "undefined" && WebSocket || typeof globalThis !== "undefined" && globalThis.WebSocket || typeof window !== "undefined" && window.WebSocket.bind(window) || typeof global !== "undefined" && global.WebSocket || class {
5335
5372
  constructor() {
@@ -5339,152 +5376,184 @@ var ws_default = typeof WebSocket !== "undefined" && WebSocket || typeof globalT
5339
5376
  }
5340
5377
  };
5341
5378
 
5342
- // src/channel/ws_0_8.ts
5343
- var WSSubscriptions = {
5344
- NEW_HEADS: "newHeads",
5345
- EVENTS: "events",
5346
- TRANSACTION_STATUS: "transactionStatus",
5347
- PENDING_TRANSACTION: "pendingTransactions"
5348
- };
5349
- var WebSocketChannel = class {
5379
+ // src/channel/ws/subscription.ts
5380
+ var Subscription = class {
5350
5381
  /**
5351
- * WebSocket RPC Node URL
5352
- * @example 'wss://starknet-node.io/rpc/v0_8'
5382
+ * The containing `WebSocketChannel` instance.
5383
+ * @internal
5353
5384
  */
5354
- nodeUrl;
5355
- // public headers: object;
5356
- // readonly retries: number;
5357
- // public requestId: number;
5358
- // readonly blockIdentifier: BlockIdentifier;
5359
- // private chainId?: StarknetChainId;
5360
- // private specVersion?: string;
5361
- // private transactionRetryIntervalFallback?: number;
5362
- // readonly waitMode: Boolean; // behave like web2 rpc and return when tx is processed
5363
- // private batchClient?: BatchClient;
5364
- /**
5365
- * ws library object
5366
- */
5367
- websocket;
5385
+ channel;
5368
5386
  /**
5369
- * Assign implementation method to get 'on reorg event data'
5370
- * @example
5371
- * ```typescript
5372
- * webSocketChannel.onReorg = async function (data) {
5373
- * // ... do something when reorg happens
5374
- * }
5375
- * ```
5387
+ * The JSON-RPC method used to create this subscription.
5388
+ * @internal
5376
5389
  */
5377
- onReorg = () => {
5378
- };
5390
+ method;
5379
5391
  /**
5380
- * Assign implementation method to get 'starknet block heads'
5381
- * @example
5382
- * ```typescript
5383
- * webSocketChannel.onNewHeads = async function (data) {
5384
- * // ... do something with head data
5385
- * }
5386
- * ```
5392
+ * The parameters used to create this subscription.
5393
+ * @internal
5387
5394
  */
5388
- onNewHeads = () => {
5389
- };
5395
+ params;
5390
5396
  /**
5391
- * Assign implementation method to get 'starknet events'
5392
- * @example
5393
- * ```typescript
5394
- * webSocketChannel.onEvents = async function (data) {
5395
- * // ... do something with event data
5396
- * }
5397
- * ```
5397
+ * The unique identifier for this subscription.
5398
+ * @internal
5398
5399
  */
5399
- onEvents = () => {
5400
- };
5400
+ id;
5401
+ events = new EventEmitter();
5402
+ buffer = [];
5403
+ maxBufferSize;
5404
+ handler = null;
5405
+ _isClosed = false;
5401
5406
  /**
5402
- * Assign method to get 'starknet transactions status'
5403
- * @example
5404
- * ```typescript
5405
- * webSocketChannel.onTransactionStatus = async function (data) {
5406
- * // ... do something with tx status data
5407
- * }
5408
- * ```
5407
+ * @internal
5408
+ * @param {WebSocketChannel} channel - The WebSocketChannel instance.
5409
+ * @param {string} method - The RPC method used for the subscription.
5410
+ * @param {any} params - The parameters for the subscription.
5411
+ * @param {SUBSCRIPTION_ID} id - The subscription ID.
5412
+ * @param {number} maxBufferSize - The maximum number of events to buffer.
5409
5413
  */
5410
- onTransactionStatus = () => {
5411
- };
5414
+ constructor(channel, method, params, id, maxBufferSize) {
5415
+ this.channel = channel;
5416
+ this.method = method;
5417
+ this.params = params;
5418
+ this.id = id;
5419
+ this.maxBufferSize = maxBufferSize;
5420
+ }
5412
5421
  /**
5413
- * Assign implementation method to get 'starknet pending transactions (mempool)'
5414
- * @example
5415
- * ```typescript
5416
- * webSocketChannel.onPendingTransaction = async function (data) {
5417
- * // ... do something with pending tx data
5418
- * }
5419
- * ```
5422
+ * Indicates if the subscription has been closed.
5423
+ * @returns {boolean} `true` if unsubscribed, `false` otherwise.
5420
5424
  */
5421
- onPendingTransaction = () => {
5422
- };
5425
+ get isClosed() {
5426
+ return this._isClosed;
5427
+ }
5423
5428
  /**
5424
- * Assign implementation to this method to listen open Event
5429
+ * Internal method to handle incoming events from the WebSocket channel.
5430
+ * If a handler is attached, it's invoked immediately. Otherwise, the event is buffered.
5431
+ * @internal
5432
+ * @param {T} data - The event data.
5425
5433
  */
5426
- onOpen = () => {
5427
- };
5434
+ _handleEvent(data) {
5435
+ if (this.handler) {
5436
+ this.handler(data);
5437
+ } else {
5438
+ if (this.buffer.length >= this.maxBufferSize) {
5439
+ const droppedEvent = this.buffer.shift();
5440
+ logger.warn(`Subscription ${this.id}: Buffer full. Dropping oldest event:`, droppedEvent);
5441
+ }
5442
+ this.buffer.push(data);
5443
+ }
5444
+ }
5428
5445
  /**
5429
- * Assign implementation to this method to listen close CloseEvent
5430
- */
5431
- onClose = () => {
5432
- };
5446
+ * Attaches a handler function to be called for each event.
5447
+ *
5448
+ * When a handler is attached, any buffered events will be passed to it sequentially.
5449
+ * Subsequent events will be passed directly as they arrive.
5450
+ *
5451
+ * @param {(data: T) => void} handler - The function to call with event data.
5452
+ * @throws {Error} If a handler is already attached to this subscription.
5453
+ */
5454
+ on(handler) {
5455
+ if (this.handler) {
5456
+ throw new Error("A handler is already attached to this subscription.");
5457
+ }
5458
+ this.handler = handler;
5459
+ while (this.buffer.length > 0) {
5460
+ const event = this.buffer.shift();
5461
+ if (event) {
5462
+ this.handler(event);
5463
+ }
5464
+ }
5465
+ }
5433
5466
  /**
5434
- * Assign implementation to this method to listen message MessageEvent
5467
+ * Sends an unsubscribe request to the node and cleans up local resources.
5468
+ * @returns {Promise<boolean>} A Promise that resolves to `true` if the unsubscription was successful.
5435
5469
  */
5436
- onMessage = () => {
5437
- };
5470
+ async unsubscribe() {
5471
+ if (this._isClosed) {
5472
+ return true;
5473
+ }
5474
+ const success = await this.channel.unsubscribe(this.id);
5475
+ if (success) {
5476
+ this._isClosed = true;
5477
+ this.channel.removeSubscription(this.id);
5478
+ this.events.emit("unsubscribe", void 0);
5479
+ this.events.clear();
5480
+ }
5481
+ return success;
5482
+ }
5483
+ };
5484
+
5485
+ // src/channel/ws/ws_0_8.ts
5486
+ var WebSocketChannel = class {
5438
5487
  /**
5439
- * Assign implementation to this method to listen error Event
5488
+ * The URL of the WebSocket RPC Node.
5489
+ * @example 'wss://starknet-sepolia.public.blastapi.io/rpc/v0_8'
5440
5490
  */
5441
- onError = () => {
5442
- };
5491
+ nodeUrl;
5443
5492
  /**
5444
- * Assign implementation to this method to listen unsubscription
5493
+ * The underlying WebSocket instance.
5445
5494
  */
5446
- onUnsubscribe = () => {
5447
- };
5448
- onUnsubscribeLocal = () => {
5449
- };
5450
- /**
5451
- * JSON RPC latest sent message id
5452
- * expecting receiving message to contain same id
5495
+ websocket;
5496
+ // Store the WebSocket implementation class to allow for custom implementations.
5497
+ WsImplementation;
5498
+ // Map of active subscriptions, keyed by their ID.
5499
+ activeSubscriptions = /* @__PURE__ */ new Map();
5500
+ maxBufferSize;
5501
+ autoReconnect;
5502
+ reconnectOptions;
5503
+ requestTimeout;
5504
+ isReconnecting = false;
5505
+ reconnectAttempts = 0;
5506
+ userInitiatedClose = false;
5507
+ reconnectTimeoutId = null;
5508
+ requestQueue = [];
5509
+ events = new EventEmitter();
5510
+ openListener = (ev) => this.events.emit("open", ev);
5511
+ closeListener = this.onCloseProxy.bind(this);
5512
+ messageListener = this.onMessageProxy.bind(this);
5513
+ errorListener = (ev) => this.events.emit("error", ev);
5514
+ /**
5515
+ * JSON RPC latest sent message ID.
5516
+ * The receiving message is expected to contain the same ID.
5453
5517
  */
5454
5518
  sendId = 0;
5455
5519
  /**
5456
- * subscriptions ids
5457
- * mapped by keys WSSubscriptions
5458
- */
5459
- subscriptions = /* @__PURE__ */ new Map();
5460
- /**
5461
- * Construct class and event listeners
5462
- * @param options WebSocketOptions
5520
+ * Creates an instance of WebSocketChannel.
5521
+ * @param {WebSocketOptions} options - The options for configuring the channel.
5463
5522
  */
5464
- constructor(options = {}) {
5465
- const nodeUrl = options.nodeUrl || "http://localhost:3000 ";
5466
- this.nodeUrl = options.websocket ? options.websocket.url : nodeUrl;
5467
- this.websocket = options.websocket || config.get("websocket") || new ws_default(nodeUrl);
5468
- this.websocket.addEventListener("open", this.onOpen.bind(this));
5469
- this.websocket.addEventListener("close", this.onCloseProxy.bind(this));
5470
- this.websocket.addEventListener("message", this.onMessageProxy.bind(this));
5471
- this.websocket.addEventListener("error", this.onError.bind(this));
5523
+ constructor(options) {
5524
+ this.nodeUrl = options.nodeUrl;
5525
+ this.maxBufferSize = options.maxBufferSize ?? 1e3;
5526
+ this.autoReconnect = options.autoReconnect ?? true;
5527
+ this.reconnectOptions = {
5528
+ retries: options.reconnectOptions?.retries ?? 5,
5529
+ delay: options.reconnectOptions?.delay ?? 2e3
5530
+ };
5531
+ this.requestTimeout = options.requestTimeout ?? 6e4;
5532
+ this.WsImplementation = options.websocket || config.get("websocket") || ws_default;
5533
+ this.websocket = new this.WsImplementation(this.nodeUrl);
5534
+ this.websocket.addEventListener("open", this.openListener);
5535
+ this.websocket.addEventListener("close", this.closeListener);
5536
+ this.websocket.addEventListener("message", this.messageListener);
5537
+ this.websocket.addEventListener("error", this.errorListener);
5472
5538
  }
5473
5539
  idResolver(id) {
5474
5540
  if (id) return id;
5475
5541
  return this.sendId++;
5476
5542
  }
5477
5543
  /**
5478
- * Send data over open ws connection
5479
- * * this would only send data on the line without awaiting 'response message'
5480
- * @example
5481
- * ```typescript
5482
- * const sentId = await this.send('starknet_method', params);
5483
- * ```
5544
+ * Sends a JSON-RPC request over the WebSocket connection without waiting for a response.
5545
+ * This is a low-level method. Prefer `sendReceive` for most use cases.
5546
+ * @param {string} method - The RPC method name.
5547
+ * @param {object} [params] - The parameters for the RPC method.
5548
+ * @param {number} [id] - A specific request ID. If not provided, an auto-incrementing ID is used.
5549
+ * @returns {number} The ID of the sent request.
5550
+ * @throws {WebSocketNotConnectedError} If the WebSocket is not connected.
5484
5551
  */
5485
5552
  send(method, params, id) {
5486
5553
  if (!this.isConnected()) {
5487
- throw Error("WebSocketChannel.send() fail due to socket disconnected");
5554
+ throw new WebSocketNotConnectedError(
5555
+ "WebSocketChannel.send() failed due to socket being disconnected"
5556
+ );
5488
5557
  }
5489
5558
  const usedId = this.idResolver(id);
5490
5559
  const rpcRequestBody = {
@@ -5497,50 +5566,88 @@ var WebSocketChannel = class {
5497
5566
  return usedId;
5498
5567
  }
5499
5568
  /**
5500
- * Any Starknet method not just websocket override
5501
- */
5502
- sendReceiveAny(method, params) {
5503
- return this.sendReceive(method, params);
5504
- }
5505
- /**
5506
- * Send request and receive response over ws line
5507
- * This method abstract ws messages into request/response model
5508
- * @param method rpc method name
5509
- * @param params rpc method parameters
5510
- * @example
5511
- * ```typescript
5512
- * const response = await this.sendReceive('starknet_method', params);
5513
- * ```
5569
+ * Sends a JSON-RPC request and returns a Promise that resolves with the result.
5570
+ * This method abstracts the request/response cycle over WebSockets.
5571
+ * If the connection is lost, it will queue the request and send it upon reconnection.
5572
+ * @template T - The expected type of the result.
5573
+ * @param {string} method - The RPC method name.
5574
+ * @param {object} [params] - The parameters for the RPC method.
5575
+ * @returns {Promise<T>} A Promise that resolves with the RPC response result.
5576
+ * @throws {TimeoutError} If the request does not receive a response within the configured `requestTimeout`.
5577
+ * @throws {WebSocketNotConnectedError} If the WebSocket is not connected and auto-reconnect is disabled.
5514
5578
  */
5515
5579
  sendReceive(method, params) {
5580
+ if (this.isReconnecting || !this.isConnected() && this.autoReconnect && !this.userInitiatedClose) {
5581
+ logger.info(`WebSocket: Connection unavailable, queueing request: ${method}`);
5582
+ return new Promise((resolve, reject) => {
5583
+ this.requestQueue.push({ method, params, resolve, reject });
5584
+ });
5585
+ }
5516
5586
  const sendId = this.send(method, params);
5517
5587
  return new Promise((resolve, reject) => {
5518
- if (!this.websocket) return;
5519
- this.websocket.onmessage = ({ data }) => {
5520
- const message = JSON.parse(data);
5588
+ let timeoutId;
5589
+ if (!this.websocket || this.websocket.readyState !== ws_default.OPEN) {
5590
+ reject(new WebSocketNotConnectedError("WebSocket not available or not connected."));
5591
+ return;
5592
+ }
5593
+ const messageHandler = (event) => {
5594
+ if (!isString(event.data)) {
5595
+ logger.warn("WebSocket received non-string message data:", event.data);
5596
+ return;
5597
+ }
5598
+ const message = JSON.parse(event.data);
5521
5599
  if (message.id === sendId) {
5600
+ clearTimeout(timeoutId);
5601
+ this.websocket.removeEventListener("message", messageHandler);
5602
+ this.websocket.removeEventListener("error", errorHandler);
5522
5603
  if ("result" in message) {
5523
5604
  resolve(message.result);
5524
5605
  } else {
5525
- reject(Error(`error on ${method}, ${message.error}`));
5606
+ reject(
5607
+ new Error(`Error on ${method} (id: ${sendId}): ${JSON.stringify(message.error)}`)
5608
+ );
5526
5609
  }
5527
5610
  }
5528
5611
  };
5529
- this.websocket.onerror = reject;
5612
+ const errorHandler = (event) => {
5613
+ clearTimeout(timeoutId);
5614
+ this.websocket.removeEventListener("message", messageHandler);
5615
+ this.websocket.removeEventListener("error", errorHandler);
5616
+ reject(
5617
+ new Error(
5618
+ `WebSocket error during ${method} (id: ${sendId}): ${event.type || "Unknown error"}`
5619
+ )
5620
+ );
5621
+ };
5622
+ this.websocket.addEventListener("message", messageHandler);
5623
+ this.websocket.addEventListener("error", errorHandler);
5624
+ timeoutId = setTimeout(() => {
5625
+ this.websocket.removeEventListener("message", messageHandler);
5626
+ this.websocket.removeEventListener("error", errorHandler);
5627
+ reject(
5628
+ new TimeoutError(
5629
+ `Request ${method} (id: ${sendId}) timed out after ${this.requestTimeout}ms`
5630
+ )
5631
+ );
5632
+ }, this.requestTimeout);
5530
5633
  });
5531
5634
  }
5532
5635
  /**
5533
- * Helper to check connection is open
5636
+ * Checks if the WebSocket connection is currently open.
5637
+ * @returns {boolean} `true` if the connection is open, `false` otherwise.
5534
5638
  */
5535
5639
  isConnected() {
5536
5640
  return this.websocket.readyState === ws_default.OPEN;
5537
5641
  }
5538
5642
  /**
5539
- * await while websocket is connected
5540
- * * could be used to block the flow until websocket is open
5643
+ * Returns a Promise that resolves when the WebSocket connection is open.
5644
+ * Can be used to block execution until the connection is established.
5645
+ * @returns {Promise<number>} A Promise that resolves with the WebSocket's `readyState` when connected.
5541
5646
  * @example
5542
5647
  * ```typescript
5543
- * const readyState = await webSocketChannel.waitForConnection();
5648
+ * const channel = new WebSocketChannel({ nodeUrl: '...' });
5649
+ * await channel.waitForConnection();
5650
+ * console.log('Connected!');
5544
5651
  * ```
5545
5652
  */
5546
5653
  async waitForConnection() {
@@ -5556,17 +5663,22 @@ var WebSocketChannel = class {
5556
5663
  return this.websocket.readyState;
5557
5664
  }
5558
5665
  /**
5559
- * Disconnect the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.
5666
+ * Closes the WebSocket connection.
5667
+ * This method is user-initiated and will prevent automatic reconnection for this closure.
5668
+ * @param {number} [code] - The WebSocket connection close code.
5669
+ * @param {string} [reason] - The WebSocket connection close reason.
5560
5670
  */
5561
5671
  disconnect(code, reason) {
5672
+ if (this.reconnectTimeoutId) {
5673
+ clearTimeout(this.reconnectTimeoutId);
5674
+ this.reconnectTimeoutId = null;
5675
+ }
5562
5676
  this.websocket.close(code, reason);
5677
+ this.userInitiatedClose = true;
5563
5678
  }
5564
5679
  /**
5565
- * await while websocket is disconnected
5566
- * @example
5567
- * ```typescript
5568
- * const readyState = await webSocketChannel.waitForDisconnection();
5569
- * ```
5680
+ * Returns a Promise that resolves when the WebSocket connection is closed.
5681
+ * @returns {Promise<number | Event>} A Promise that resolves with the WebSocket's `readyState` or a `CloseEvent` when disconnected.
5570
5682
  */
5571
5683
  async waitForDisconnection() {
5572
5684
  if (this.websocket.readyState !== ws_default.CLOSED) {
@@ -5579,206 +5691,233 @@ var WebSocketChannel = class {
5579
5691
  return this.websocket.readyState;
5580
5692
  }
5581
5693
  /**
5582
- * Unsubscribe from starknet subscription
5583
- * @param subscriptionId
5584
- * @param ref internal usage, only for managed subscriptions
5694
+ * Unsubscribes from a Starknet subscription.
5695
+ * It is recommended to use the `unsubscribe()` method on the `Subscription` object instead.
5696
+ * @internal
5697
+ * @param {SUBSCRIPTION_ID} subscriptionId - The ID of the subscription to unsubscribe from.
5698
+ * @returns {Promise<boolean>} A Promise that resolves with `true` if the unsubscription was successful.
5585
5699
  */
5586
- async unsubscribe(subscriptionId, ref) {
5700
+ async unsubscribe(subscriptionId) {
5587
5701
  const status = await this.sendReceive("starknet_unsubscribe", {
5588
5702
  subscription_id: subscriptionId
5589
5703
  });
5590
5704
  if (status) {
5591
- if (ref) {
5592
- this.subscriptions.delete(ref);
5593
- }
5594
- this.onUnsubscribeLocal(subscriptionId);
5595
- this.onUnsubscribe(subscriptionId);
5705
+ this.events.emit("unsubscribe", subscriptionId);
5596
5706
  }
5597
5707
  return status;
5598
5708
  }
5599
5709
  /**
5600
- * await while subscription is unsubscribed
5601
- * @param forSubscriptionId if defined trigger on subscriptionId else trigger on any
5602
- * @returns subscriptionId | onerror(Event)
5710
+ * Returns a Promise that resolves when a specific subscription is successfully unsubscribed.
5711
+ * @param {SUBSCRIPTION_ID} targetId - The ID of the subscription to wait for.
5712
+ * @returns {Promise<void>}
5603
5713
  * @example
5604
5714
  * ```typescript
5605
- * const subscriptionId = await webSocketChannel.waitForUnsubscription();
5715
+ * await channel.waitForUnsubscription(mySubscription.id);
5716
+ * console.log('Successfully unsubscribed.');
5606
5717
  * ```
5607
5718
  */
5608
- async waitForUnsubscription(forSubscriptionId) {
5609
- return new Promise((resolve, reject) => {
5610
- if (!this.websocket) return;
5611
- this.onUnsubscribeLocal = (subscriptionId) => {
5612
- if (forSubscriptionId === void 0) {
5613
- resolve(subscriptionId);
5614
- } else if (subscriptionId === forSubscriptionId) {
5615
- resolve(subscriptionId);
5719
+ waitForUnsubscription(targetId) {
5720
+ return new Promise((resolve) => {
5721
+ const listener = (unsubId) => {
5722
+ if (unsubId === targetId) {
5723
+ this.events.off("unsubscribe", listener);
5724
+ resolve();
5616
5725
  }
5617
5726
  };
5618
- this.websocket.onerror = reject;
5727
+ this.events.on("unsubscribe", listener);
5619
5728
  });
5620
5729
  }
5621
5730
  /**
5622
- * Reconnect re-create this.websocket instance
5731
+ * Manually initiates a reconnection attempt.
5732
+ * This creates a new WebSocket instance and re-establishes listeners.
5623
5733
  */
5624
5734
  reconnect() {
5625
- this.websocket = new ws_default(this.nodeUrl);
5626
- this.websocket.addEventListener("open", this.onOpen.bind(this));
5627
- this.websocket.addEventListener("close", this.onCloseProxy.bind(this));
5628
- this.websocket.addEventListener("message", this.onMessageProxy.bind(this));
5629
- this.websocket.addEventListener("error", this.onError.bind(this));
5735
+ this.userInitiatedClose = false;
5736
+ this.websocket = new this.WsImplementation(this.nodeUrl);
5737
+ this.websocket.addEventListener("open", this.openListener);
5738
+ this.websocket.addEventListener("close", this.closeListener);
5739
+ this.websocket.addEventListener("message", this.messageListener);
5740
+ this.websocket.addEventListener("error", this.errorListener);
5741
+ }
5742
+ _processRequestQueue() {
5743
+ logger.info(`WebSocket: Processing ${this.requestQueue.length} queued requests.`);
5744
+ while (this.requestQueue.length > 0) {
5745
+ const { method, params, resolve, reject } = this.requestQueue.shift();
5746
+ this.sendReceive(method, params).then(resolve).catch(reject);
5747
+ }
5748
+ }
5749
+ async _restoreSubscriptions() {
5750
+ const oldSubscriptions = Array.from(this.activeSubscriptions.values());
5751
+ this.activeSubscriptions.clear();
5752
+ const restorePromises = oldSubscriptions.map(async (sub) => {
5753
+ try {
5754
+ const newSubId = await this.sendReceive(sub.method, sub.params);
5755
+ sub.id = newSubId;
5756
+ this.activeSubscriptions.set(newSubId, sub);
5757
+ logger.info(`Subscription ${sub.method} restored with new ID: ${newSubId}`);
5758
+ } catch (error) {
5759
+ logger.error(`Failed to restore subscription ${sub.method}:`, error);
5760
+ }
5761
+ });
5762
+ await Promise.all(restorePromises);
5630
5763
  }
5631
- // TODO: Add/Test ping service. It seems this work out of the box from pathfinder. If net disc. it will auto replay.
5632
- reconnectAndUpdate() {
5633
- this.reconnect();
5764
+ _startReconnect() {
5765
+ if (this.isReconnecting || !this.autoReconnect) {
5766
+ return;
5767
+ }
5768
+ this.isReconnecting = true;
5769
+ this.reconnectAttempts = 0;
5770
+ const tryReconnect = () => {
5771
+ if (this.reconnectAttempts >= this.reconnectOptions.retries) {
5772
+ logger.error("WebSocket: Maximum reconnection retries reached. Giving up.");
5773
+ this.isReconnecting = false;
5774
+ return;
5775
+ }
5776
+ this.reconnectAttempts += 1;
5777
+ logger.info(
5778
+ `WebSocket: Connection lost. Attempting to reconnect... (${this.reconnectAttempts}/${this.reconnectOptions.retries})`
5779
+ );
5780
+ this.reconnect();
5781
+ this.websocket.onopen = async () => {
5782
+ logger.info("WebSocket: Reconnection successful.");
5783
+ this.isReconnecting = false;
5784
+ this.reconnectAttempts = 0;
5785
+ await this._restoreSubscriptions();
5786
+ this._processRequestQueue();
5787
+ this.events.emit("open", new Event("open"));
5788
+ };
5789
+ this.websocket.onerror = () => {
5790
+ const delay = this.reconnectOptions.delay * 2 ** (this.reconnectAttempts - 1);
5791
+ logger.info(`WebSocket: Reconnect attempt failed. Retrying in ${delay}ms.`);
5792
+ this.reconnectTimeoutId = setTimeout(tryReconnect, delay);
5793
+ };
5794
+ };
5795
+ tryReconnect();
5634
5796
  }
5635
5797
  onCloseProxy(ev) {
5636
- this.websocket.removeEventListener("open", this.onOpen);
5637
- this.websocket.removeEventListener("close", this.onCloseProxy);
5638
- this.websocket.removeEventListener("message", this.onMessageProxy);
5639
- this.websocket.removeEventListener("error", this.onError);
5640
- this.onClose(ev);
5798
+ this.websocket.removeEventListener("open", this.openListener);
5799
+ this.websocket.removeEventListener("close", this.closeListener);
5800
+ this.websocket.removeEventListener("message", this.messageListener);
5801
+ this.websocket.removeEventListener("error", this.errorListener);
5802
+ this.events.emit("close", ev);
5803
+ if (!this.userInitiatedClose) {
5804
+ this._startReconnect();
5805
+ }
5641
5806
  }
5642
5807
  onMessageProxy(event) {
5643
- const message = JSON.parse(event.data);
5644
- const eventName = message.method;
5645
- switch (eventName) {
5646
- case "starknet_subscriptionReorg":
5647
- this.onReorg(message.params);
5648
- break;
5649
- case "starknet_subscriptionNewHeads":
5650
- this.onNewHeads(message.params);
5651
- break;
5652
- case "starknet_subscriptionEvents":
5653
- this.onEvents(message.params);
5654
- break;
5655
- case "starknet_subscriptionTransactionStatus":
5656
- this.onTransactionStatus(message.params);
5657
- break;
5658
- case "starknet_subscriptionPendingTransactions":
5659
- this.onPendingTransaction(message.params);
5660
- break;
5661
- default:
5662
- break;
5808
+ let message;
5809
+ try {
5810
+ message = JSON.parse(event.data);
5811
+ } catch (error) {
5812
+ logger.error(
5813
+ `WebSocketChannel: Error parsing incoming message: ${event.data}, Error: ${error}`
5814
+ );
5815
+ return;
5663
5816
  }
5664
- this.onMessage(event);
5665
- }
5666
- /**
5667
- * subscribe to new block heads
5668
- * * you can subscribe to this event multiple times and you need to manage subscriptions manually
5669
- */
5670
- subscribeNewHeadsUnmanaged(blockIdentifier) {
5671
- const block_id = blockIdentifier ? new Block(blockIdentifier).identifier : void 0;
5672
- return this.sendReceive("starknet_subscribeNewHeads", {
5673
- ...{ block_id }
5674
- });
5817
+ if (message.method && isObject(message.params) && "subscription_id" in message.params) {
5818
+ const { result, subscription_id } = message.params;
5819
+ const subscription = this.activeSubscriptions.get(subscription_id);
5820
+ if (subscription) {
5821
+ subscription._handleEvent(result);
5822
+ } else {
5823
+ logger.warn(
5824
+ `WebSocketChannel: Received event for untracked subscription ID: ${subscription_id}.`
5825
+ );
5826
+ }
5827
+ }
5828
+ logger.debug("onMessageProxy:", event.data);
5829
+ this.events.emit("message", event);
5675
5830
  }
5676
5831
  /**
5677
- * subscribe to new block heads
5832
+ * Subscribes to new block headers.
5833
+ * @param {SubscriptionBlockIdentifier} [blockIdentifier] - The block to start receiving notifications from. Defaults to 'latest'.
5834
+ * @returns {Promise<Subscription<BLOCK_HEADER>>} A Promise that resolves with a `Subscription` object for new block headers.
5678
5835
  */
5679
5836
  async subscribeNewHeads(blockIdentifier) {
5680
- if (this.subscriptions.get(WSSubscriptions.NEW_HEADS)) return false;
5681
- const subId = await this.subscribeNewHeadsUnmanaged(blockIdentifier);
5682
- this.subscriptions.set(WSSubscriptions.NEW_HEADS, subId);
5683
- return subId;
5684
- }
5685
- /**
5686
- * Unsubscribe newHeads subscription
5687
- */
5688
- async unsubscribeNewHeads() {
5689
- const subId = this.subscriptions.get(WSSubscriptions.NEW_HEADS);
5690
- if (!subId) throw Error("There is no subscription on this event");
5691
- return this.unsubscribe(subId, WSSubscriptions.NEW_HEADS);
5692
- }
5693
- /**
5694
- * subscribe to 'starknet events'
5695
- * * you can subscribe to this event multiple times and you need to manage subscriptions manually
5696
- */
5697
- subscribeEventsUnmanaged(fromAddress, keys, blockIdentifier) {
5698
- const block_id = blockIdentifier ? new Block(blockIdentifier).identifier : void 0;
5699
- return this.sendReceive("starknet_subscribeEvents", {
5700
- ...{ from_address: fromAddress !== void 0 ? toHex(fromAddress) : void 0 },
5701
- ...{ keys },
5702
- ...{ block_id }
5703
- });
5837
+ const method = "starknet_subscribeNewHeads";
5838
+ const params = {
5839
+ block_id: blockIdentifier ? new Block(blockIdentifier).identifier : void 0
5840
+ };
5841
+ const subId = await this.sendReceive(method, params);
5842
+ const subscription = new Subscription(this, method, params, subId, this.maxBufferSize);
5843
+ this.activeSubscriptions.set(subId, subscription);
5844
+ return subscription;
5704
5845
  }
5705
5846
  /**
5706
- * subscribe to 'starknet events'
5847
+ * Subscribes to events matching a given filter.
5848
+ * @param {BigNumberish} [fromAddress] - The contract address to filter by.
5849
+ * @param {string[][]} [keys] - The event keys to filter by.
5850
+ * @param {SubscriptionBlockIdentifier} [blockIdentifier] - The block to start receiving notifications from. Defaults to 'latest'.
5851
+ * @returns {Promise<Subscription<EMITTED_EVENT>>} A Promise that resolves with a `Subscription` object for the specified events.
5707
5852
  */
5708
5853
  async subscribeEvents(fromAddress, keys, blockIdentifier) {
5709
- if (this.subscriptions.get(WSSubscriptions.EVENTS)) return false;
5710
- const subId = await this.subscribeEventsUnmanaged(fromAddress, keys, blockIdentifier);
5711
- this.subscriptions.set(WSSubscriptions.EVENTS, subId);
5712
- return subId;
5713
- }
5714
- /**
5715
- * Unsubscribe 'starknet events' subscription
5716
- */
5717
- unsubscribeEvents() {
5718
- const subId = this.subscriptions.get(WSSubscriptions.EVENTS);
5719
- if (!subId) throw Error("There is no subscription ID for this event");
5720
- return this.unsubscribe(subId, WSSubscriptions.EVENTS);
5721
- }
5722
- /**
5723
- * subscribe to transaction status
5724
- * * you can subscribe to this event multiple times and you need to manage subscriptions manually
5725
- */
5726
- subscribeTransactionStatusUnmanaged(transactionHash, blockIdentifier) {
5727
- const transaction_hash = toHex(transactionHash);
5728
- const block_id = blockIdentifier ? new Block(blockIdentifier).identifier : void 0;
5729
- return this.sendReceive("starknet_subscribeTransactionStatus", {
5730
- transaction_hash,
5731
- ...{ block_id }
5732
- });
5854
+ const method = "starknet_subscribeEvents";
5855
+ const params = {
5856
+ from_address: fromAddress !== void 0 ? toHex(fromAddress) : void 0,
5857
+ keys,
5858
+ block_id: blockIdentifier ? new Block(blockIdentifier).identifier : void 0
5859
+ };
5860
+ const subId = await this.sendReceive(method, params);
5861
+ const subscription = new Subscription(this, method, params, subId, this.maxBufferSize);
5862
+ this.activeSubscriptions.set(subId, subscription);
5863
+ return subscription;
5733
5864
  }
5734
5865
  /**
5735
- * subscribe to transaction status
5866
+ * Subscribes to status updates for a specific transaction.
5867
+ * @param {BigNumberish} transactionHash - The hash of the transaction to monitor.
5868
+ * @param {SubscriptionBlockIdentifier} [blockIdentifier] - The block context. Not typically required.
5869
+ * @returns {Promise<Subscription<NEW_TXN_STATUS>>} A Promise that resolves with a `Subscription` object for the transaction's status.
5736
5870
  */
5737
- async subscribeTransactionStatus(transactionHash) {
5738
- if (this.subscriptions.get(WSSubscriptions.TRANSACTION_STATUS)) return false;
5739
- const subId = await this.subscribeTransactionStatusUnmanaged(transactionHash);
5740
- this.subscriptions.set(WSSubscriptions.TRANSACTION_STATUS, subId);
5741
- return subId;
5871
+ async subscribeTransactionStatus(transactionHash, blockIdentifier) {
5872
+ const method = "starknet_subscribeTransactionStatus";
5873
+ const params = {
5874
+ transaction_hash: toHex(transactionHash),
5875
+ block_id: blockIdentifier ? new Block(blockIdentifier).identifier : void 0
5876
+ };
5877
+ const subId = await this.sendReceive(method, params);
5878
+ const subscription = new Subscription(this, method, params, subId, this.maxBufferSize);
5879
+ this.activeSubscriptions.set(subId, subscription);
5880
+ return subscription;
5742
5881
  }
5743
5882
  /**
5744
- * unsubscribe 'transaction status' subscription
5883
+ * Subscribes to pending transactions.
5884
+ * @param {boolean} [transactionDetails] - If `true`, the full transaction details are included. Defaults to `false` (hash only).
5885
+ * @param {BigNumberish[]} [senderAddress] - An array of sender addresses to filter by.
5886
+ * @returns {Promise<Subscription<TXN_HASH | TXN_WITH_HASH>>} A Promise that resolves with a `Subscription` object for pending transactions.
5745
5887
  */
5746
- async unsubscribeTransactionStatus() {
5747
- const subId = this.subscriptions.get(WSSubscriptions.TRANSACTION_STATUS);
5748
- if (!subId) throw Error("There is no subscription ID for this event");
5749
- return this.unsubscribe(subId, WSSubscriptions.TRANSACTION_STATUS);
5888
+ async subscribePendingTransaction(transactionDetails, senderAddress) {
5889
+ const method = "starknet_subscribePendingTransactions";
5890
+ const params = {
5891
+ transaction_details: transactionDetails,
5892
+ sender_address: senderAddress && bigNumberishArrayToHexadecimalStringArray(senderAddress)
5893
+ };
5894
+ const subId = await this.sendReceive(method, params);
5895
+ const subscription = new Subscription(this, method, params, subId, this.maxBufferSize);
5896
+ this.activeSubscriptions.set(subId, subscription);
5897
+ return subscription;
5750
5898
  }
5751
5899
  /**
5752
- * subscribe to pending transactions (mempool)
5753
- * * you can subscribe to this event multiple times and you need to manage subscriptions manually
5900
+ * Internal method to remove subscription from active map.
5901
+ * @internal
5754
5902
  */
5755
- subscribePendingTransactionUnmanaged(transactionDetails, senderAddress) {
5756
- return this.sendReceive("starknet_subscribePendingTransactions", {
5757
- ...{ transaction_details: transactionDetails },
5758
- ...{
5759
- sender_address: senderAddress && bigNumberishArrayToHexadecimalStringArray(senderAddress)
5760
- }
5761
- });
5903
+ removeSubscription(id) {
5904
+ this.activeSubscriptions.delete(id);
5762
5905
  }
5763
5906
  /**
5764
- * subscribe to pending transactions (mempool)
5907
+ * Adds a listener for a given event.
5908
+ * @param event The event name.
5909
+ * @param listener The listener function to add.
5765
5910
  */
5766
- async subscribePendingTransaction(transactionDetails, senderAddress) {
5767
- if (this.subscriptions.get(WSSubscriptions.TRANSACTION_STATUS)) return false;
5768
- const subId = await this.subscribePendingTransactionUnmanaged(
5769
- transactionDetails,
5770
- senderAddress
5771
- );
5772
- this.subscriptions.set(WSSubscriptions.PENDING_TRANSACTION, subId);
5773
- return subId;
5911
+ on(event, listener) {
5912
+ this.events.on(event, listener);
5774
5913
  }
5775
5914
  /**
5776
- * unsubscribe 'pending transaction' subscription
5915
+ * Removes a listener for a given event.
5916
+ * @param event The event name.
5917
+ * @param listener The listener function to remove.
5777
5918
  */
5778
- async unsubscribePendingTransaction() {
5779
- const subId = this.subscriptions.get(WSSubscriptions.PENDING_TRANSACTION);
5780
- if (!subId) throw Error("There is no subscription ID for this event");
5781
- return this.unsubscribe(subId, WSSubscriptions.PENDING_TRANSACTION);
5919
+ off(event, listener) {
5920
+ this.events.off(event, listener);
5782
5921
  }
5783
5922
  };
5784
5923
 
@@ -10645,7 +10784,6 @@ export {
10645
10784
  Contract,
10646
10785
  ContractFactory,
10647
10786
  ContractInterface,
10648
- CustomError,
10649
10787
  EDAMode,
10650
10788
  EDataAvailabilityMode,
10651
10789
  ETH_ADDRESS,
@@ -10682,6 +10820,8 @@ export {
10682
10820
  RpcProvider2 as RpcProvider,
10683
10821
  Signer,
10684
10822
  SignerInterface,
10823
+ Subscription,
10824
+ TimeoutError,
10685
10825
  TransactionExecutionStatus,
10686
10826
  TransactionFinalityStatus,
10687
10827
  TransactionType,
@@ -10698,9 +10838,9 @@ export {
10698
10838
  UINT_512_MIN,
10699
10839
  Uint,
10700
10840
  ValidateType,
10701
- WSSubscriptions,
10702
10841
  WalletAccount,
10703
10842
  WebSocketChannel,
10843
+ WebSocketNotConnectedError,
10704
10844
  addAddressPadding,
10705
10845
  byteArray_exports as byteArray,
10706
10846
  cairo_exports as cairo,
@@ -10714,8 +10854,6 @@ export {
10714
10854
  eth_exports as eth,
10715
10855
  events_exports as events,
10716
10856
  extractContractHashes,
10717
- fixProto,
10718
- fixStack,
10719
10857
  getCalldata,
10720
10858
  getChecksumAddress,
10721
10859
  getLedgerPathBuffer111 as getLedgerPathBuffer,