@tonconnect/sdk 3.0.1-beta.0 → 3.0.1-beta.2

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/lib/esm/index.mjs CHANGED
@@ -343,54 +343,6 @@ function encodeTelegramUrlParameters(parameters) {
343
343
  .replaceAll('%', '--');
344
344
  }
345
345
 
346
- /**
347
- * Creates an AbortController instance with an optional AbortSignal.
348
- *
349
- * @param {AbortSignal} [signal] - An optional AbortSignal to use for aborting the controller.
350
- * @returns {AbortController} - An instance of AbortController.
351
- */
352
- function createAbortController(signal) {
353
- const abortController = new AbortController();
354
- if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
355
- abortController.abort();
356
- }
357
- else {
358
- signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', () => abortController.abort(), { once: true });
359
- }
360
- return abortController;
361
- }
362
- /**
363
- * Executes a function and provides deferred behavior, allowing for a timeout and abort functionality.
364
- *
365
- * @param {Deferrable<T>} fn - The function to execute. It should return a promise that resolves with the desired result.
366
- * @param {DeferOptions} options - Optional configuration options for the defer behavior.
367
- * @returns {Promise<T>} - A promise that resolves with the result of the executed function, or rejects with an error if it times out or is aborted.
368
- */
369
- function defer(fn, options) {
370
- const timeout = options === null || options === void 0 ? void 0 : options.timeout;
371
- const signal = options === null || options === void 0 ? void 0 : options.signal;
372
- const abortController = createAbortController(signal);
373
- return new Promise((resolve, reject) => {
374
- if (abortController.signal.aborted) {
375
- reject(new TonConnectError('Operation aborted'));
376
- return;
377
- }
378
- let timeoutId;
379
- if (typeof timeout !== 'undefined') {
380
- timeoutId = setTimeout(() => {
381
- reject(new TonConnectError(`Timeout after ${timeout}ms`));
382
- abortController.abort();
383
- }, timeout);
384
- }
385
- abortController.signal.addEventListener('abort', () => {
386
- clearTimeout(timeoutId);
387
- reject(new TonConnectError('Operation aborted'));
388
- }, { once: true });
389
- const deferOptions = { timeout, abort: abortController.signal };
390
- fn(resolve, reject, deferOptions).finally(() => clearTimeout(timeoutId));
391
- });
392
- }
393
-
394
346
  /**
395
347
  * Delays the execution of code for a specified number of milliseconds.
396
348
  * @param {number} timeout - The number of milliseconds to delay the execution.
@@ -399,21 +351,38 @@ function defer(fn, options) {
399
351
  */
