@solana-mobile/wallet-adapter-mobile 2.1.3 → 2.1.4

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.
@@ -1,6 +1,8 @@
1
- import { BaseSignInMessageSignerWalletAdapter, WalletReadyState, WalletPublicKeyError, WalletNotReadyError, WalletConnectionError, WalletDisconnectedError, WalletNotConnectedError, WalletSignTransactionError, WalletSendTransactionError, WalletSignMessageError } from '@solana/wallet-adapter-base';
1
+ import { BaseSignInMessageSignerWalletAdapter, WalletReadyState, WalletPublicKeyError, WalletNotReadyError, WalletConnectionError, WalletDisconnectedError, WalletNotConnectedError, WalletSignTransactionError, WalletSendTransactionError, WalletSignMessageError, isVersionedTransaction as isVersionedTransaction$1 } from '@solana/wallet-adapter-base';
2
2
  import { PublicKey } from '@solana/web3.js';
3
- import { transact } from '@solana-mobile/mobile-wallet-adapter-protocol-web3js';
3
+ import { transact, transactRemote } from '@solana-mobile/mobile-wallet-adapter-protocol-web3js';
4
+ import QRCode from 'qrcode';
5
+ import { toUint8Array as toUint8Array$1 } from 'js-base64';
4
6
 
5
7
  /******************************************************************************
6
8
  Copyright (c) Microsoft Corporation.
@@ -34,7 +36,7 @@ function toUint8Array(base64EncodedByteArray) {
34
36
  .map((c) => c.charCodeAt(0)));
35
37
  }
36
38
 
37
- function getIsSupported() {
39
+ function getIsSupported$1() {
38
40
  return (typeof window !== 'undefined' &&
39
41
  window.isSecureContext &&
40
42
  typeof document !== 'undefined' &&
@@ -42,14 +44,24 @@ function getIsSupported() {
42
44
  }
43
45
 
44
46
  const SolanaMobileWalletAdapterWalletName = 'Mobile Wallet Adapter';
45
- const SIGNATURE_LENGTH_IN_BYTES = 64;
46
- function getPublicKeyFromAddress(address) {
47
+ const SIGNATURE_LENGTH_IN_BYTES$1 = 64;
48
+ function getPublicKeyFromAddress$1(address) {
47
49
  const publicKeyByteArray = toUint8Array(address);
48
50
  return new PublicKey(publicKeyByteArray);
49
51
  }
50
52
  function isVersionedTransaction(transaction) {
51
53
  return 'version' in transaction;
52
54
  }
55
+ function clusterToChainId(cluster) {
56
+ switch (cluster) {
57
+ case 'mainnet-beta':
58
+ return 'solana:mainnet';
59
+ case 'testnet':
60
+ return 'solana:testnet';
61
+ case 'devnet':
62
+ return 'solana:devnet';
63
+ }
64
+ }
53
65
  class SolanaMobileWalletAdapter extends BaseSignInMessageSignerWalletAdapter {
54
66
  constructor(config) {
55
67
  var _a;
@@ -67,11 +79,12 @@ class SolanaMobileWalletAdapter extends BaseSignInMessageSignerWalletAdapter {
67
79
  * 'generation' don't continue to do work and throw exceptions.
68
80
  */
69
81
  this._connectionGeneration = 0;
70
- this._readyState = getIsSupported() ? WalletReadyState.Loadable : WalletReadyState.Unsupported;
82
+ this._readyState = getIsSupported$1() ? WalletReadyState.Loadable : WalletReadyState.Unsupported;
71
83
  this._authorizationResultCache = config.authorizationResultCache;
72
84
  this._addressSelector = config.addressSelector;
73
85
  this._appIdentity = config.appIdentity;
74
- this._chain = (_a = config.chain) !== null && _a !== void 0 ? _a : config.cluster;
86
+ this._chain = (_a = config.chain) !== null && _a !== void 0 ? _a : clusterToChainId(config.cluster);
87
+ this._hostAuthority = config.remoteHostAuthority;
75
88
  this._onWalletNotFound = config.onWalletNotFound;
