@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/cjs/index.cjs CHANGED
@@ -346,54 +346,6 @@ function encodeTelegramUrlParameters(parameters) {
346
346
  .replaceAll('%', '--');
347
347
  }
348
348
 
349
- /**
350
- * Creates an AbortController instance with an optional AbortSignal.
351
- *
352
- * @param {AbortSignal} [signal] - An optional AbortSignal to use for aborting the controller.
353
- * @returns {AbortController} - An instance of AbortController.
354
- */
355
- function createAbortController(signal) {
356
- const abortController = new AbortController();
357
- if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
358
- abortController.abort();
359
- }
360
- else {
361
- signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', () => abortController.abort(), { once: true });
362
- }
363
- return abortController;
364
- }
365
- /**
366
- * Executes a function and provides deferred behavior, allowing for a timeout and abort functionality.
367
- *
368
- * @param {Deferrable<T>} fn - The function to execute. It should return a promise that resolves with the desired result.
369
- * @param {DeferOptions} options - Optional configuration options for the defer behavior.
370
- * @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.
371
- */
372
- function defer(fn, options) {
373
- const timeout = options === null || options === void 0 ? void 0 : options.timeout;
374
- const signal = options === null || options === void 0 ? void 0 : options.signal;
375
- const abortController = createAbortController(signal);
376
- return new Promise((resolve, reject) => {
377
- if (abortController.signal.aborted) {
378
- reject(new TonConnectError('Operation aborted'));
379
- return;
380
- }
381
- let timeoutId;
382
- if (typeof timeout !== 'undefined') {
383
- timeoutId = setTimeout(() => {
384
- reject(new TonConnectError(`Timeout after ${timeout}ms`));
385
- abortController.abort();
386
- }, timeout);
387
- }
388
- abortController.signal.addEventListener('abort', () => {
389
- clearTimeout(timeoutId);
390
- reject(new TonConnectError('Operation aborted'));
391
- }, { once: true });
392
- const deferOptions = { timeout, abort: abortController.signal };
393
- fn(resolve, reject, deferOptions).finally(() => clearTimeout(timeoutId));
394
- });
395
- }
396
-
397
349
  /**
398
350
  * Delays the execution of code for a specified number of milliseconds.
399
351
  * @param {number} timeout - The number of milliseconds to delay the execution.
@@ -402,21 +354,38 @@ function defer(fn, options) {
402
354
  */
