starknet 7.5.0 → 7.6.0

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
@@ -3559,6 +3559,10 @@ function toAnyPatchVersion(version) {
3559
3559
  }
3560
3560
  return `${parts[0]}.${parts[1]}.*`;
3561
3561
  }
3562
+ function toApiVersion(version) {
3563
+ const [major, minor] = version.replace(/^v/, "").split(".");
3564
+ return `v${major}_${minor}`;
3565
+ }
3562
3566
  function isPendingBlock(response) {
3563
3567
  return response.status === "PENDING";
3564
3568
  }
@@ -3843,6 +3847,18 @@ var RpcError = class extends LibraryError {
3843
3847
  return rpc_default[typeName] === this.code;
3844
3848
  }
3845
3849
  };
3850
+ var TimeoutError = class extends LibraryError {
3851
+ constructor(message) {
3852
+ super(message);
3853
+ this.name = "TimeoutError";
3854
+ }
3855
+ };
3856
+ var WebSocketNotConnectedError = class extends LibraryError {
3857
+ constructor(message) {
3858
+ super(message);
3859
+ this.name = "WebSocketNotConnectedError";
3860
+ }
3861
+ };
3846
3862
 
3847
3863
  // src/utils/eth.ts
3848
3864
  var eth_exports = {};
@@ -3875,6 +3891,7 @@ __export(provider_exports, {
3875
3891
  createSierraContractClass: () => createSierraContractClass,
3876
3892
  getDefaultNodeUrl: () => getDefaultNodeUrl,
3877
3893
  getDefaultNodes: () => getDefaultNodes,
3894
+ getSupportedRpcVersions: () => getSupportedRpcVersions,
3878
3895
  parseContract: () => parseContract,
3879
3896
  validBlockTags: () => validBlockTags,
3880
3897
  wait: () => wait
@@ -3912,15 +3929,17 @@ var getDefaultNodeUrl = (networkName, mute = false, rpcVersion) => {
3912
3929
  return nodes[randIdx];
3913
3930
  };
3914
3931
  function getDefaultNodes(rpcVersion) {
3915
- const vToUrl = (versionString) => `v${versionString.replace(/^v/, "").replace(/\./g, "_")}`;
3916
3932
  const nodes = { ...RPC_DEFAULT_NODES };
3917
3933
  Object.keys(nodes).forEach(function(key, _) {
3918
3934
  nodes[key] = nodes[key].map((it) => {
3919
- return `${it}${vToUrl(rpcVersion)}`;
3935
+ return `${it}${toApiVersion(rpcVersion)}`;
3920
3936
  });
3921
3937
  });
3922
3938
  return nodes;
3923
3939
  }
3940
+ function getSupportedRpcVersions() {
3941
+ return [...new Set(Object.values(_SupportedRpcVersion))];
3942
+ }
3924
3943
  var validBlockTags = Object.values(BlockTag);
3925
3944
  var Block = class {
3926
3945
  /**
@@ -5293,7 +5312,8 @@ var RpcChannel2 = class {
5293
5312
  type: RPCSPEC08.ETransactionType.INVOKE,
5294
5313
  sender_address: invocation.contractAddress,
5295
5314
  calldata: CallData.toHex(invocation.calldata),
5296
- version: toHex(defaultVersions.v3),
5315
+ version: toHex(invocation.version || defaultVersions.v3),
5316
+ // invocation.version as simulate can use fee and normal version
5297
5317
  ...details
5298
5318
  };
5299
5319
  }
@@ -5311,7 +5331,8 @@ var RpcChannel2 = class {
5311
5331
  },
5312
5332
  compiled_class_hash: invocation.compiledClassHash || "",
5313
5333
  sender_address: invocation.senderAddress,
5314
- version: toHex(defaultVersions.v3),
5334
+ version: toHex(invocation.version || defaultVersions.v3),
5335
+ // invocation.version as simulate can use fee and normal version
5315
5336
  ...details
5316
5337
  };
5317
5338
  }
@@ -5322,7 +5343,8 @@ var RpcChannel2 = class {
5322
5343
  constructor_calldata: CallData.toHex(invocation.constructorCalldata || []),
5323
5344
  class_hash: toHex(invocation.classHash),
5324
5345
  contract_address_salt: toHex(invocation.addressSalt || 0),
5325
- version: toHex(defaultVersions.v3),
5346
+ version: toHex(invocation.version || defaultVersions.v3),
5347
+ // invocation.version as simulate can use fee and normal version
5326
5348
  ...restDetails
5327
5349
  };
5328
5350
  }
@@ -5330,6 +5352,31 @@ var RpcChannel2 = class {
5330
5352
  }
5331
5353
  };
5332
5354
 
5355
+ // src/utils/eventEmitter.ts
5356
+ var EventEmitter = class {
5357
+ listeners = {};
5358
+ on(event, listener) {
5359
+ if (!this.listeners[event]) {
5360
+ this.listeners[event] = [];
5361
+ }
5362
+ this.listeners[event].push(listener);
5363
+ }
5364
+ off(event, listener) {
5365
+ if (!this.listeners[event]) {
5366
+ return;
5367
+ }
5368
+ this.listeners[event] = this.listeners[event].filter((l) => l !== listener);
5369
+ }
5370
+ emit(event, data) {
5371
+ if (this.listeners[event]) {
5372
+ this.listeners[event].forEach((listener) => listener(data));
5373
+ }
5374
+ }
5375
+ clear() {
5376
+ this.listeners = {};
5377
+ }
5378
+ };
5379
+
5333
5380
  // src/utils/connect/ws.ts
5334
5381
  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
5382
  constructor() {
@@ -5339,152 +5386,184 @@ var ws_default = typeof WebSocket !== "undefined" && WebSocket || typeof globalT
5339
5386
  }
5340
5387
  };
5341
5388
 
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 {
5389
+ // src/channel/ws/subscription.ts
5390
+ var Subscription = class {
5350
5391
  /**
5351
- * WebSocket RPC Node URL
5352
- * @example 'wss://starknet-node.io/rpc/v0_8'
5392
+ * The containing `WebSocketChannel` instance.
5393
+ * @internal
5353
5394
  */
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;
5395
+ channel;
5368
5396
  /**
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
- * ```
5397
+ * The JSON-RPC method used to create this subscription.
5398
+ * @internal
5376
5399
  */
5377
- onReorg = () => {
5378
- };
5400
+ method;
5379
5401
  /**
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
- * ```
5402
+ * The parameters used to create this subscription.
5403
+ * @internal
5387
5404
  */
5388
- onNewHeads = () => {
5389
- };
5405
+ params;
5390
5406
  /**
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
- * ```
5407
+ * The unique identifier for this subscription.
5408
+ * @internal
5398
5409
  */
5399
- onEvents = () => {
5400
- };
5410
+ id;
5411
+ events = new EventEmitter();
5412
+ buffer = [];
5413
+ maxBufferSize;
5414
+ handler = null;
5415
+ _isClosed = false;
5401
5416
  /**
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
- * ```
5417
+ * @internal
5418
+ * @param {WebSocketChannel} channel - The WebSocketChannel instance.
5419
+ * @param {string} method - The RPC method used for the subscription.
5420
+ * @param {any} params - The parameters for the subscription.
5421
+ * @param {SUBSCRIPTION_ID} id - The subscription ID.
5422
+ * @param {number} maxBufferSize - The maximum number of events to buffer.
5409
5423
  */
5410
- onTransactionStatus = () => {
5411
- };
5424
+ constructor(channel, method, params, id, maxBufferSize) {
5425
+ this.channel = channel;
5426
+ this.method = method;
5427
+ this.params = params;
5428
+ this.id = id;
5429
+ this.maxBufferSize = maxBufferSize;
5430
+ }
5412
5431
  /**
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
- * ```
5432
+ * Indicates if the subscription has been closed.
5433
+ * @returns {boolean} `true` if unsubscribed, `false` otherwise.
5420
5434
  */
5421
- onPendingTransaction = () => {
5422
- };
5435
+ get isClosed() {
5436
+ return this._isClosed;
5437
+ }
5423
5438
  /**
5424
- * Assign implementation to this method to listen open Event
5439
+ * Internal method to handle incoming events from the WebSocket channel.
5440
+ * If a handler is attached, it's invoked immediately. Otherwise, the event is buffered.
5441
+ * @internal
5442
+ * @param {T} data - The event data.
5425
5443
  */
5426
- onOpen = () => {
5427
- };
5444
+ _handleEvent(data) {
5445
+ if (this.handler) {
5446
+ this.handler(data);
5447
+ } else {
5448
+ if (this.buffer.length >= this.maxBufferSize) {
5449
+ const droppedEvent = this.buffer.shift();
5450
+ logger.warn(`Subscription ${this.id}: Buffer full. Dropping oldest event:`, droppedEvent);
5451
+ }
5452
+ this.buffer.push(data);
5453
+ }
5454
+ }
5428
5455
  /**
5429
- * Assign implementation to this method to listen close CloseEvent
5430
- */
5431
- onClose = () => {
5432
- };
5456
+ * Attaches a handler function to be called for each event.
5457
+ *
5458
+ * When a handler is attached, any buffered events will be passed to it sequentially.
5459
+ * Subsequent events will be passed directly as they arrive.
5460
+ *
5461
+ * @param {(data: T) => void} handler - The function to call with event data.
5462
+ * @throws {Error} If a handler is already attached to this subscription.
5463
+ */
5464
+ on(handler) {
5465
+ if (this.handler) {
5466
+ throw new Error("A handler is already attached to this subscription.");
5467
+ }
5468
+ this.handler = handler;
5469
+ while (this.buffer.length > 0) {
5470
+ const event = this.buffer.shift();
5471
+ if (event) {
5472
+ this.handler(event);
5473
+ }
5474
+ }
5475
+ }
5433
5476
  /**
5434
- * Assign implementation to this method to listen message MessageEvent
5477
+ * Sends an unsubscribe request to the node and cleans up local resources.
5478
+ * @returns {Promise<boolean>} A Promise that resolves to `true` if the unsubscription was successful.
5435
5479
  */
5436
- onMessage = () => {
5437
- };
5480
+ async unsubscribe() {
5481
+ if (this._isClosed) {
5482
+ return true;
5483
+ }
5484
+ const success = await this.channel.unsubscribe(this.id);
5485
+ if (success) {
5486
+ this._isClosed = true;
5487
+ this.channel.removeSubscription(this.id);
5488
+ this.events.emit("unsubscribe", void 0);
5489
+ this.events.clear();
5490
+ }
5491
+ return success;
5492
+ }
5493
+ };
5494
+
5495
+ // src/channel/ws/ws_0_8.ts
5496
+ var WebSocketChannel = class {
5438
5497
  /**
5439
- * Assign implementation to this method to listen error Event
5498
+ * The URL of the WebSocket RPC Node.
5499
+ * @example 'wss://starknet-sepolia.public.blastapi.io/rpc/v0_8'
5440
5500
  */
5441
- onError = () => {
5442
- };
5501
+ nodeUrl;
5443
5502
  /**
5444
- * Assign implementation to this method to listen unsubscription
5503
+ * The underlying WebSocket instance.
5445
5504
  */
5446
- onUnsubscribe = () => {
5447
- };
5448
- onUnsubscribeLocal = () => {
5449
- };
5450
- /**
5451
- * JSON RPC latest sent message id
5452
- * expecting receiving message to contain same id
5505
+ websocket;
5506
+ // Store the WebSocket implementation class to allow for custom implementations.
5507
+ WsImplementation;
5508
+ // Map of active subscriptions, keyed by their ID.
5509
+ activeSubscriptions = /* @__PURE__ */ new Map();
5510
+ maxBufferSize;
5511
+ autoReconnect;
5512
+ reconnectOptions;
5513
+ requestTimeout;
5514
+ isReconnecting = false;
5515
+ reconnectAttempts = 0;
5516
+ userInitiatedClose = false;
5517
+ reconnectTimeoutId = null;
5518
+ requestQueue = [];
5519
+ events = new EventEmitter();
5520
+ openListener = (ev) => this.events.emit("open", ev);
5521
+ closeListener = this.onCloseProxy.bind(this);
5522
+ messageListener = this.onMessageProxy.bind(this);
5523
+ errorListener = (ev) => this.events.emit("error", ev);
5524
+ /**
5525
+ * JSON RPC latest sent message ID.
5526
+ * The receiving message is expected to contain the same ID.
5453
5527
  */
5454
5528
  sendId = 0;
5455
5529
  /**
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
5530
+ * Creates an instance of WebSocketChannel.
5531
+ * @param {WebSocketOptions} options - The options for configuring the channel.
5463
5532
  */
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));
5533
+ constructor(options) {
5534
+ this.nodeUrl = options.nodeUrl;
5535
+ this.maxBufferSize = options.maxBufferSize ?? 1e3;
5536
+ this.autoReconnect = options.autoReconnect ?? true;
5537
+ this.reconnectOptions = {
5538
+ retries: options.reconnectOptions?.retries ?? 5,
5539
+ delay: options.reconnectOptions?.delay ?? 2e3
5540
+ };
5541
+ this.requestTimeout = options.requestTimeout ?? 6e4;
5542
+ this.WsImplementation = options.websocket || config.get("websocket") || ws_default;
5543
+ this.websocket = new this.WsImplementation(this.nodeUrl);
5544
+ this.websocket.addEventListener("open", this.openListener);
5545
+ this.websocket.addEventListener("close", this.closeListener);
5546
+ this.websocket.addEventListener("message", this.messageListener);
5547
+ this.websocket.addEventListener("error", this.errorListener);
5472
5548
  }
5473
5549
  idResolver(id) {
5474
5550
  if (id) return id;
5475
5551
  return this.sendId++;
5476
5552
  }
5477
5553
  /**
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
- * ```
5554
+ * Sends a JSON-RPC request over the WebSocket connection without waiting for a response.
5555
+ * This is a low-level method. Prefer `sendReceive` for most use cases.
5556
+ * @param {string} method - The RPC method name.
5557
+ * @param {object} [params] - The parameters for the RPC method.
5558
+ * @param {number} [id] - A specific request ID. If not provided, an auto-incrementing ID is used.
5559
+ * @returns {number} The ID of the sent request.
5560
+ * @throws {WebSocketNotConnectedError} If the WebSocket is not connected.
5484
5561
  */
5485
5562
  send(method, params, id) {
5486
5563
  if (!this.isConnected()) {
5487
- throw Error("WebSocketChannel.send() fail due to socket disconnected");
5564
+ throw new WebSocketNotConnectedError(
5565
+ "WebSocketChannel.send() failed due to socket being disconnected"
5566
+ );
5488
5567
  }
5489
5568
  const usedId = this.idResolver(id);
5490
5569
  const rpcRequestBody = {
@@ -5497,50 +5576,88 @@ var WebSocketChannel = class {
5497
5576
  return usedId;
5498
5577
  }
5499
5578
  /**
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
- * ```
5579
+ * Sends a JSON-RPC request and returns a Promise that resolves with the result.
5580
+ * This method abstracts the request/response cycle over WebSockets.
5581
+ * If the connection is lost, it will queue the request and send it upon reconnection.
5582
+ * @template T - The expected type of the result.
5583
+ * @param {string} method - The RPC method name.
5584
+ * @param {object} [params] - The parameters for the RPC method.
5585
+ * @returns {Promise<T>} A Promise that resolves with the RPC response result.
5586
+ * @throws {TimeoutError} If the request does not receive a response within the configured `requestTimeout`.
5587
+ * @throws {WebSocketNotConnectedError} If the WebSocket is not connected and auto-reconnect is disabled.
5514
5588
  */
5515
5589
  sendReceive(method, params) {
5590
+ if (this.isReconnecting || !this.isConnected() && this.autoReconnect && !this.userInitiatedClose) {
5591
+ logger.info(`WebSocket: Connection unavailable, queueing request: ${method}`);
5592
+ return new Promise((resolve, reject) => {
5593
+ this.requestQueue.push({ method, params, resolve, reject });
5594
+ });
5595
+ }
5516
5596
  const sendId = this.send(method, params);
5517
5597
  return new Promise((resolve, reject) => {
5518
- if (!this.websocket) return;
5519
- this.websocket.onmessage = ({ data }) => {
5520
- const message = JSON.parse(data);
5598
+ let timeoutId;
5599
+ if (!this.websocket || this.websocket.readyState !== ws_default.OPEN) {
5600
+ reject(new WebSocketNotConnectedError("WebSocket not available or not connected."));
5601
+ return;
5602
+ }
5603
+ const messageHandler = (event) => {
5604
+ if (!isString(event.data)) {
5605
+ logger.warn("WebSocket received non-string message data:", event.data);
5606
+ return;
5607
+ }
5608
+ const message = JSON.parse(event.data);
5521
5609
  if (message.id === sendId) {
5610
+ clearTimeout(timeoutId);
5611
+ this.websocket.removeEventListener("message", messageHandler);
5612
+ this.websocket.removeEventListener("error", errorHandler);
5522
5613
  if ("result" in message) {
5523
5614
  resolve(message.result);
5524
5615
  } else {
5525
- reject(Error(`error on ${method}, ${message.error}`));
5616
+ reject(
5617
+ new Error(`Error on ${method} (id: ${sendId}): ${JSON.stringify(message.error)}`)
5618
+ );
5526
5619
  }
5527
5620
  }
5528
5621
  };
5529
- this.websocket.onerror = reject;
5622
+ const errorHandler = (event) => {
5623
+ clearTimeout(timeoutId);
5624
+ this.websocket.removeEventListener("message", messageHandler);
5625
+ this.websocket.removeEventListener("error", errorHandler);
5626
+ reject(
5627
+ new Error(
5628
+ `WebSocket error during ${method} (id: ${sendId}): ${event.type || "Unknown error"}`
5629
+ )
5630
+ );
5631
+ };
5632
+ this.websocket.addEventListener("message", messageHandler);
5633
+ this.websocket.addEventListener("error", errorHandler);
5634
+ timeoutId = setTimeout(() => {
5635
+ this.websocket.removeEventListener("message", messageHandler);
5636
+ this.websocket.removeEventListener("error", errorHandler);
5637
+ reject(
5638
+ new TimeoutError(
5639
+ `Request ${method} (id: ${sendId}) timed out after ${this.requestTimeout}ms`
5640
+ )
5641
+ );
5642
+ }, this.requestTimeout);
5530
5643
  });
5531
5644
  }
5532
5645
  /**
5533
- * Helper to check connection is open
5646
+ * Checks if the WebSocket connection is currently open.
5647
+ * @returns {boolean} `true` if the connection is open, `false` otherwise.
5534
5648
  */
5535
5649
  isConnected() {
5536
5650
  return this.websocket.readyState === ws_default.OPEN;
5537
5651
  }
5538
5652
  /**
5539
- * await while websocket is connected
5540
- * * could be used to block the flow until websocket is open
5653
+ * Returns a Promise that resolves when the WebSocket connection is open.
5654
+ * Can be used to block execution until the connection is established.
5655
+ * @returns {Promise<number>} A Promise that resolves with the WebSocket's `readyState` when connected.
5541
5656
  * @example
5542
5657
  * ```typescript
5543
- * const readyState = await webSocketChannel.waitForConnection();
5658
+ * const channel = new WebSocketChannel({ nodeUrl: '...' });
5659
+ * await channel.waitForConnection();
5660
+ * console.log('Connected!');
5544
5661
  * ```
5545
5662
  */
5546
5663
  async waitForConnection() {
@@ -5556,17 +5673,22 @@ var WebSocketChannel = class {
5556
5673
  return this.websocket.readyState;
5557
5674
  }
5558
5675
  /**
5559
- * Disconnect the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.
5676
+ * Closes the WebSocket connection.
5677
+ * This method is user-initiated and will prevent automatic reconnection for this closure.
5678
+ * @param {number} [code] - The WebSocket connection close code.
5679
+ * @param {string} [reason] - The WebSocket connection close reason.
5560
5680
  */
5561
5681
  disconnect(code, reason) {
5682
+ if (this.reconnectTimeoutId) {
5683
+ clearTimeout(this.reconnectTimeoutId);
5684
+ this.reconnectTimeoutId = null;
5685
+ }
5562
5686
  this.websocket.close(code, reason);
5687
+ this.userInitiatedClose = true;
5563
5688
  }
5564
5689
  /**
5565
- * await while websocket is disconnected
5566
- * @example
5567
- * ```typescript
5568
- * const readyState = await webSocketChannel.waitForDisconnection();
5569
- * ```
5690
+ * Returns a Promise that resolves when the WebSocket connection is closed.
5691
+ * @returns {Promise<number | Event>} A Promise that resolves with the WebSocket's `readyState` or a `CloseEvent` when disconnected.
5570
5692
  */
5571
5693
  async waitForDisconnection() {
5572
5694
  if (this.websocket.readyState !== ws_default.CLOSED) {
@@ -5579,206 +5701,233 @@ var WebSocketChannel = class {
5579
5701
  return this.websocket.readyState;
5580
5702
  }
5581
5703
  /**
5582
- * Unsubscribe from starknet subscription
5583
- * @param subscriptionId
5584
- * @param ref internal usage, only for managed subscriptions
5704
+ * Unsubscribes from a Starknet subscription.
5705
+ * It is recommended to use the `unsubscribe()` method on the `Subscription` object instead.
5706
+ * @internal
5707
+ * @param {SUBSCRIPTION_ID} subscriptionId - The ID of the subscription to unsubscribe from.
5708
+ * @returns {Promise<boolean>} A Promise that resolves with `true` if the unsubscription was successful.
5585
5709
  */
5586
- async unsubscribe(subscriptionId, ref) {
5710
+ async unsubscribe(subscriptionId) {
5587
5711
  const status = await this.sendReceive("starknet_unsubscribe", {
5588
5712
  subscription_id: subscriptionId
5589
5713
  });
5590
5714
  if (status) {
5591
- if (ref) {
5592
- this.subscriptions.delete(ref);
5593
- }
5594
- this.onUnsubscribeLocal(subscriptionId);
5595
- this.onUnsubscribe(subscriptionId);
5715
+ this.events.emit("unsubscribe", subscriptionId);
5596
5716
  }
5597
5717
  return status;
5598
5718
  }
5599
5719
  /**
5600
- * await while subscription is unsubscribed
5601
- * @param forSubscriptionId if defined trigger on subscriptionId else trigger on any
5602
- * @returns subscriptionId | onerror(Event)
5720
+ * Returns a Promise that resolves when a specific subscription is successfully unsubscribed.
5721
+ * @param {SUBSCRIPTION_ID} targetId - The ID of the subscription to wait for.
5722
+ * @returns {Promise<void>}
5603
5723
  * @example
5604
5724
  * ```typescript
5605
- * const subscriptionId = await webSocketChannel.waitForUnsubscription();
5725
+ * await channel.waitForUnsubscription(mySubscription.id);
5726
+ * console.log('Successfully unsubscribed.');
5606
5727
  * ```
5607
5728
  */
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);
5729
+ waitForUnsubscription(targetId) {
5730
+ return new Promise((resolve) => {
5731
+ const listener = (unsubId) => {
5732
+ if (unsubId === targetId) {
5733
+ this.events.off("unsubscribe", listener);
5734
+ resolve();
5616
5735
  }
5617
5736
  };
5618
- this.websocket.onerror = reject;
5737
+ this.events.on("unsubscribe", listener);
5619
5738
  });
5620
5739
  }
5621
5740
  /**
5622
- * Reconnect re-create this.websocket instance
5741
+ * Manually initiates a reconnection attempt.
5742
+ * This creates a new WebSocket instance and re-establishes listeners.
5623
5743
  */
5624
5744
  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));
5745
+ this.userInitiatedClose = false;
5746
+ this.websocket = new this.WsImplementation(this.nodeUrl);
5747
+ this.websocket.addEventListener("open", this.openListener);
5748
+ this.websocket.addEventListener("close", this.closeListener);
5749
+ this.websocket.addEventListener("message", this.messageListener);
5750
+ this.websocket.addEventListener("error", this.errorListener);
5751
+ }
5752
+ _processRequestQueue() {
5753
+ logger.info(`WebSocket: Processing ${this.requestQueue.length} queued requests.`);
5754
+ while (this.requestQueue.length > 0) {
5755
+ const { method, params, resolve, reject } = this.requestQueue.shift();
5756
+ this.sendReceive(method, params).then(resolve).catch(reject);
5757
+ }
5758
+ }
5759
+ async _restoreSubscriptions() {
5760
+ const oldSubscriptions = Array.from(this.activeSubscriptions.values());
5761
+ this.activeSubscriptions.clear();
5762
+ const restorePromises = oldSubscriptions.map(async (sub) => {
5763
+ try {
5764
+ const newSubId = await this.sendReceive(sub.method, sub.params);
5765
+ sub.id = newSubId;
5766
+ this.activeSubscriptions.set(newSubId, sub);
5767
+ logger.info(`Subscription ${sub.method} restored with new ID: ${newSubId}`);
5768
+ } catch (error) {
5769
+ logger.error(`Failed to restore subscription ${sub.method}:`, error);
5770
+ }
5771
+ });
5772
+ await Promise.all(restorePromises);
5630
5773
  }
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();
5774
+ _startReconnect() {
5775
+ if (this.isReconnecting || !this.autoReconnect) {
5776
+ return;
5777
+ }
5778
+ this.isReconnecting = true;
5779
+ this.reconnectAttempts = 0;
5780
+ const tryReconnect = () => {
5781
+ if (this.reconnectAttempts >= this.reconnectOptions.retries) {
5782
+ logger.error("WebSocket: Maximum reconnection retries reached. Giving up.");
5783
+ this.isReconnecting = false;
5784
+ return;
5785
+ }
5786
+ this.reconnectAttempts += 1;
5787
+ logger.info(
5788
+ `WebSocket: Connection lost. Attempting to reconnect... (${this.reconnectAttempts}/${this.reconnectOptions.retries})`
5789
+ );
5790
+ this.reconnect();
5791
+ this.websocket.onopen = async () => {
5792
+ logger.info("WebSocket: Reconnection successful.");
5793
+ this.isReconnecting = false;
5794
+ this.reconnectAttempts = 0;
5795
+ await this._restoreSubscriptions();
5796
+ this._processRequestQueue();
5797
+ this.events.emit("open", new Event("open"));
5798
+ };
5799
+ this.websocket.onerror = () => {
5800
+ const delay = this.reconnectOptions.delay * 2 ** (this.reconnectAttempts - 1);
5801
+ logger.info(`WebSocket: Reconnect attempt failed. Retrying in ${delay}ms.`);
5802
+ this.reconnectTimeoutId = setTimeout(tryReconnect, delay);
5803
+ };
5804
+ };
5805
+ tryReconnect();
5634
5806
  }
5635
5807
  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);
5808
+ this.websocket.removeEventListener("open", this.openListener);
5809
+ this.websocket.removeEventListener("close", this.closeListener);
5810
+ this.websocket.removeEventListener("message", this.messageListener);
5811
+ this.websocket.removeEventListener("error", this.errorListener);
5812
+ this.events.emit("close", ev);
5813
+ if (!this.userInitiatedClose) {
5814
+ this._startReconnect();
5815
+ }
5641
5816
  }
5642
5817
  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;
5818
+ let message;
5819
+ try {
5820
+ message = JSON.parse(event.data);
5821
+ } catch (error) {
5822
+ logger.error(
5823
+ `WebSocketChannel: Error parsing incoming message: ${event.data}, Error: ${error}`
5824
+ );
5825
+ return;
5663
5826
  }
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
- });
5827
+ if (message.method && isObject(message.params) && "subscription_id" in message.params) {
5828
+ const { result, subscription_id } = message.params;
5829
+ const subscription = this.activeSubscriptions.get(subscription_id);
5830
+ if (subscription) {
5831
+ subscription._handleEvent(result);
5832
+ } else {
5833
+ logger.warn(
5834
+ `WebSocketChannel: Received event for untracked subscription ID: ${subscription_id}.`
5835
+ );
5836
+ }
5837
+ }
5838
+ logger.debug("onMessageProxy:", event.data);
5839
+ this.events.emit("message", event);
5675
5840
  }