76
89
  if (this._readyState !== WalletReadyState.Unsupported) {
77
90
  this._authorizationResultCache.get().then((authorizationResult) => {
@@ -87,7 +100,7 @@ class SolanaMobileWalletAdapter extends BaseSignInMessageSignerWalletAdapter {
87
100
  get publicKey() {
88
101
  if (this._publicKey == null && this._selectedAddress != null) {
89
102
  try {
90
- this._publicKey = getPublicKeyFromAddress(this._selectedAddress);
103
+ this._publicKey = getPublicKeyFromAddress$1(this._selectedAddress);
91
104
  }
92
105
  catch (e) {
93
106
  throw new WalletPublicKeyError((e instanceof Error && (e === null || e === void 0 ? void 0 : e.message)) || 'Unknown error', e);
@@ -262,9 +275,10 @@ class SolanaMobileWalletAdapter extends BaseSignInMessageSignerWalletAdapter {
262
275
  return __awaiter(this, void 0, void 0, function* () {
263
276
  const walletUriBase = (_a = this._authorizationResult) === null || _a === void 0 ? void 0 : _a.wallet_uri_base;
264
277
  const config = walletUriBase ? { baseUri: walletUriBase } : undefined;
278
+ const remoteConfig = this._hostAuthority ? { remoteHostAuthority: this._hostAuthority } : undefined;
265
279
  const currentConnectionGeneration = this._connectionGeneration;
266
280
  try {
267
- return yield transact(callback, config);
281
+ return yield transact(callback, Object.assign(Object.assign({}, config), remoteConfig));
268
282
  }
269
283
  catch (e) {
270
284
  if (this._connectionGeneration !== currentConnectionGeneration) {
@@ -420,7 +434,7 @@ class SolanaMobileWalletAdapter extends BaseSignInMessageSignerWalletAdapter {
420
434
  addresses: [selectedAddress],
421
435
  payloads: [message],
422
436
  });
423
- const signature = signedMessage.slice(-SIGNATURE_LENGTH_IN_BYTES);
437
+ const signature = signedMessage.slice(-SIGNATURE_LENGTH_IN_BYTES$1);
424
438
  return signature;
425
439
  }));
426
440
  }
@@ -464,6 +478,807 @@ class SolanaMobileWalletAdapter extends BaseSignInMessageSignerWalletAdapter {
464
478
  }
465
479
  }
466
480
 
481
+ const BluetoothHtml = `
482
+ <div class="mobile-wallet-adapter-embedded-modal-content">
483
+ <button id="mobile-wallet-adapter-embedded-modal-close" class="mobile-wallet-adapter-embedded-modal-close">
484
+ <svg width="14" height="14">
485
+ <path d="M14 12.461 8.3 6.772l5.234-5.233L12.006 0 6.772 5.234 1.54 0 0 1.539l5.234 5.233L0 12.006l1.539 1.528L6.772 8.3l5.69 5.7L14 12.461z" />
486
+ </svg>
487
+ </button>
488
+ <h1><b>Jupiter</b> wants to connect</h1>
489
+ <p class="mobile-wallet-adapter-embedded-modal-subtitle">Connect to your mobile wallet app through Bluetooth.</p>
490
+ <div class="mobile-wallet-adapter-embedded-modal-connection-status-container">
491
+ <div id="status-not-connected" class="connection-status">
492
+ <svg class="bluetooth-icon" width="24" height="24" viewBox="0 0 24 24">
493
+ <path fill="#a0a0a0" d="M14.24 12.01l2.32 2.32c.28-.72.44-1.51.44-2.33 0-.82-.16-1.59-.43-2.31l-2.33 2.32zm5.29-5.3l-1.26 1.26c.63 1.21.98 2.57.98 4.02s-.36 2.82-.98 4.02l1.2 1.2c.97-1.54 1.54-3.36 1.54-5.31-.01-1.89-.55-3.67-1.48-5.19zm-3.82 1L10 2H9v7.59L4.41 5 3 6.41 8.59 12 3 17.59 4.41 19 9 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM11 5.83l1.88 1.88L11 9.59V5.83zm1.88 10.46L11 18.17v-3.76l1.88 1.88z"/>
494
+ </svg>
495
+ <p>Not connected</p>
496
+ </div>
497
+ <div id="status-connecting" class="connection-status" style="display:none;">
498
+ <div class="spinner"></div>
499
+ <p>Connecting...</p>
500
+ </div>
501
+ <div id="status-connected" class="connection-status" style="display:none;">
502
+ <svg class="checkmark-icon" width="24" height="24" viewBox="0 0 24 24">
503
+ <path fill="#4CAF50" d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
504
+ </svg>
505
+ <p>Connected</p>
506
+ </div>
507
+ </div>
508
+ <div class="button-group">
509
+ <button id="cancel-btn" class="cancel-btn">Cancel</button>
510
+ <button id="connect-btn" class="connect-btn">Connect</button>
511
+ </div>
512
+ </div>
513
+ `;
514
+
515
+ const QRCodeHtml = `
516
+ <div class="mobile-wallet-adapter-embedded-modal-content">
517
+ <button id="mobile-wallet-adapter-embedded-modal-close" class="mobile-wallet-adapter-embedded-modal-close">
518
+ <svg width="14" height="14">
519
+ <path d="M14 12.461 8.3 6.772l5.234-5.233L12.006 0 6.772 5.234 1.54 0 0 1.539l5.234 5.233L0 12.006l1.539 1.528L6.772 8.3l5.69 5.7L14 12.461z" />
520
+ </svg>
521
+ </button>
522
+ <h1>Scan to connect</h1>
523
+ <p class="mobile-wallet-adapter-embedded-modal-subtitle">Use your wallet app to scan the QR Code and connect.</p>
524
+ <div id="mobile-wallet-adapter-embedded-modal-qr-code-container" />
525
+ </div>
526
+ `;
527
+
528
+ const css = `
529
+ .mobile-wallet-adapter-embedded-modal {
530
+ display: flex; /* Use flexbox to center content */
531
+ flex-direction: column;
532
+ justify-content: center; /* Center horizontally */
533
+ align-items: center; /* Center vertically */
534
+ position: fixed; /* Stay in place */
535
+ z-index: 1; /* Sit on top */
536
+ left: 0;
537
+ top: 0;
538
+ width: 100%; /* Full width */
539
+ height: 100%; /* Full height */
540
+ background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
541
+ }
542
+
543
+ .mobile-wallet-adapter-embedded-modal-content {
544
+ background: #10141f;
545
+ padding: 20px;
546
+ border-radius: 10px;
547
+ width: 80%;
548
+ max-width: 500px;
549
+ text-align: center;
550
+ position: relative;
551
+ display: flex;
552
+ flex-direction: column;
553
+ align-items: center; /* Center children horizontally */
554
+ }
555
+
556
+ .mobile-wallet-adapter-embedded-modal-subtitle {
557
+ color: #D8D8D8;
558
+ }
559
+
560
+ .mobile-wallet-adapter-embedded-modal-close {
561
+ display: flex;
562
+ align-items: center;
563
+ justify-content: center;
564
+ position: absolute;
565
+ top: 18px;
566
+ right: 18px;
567
+ padding: 12px;
568
+ cursor: pointer;
569
+ background: #1a1f2e;
570
+ border: none;
571
+ border-radius: 50%;
572
+ }
573
+
574
+ .mobile-wallet-adapter-embedded-modal-close:focus-visible {
575
+ outline-color: white;
576
+ }
577
+
578
+ .mobile-wallet-adapter-embedded-modal-close svg {
579
+ fill: #777;
580
+ transition: fill 200ms ease 0s;
581
+ }
582
+
583
+ .mobile-wallet-adapter-embedded-modal-close:hover svg {
584
+ fill: #fff;
585
+ }
586
+
587
+ .icon-container {
588
+ display: flex;
589
+ justify-content: center;
590
+ margin-bottom: 20px;
591
+ }
592
+
593
+ .icon {
594
+ width: 80px;
595
+ height: 80px;
596
+ border-radius: 50%;
597
+ background-color: #ddd; /* Placeholder for icon background */
598
+ }
599
+
600
+ /* Modal Title */
601
+ .mobile-wallet-adapter-embedded-modal-content h1 {
602
+ color: white;
603
+ font-size: 24px;
604
+ }
605
+
606
+ .button-group {
607
+ display: flex;
608
+ width: 100%;
609
+ gap: 10px;
610
+ }
611
+
612
+ .connect-btn, .cancel-btn {
613
+ flex: 1;
614
+ padding: 12px 20px;
615
+ font-size: 16px;
616
+ cursor: pointer;
617
+ border-radius: 10px;
618
+ transition: all 0.3s ease;
619
+ }
620
+
621
+ .connect-btn {
622
+ background-color: #007bff;
623
+ color: white;
624
+ border: none;
625
+ }
626
+
627
+ .connect-btn:hover {
628
+ background-color: #0056b3;
629
+ }
630
+
631
+ .cancel-btn {
632
+ background-color: transparent;
633
+ color: #a0a0a0;
634
+ border: 1px solid #a0a0a0;
635
+ }
636
+
637
+ .cancel-btn:hover {
638
+ background-color: rgba(160, 160, 160, 0.1);
639
+ }
640
+
641
+ /* BT Connection Status */
642
+
643
+ .mobile-wallet-adapter-embedded-modal-connection-status-container {
644
+ margin: 20px 0px 20px 0px;
645
+ }
646
+
647
+ .connection-status {
648
+ display: flex;
649
+ flex-direction: column;
650
+ align-items: center;
651
+ justify-content: center;
652
+ margin: 20px 0;
653
+ }
654
+
655
+ .connection-status p {
656
+ margin-top: 10px;
657
+ color: #a0a0a0;
658
+ }
659
+
660
+ .bluetooth-icon, .checkmark-icon {
661
+ width: 48px;
662
+ height: 48px;
663
+ }
664
+
665
+ .spinner {
666
+ border: 4px solid #f3f3f3;
667
+ border-top: 4px solid #3498db;
668
+ border-radius: 50%;
669
+ width: 40px;
670
+ height: 40px;
671
+ animation: spin 1s linear infinite;
672
+ }
673
+
674
+ @keyframes spin {
675
+ 0% { transform: rotate(0deg); }
676
+ 100% { transform: rotate(360deg); }
677
+ }
678
+
679
+ /* QR Code */
680
+
681
+ #mobile-wallet-adapter-embedded-modal-qr-code-container {
682
+ width: 500px;
683
+ height: 500px;
684
+ align-content: center;
685
+ }
686
+ `;
687
+
688
+ class EmbeddedModal {
689
+ constructor(title) {
690
+ this._root = null;
691
+ this._title = title;
692
+ // Bind methods to ensure `this` context is correct
693
+ this.init = this.init.bind(this);
694
+ this.injectQRCodeHTML = this.injectQRCodeHTML.bind(this);
695
+ this.injectBluetoothHTML = this.injectBluetoothHTML.bind(this);
696
+ this.open = this.open.bind(this);
697
+ this.close = this.close.bind(this);
698
+ this.connect = this.connect.bind(this);
699
+ this._root = document.getElementById('mobile-wallet-adapter-embedded-root-ui');
700
+ }
701
+ init(qrCode) {
702
+ return __awaiter(this, void 0, void 0, function* () {
703
+ console.log('Injecting modal');
704
+ this.injectStyles();
705
+ this.injectQRCodeHTML(qrCode);
706
+ });
707
+ }
708
+ setConnectionStatus(status) {
709
+ if (!this._root)
710
+ return;
711
+ const statuses = ['not-connected', 'connecting', 'connected'];
712
+ statuses.forEach((s) => {
713
+ const el = this._root.querySelector(`#status-${s}`);
714
+ if (el instanceof HTMLElement) {
715
+ el.style.display = s === status ? 'flex' : 'none';
716
+ }
717
+ });
718
+ }
719
+ injectStyles() {
720
+ // Check if the styles have already been injected
721
+ if (document.getElementById('mobile-wallet-adapter-styles')) {
722
+ return;
723
+ }
724
+ const styleElement = document.createElement('style');
725
+ styleElement.id = 'mobile-wallet-adapter-styles';
726
+ styleElement.textContent = css;
727
+ document.head.appendChild(styleElement);
728
+ }
729
+ populateQRCode(qrUrl) {
730
+ return __awaiter(this, void 0, void 0, function* () {
731
+ const qrcodeContainer = document.getElementById('mobile-wallet-adapter-embedded-modal-qr-code-container');
732
+ if (qrcodeContainer) {
733
+ const qrCodeElement = yield QRCode.toCanvas(qrUrl, { width: 400 });
734
+ if (qrcodeContainer.firstElementChild !== null) {
735
+ qrcodeContainer.replaceChild(qrCodeElement, qrcodeContainer.firstElementChild);
736
+ }
737
+ else
738
+ qrcodeContainer.appendChild(qrCodeElement);
739
+ }
740
+ else {
741
+ console.error('QRCode Container not found');
742
+ }
743
+ });
744
+ }
745
+ injectQRCodeHTML(qrCode) {
746
+ // Check if the HTML has already been injected
747
+ if (document.getElementById('mobile-wallet-adapter-embedded-root-ui')) {
748
+ if (!this._root)
749
+ this._root = document.getElementById('mobile-wallet-adapter-embedded-root-ui');
750
+ this.populateQRCode(qrCode);
751
+ return;
752
+ }
753
+ // Create a container for the modal
754
+ this._root = document.createElement('div');
755
+ this._root.id = 'mobile-wallet-adapter-embedded-root-ui';
756
+ this._root.className = 'mobile-wallet-adapter-embedded-modal';
757
+ this._root.innerHTML = QRCodeHtml;
758
+ this._root.style.display = 'none';
759
+ // Append the modal to the body
760
+ document.body.appendChild(this._root);
761
+ // Render the QRCode
762
+ this.populateQRCode(qrCode);
763
+ this.attachEventListeners();
764
+ }
765
+ injectBluetoothHTML() {
766
+ // Check if the HTML has already been injected
767
+ if (document.getElementById('mobile-wallet-adapter-embedded-root-ui')) {
768
+ return;
769
+ }
770
+ this._root = document.createElement('div');
771
+ this._root.id = 'mobile-wallet-adapter-embedded-root-ui';
772
+ this._root.className = 'mobile-wallet-adapter-embedded-modal';
773
+ this._root.innerHTML = BluetoothHtml;
774
+ document.body.appendChild(this._root);
775
+ this.attachEventListeners();
776
+ }
777
+ attachEventListeners() {
778
+ if (!this._root)
779
+ return;
780
+ const closeBtn = this._root.querySelector('#mobile-wallet-adapter-embedded-modal-close');
781
+ const cancelBtn = this._root.querySelector('#cancel-btn');
782
+ const connectBtn = this._root.querySelector('#connect-btn');
783
+ closeBtn === null || closeBtn === void 0 ? void 0 : closeBtn.addEventListener('click', () => this.close());
784
+ cancelBtn === null || cancelBtn === void 0 ? void 0 : cancelBtn.addEventListener('click', () => this.close());
785
+ connectBtn === null || connectBtn === void 0 ? void 0 : connectBtn.addEventListener('click', () => this.connect());
786
+ }
787
+ open() {
788
+ console.debug('Modal open');
789
+ if (this._root) {
790
+ this._root.style.display = 'flex';
791
+ this.setConnectionStatus('not-connected'); // Reset status when opening
792
+ }
793
+ }
794
+ close() {
795
+ console.debug('Modal close');
796
+ if (this._root) {
797
+ this._root.style.display = 'none';
798
+ this.setConnectionStatus('not-connected'); // Reset status when closing
799
+ }
800
+ }
801
+ connect() {
802
+ console.log('Connecting...');
803
+ // Mock connection
804
+ this.setConnectionStatus('connecting');
805
+ // Simulate connection process
806
+ setTimeout(() => {
807
+ this.setConnectionStatus('connected');
808
+ console.log('Connected!');
809
+ }, 5000); // 5 seconds delay
810
+ }
811
+ }
812
+
813
+ const SolanaMobileWalletAdapterRemoteWalletName = 'MWA (Remote)';
814
+ const SIGNATURE_LENGTH_IN_BYTES = 64;
815
+ function getPublicKeyFromAddress(address) {
816
+ const publicKeyByteArray = toUint8Array$1(address);
817
+ return new PublicKey(publicKeyByteArray);
818
+ }
819
+ /**
820
+ * Determine the mobile operating system.
821
+ * Returns true if running on a mobile operating system, or false otherwise.
822
+ *
823
+ * @returns {boolean}
824
+ */
825
+ function isMobileOperatingSystem() {
826
+ var userAgent = navigator.userAgent;
827
+ // Windows Phone must come first because its UA also contains "Android"
828
+ if (/windows phone/i.test(userAgent)) {
829
+ return true;
830
+ }
831
+ if (/android/i.test(userAgent)) {
832
+ return true;
833
+ }
834
+ // iOS detection from: http://stackoverflow.com/a/9039885/177710
835
+ if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
836
+ return true;
837
+ }
838
+ return false;
839
+ }
840
+ function getIsSupported() {
841
+ return (typeof window !== 'undefined' &&
842
+ window.isSecureContext &&
843
+ typeof document !== 'undefined' &&
844
+ !isMobileOperatingSystem());
845
+ }
846
+ /**
847
+ * This burner wallet adapter is unsafe to use and is only included to provide an easy way for applications to test
848
+ * Wallet Adapter without using a third-party wallet.
849
+ */
850
+ class SolanaMobileWalletAdapterRemote extends BaseSignInMessageSignerWalletAdapter {
851
+ constructor(config) {
852
+ super();
853
+ this.supportedTransactionVersions = new Set(
854
+ // FIXME(#244): We can't actually know what versions are supported until we know which wallet we're talking to.
855
+ ['legacy', 0]);
856
+ this.name = SolanaMobileWalletAdapterRemoteWalletName;
857
+ this.url = 'https://solanamobile.com/wallets';
858
+ this.icon = 'data:image/svg+xml;base64,PHN2ZyBmaWxsPSJub25lIiBoZWlnaHQ9IjI4IiB3aWR0aD0iMjgiIHZpZXdCb3g9Ii0zIDAgMjggMjgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgZmlsbD0iI0RDQjhGRiI+PHBhdGggZD0iTTE3LjQgMTcuNEgxNXYyLjRoMi40di0yLjRabTEuMi05LjZoLTIuNHYyLjRoMi40VjcuOFoiLz48cGF0aCBkPSJNMjEuNiAzVjBoLTIuNHYzaC0zLjZWMGgtMi40djNoLTIuNHY2LjZINC41YTIuMSAyLjEgMCAxIDEgMC00LjJoMi43VjNINC41QTQuNSA0LjUgMCAwIDAgMCA3LjVWMjRoMjEuNnYtNi42aC0yLjR2NC4ySDIuNFYxMS41Yy41LjMgMS4yLjQgMS44LjVoNy41QTYuNiA2LjYgMCAwIDAgMjQgOVYzaC0yLjRabTAgNS43YTQuMiA0LjIgMCAxIDEtOC40IDBWNS40aDguNHYzLjNaIi8+PC9nPjwvc3ZnPg==';
859
+ this._connecting = false;
860
+ /**
861
+ * Every time the connection is recycled in some way (eg. `disconnect()` is called)
862
+ * increment this and use it to make sure that `transact` calls from the previous
863
+ * 'generation' don't continue to do work and throw exceptions.
864
+ */
865
+ this._connectionGeneration = 0;
866
+ this._readyState = getIsSupported() ? WalletReadyState.Loadable : WalletReadyState.Unsupported;
867
+ this._authorizationResultCache = config.authorizationResultCache;
868
+ this._addressSelector = config.addressSelector;
869
+ this._appIdentity = config.appIdentity;
870
+ this._chain = config.chain;
871
+ this._hostAuthority = config.remoteHostAuthority;
872
+ this._onWalletNotFound = config.onWalletNotFound;
873
+ if (this._readyState !== WalletReadyState.Unsupported) {
874
+ this._authorizationResultCache.get().then((authorizationResult) => {
875
+ if (authorizationResult) {
876
+ // Having a prior authorization result is, right now, the best
877
+ // indication that a mobile wallet is installed. There is no API
878
+ // we can use to test for whether the association URI is supported.
879
+ this.declareWalletAsInstalled();
880
+ }
881
+ });
882
+ }
883
+ }
884
+ get publicKey() {
885
+ if (this._publicKey == null && this._selectedAddress != null) {
886
+ try {
887
+ this._publicKey = getPublicKeyFromAddress(this._selectedAddress);
888
+ }
889
+ catch (e) {
890
+ throw new WalletPublicKeyError((e instanceof Error && (e === null || e === void 0 ? void 0 : e.message)) || 'Unknown error', e);
891
+ }
892
+ }
893
+ return this._publicKey ? this._publicKey : null;
894
+ }
895
+ get connected() {
896
+ return !!this._authorizationResult;
897
+ }
898
+ get connecting() {
899
+ return this._connecting;
900
+ }
901
+ get readyState() {
902
+ return this._readyState;
903
+ }
904
+ declareWalletAsInstalled() {
905
+ if (this._readyState !== WalletReadyState.Installed) {
906
+ this.emit('readyStateChange', (this._readyState = WalletReadyState.Installed));
907
+ }
908
+ }
909
+ runWithGuard(callback) {
910
+ return __awaiter(this, void 0, void 0, function* () {
911
+ try {
912
+ return yield callback();
913
+ }
914
+ catch (e) {
915
+ this.emit('error', e);
916
+ throw e;
917
+ }
918
+ });
919
+ }
920
+ autoConnect() {
921
+ return __awaiter(this, void 0, void 0, function* () {
922
+ if (this.connecting || this.connected) {
923
+ return;
924
+ }
925
+ return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {
926
+ if (this._readyState !== WalletReadyState.Installed && this._readyState !== WalletReadyState.Loadable) {
927
+ throw new WalletNotReadyError();
928
+ }
929
+ this._connecting = true;
930
+ try {
931
+ const cachedAuthorizationResult = yield this._authorizationResultCache.get();
932
+ if (cachedAuthorizationResult) {
933
+ // TODO: Evaluate whether there's any threat to not `awaiting` this expression
934
+ this.handleAuthorizationResult(cachedAuthorizationResult);
935
+ }
936
+ }
937
+ catch (e) {
938
+ throw new WalletConnectionError((e instanceof Error && e.message) || 'Unknown error', e);
939
+ }
940
+ finally {
941
+ this._connecting = false;
942
+ }
943
+ }));
944
+ });
945
+ }
946
+ connect() {
947
+ return __awaiter(this, void 0, void 0, function* () {
948
+ if (this.connecting || this.connected) {
949
+ return;
950
+ }
951
+ return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {
952
+ if (this._readyState !== WalletReadyState.Installed && this._readyState !== WalletReadyState.Loadable) {
953
+ throw new WalletNotReadyError();
954
+ }
955
+ this._connecting = true;
956
+ try {
957
+ yield this.performAuthorization();
958
+ }
959
+ catch (e) {
960
+ throw new WalletConnectionError((e instanceof Error && e.message) || 'Unknown error', e);
961
+ }
962
+ finally {
963
+ this._connecting = false;
964
+ }
965
+ }));
966
+ });
967
+ }
968
+ performAuthorization(signInPayload) {
969
+ return __awaiter(this, void 0, void 0, function* () {
970
+ try {
971
+ const cachedAuthorizationResult = yield this._authorizationResultCache.get();
972
+ if (cachedAuthorizationResult) {
973
+ // TODO: Evaluate whether there's any threat to not `awaiting` this expression
974
+ this.handleAuthorizationResult(cachedAuthorizationResult);
975
+ return cachedAuthorizationResult;
976
+ }
977
+ if (this._wallet)
978
+ delete this._wallet;
979
+ return yield this.transact((wallet) => __awaiter(this, void 0, void 0, function* () {
980
+ this._wallet = wallet;
981
+ const authorizationResult = yield wallet.authorize({
982
+ chain: this._chain,
983
+ identity: this._appIdentity,
984
+ sign_in_payload: signInPayload,
985
+ });
986
+ // TODO: Evaluate whether there's any threat to not `awaiting` this expression
987
+ Promise.all([
988
+ this._authorizationResultCache.set(authorizationResult),
989
+ this.handleAuthorizationResult(authorizationResult),
990
+ ]);
991
+ return authorizationResult;
992
+ }));
993
+ }
994
+ catch (e) {
995
+ throw new WalletConnectionError((e instanceof Error && e.message) || 'Unknown error', e);
996
+ }
997
+ });
998
+ }
999
+ handleAuthorizationResult(authorizationResult) {
1000
+ var _a;
1001
+ return __awaiter(this, void 0, void 0, function* () {
1002
+ const didPublicKeysChange =
1003
+ // Case 1: We started from having no authorization.
1004
+ this._authorizationResult == null ||
1005
+ // Case 2: The number of authorized accounts changed.
1006
+ ((_a = this._authorizationResult) === null || _a === void 0 ? void 0 : _a.accounts.length) !== authorizationResult.accounts.length ||
1007
+ // Case 3: The new list of addresses isn't exactly the same as the old list, in the same order.
1008
+ this._authorizationResult.accounts.some((account, ii) => account.address !== authorizationResult.accounts[ii].address);
1009
+ this._authorizationResult = authorizationResult;
1010
+ this.declareWalletAsInstalled();
1011
+ if (didPublicKeysChange) {
1012
+ const nextSelectedAddress = yield this._addressSelector.select(authorizationResult.accounts.map(({ address }) => address));
1013
+ if (nextSelectedAddress !== this._selectedAddress) {
1014
+ this._selectedAddress = nextSelectedAddress;
1015
+ delete this._publicKey;
1016
+ this.emit('connect',
1017
+ // Having just set `this._selectedAddress`, `this.publicKey` is definitely non-null
1018
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1019
+ this.publicKey);
1020
+ }
1021
+ }
1022
+ });
1023
+ }
1024
+ performReauthorization(wallet, authToken) {
1025
+ return __awaiter(this, void 0, void 0, function* () {
1026
+ try {
1027
+ const authorizationResult = yield wallet.authorize({
1028
+ auth_token: authToken,
1029
+ identity: this._appIdentity,
1030
+ });
1031
+ // TODO: Evaluate whether there's any threat to not `awaiting` this expression
1032
+ Promise.all([
1033
+ this._authorizationResultCache.set(authorizationResult),
1034
+ this.handleAuthorizationResult(authorizationResult),
1035
+ ]);
1036
+ }
1037
+ catch (e) {
1038
+ this.disconnect();
1039
+ throw new WalletDisconnectedError((e instanceof Error && (e === null || e === void 0 ? void 0 : e.message)) || 'Unknown error', e);
1040
+ }
1041
+ });
1042
+ }
1043
+ disconnect() {
1044
+ var _a;
1045
+ return __awaiter(this, void 0, void 0, function* () {
1046
+ // TODO: figure out why this call throws "TypeError: _a.terminateSession is not a function"
1047
+ // even though the session termination is actually executed (websocket closes).
1048
+ try {
1049
+ (_a = this._wallet) === null || _a === void 0 ? void 0 : _a.terminateSession();
1050
+ }
1051
+ catch (e) { }
1052
+ this._authorizationResultCache.clear(); // TODO: Evaluate whether there's any threat to not `awaiting` this expression
1053
+ this._connecting = false;
1054
+ this._connectionGeneration++;
1055
+ delete this._authorizationResult;
1056
+ delete this._publicKey;
1057
+ delete this._selectedAddress;
1058
+ delete this._wallet;
1059
+ this.emit('disconnect');
1060
+ });
1061
+ }
1062
+ transact(callback) {
1063
+ var _a;
1064
+ return __awaiter(this, void 0, void 0, function* () {
1065
+ const walletUriBase = (_a = this._authorizationResult) === null || _a === void 0 ? void 0 : _a.wallet_uri_base;
1066
+ const baseConfig = walletUriBase ? { baseUri: walletUriBase } : undefined;
1067
+ const remoteConfig = Object.assign(Object.assign({}, baseConfig), { remoteHostAuthority: this._hostAuthority });
1068
+ const currentConnectionGeneration = this._connectionGeneration;
1069
+ const modal = new EmbeddedModal('MWA QR');
1070
+ if (this._wallet) {
1071
+ return callback(this._wallet);
1072
+ }
1073
+ try {
1074
+ const { associationUrl, result: promise } = yield transactRemote((wallet) => __awaiter(this, void 0, void 0, function* () {
1075
+ const result = yield callback(wallet);
1076
+ modal.close();
1077
+ return result;
1078
+ }), remoteConfig);
1079
+ modal.init(associationUrl.toString());
1080
+ modal.open();
1081
+ return yield promise;
1082
+ }
1083
+ catch (e) {
1084
+ modal.close();
1085
+ if (this._connectionGeneration !== currentConnectionGeneration) {
1086
+ yield new Promise(() => { }); // Never resolve.
1087
+ }
1088
+ if (e instanceof Error &&
1089
+ e.name === 'SolanaMobileWalletAdapterError' &&
1090
+ e.code === 'ERROR_WALLET_NOT_FOUND') {
1091
+ yield this._onWalletNotFound(this);
1092
+ }
1093
+ throw e;
1094
+ }
1095
+ });
1096
+ }
1097
+ assertIsAuthorized() {
1098
+ if (!this._authorizationResult || !this._selectedAddress)
1099
+ throw new WalletNotConnectedError();
1100
+ return {
1101
+ authToken: this._authorizationResult.auth_token,
1102
+ selectedAddress: this._selectedAddress,
1103
+ };
1104
+ }
1105
+ performSignTransactions(transactions) {
1106
+ return __awaiter(this, void 0, void 0, function* () {
1107
+ const { authToken } = this.assertIsAuthorized();
1108
+ try {
1109
+ return yield this.transact((wallet) => __awaiter(this, void 0, void 0, function* () {
1110
+ yield this.performReauthorization(wallet, authToken);
1111
+ const signedTransactions = yield wallet.signTransactions({
1112
+ transactions,
1113
+ });
1114
+ return signedTransactions;
1115
+ }));
1116
+ }
1117
+ catch (error) {
1118
+ throw new WalletSignTransactionError(error === null || error === void 0 ? void 0 : error.message, error);
1119
+ }
1120
+ });
1121
+ }
1122
+ sendTransaction(transaction, connection, options) {
1123
+ return __awaiter(this, void 0, void 0, function* () {
1124
+ return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {
1125
+ const { authToken } = this.assertIsAuthorized();
1126
+ const minContextSlot = options === null || options === void 0 ? void 0 : options.minContextSlot;
1127
+ try {
1128
+ return yield this.transact((wallet) => __awaiter(this, void 0, void 0, function* () {
1129
+ function getTargetCommitment() {
1130
+ let targetCommitment;
1131
+ switch (connection.commitment) {
1132
+ case 'confirmed':
1133
+ case 'finalized':
1134
+ case 'processed':
1135
+ targetCommitment = connection.commitment;
1136
+ break;
1137
+ default:
1138
+ targetCommitment = 'finalized';
1139
+ }
1140
+ let targetPreflightCommitment;
1141
+ switch (options === null || options === void 0 ? void 0 : options.preflightCommitment) {
1142
+ case 'confirmed':
1143
+ case 'finalized':
1144
+ case 'processed':
1145
+ targetPreflightCommitment = options.preflightCommitment;
1146
+ break;
1147
+ case undefined:
1148
+ targetPreflightCommitment = targetCommitment;
1149
+ break;
1150
+ default:
1151
+ targetPreflightCommitment = 'finalized';
1152
+ }
1153
+ const preflightCommitmentScore = targetPreflightCommitment === 'finalized'
1154
+ ? 2
1155
+ : targetPreflightCommitment === 'confirmed'
1156
+ ? 1
1157
+ : 0;
1158
+ const targetCommitmentScore = targetCommitment === 'finalized' ? 2 : targetCommitment === 'confirmed' ? 1 : 0;
1159
+ return preflightCommitmentScore < targetCommitmentScore
1160
+ ? targetPreflightCommitment
1161
+ : targetCommitment;
1162
+ }
1163
+ const [capabilities, _1, _2] = yield Promise.all([
1164
+ wallet.getCapabilities(),
1165
+ this.performReauthorization(wallet, authToken),
1166
+ isVersionedTransaction$1(transaction)
1167
+ ? null
1168
+ : /**
1169
+ * Unlike versioned transactions, legacy `Transaction` objects
1170
+ * may not have an associated `feePayer` or `recentBlockhash`.
1171
+ * This code exists to patch them up in case they are missing.
1172
+ */
1173
+ (() => __awaiter(this, void 0, void 0, function* () {
1174
+ var _a;
1175
+ transaction.feePayer || (transaction.feePayer = (_a = this.publicKey) !== null && _a !== void 0 ? _a : undefined);
1176
+ if (transaction.recentBlockhash == null) {
1177
+ const { blockhash } = yield connection.getLatestBlockhash({
1178
+ commitment: getTargetCommitment(),
1179
+ });
1180
+ transaction.recentBlockhash = blockhash;
1181
+ }
1182
+ }))(),
1183
+ ]);
1184
+ if (capabilities.supports_sign_and_send_transactions) {
1185
+ const signatures = yield wallet.signAndSendTransactions({
1186
+ minContextSlot,
1187
+ transactions: [transaction],
1188
+ });
1189
+ return signatures[0];
1190
+ }
1191
+ else {
1192
+ const [signedTransaction] = yield wallet.signTransactions({
1193
+ transactions: [transaction],
1194
+ });
1195
+ if (isVersionedTransaction$1(signedTransaction)) {
1196
+ return yield connection.sendTransaction(signedTransaction);
1197
+ }
1198
+ else {
1199
+ const serializedTransaction = signedTransaction.serialize();
1200
+ return yield connection.sendRawTransaction(serializedTransaction, Object.assign(Object.assign({}, options), { preflightCommitment: getTargetCommitment() }));
1201
+ }
1202
+ }
1203
+ }));
1204
+ }
1205
+ catch (error) {
1206
+ throw new WalletSendTransactionError(error === null || error === void 0 ? void 0 : error.message, error);
1207
+ }
1208
+ }));
1209
+ });
1210
+ }
1211
+ signTransaction(transaction) {
1212
+ return __awaiter(this, void 0, void 0, function* () {
1213
+ return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {
1214
+ const [signedTransaction] = yield this.performSignTransactions([transaction]);
1215
+ return signedTransaction;
1216
+ }));
1217
+ });
1218
+ }
1219
+ signAllTransactions(transactions) {
1220
+ return __awaiter(this, void 0, void 0, function* () {
1221
+ return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {
1222
+ const signedTransactions = yield this.performSignTransactions(transactions);
1223
+ return signedTransactions;
1224
+ }));
1225
+ });
1226
+ }
1227
+ signMessage(message) {
1228
+ return __awaiter(this, void 0, void 0, function* () {
1229
+ return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {
1230
+ const { authToken, selectedAddress } = this.assertIsAuthorized();
1231
+ try {
1232
+ return yield this.transact((wallet) => __awaiter(this, void 0, void 0, function* () {
1233
+ yield this.performReauthorization(wallet, authToken);
1234
+ const [signedMessage] = yield wallet.signMessages({
1235
+ addresses: [selectedAddress],
1236
+ payloads: [message],
1237
+ });
1238
+ const signature = signedMessage.slice(-SIGNATURE_LENGTH_IN_BYTES);
1239
+ return signature;
1240
+ }));
1241
+ }
1242
+ catch (error) {
1243
+ throw new WalletSignMessageError(error === null || error === void 0 ? void 0 : error.message, error);
1244
+ }
1245
+ }));
1246
+ });
1247
+ }
1248
+ signIn(input) {
1249
+ return __awaiter(this, void 0, void 0, function* () {
1250
+ return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {
1251
+ var _a, _b;
1252
+ if (this._readyState !== WalletReadyState.Installed && this._readyState !== WalletReadyState.Loadable) {
1253
+ throw new WalletNotReadyError();
1254
+ }
1255
+ this._connecting = true;
1256
+ try {
1257
+ const authorizationResult = yield this.performAuthorization(Object.assign(Object.assign({}, input), { domain: (_a = input === null || input === void 0 ? void 0 : input.domain) !== null && _a !== void 0 ? _a : window.location.host }));
1258
+ if (!authorizationResult.sign_in_result) {
1259
+ throw new Error("Sign in failed, no sign in result returned by wallet");
1260
+ }
1261
+ const signedInAddress = authorizationResult.sign_in_result.address;
1262
+ const signedInAccount = Object.assign(Object.assign({}, (_b = authorizationResult.accounts.find(acc => acc.address == signedInAddress)) !== null && _b !== void 0 ? _b : {
1263
+ address: signedInAddress
1264
+ }), { publicKey: toUint8Array$1(signedInAddress) });
1265
+ return {
1266
+ account: signedInAccount,
1267
+ signedMessage: toUint8Array$1(authorizationResult.sign_in_result.signed_message),
1268
+ signature: toUint8Array$1(authorizationResult.sign_in_result.signature)
1269
+ };
1270
+ }
1271
+ catch (e) {
1272
+ throw new WalletConnectionError((e instanceof Error && e.message) || 'Unknown error', e);
1273
+ }
1274
+ finally {
1275
+ this._connecting = false;
1276
+ }
1277
+ }));
1278
+ });
1279
+ }
1280
+ }
1281
+
467
1282
  function createDefaultAddressSelector() {
468
1283
  return {
469
1284
  select(addresses) {
@@ -533,4 +1348,4 @@ function createDefaultWalletNotFoundHandler() {
533
1348
  return defaultWalletNotFoundHandler;
534
1349
  }
535
1350
 
536
- export { SolanaMobileWalletAdapter, SolanaMobileWalletAdapterWalletName, createDefaultAddressSelector, createDefaultAuthorizationResultCache, createDefaultWalletNotFoundHandler };
1351
+ export { SolanaMobileWalletAdapter, SolanaMobileWalletAdapterRemote, SolanaMobileWalletAdapterRemoteWalletName, SolanaMobileWalletAdapterWalletName, createDefaultAddressSelector, createDefaultAuthorizationResultCache, createDefaultWalletNotFoundHandler };