403
355
  function delay(timeout, options) {
404
356
  return __awaiter(this, void 0, void 0, function* () {
405
- return yield defer((resolve, reject, options) => __awaiter(this, void 0, void 0, function* () {
357
+ return new Promise((resolve, reject) => {
406
358
  var _a, _b;
407
- if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
359
+ if ((_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
408
360
  reject(new TonConnectError('Delay aborted'));
409
361
  return;
410
362
  }
411
363
  const timeoutId = setTimeout(() => resolve(), timeout);
412
- (_b = options.signal) === null || _b === void 0 ? void 0 : _b.addEventListener('abort', () => {
364
+ (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.addEventListener('abort', () => {
413
365
  clearTimeout(timeoutId);
414
366
  reject(new TonConnectError('Delay aborted'));
415
367
  });
416
- }), { signal: options === null || options === void 0 ? void 0 : options.signal });
368
+ });
417
369
  });
418
370
  }
419
371
 
372
+ /**
373
+ * Creates an AbortController instance with an optional AbortSignal.
374
+ *
375
+ * @param {AbortSignal} [signal] - An optional AbortSignal to use for aborting the controller.
376
+ * @returns {AbortController} - An instance of AbortController.
377
+ */
378
+ function createAbortController(signal) {
379
+ const abortController = new AbortController();
380
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
381
+ abortController.abort();
382
+ }
383
+ else {
384
+ signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', () => abortController.abort(), { once: true });
385
+ }
386
+ return abortController;
387
+ }
388
+
420
389
  /**
421
390
  * Function to call ton api until we get response.
422
391
  * Because ton network is pretty unstable we need to make sure response is final.
@@ -444,7 +413,9 @@ function callForSuccess(fn, options) {
444
413
  catch (err) {
445
414
  lastError = err;
446
415
  i++;
447
- yield delay(delayMs);
416
+ if (i < attempts) {
417
+ yield delay(delayMs);
418
+ }
448
419
  }
449
420
  }
450
421
  throw lastError;
@@ -489,16 +460,21 @@ function createResource(createFn, disposeFn) {
489
460
  let currentResource = null;
490
461
  let currentArgs = null;
491
462
  let currentPromise = null;
463
+ let currentSignal = null;
492
464
  let abortController = null;
493
465
  // create a new resource
494
- const create = (...args) => __awaiter(this, void 0, void 0, function* () {
466
+ const create = (signal, ...args) => __awaiter(this, void 0, void 0, function* () {
467
+ currentSignal = signal !== null && signal !== void 0 ? signal : null;
495
468
  abortController === null || abortController === void 0 ? void 0 : abortController.abort();
496
- abortController = createAbortController();
497
- currentArgs = args;
498
- const promise = createFn(abortController.signal, ...args);
469
+ abortController = createAbortController(signal);
470
+ if (abortController.signal.aborted) {
471
+ throw new TonConnectError('Resource creation was aborted');
472
+ }
473
+ currentArgs = args !== null && args !== void 0 ? args : null;
474
+ const promise = createFn(signal, ...args);
499
475
  currentPromise = promise;
500
476
  const resource = yield promise;
501
- if (currentPromise !== promise) {
477
+ if (currentPromise !== promise && resource !== currentResource) {
502
478
  yield disposeFn(resource);
503
479
  throw new TonConnectError('Resource creation was aborted by a new resource creation');
504
480
  }
@@ -511,20 +487,35 @@ function createResource(createFn, disposeFn) {
511
487
  };
512
488
  // dispose the current resource
513
489
  const dispose = () => __awaiter(this, void 0, void 0, function* () {
514
- const resource = currentResource;
515
- currentResource = null;
516
- const promise = currentPromise;
517
- currentPromise = null;
518
- abortController === null || abortController === void 0 ? void 0 : abortController.abort();
519
- yield Promise.allSettled([
520
- resource ? disposeFn(resource) : Promise.resolve(),
521
- promise ? disposeFn(yield promise) : Promise.resolve()
522
- ]);
490
+ try {
491
+ const resource = currentResource;
492
+ currentResource = null;
493
+ const promise = currentPromise;
494
+ currentPromise = null;
495
+ abortController === null || abortController === void 0 ? void 0 : abortController.abort();
496
+ yield Promise.allSettled([
497
+ resource ? disposeFn(resource) : Promise.resolve(),
498
+ promise ? disposeFn(yield promise) : Promise.resolve()
499
+ ]);
500
+ }
501
+ catch (e) {
502
+ logError('Failed to dispose the resource', e);
503
+ }
523
504
  });
524
505
  // recreate the current resource
525
- const recreate = () => __awaiter(this, void 0, void 0, function* () {
526
- yield dispose();
527
- return create(...(currentArgs !== null && currentArgs !== void 0 ? currentArgs : []));
506
+ const recreate = (delayMs) => __awaiter(this, void 0, void 0, function* () {
507
+ const resource = currentResource;
508
+ const promise = currentPromise;
509
+ const args = currentArgs;
510
+ const signal = currentSignal;
511
+ yield delay(delayMs);
512
+ if (resource === currentResource &&
513
+ promise === currentPromise &&
514
+ args === currentArgs &&
515
+ signal === currentSignal) {
516
+ return create(currentSignal, ...(args !== null && args !== void 0 ? args : []));
517
+ }
518
+ throw new TonConnectError('Resource recreation was aborted by a new resource creation');
528
519
  });
529
520
  return {
530
521
  create,
@@ -534,6 +525,38 @@ function createResource(createFn, disposeFn) {
534
525
  };
535
526
  }
536
527
 
528
+ /**
529
+ * Executes a function and provides deferred behavior, allowing for a timeout and abort functionality.
530
+ *
531
+ * @param {Deferrable<T>} fn - The function to execute. It should return a promise that resolves with the desired result.
532
+ * @param {DeferOptions} options - Optional configuration options for the defer behavior.
533
+ * @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.
534
+ */
535
+ function timeout(fn, options) {
536
+ const timeout = options === null || options === void 0 ? void 0 : options.timeout;
537
+ const signal = options === null || options === void 0 ? void 0 : options.signal;
538
+ const abortController = createAbortController(signal);
539
+ return new Promise((resolve, reject) => {
540
+ if (abortController.signal.aborted) {
541
+ reject(new TonConnectError('Operation aborted'));
542
+ return;
543
+ }
544
+ let timeoutId;
545
+ if (typeof timeout !== 'undefined') {
546
+ timeoutId = setTimeout(() => {
547
+ abortController.abort();
548
+ reject(new TonConnectError(`Timeout after ${timeout}ms`));
549
+ }, timeout);
550
+ }
551
+ abortController.signal.addEventListener('abort', () => {
552
+ clearTimeout(timeoutId);
553
+ reject(new TonConnectError('Operation aborted'));
554
+ }, { once: true });
555
+ const deferOptions = { timeout, abort: abortController.signal };
556
+ fn(resolve, reject, deferOptions).finally(() => clearTimeout(timeoutId));
557
+ });
558
+ }
559
+
537
560
  class BridgeGateway {
538
561
  constructor(storage, bridgeUrl, sessionId, listener, errorsListener) {
539
562
  this.bridgeUrl = bridgeUrl;
@@ -544,7 +567,8 @@ class BridgeGateway {
544
567
  this.postPath = 'message';
545
568
  this.heartbeatMessage = 'heartbeat';
546
569
  this.defaultTtl = 300;
547
- this.eventSource = createResource((signal, options) => __awaiter(this, void 0, void 0, function* () {
570
+ this.defaultReconnectDelay = 5000;
571
+ this.eventSource = createResource((signal, openingDeadlineMS) => __awaiter(this, void 0, void 0, function* () {
548
572
  const eventSourceConfig = {
549
573
  bridgeUrl: this.bridgeUrl,
550
574
  ssePath: this.ssePath,
@@ -552,9 +576,10 @@ class BridgeGateway {
552
576
  bridgeGatewayStorage: this.bridgeGatewayStorage,
553
577
  errorHandler: this.errorsHandler.bind(this),
554
578
  messageHandler: this.messagesHandler.bind(this),
555
- signal: signal
579
+ signal: signal,
580
+ openingDeadlineMS: openingDeadlineMS
556
581
  };
557
- return yield createEventSource(eventSourceConfig, options);
582
+ return yield createEventSource(eventSourceConfig);
558
583
  }), (resource) => __awaiter(this, void 0, void 0, function* () {
559
584
  resource.close();
560
585
  }));
@@ -574,10 +599,11 @@ class BridgeGateway {
574
599
  }
575
600
  registerSession(options) {
576
601
  return __awaiter(this, void 0, void 0, function* () {
577
- yield this.eventSource.create(options);
602
+ yield this.eventSource.create(options === null || options === void 0 ? void 0 : options.signal, options === null || options === void 0 ? void 0 : options.openingDeadlineMS);
578
603
  });
579
604
  }
580
605
  send(message, receiver, topic, ttlOrOptions) {
606
+ var _a;
581
607
  return __awaiter(this, void 0, void 0, function* () {
582
608
  // TODO: remove deprecated method
583
609
  const options = {};
@@ -587,6 +613,7 @@ class BridgeGateway {
587
613
  else {
588
614
  options.ttl = ttlOrOptions === null || ttlOrOptions === void 0 ? void 0 : ttlOrOptions.ttl;
589
615
  options.signal = ttlOrOptions === null || ttlOrOptions === void 0 ? void 0 : ttlOrOptions.signal;
616
+ options.attempts = ttlOrOptions === null || ttlOrOptions === void 0 ? void 0 : ttlOrOptions.attempts;
590
617
  }
591
618
  const url = new URL(addPathToUrl(this.bridgeUrl, this.postPath));
592
619
  url.searchParams.append('client_id', this.sessionId);
@@ -599,21 +626,25 @@ class BridgeGateway {
599
626
  if (!response.ok) {
600
627
  throw new TonConnectError(`Bridge send failed, status ${response.status}`);
601
628
  }
602
- }), { attempts: Number.MAX_SAFE_INTEGER, delayMs: 5000, signal: options === null || options === void 0 ? void 0 : options.signal });
629
+ }), {
630
+ attempts: (_a = options === null || options === void 0 ? void 0 : options.attempts) !== null && _a !== void 0 ? _a : Number.MAX_SAFE_INTEGER,
631
+ delayMs: 5000,
632
+ signal: options === null || options === void 0 ? void 0 : options.signal
633
+ });
603
634
  });
604
635
  }
605
636
  pause() {
606
- var _a;
607
- (_a = this.eventSource) === null || _a === void 0 ? void 0 : _a.dispose();
637
+ this.eventSource.dispose().catch(e => logError(`Bridge pause failed, ${e}`));
608
638
  }
609
639
  unPause() {
610
640
  return __awaiter(this, void 0, void 0, function* () {
611
- yield this.eventSource.recreate();
641
+ const RECREATE_WITHOUT_DELAY = 0;
642
+ yield this.eventSource.recreate(RECREATE_WITHOUT_DELAY);
612
643
  });
613
644
  }
614
645
  close() {
615
646
  return __awaiter(this, void 0, void 0, function* () {
616
- yield this.eventSource.dispose();
647
+ yield this.eventSource.dispose().catch(e => logError(`Bridge close failed, ${e}`));
617
648
  });
618
649
  }
619
650
  setListener(listener) {
@@ -635,22 +666,25 @@ class BridgeGateway {
635
666
  return response;
636
667
  });
637
668
  }
638
- errorsHandler(e) {
669
+ errorsHandler(eventSource, e) {
639
670
  return __awaiter(this, void 0, void 0, function* () {
640
671
  if (this.isConnecting) {
641
672
  logError('Bridge error', JSON.stringify(e));
642
673
  return;
643
674
  }
644
675
  if (this.isReady) {
645
- this.errorsListener(e);
676
+ try {
677
+ this.errorsListener(e);
678
+ }
679
+ catch (e) { }
646
680
  return;
647
681
  }
648
682
  if (this.isClosed) {
649
- logDebug('Bridge reconnecting, 200ms delay');
650
- yield delay(200);
651
- yield this.eventSource.recreate();
652
- return;
683
+ eventSource.close();
684
+ logDebug(`Bridge reconnecting, ${this.defaultReconnectDelay}ms delay`);
685
+ return yield this.eventSource.recreate(this.defaultReconnectDelay);
653
686
  }
687
+ throw new TonConnectError('Bridge error, unknown state');
654
688
  });
655
689
  }
656
690
  messagesHandler(e) {
@@ -673,9 +707,13 @@ class BridgeGateway {
673
707
  });
674
708
  }
675
709
  }
676
- function createEventSource(config, options) {
710
+ /**
711
+ * Creates an event source.
712
+ * @param {CreateEventSourceConfig} config - Configuration for creating an event source.
713
+ */
714
+ function createEventSource(config) {
677
715
  return __awaiter(this, void 0, void 0, function* () {
678
- return yield defer((resolve, reject, deferOptions) => __awaiter(this, void 0, void 0, function* () {
716
+ return yield timeout((resolve, reject, deferOptions) => __awaiter(this, void 0, void 0, function* () {
679
717
  var _a;
680
718
  const abortController = createAbortController(deferOptions.signal);
681
719
  const signal = abortController.signal;
@@ -694,15 +732,25 @@ function createEventSource(config, options) {
694
732
  return;
695
733
  }
696
734
  const eventSource = new EventSource(url.toString());
697
- eventSource.onerror = (reason) => {
735
+ eventSource.onerror = (reason) => __awaiter(this, void 0, void 0, function* () {
698
736
  if (signal.aborted) {
737
+ eventSource.close();
699
738
  reject(new TonConnectError('Bridge connection aborted'));
700
739
  return;
701
740
  }
702
- config.errorHandler(reason);
703
- };
741
+ try {
742
+ const newInstance = yield config.errorHandler(eventSource, reason);
743
+ if (newInstance && newInstance !== eventSource) {
744
+ resolve(newInstance);
745
+ }
746
+ }
747
+ catch (e) {
748
+ reject(e);
749
+ }
750
+ });
704
751
  eventSource.onopen = () => {
705
752
  if (signal.aborted) {
753
+ eventSource.close();
706
754
  reject(new TonConnectError('Bridge connection aborted'));
707
755
  return;
708
756
  }
@@ -711,12 +759,11 @@ function createEventSource(config, options) {
711
759
  eventSource.onmessage = (event) => {
712
760
  config.messageHandler(event);
713
761
  };
714
- (_a = config === null || config === void 0 ? void 0 : config.signal) === null || _a === void 0 ? void 0 : _a.addEventListener('abort', () => {
715
- logError('Bridge connection aborted');
762
+ (_a = config.signal) === null || _a === void 0 ? void 0 : _a.addEventListener('abort', () => {
716
763
  eventSource.close();
717
764
  reject(new TonConnectError('Bridge connection aborted'));
718
765
  });
719
- }), { timeout: options === null || options === void 0 ? void 0 : options.openingDeadlineMS, signal: config === null || config === void 0 ? void 0 : config.signal });
766
+ }), { timeout: config.openingDeadlineMS, signal: config.signal });
720
767
  });
721
768
  }
722
769
 
@@ -908,6 +955,10 @@ class BridgeProvider {
908
955
  });
909
956
  }
910
957
  connect(message, options) {
958
+ var _a;
959
+ const abortController = createAbortController(options === null || options === void 0 ? void 0 : options.signal);
960
+ (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort();
961
+ this.abortController = abortController;
911
962
  this.closeGateways();
912
963
  const sessionCrypto = new protocol.SessionCrypto();
913
964
  this.session = {
@@ -923,13 +974,16 @@ class BridgeProvider {
923
974
  sessionCrypto
924
975
  })
925
976
  .then(() => __awaiter(this, void 0, void 0, function* () {
977
+ if (abortController.signal.aborted) {
978
+ return;
979
+ }
926
980
  yield callForSuccess(_options => this.openGateways(sessionCrypto, {
927
981
  openingDeadlineMS: options === null || options === void 0 ? void 0 : options.openingDeadlineMS,
928
982
  signal: _options === null || _options === void 0 ? void 0 : _options.signal
929
983
  }), {
930
984
  attempts: Number.MAX_SAFE_INTEGER,
931
985
  delayMs: 5000,
932
- signal: options === null || options === void 0 ? void 0 : options.signal
986
+ signal: abortController.signal
933
987
  });
934
988
  }));
935
989
  const universalLink = 'universalLink' in this.walletConnectionSource &&
@@ -1008,6 +1062,7 @@ class BridgeProvider {
1008
1062
  else {
1009
1063
  options.onRequestSent = optionsOrOnRequestSent === null || optionsOrOnRequestSent === void 0 ? void 0 : optionsOrOnRequestSent.onRequestSent;
1010
1064
  options.signal = optionsOrOnRequestSent === null || optionsOrOnRequestSent === void 0 ? void 0 : optionsOrOnRequestSent.signal;
1065
+ options.attempts = optionsOrOnRequestSent === null || optionsOrOnRequestSent === void 0 ? void 0 : optionsOrOnRequestSent.attempts;
1011
1066
  }
1012
1067
  return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
1013
1068
  var _a;
@@ -1019,7 +1074,7 @@ class BridgeProvider {
1019
1074
  logDebug('Send http-bridge request:', Object.assign(Object.assign({}, request), { id }));
1020
1075
  const encodedRequest = this.session.sessionCrypto.encrypt(JSON.stringify(Object.assign(Object.assign({}, request), { id })), protocol.hexToByteArray(this.session.walletPublicKey));
1021
1076
  try {
1022
- yield this.gateway.send(encodedRequest, this.session.walletPublicKey, request.method, { signal: options === null || options === void 0 ? void 0 : options.signal });
1077
+ 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 });
1023
1078
  (_a = options === null || options === void 0 ? void 0 : options.onRequestSent) === null || _a === void 0 ? void 0 : _a.call(options);
1024
1079
  this.pendingRequests.set(id.toString(), resolve);
1025
1080
  }
@@ -1038,15 +1093,23 @@ class BridgeProvider {
1038
1093
  return __awaiter(this, void 0, void 0, function* () {
1039
1094
  return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
1040
1095
  let called = false;
1096
+ let timeoutId = null;
1041
1097
  const onRequestSent = () => {
1042
- called = true;
1043
- this.removeBridgeAndSession().then(resolve);
1098
+ if (!called) {
1099
+ called = true;
1100
+ this.removeBridgeAndSession().then(resolve);
1101
+ }
1044
1102
  };
1045
1103
  try {
1046
1104
  this.closeGateways();
1105
+ const abortController = createAbortController(options === null || options === void 0 ? void 0 : options.signal);
1106
+ timeoutId = setTimeout(() => {
1107
+ abortController.abort();
1108
+ }, this.defaultOpeningDeadlineMS);
1047
1109
  yield this.sendRequest({ method: 'disconnect', params: [] }, {
1048
1110
  onRequestSent: onRequestSent,
1049
- signal: options === null || options === void 0 ? void 0 : options.signal
1111
+ signal: abortController.signal,
1112
+ attempts: 1,
1050
1113
  });
1051
1114
  }
1052
1115
  catch (e) {
@@ -1055,6 +1118,12 @@ class BridgeProvider {
1055
1118
  this.removeBridgeAndSession().then(resolve);
1056
1119
  }
1057
1120
  }
1121
+ finally {
1122
+ if (timeoutId) {
1123
+ clearTimeout(timeoutId);
1124
+ }
1125
+ onRequestSent();
1126
+ }
1058
1127
  }));
1059
1128
  });
1060
1129
  }
@@ -1189,11 +1258,7 @@ class BridgeProvider {
1189
1258
  return url.toString();
1190
1259
  }
1191
1260
  openGateways(sessionCrypto, options) {
1192
- var _a;
1193
1261
  return __awaiter(this, void 0, void 0, function* () {
1194
- const abortController = createAbortController(options === null || options === void 0 ? void 0 : options.signal);
1195
- (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort();
1196
- this.abortController = abortController;
1197
1262
  if (Array.isArray(this.walletConnectionSource)) {
1198
1263
  // close all gateways before opening new ones
1199
1264
  this.pendingGateways.map(bridge => bridge.close().catch(e => console.error(e)));
@@ -1206,6 +1271,9 @@ class BridgeProvider {
1206
1271
  return gateway;
1207
1272
  });
1208
1273
  yield Promise.allSettled(this.pendingGateways.map(bridge => callForSuccess((_options) => {
1274
+ if (!this.pendingGateways.some(item => item === bridge)) {
1275
+ return bridge.close();
1276
+ }
1209
1277
  return bridge.registerSession({
1210
1278
  openingDeadlineMS: options === null || options === void 0 ? void 0 : options.openingDeadlineMS,
1211
1279
  signal: _options.signal
@@ -1213,7 +1281,7 @@ class BridgeProvider {
1213
1281
  }, {
1214
1282
  attempts: Number.MAX_SAFE_INTEGER,
1215
1283
  delayMs: 5000,
1216
- signal: abortController.signal
1284
+ signal: options === null || options === void 0 ? void 0 : options.signal
1217
1285
  })));
1218
1286
  return;
1219
1287
  }
@@ -1225,7 +1293,7 @@ class BridgeProvider {
1225
1293
  this.gateway = new BridgeGateway(this.storage, this.walletConnectionSource.bridgeUrl, sessionCrypto.sessionId, this.gatewayListener.bind(this), this.gatewayErrorsListener.bind(this));
1226
1294
  return yield this.gateway.registerSession({
1227
1295
  openingDeadlineMS: options === null || options === void 0 ? void 0 : options.openingDeadlineMS,
1228
- signal: abortController.signal
1296
+ signal: options === null || options === void 0 ? void 0 : options.signal
1229
1297
  });
1230
1298
  }
1231
1299
  });
@@ -2033,6 +2101,11 @@ class TonConnect {
2033
2101
  }
2034
2102
  (_b = this.provider) === null || _b === void 0 ? void 0 : _b.closeConnection();
2035
2103
  this.provider = this.createProvider(wallet);
2104
+ abortController.signal.addEventListener('abort', () => {
2105
+ var _a;
2106
+ (_a = this.provider) === null || _a === void 0 ? void 0 : _a.closeConnection();
2107
+ this.provider = null;
2108
+ });
2036
2109
  return this.provider.connect(this.createConnectRequest(options === null || options === void 0 ? void 0 : options.request), {
2037
2110
  openingDeadlineMS: options === null || options === void 0 ? void 0 : options.openingDeadlineMS,
2038
2111
  signal: abortController.signal
@@ -2093,6 +2166,10 @@ class TonConnect {
2093
2166
  (_b = this.provider) === null || _b === void 0 ? void 0 : _b.closeConnection();
2094
2167
  this.provider = provider;
2095
2168
  provider.listen(this.walletEventsListener.bind(this));
2169
+ abortController.signal.addEventListener('abort', () => {
2170
+ provider === null || provider === void 0 ? void 0 : provider.closeConnection();
2171
+ provider = null;
2172
+ });
2096
2173
  return yield callForSuccess((_options) => __awaiter(this, void 0, void 0, function* () {
2097
2174
  return provider === null || provider === void 0 ? void 0 : provider.restoreConnection({
2098
2175
  openingDeadlineMS: options === null || options === void 0 ? void 0 : options.openingDeadlineMS,
@@ -2139,21 +2216,22 @@ class TonConnect {
2139
2216
  * Disconnect form thw connected wallet and drop current session.
2140
2217
  */
2141
2218
  disconnect(options) {
2142
- var _a, _b;
2219
+ var _a;
2143
2220
  return __awaiter(this, void 0, void 0, function* () {
2144
2221
  if (!this.connected) {
2145
2222
  throw new WalletNotConnectedError();
2146
2223
  }
2147
2224
  const abortController = createAbortController(options === null || options === void 0 ? void 0 : options.signal);
2148
- (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort();
2225
+ const prevAbortController = this.abortController;
2149
2226
  this.abortController = abortController;
2150
2227
  if (abortController.signal.aborted) {
2151
2228
  throw new TonConnectError('Disconnect was aborted');
2152
2229
  }
2153
2230
  this.onWalletDisconnected();
2154
- yield ((_b = this.provider) === null || _b === void 0 ? void 0 : _b.disconnect({
2231
+ yield ((_a = this.provider) === null || _a === void 0 ? void 0 : _a.disconnect({
2155
2232
  signal: abortController.signal
2156
2233
  }));
2234
+ prevAbortController === null || prevAbortController === void 0 ? void 0 : prevAbortController.abort();
2157
2235
  });
2158
2236
  }
2159
2237
  /**
@@ -2188,12 +2266,12 @@ class TonConnect {
2188
2266
  this.pauseConnection();
2189
2267
  }
2190
2268
  else {
2191
- this.unPauseConnection();
2269
+ this.unPauseConnection().catch(e => logError('Cannot unpause connection', e));
2192
2270
  }
2193
2271
  });
2194
2272
  }
2195
2273
  catch (e) {
2196
- console.error('Cannot subscribe to the document.visibilitychange: ', e);
2274
+ logError('Cannot subscribe to the document.visibilitychange: ', e);
2197
2275
  }
2198
2276
  }
2199
2277
  createProvider(wallet) {