5676
5841
  /**
5677
- * subscribe to new block heads
5842
+ * Subscribes to new block headers.
5843
+ * @param {SubscriptionBlockIdentifier} [blockIdentifier] - The block to start receiving notifications from. Defaults to 'latest'.
5844
+ * @returns {Promise<Subscription<BLOCK_HEADER>>} A Promise that resolves with a `Subscription` object for new block headers.
5678
5845
  */
5679
5846
  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
- });
5847
+ const method = "starknet_subscribeNewHeads";
5848
+ const params = {
5849
+ block_id: blockIdentifier ? new Block(blockIdentifier).identifier : void 0
5850
+ };
5851
+ const subId = await this.sendReceive(method, params);
5852
+ const subscription = new Subscription(this, method, params, subId, this.maxBufferSize);
5853
+ this.activeSubscriptions.set(subId, subscription);
5854
+ return subscription;
5704
5855
  }
5705
5856
  /**
5706
- * subscribe to 'starknet events'
5857
+ * Subscribes to events matching a given filter.
5858
+ * @param {BigNumberish} [fromAddress] - The contract address to filter by.
5859
+ * @param {string[][]} [keys] - The event keys to filter by.
5860
+ * @param {SubscriptionBlockIdentifier} [blockIdentifier] - The block to start receiving notifications from. Defaults to 'latest'.
5861
+ * @returns {Promise<Subscription<EMITTED_EVENT>>} A Promise that resolves with a `Subscription` object for the specified events.
5707
5862
  */