400
352
  function delay(timeout, options) {
401
353
  return __awaiter(this, void 0, void 0, function* () {
402
- return yield defer((resolve, reject, options) => __awaiter(this, void 0, void 0, function* () {
354
+ return new Promise((resolve, reject) => {
403
355
  var _a, _b;
404
- if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
356
+ if ((_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
405
357
  reject(new TonConnectError('Delay aborted'));
406
358
  return;
407
359
  }
408
360
  const timeoutId = setTimeout(() => resolve(), timeout);
409
- (_b = options.signal) === null || _b === void 0 ? void 0 : _b.addEventListener('abort', () => {
361
+ (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.addEventListener('abort', () => {
410
362
  clearTimeout(timeoutId);
411
363
  reject(new TonConnectError('Delay aborted'));
412
364
  });
413
- }), { signal: options === null || options === void 0 ? void 0 : options.signal });
365
+ });
414
366
  });
415
367
  }
416
368
 
369
+ /**
370
+ * Creates an AbortController instance with an optional AbortSignal.
371
+ *
372
+ * @param {AbortSignal} [signal] - An optional AbortSignal to use for aborting the controller.
373
+ * @returns {AbortController} - An instance of AbortController.
374
+ */
375
+ function createAbortController(signal) {
376
+ const abortController = new AbortController();
377
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
378
+ abortController.abort();
379
+ }
380
+ else {
381
+ signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', () => abortController.abort(), { once: true });
382
+ }
383
+ return abortController;
384
+ }
385
+
417
386
  /**
418
387
  * Function to call ton api until we get response.
419
388
  * Because ton network is pretty unstable we need to make sure response is final.
@@ -441,7 +410,9 @@ function callForSuccess(fn, options) {
441
410
  catch (err) {
442
411
  lastError = err;
443
412
  i++;
444
- yield delay(delayMs);
413
+ if (i < attempts) {
414
+ yield delay(delayMs);
415
+ }
445
416
  }
446
417
  }
447
418
  throw lastError;
@@ -486,16 +457,21 @@ function createResource(createFn, disposeFn) {
486
457
  let currentResource = null;
487
458
  let currentArgs = null;
488
459
  let currentPromise = null;
460
+ let currentSignal = null;
489
461
  let abortController = null;
490
462
  // create a new resource
491
- const create = (...args) => __awaiter(this, void 0, void 0, function* () {
463
+ const create = (signal, ...args) => __awaiter(this, void 0, void 0, function* () {
464
+ currentSignal = signal !== null && signal !== void 0 ? signal : null;
492
465
  abortController === null || abortController === void 0 ? void 0 : abortController.abort();
493
- abortController = createAbortController();
494
- currentArgs = args;
495
- const promise = createFn(abortController.signal, ...args);
466
+ abortController = createAbortController(signal);
467
+ if (abortController.signal.aborted) {
468
+ throw new TonConnectError('Resource creation was aborted');
469
+ }
470
+ currentArgs = args !== null && args !== void 0 ? args : null;
471
+ const promise = createFn(signal, ...args);
496
472
  currentPromise = promise;
497
473
  const resource = yield promise;
498
- if (currentPromise !== promise) {
474
+ if (currentPromise !== promise && resource !== currentResource) {
499
475
  yield disposeFn(resource);
500
476
  throw new TonConnectError('Resource creation was aborted by a new resource creation');
501
477
  }
@@ -508,20 +484,35 @@ function createResource(createFn, disposeFn) {
508
484
  };
509
485
  // dispose the current resource
510
486
  const dispose = () => __awaiter(this, void 0, void 0, function* () {
511
- const resource = currentResource;
512
- currentResource = null;
513
- const promise = currentPromise;
514
- currentPromise = null;
515
- abortController === null || abortController === void 0 ? void 0 : abortController.abort();
516
- yield Promise.allSettled([
517
- resource ? disposeFn(resource) : Promise.resolve(),
518
- promise ? disposeFn(yield promise) : Promise.resolve()
519
- ]);
487
+ try {
488
+ const resource = currentResource;
489
+ currentResource = null;
490
+ const promise = currentPromise;
491
+ currentPromise = null;
492
+ abortController === null || abortController === void 0 ? void 0 : abortController.abort();
493
+ yield Promise.allSettled([
494
+ resource ? disposeFn(resource) : Promise.resolve(),
495
+ promise ? disposeFn(yield promise) : Promise.resolve()
496
+ ]);
497
+ }
498
+ catch (e) {
499
+ logError('Failed to dispose the resource', e);
500
+ }
520
501
  });
521
502
  // recreate the current resource
522
- const recreate = () => __awaiter(this, void 0, void 0, function* () {
523
- yield dispose();
524
- return create(...(currentArgs !== null && currentArgs !== void 0 ? currentArgs : []));
503
+ const recreate = (delayMs) => __awaiter(this, void 0, void 0, function* () {
504
+ const resource = currentResource;
505
+ const promise = currentPromise;
506
+ const args = currentArgs;
507
+ const signal = currentSignal;
508
+ yield delay(delayMs);
509
+ if (resource === currentResource &&
510
+ promise === currentPromise &&
511
+ args === currentArgs &&
512
+ signal === currentSignal) {
513
+ return create(currentSignal, ...(args !== null && args !== void 0 ? args : []));
514
+ }
515
+ throw new TonConnectError('Resource recreation was aborted by a new resource creation');
525
516
  });
526
517
  return {
527
518
  create,
@@ -531,6 +522,38 @@ function createResource(createFn, disposeFn) {
531
522
  };
532
523
  }
533
524
 
525
+ /**
526
+ * Executes a function and provides deferred behavior, allowing for a timeout and abort functionality.
527
+ *
528
+ * @param {Deferrable<T>} fn - The function to execute. It should return a promise that resolves with the desired result.
529
+ * @param {DeferOptions} options - Optional configuration options for the defer behavior.
530
+ * @returns {Promise<T>} - A promise that resolves with the result of the executed function, or rejects with an error if it times out or is aborted.
531
+ */
532
+ function timeout(fn, options) {
533
+ const timeout = options === null || options === void 0 ? void 0 : options.timeout;
534
+ const signal = options === null || options === void 0 ? void 0 : options.signal;
535
+ const abortController = createAbortController(signal);
536
+ return new Promise((resolve, reject) => {
537
+ if (abortController.signal.aborted) {
538
+ reject(new TonConnectError('Operation aborted'));
539
+ return;
540
+ }
541
+ let timeoutId;
542
+ if (typeof timeout !== 'undefined') {
543
+ timeoutId = setTimeout(() => {
544
+ abortController.abort();
545
+ reject(new TonConnectError(`Timeout after ${timeout}ms`));
546
+ }, timeout);
547
+ }
548
+ abortController.signal.addEventListener('abort', () => {
549
+ clearTimeout(timeoutId);
550
+ reject(new TonConnectError('Operation aborted'));
551
+ }, { once: true });
552
+ const deferOptions = { timeout, abort: abortController.signal };
553
+ fn(resolve, reject, deferOptions).finally(() => clearTimeout(timeoutId));
554
+ });
555
+ }
556
+
534
557
  class BridgeGateway {
535
558
  constructor(storage, bridgeUrl, sessionId, listener, errorsListener) {
536
559
  this.bridgeUrl = bridgeUrl;
@@ -541,7 +564,8 @@ class BridgeGateway {
541
564
  this.postPath = 'message';
542
565
  this.heartbeatMessage = 'heartbeat';
543
566
  this.defaultTtl = 300;
544
- this.eventSource = createResource((signal, options) => __awaiter(this, void 0, void 0, function* () {
567
+ this.defaultReconnectDelay = 5000;
568
+ this.eventSource = createResource((signal, openingDeadlineMS) => __awaiter(this, void 0, void 0, function* () {
545
569
  const eventSourceConfig = {
546
570
  bridgeUrl: this.bridgeUrl,
547
571
  ssePath: this.ssePath,
@@ -549,9 +573,10 @@ class BridgeGateway {
549
573
  bridgeGatewayStorage: this.bridgeGatewayStorage,
550
574
  errorHandler: this.errorsHandler.bind(this),
551
575
  messageHandler: this.messagesHandler.bind(this),
552
- signal: signal
576
+ signal: signal,
577
+ openingDeadlineMS: openingDeadlineMS
553
578
  };
554
- return yield createEventSource(eventSourceConfig, options);
579
+ return yield createEventSource(eventSourceConfig);
555
580
  }), (resource) => __awaiter(this, void 0, void 0, function* () {
556
581
  resource.close();
557
582
  }));
@@ -571,10 +596,11 @@ class BridgeGateway {
571
596
  }
572
597
  registerSession(options) {
573
598
  return __awaiter(this, void 0, void 0, function* () {
574
- yield this.eventSource.create(options);
599
+ yield this.eventSource.create(options === null || options === void 0 ? void 0 : options.signal, options === null || options === void 0 ? void 0 : options.openingDeadlineMS);
575
600
  });
576
601
  }
577
602
  send(message, receiver, topic, ttlOrOptions) {
603
+ var _a;
578
604
  return __awaiter(this, void 0, void 0, function* () {
579
605
  // TODO: remove deprecated method
580
606
  const options = {};
@@ -584,6 +610,7 @@ class BridgeGateway {
584
610
  else {
585
611
  options.ttl = ttlOrOptions === null || ttlOrOptions === void 0 ? void 0 : ttlOrOptions.ttl;
586
612
  options.signal = ttlOrOptions === null || ttlOrOptions === void 0 ? void 0 : ttlOrOptions.signal;
613
+ options.attempts = ttlOrOptions === null || ttlOrOptions === void 0 ? void 0 : ttlOrOptions.attempts;
587
614
  }
588
615
  const url = new URL(addPathToUrl(this.bridgeUrl, this.postPath));
589
616
  url.searchParams.append('client_id', this.sessionId);
@@ -596,21 +623,25 @@ class BridgeGateway {
596
623
  if (!response.ok) {
597
624
  throw new TonConnectError(`Bridge send failed, status ${response.status}`);
598
625
  }
599
- }), { attempts: Number.MAX_SAFE_INTEGER, delayMs: 5000, signal: options === null || options === void 0 ? void 0 : options.signal });
626
+ }), {
627
+ attempts: (_a = options === null || options === void 0 ? void 0 : options.attempts) !== null && _a !== void 0 ? _a : Number.MAX_SAFE_INTEGER,
628
+ delayMs: 5000,
629
+ signal: options === null || options === void 0 ? void 0 : options.signal
630
+ });
600
631
  });
601
632
  }
602
633
  pause() {
603
- var _a;
604
- (_a = this.eventSource) === null || _a === void 0 ? void 0 : _a.dispose();
634
+ this.eventSource.dispose().catch(e => logError(`Bridge pause failed, ${e}`));
605
635
  }
606
636
  unPause() {
607
637
  return __awaiter(this, void 0, void 0, function* () {
608
- yield this.eventSource.recreate();
638
+ const RECREATE_WITHOUT_DELAY = 0;
639
+ yield this.eventSource.recreate(RECREATE_WITHOUT_DELAY);
609
640
  });
610
641
  }
611
642
  close() {
612
643
  return __awaiter(this, void 0, void 0, function* () {
613
- yield this.eventSource.dispose();
644
+ yield this.eventSource.dispose().catch(e => logError(`Bridge close failed, ${e}`));
614
645
  });
615
646
  }
616
647
  setListener(listener) {
@@ -632,22 +663,25 @@ class BridgeGateway {
632
663
  return response;
633
664
  });
634
665
  }
635
- errorsHandler(e) {
666
+ errorsHandler(eventSource, e) {
636
667
  return __awaiter(this, void 0, void 0, function* () {
637
668
  if (this.isConnecting) {
638
669
  logError('Bridge error', JSON.stringify(e));
639
670
  return;
640
671
  }
641
672
  if (this.isReady) {
642
- this.errorsListener(e);
673
+ try {
674
+ this.errorsListener(e);
675
+ }
676
+ catch (e) { }
643
677
  return;
644
678
  }
645
679
  if (this.isClosed) {
646
- logDebug('Bridge reconnecting, 200ms delay');
647
- yield delay(200);
648
- yield this.eventSource.recreate();
649
- return;
680
+ eventSource.close();
681
+ logDebug(`Bridge reconnecting, ${this.defaultReconnectDelay}ms delay`);
682
+ return yield this.eventSource.recreate(this.defaultReconnectDelay);
650
683
  }
684
+ throw new TonConnectError('Bridge error, unknown state');
651
685
  });
652
686
  }
653
687
  messagesHandler(e) {
@@ -670,9 +704,13 @@ class BridgeGateway {
670
704
  });
671
705
  }
672
706
  }
673
- function createEventSource(config, options) {
707
+ /**
708
+ * Creates an event source.
709
+ * @param {CreateEventSourceConfig} config - Configuration for creating an event source.
710
+ */
711
+ function createEventSource(config) {
674
712
  return __awaiter(this, void 0, void 0, function* () {
675
- return yield defer((resolve, reject, deferOptions) => __awaiter(this, void 0, void 0, function* () {
713
+ return yield timeout((resolve, reject, deferOptions) => __awaiter(this, void 0, void 0, function* () {
676
714
  var _a;
677
715
  const abortController = createAbortController(deferOptions.signal);
678
716
  const signal = abortController.signal;
@@ -691,15 +729,25 @@ function createEventSource(config, options) {
691
729
  return;
692
730
  }
693
731
  const eventSource = new EventSource(url.toString());
694
- eventSource.onerror = (reason) => {
732
+ eventSource.onerror = (reason) => __awaiter(this, void 0, void 0, function* () {
695
733
  if (signal.aborted) {
734
+ eventSource.close();
696
735
  reject(new TonConnectError('Bridge connection aborted'));
697
736
  return;
698
737
  }
699
- config.errorHandler(reason);
700
- };
738
+ try {
739
+ const newInstance = yield config.errorHandler(eventSource, reason);
740
+ if (newInstance && newInstance !== eventSource) {
741
+ resolve(newInstance);
742
+ }
743
+ }
744
+ catch (e) {
745
+ reject(e);
746
+ }
747
+ });
701
748
  eventSource.onopen = () => {
702
749
  if (signal.aborted) {
750
+ eventSource.close();
703
751
  reject(new TonConnectError('Bridge connection aborted'));
704
752
  return;
705
753
  }
@@ -708,12 +756,11 @@ function createEventSource(config, options) {
708
756
  eventSource.onmessage = (event) => {
709
757
  config.messageHandler(event);
710
758
  };
711
- (_a = config === null || config === void 0 ? void 0 : config.signal) === null || _a === void 0 ? void 0 : _a.addEventListener('abort', () => {
712
- logError('Bridge connection aborted');
759
+ (_a = config.signal) === null || _a === void 0 ? void 0 : _a.addEventListener('abort', () => {
713
760
  eventSource.close();
714
761
  reject(new TonConnectError('Bridge connection aborted'));
715
762
  });
716
- }), { timeout: options === null || options === void 0 ? void 0 : options.openingDeadlineMS, signal: config === null || config === void 0 ? void 0 : config.signal });
763
+ }), { timeout: config.openingDeadlineMS, signal: config.signal });
717
764
  });
718
765
  }
719
766
 
@@ -905,6 +952,10 @@ class BridgeProvider {
905
952
  });
906
953
  }
907
954
  connect(message, options) {
955
+ var _a;
956
+ const abortController = createAbortController(options === null || options === void 0 ? void 0 : options.signal);
957
+ (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort();
958
+ this.abortController = abortController;
908
959
  this.closeGateways();
909
960
  const sessionCrypto = new SessionCrypto();
910
961
  this.session = {
@@ -920,13 +971,16 @@ class BridgeProvider {
920
971
  sessionCrypto
921
972
  })
922
973
  .then(() => __awaiter(this, void 0, void 0, function* () {
974
+ if (abortController.signal.aborted) {
975
+ return;
976
+ }
923
977
  yield callForSuccess(_options => this.openGateways(sessionCrypto, {
924
978
  openingDeadlineMS: options === null || options === void 0 ? void 0 : options.openingDeadlineMS,
925
979
  signal: _options === null || _options === void 0 ? void 0 : _options.signal
926
980
  }), {
927
981
  attempts: Number.MAX_SAFE_INTEGER,
928
982
  delayMs: 5000,
929
- signal: options === null || options === void 0 ? void 0 : options.signal
983
+ signal: abortController.signal
930
984
  });
931
985
  }));
932
986
  const universalLink = 'universalLink' in this.walletConnectionSource &&
@@ -1005,6 +1059,7 @@ class BridgeProvider {
1005
1059
  else {
1006
1060
  options.onRequestSent = optionsOrOnRequestSent === null || optionsOrOnRequestSent === void 0 ? void 0 : optionsOrOnRequestSent.onRequestSent;
1007
1061
  options.signal = optionsOrOnRequestSent === null || optionsOrOnRequestSent === void 0 ? void 0 : optionsOrOnRequestSent.signal;
1062
+ options.attempts = optionsOrOnRequestSent === null || optionsOrOnRequestSent === void 0 ? void 0 : optionsOrOnRequestSent.attempts;
1008
1063
  }
1009
1064
  return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
1010
1065
  var _a;
@@ -1016,7 +1071,7 @@ class BridgeProvider {
1016
1071
  logDebug('Send http-bridge request:', Object.assign(Object.assign({}, request), { id }));
1017
1072
  const encodedRequest = this.session.sessionCrypto.encrypt(JSON.stringify(Object.assign(Object.assign({}, request), { id })), hexToByteArray(this.session.walletPublicKey));
1018
1073
  try {
1019
- yield this.gateway.send(encodedRequest, this.session.walletPublicKey, request.method, { signal: options === null || options === void 0 ? void 0 : options.signal });
1074
+ yield this.gateway.send(encodedRequest, this.session.walletPublicKey, request.method, { attempts: options === null || options === void 0 ? void 0 : options.attempts, signal: options === null || options === void 0 ? void 0 : options.signal });
1020
1075
  (_a = options === null || options === void 0 ? void 0 : options.onRequestSent) === null || _a === void 0 ? void 0 : _a.call(options);
1021
1076
  this.pendingRequests.set(id.toString(), resolve);
1022
1077
  }
@@ -1035,15 +1090,23 @@ class BridgeProvider {
1035
1090
  return __awaiter(this, void 0, void 0, function* () {
1036
1091
  return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
1037
1092
  let called = false;
1093
+ let timeoutId = null;
1038
1094
  const onRequestSent = () => {
1039
- called = true;
1040
- this.removeBridgeAndSession().then(resolve);
1095
+ if (!called) {
1096
+ called = true;
1097
+ this.removeBridgeAndSession().then(resolve);
1098
+ }
1041
1099
  };
1042
1100
  try {
1043
1101
  this.closeGateways();
1102
+ const abortController = createAbortController(options === null || options === void 0 ? void 0 : options.signal);
1103
+ timeoutId = setTimeout(() => {
1104
+ abortController.abort();
1105
+ }, this.defaultOpeningDeadlineMS);
1044
1106
  yield this.sendRequest({ method: 'disconnect', params: [] }, {
1045
1107
  onRequestSent: onRequestSent,
1046
- signal: options === null || options === void 0 ? void 0 : options.signal
1108
+ signal: abortController.signal,
1109
+ attempts: 1,
1047
1110
  });
1048
1111
  }
1049
1112
  catch (e) {
@@ -1052,6 +1115,12 @@ class BridgeProvider {
1052
1115
  this.removeBridgeAndSession().then(resolve);
1053
1116
  }
1054
1117
  }
1118
+ finally {
1119
+ if (timeoutId) {
1120
+ clearTimeout(timeoutId);
1121
+ }
1122
+ onRequestSent();
1123
+ }
1055
1124
  }));
1056
1125
  });
1057
1126
  }
@@ -1186,11 +1255,7 @@ class BridgeProvider {
1186
1255
  return url.toString();
1187
1256
  }
1188
1257
  openGateways(sessionCrypto, options) {
1189
- var _a;
1190
1258
  return __awaiter(this, void 0, void 0, function* () {
1191
- const abortController = createAbortController(options === null || options === void 0 ? void 0 : options.signal);
1192
- (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort();
1193
- this.abortController = abortController;
1194
1259
  if (Array.isArray(this.walletConnectionSource)) {
1195
1260
  // close all gateways before opening new ones
1196
1261
  this.pendingGateways.map(bridge => bridge.close().catch(e => console.error(e)));
@@ -1203,6 +1268,9 @@ class BridgeProvider {
1203
1268
  return gateway;
1204
1269
  });
1205
1270
  yield Promise.allSettled(this.pendingGateways.map(bridge => callForSuccess((_options) => {
1271
+ if (!this.pendingGateways.some(item => item === bridge)) {
1272
+ return bridge.close();
1273
+ }
1206
1274
  return bridge.registerSession({
1207
1275
  openingDeadlineMS: options === null || options === void 0 ? void 0 : options.openingDeadlineMS,
1208
1276
  signal: _options.signal
@@ -1210,7 +1278,7 @@ class BridgeProvider {
1210
1278
  }, {
1211
1279
  attempts: Number.MAX_SAFE_INTEGER,
1212
1280
  delayMs: 5000,
1213
- signal: abortController.signal
1281
+ signal: options === null || options === void 0 ? void 0 : options.signal
1214
1282
  })));
1215
1283
  return;
1216
1284
  }
@@ -1222,7 +1290,7 @@ class BridgeProvider {
1222
1290
  this.gateway = new BridgeGateway(this.storage, this.walletConnectionSource.bridgeUrl, sessionCrypto.sessionId, this.gatewayListener.bind(this), this.gatewayErrorsListener.bind(this));
1223
1291
  return yield this.gateway.registerSession({
1224
1292
  openingDeadlineMS: options === null || options === void 0 ? void 0 : options.openingDeadlineMS,
1225
- signal: abortController.signal
1293
+ signal: options === null || options === void 0 ? void 0 : options.signal
1226
1294
  });
1227
1295
  }
1228
1296
  });
@@ -2030,6 +2098,11 @@ class TonConnect {
2030
2098
  }
2031
2099
  (_b = this.provider) === null || _b === void 0 ? void 0 : _b.closeConnection();
2032
2100
  this.provider = this.createProvider(wallet);
2101
+ abortController.signal.addEventListener('abort', () => {
2102
+ var _a;
2103
+ (_a = this.provider) === null || _a === void 0 ? void 0 : _a.closeConnection();
2104
+ this.provider = null;
2105
+ });
2033
2106
  return this.provider.connect(this.createConnectRequest(options === null || options === void 0 ? void 0 : options.request), {
2034
2107
  openingDeadlineMS: options === null || options === void 0 ? void 0 : options.openingDeadlineMS,
2035
2108
  signal: abortController.signal
@@ -2090,6 +2163,10 @@ class TonConnect {
2090
2163
  (_b = this.provider) === null || _b === void 0 ? void 0 : _b.closeConnection();
2091
2164
  this.provider = provider;
2092
2165
  provider.listen(this.walletEventsListener.bind(this));
2166
+ abortController.signal.addEventListener('abort', () => {
2167
+ provider === null || provider === void 0 ? void 0 : provider.closeConnection();
2168
+ provider = null;
2169
+ });
2093
2170
  return yield callForSuccess((_options) => __awaiter(this, void 0, void 0, function* () {
2094
2171
  return provider === null || provider === void 0 ? void 0 : provider.restoreConnection({
2095
2172
  openingDeadlineMS: options === null || options === void 0 ? void 0 : options.openingDeadlineMS,
@@ -2136,21 +2213,22 @@ class TonConnect {
2136
2213
  * Disconnect form thw connected wallet and drop current session.
2137
2214
  */
2138
2215
  disconnect(options) {
2139
- var _a, _b;
2216
+ var _a;
2140
2217
  return __awaiter(this, void 0, void 0, function* () {
2141
2218
  if (!this.connected) {
2142
2219
  throw new WalletNotConnectedError();
2143
2220
  }
2144
2221
  const abortController = createAbortController(options === null || options === void 0 ? void 0 : options.signal);
2145
- (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort();
2222
+ const prevAbortController = this.abortController;
2146
2223
  this.abortController = abortController;
2147
2224
  if (abortController.signal.aborted) {
2148
2225
  throw new TonConnectError('Disconnect was aborted');
2149
2226
  }
2150
2227
  this.onWalletDisconnected();
2151
- yield ((_b = this.provider) === null || _b === void 0 ? void 0 : _b.disconnect({
2228
+ yield ((_a = this.provider) === null || _a === void 0 ? void 0 : _a.disconnect({
2152
2229
  signal: abortController.signal
2153
2230
  }));
2231
+ prevAbortController === null || prevAbortController === void 0 ? void 0 : prevAbortController.abort();
2154
2232
  });
2155
2233
  }
2156
2234
  /**
@@ -2185,12 +2263,12 @@ class TonConnect {
2185
2263
  this.pauseConnection();
2186
2264
  }
2187
2265
  else {
2188
- this.unPauseConnection();
2266
+ this.unPauseConnection().catch(e => logError('Cannot unpause connection', e));
2189
2267
  }
2190
2268
  });
2191
2269
  }
2192
2270
  catch (e) {
2193
- console.error('Cannot subscribe to the document.visibilitychange: ', e);
2271
+ logError('Cannot subscribe to the document.visibilitychange: ', e);
2194
2272
  }
2195
2273
  }
2196
2274
  createProvider(wallet) {