5708
5863
  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
- });
5864
+ const method = "starknet_subscribeEvents";
5865
+ const params = {
5866
+ from_address: fromAddress !== void 0 ? toHex(fromAddress) : void 0,
5867
+ keys,
5868
+ block_id: blockIdentifier ? new Block(blockIdentifier).identifier : void 0
5869
+ };
5870
+ const subId = await this.sendReceive(method, params);
5871
+ const subscription = new Subscription(this, method, params, subId, this.maxBufferSize);
5872
+ this.activeSubscriptions.set(subId, subscription);
5873
+ return subscription;
5733
5874
  }
5734
5875
  /**
5735
- * subscribe to transaction status
5876
+ * Subscribes to status updates for a specific transaction.
5877
+ * @param {BigNumberish} transactionHash - The hash of the transaction to monitor.
5878
+ * @param {SubscriptionBlockIdentifier} [blockIdentifier] - The block context. Not typically required.
5879
+ * @returns {Promise<Subscription<NEW_TXN_STATUS>>} A Promise that resolves with a `Subscription` object for the transaction's status.
5736
5880
  */
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;
5881
+ async subscribeTransactionStatus(transactionHash, blockIdentifier) {
5882
+ const method = "starknet_subscribeTransactionStatus";
5883
+ const params = {
5884
+ transaction_hash: toHex(transactionHash),
5885
+ block_id: blockIdentifier ? new Block(blockIdentifier).identifier : void 0
5886
+ };
5887
+ const subId = await this.sendReceive(method, params);
5888
+ const subscription = new Subscription(this, method, params, subId, this.maxBufferSize);
5889
+ this.activeSubscriptions.set(subId, subscription);
5890
+ return subscription;
5742
5891
  }
5743
5892
  /**
5744
- * unsubscribe 'transaction status' subscription
5893
+ * Subscribes to pending transactions.
5894
+ * @param {boolean} [transactionDetails] - If `true`, the full transaction details are included. Defaults to `false` (hash only).
5895
+ * @param {BigNumberish[]} [senderAddress] - An array of sender addresses to filter by.
5896
+ * @returns {Promise<Subscription<TXN_HASH | TXN_WITH_HASH>>} A Promise that resolves with a `Subscription` object for pending transactions.
5745
5897
  */
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);
5898
+ async subscribePendingTransaction(transactionDetails, senderAddress) {
5899
+ const method = "starknet_subscribePendingTransactions";
5900
+ const params = {
5901
+ transaction_details: transactionDetails,
5902
+ sender_address: senderAddress && bigNumberishArrayToHexadecimalStringArray(senderAddress)
5903
+ };
5904
+ const subId = await this.sendReceive(method, params);
5905
+ const subscription = new Subscription(this, method, params, subId, this.maxBufferSize);
5906
+ this.activeSubscriptions.set(subId, subscription);
5907
+ return subscription;
5750
5908
  }
5751
5909
  /**
5752
- * subscribe to pending transactions (mempool)
5753
- * * you can subscribe to this event multiple times and you need to manage subscriptions manually
5910
+ * Internal method to remove subscription from active map.
5911
+ * @internal
5754
5912
  */
5755
- subscribePendingTransactionUnmanaged(transactionDetails, senderAddress) {
5756
- return this.sendReceive("starknet_subscribePendingTransactions", {
5757
- ...{ transaction_details: transactionDetails },
5758
- ...{
5759
- sender_address: senderAddress && bigNumberishArrayToHexadecimalStringArray(senderAddress)
5760
- }
5761
- });
5913
+ removeSubscription(id) {
5914
+ this.activeSubscriptions.delete(id);
5762
5915
  }
5763
5916
  /**
5764
- * subscribe to pending transactions (mempool)
5917
+ * Adds a listener for a given event.
5918
+ * @param event The event name.
5919
+ * @param listener The listener function to add.
5765
5920
  */
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;
5921
+ on(event, listener) {
5922
+ this.events.on(event, listener);
5774
5923
  }
5775
5924
  /**
5776
- * unsubscribe 'pending transaction' subscription
5925
+ * Removes a listener for a given event.
5926
+ * @param event The event name.
5927
+ * @param listener The listener function to remove.
5777
5928
  */
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);
5929
+ off(event, listener) {
5930
+ this.events.off(event, listener);
5782
5931
  }
5783
5932
  };
5784
5933
 
@@ -10645,7 +10794,6 @@ export {
10645
10794
  Contract,
10646
10795
  ContractFactory,
10647
10796
  ContractInterface,
10648
- CustomError,
10649
10797
  EDAMode,
10650
10798
  EDataAvailabilityMode,
10651
10799
  ETH_ADDRESS,
@@ -10682,6 +10830,8 @@ export {
10682
10830
  RpcProvider2 as RpcProvider,
10683
10831
  Signer,
10684
10832
  SignerInterface,
10833
+ Subscription,
10834
+ TimeoutError,
10685
10835
  TransactionExecutionStatus,
10686
10836
  TransactionFinalityStatus,
10687
10837
  TransactionType,
@@ -10698,9 +10848,9 @@ export {
10698
10848
  UINT_512_MIN,
10699
10849
  Uint,
10700
10850
  ValidateType,
10701
- WSSubscriptions,
10702
10851
  WalletAccount,
10703
10852
  WebSocketChannel,
10853
+ WebSocketNotConnectedError,
10704
10854
  addAddressPadding,
10705
10855
  byteArray_exports as byteArray,
10706
10856
  cairo_exports as cairo,
@@ -10714,8 +10864,6 @@ export {
10714
10864
  eth_exports as eth,
10715
10865
  events_exports as events,
10716
10866
  extractContractHashes,
10717
- fixProto,
10718
- fixStack,
10719
10867
  getCalldata,
10720
10868
  getChecksumAddress,
10721
10869
  getLedgerPathBuffer111 as getLedgerPathBuffer,
@@ -10745,6 +10893,7 @@ export {
10745
10893
  stark_exports as stark,
10746
10894
  starknetId_exports as starknetId,
10747
10895
  toAnyPatchVersion,
10896
+ toApiVersion,
10748
10897
  transaction_exports as transaction,
10749
10898
  typedData_exports as typedData,
10750
10899
  types_exports as types,