@solana-mobile/wallet-standard-mobile 0.5.0 → 0.5.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.
@@ -1,15 +1,39 @@
1
- 'use strict';
2
-
3
- var walletStandardFeatures = require('@solana/wallet-standard-features');
4
- var QRCode = require('qrcode');
5
- var mobileWalletAdapterProtocol = require('@solana-mobile/mobile-wallet-adapter-protocol');
6
- var features = require('@wallet-standard/features');
7
- var jsBase64 = require('js-base64');
8
- var base58 = require('bs58');
9
- var wallet = require('@wallet-standard/wallet');
10
- var AsyncStorage = require('@react-native-async-storage/async-storage');
11
- var walletStandardChains = require('@solana/wallet-standard-chains');
12
-
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ let _solana_wallet_standard_features = require("@solana/wallet-standard-features");
25
+ let _solana_mobile_mobile_wallet_adapter_protocol = require("@solana-mobile/mobile-wallet-adapter-protocol");
26
+ let _wallet_standard_features = require("@wallet-standard/features");
27
+ let bs58 = require("bs58");
28
+ bs58 = __toESM(bs58);
29
+ let js_base64 = require("js-base64");
30
+ let qrcode = require("qrcode");
31
+ qrcode = __toESM(qrcode);
32
+ let _wallet_standard_wallet = require("@wallet-standard/wallet");
33
+ let _react_native_async_storage_async_storage = require("@react-native-async-storage/async-storage");
34
+ _react_native_async_storage_async_storage = __toESM(_react_native_async_storage_async_storage);
35
+ let _solana_wallet_standard_chains = require("@solana/wallet-standard-chains");
36
+ //#region src/embedded-modal/loadingSpinner.ts
13
37
  const modalHtml$1 = `
14
38
  <div class="mobile-wallet-adapter-embedded-loading-indicator" role="dialog" aria-modal="true" aria-labelledby="modal-title">
15
39
  <div data-modal-close style="position: absolute; width: 100%; height: 100%;"></div>
@@ -90,92 +114,76 @@ const css$6 = `
90
114
  }
91
115
  }
92
116
  `;
93
- class EmbeddedLoadingSpinner {
94
- #root = null;
95
- #eventListeners = {};
96
- #listenersAttached = false;
97
- dom = null;
98
- constructor() {
99
- // Bind methods to ensure `this` context is correct
100
- this.init = this.init.bind(this);
101
- this.#root = document.getElementById('mobile-wallet-adapter-embedded-root-ui');
102
- }
103
- async init() {
104
- console.log('Injecting modal');
105
- this.#injectHTML();
106
- }
107
- open = () => {
108
- console.debug('Modal open');
109
- this.#attachEventListeners();
110
- if (this.#root) {
111
- this.#root.style.display = 'flex';
112
- }
113
- };
114
- close = (event = undefined) => {
115
- console.debug('Modal close');
116
- this.#removeEventListeners();
117
- if (this.#root) {
118
- this.#root.style.display = 'none';
119
- }
120
- this.#eventListeners['close']?.forEach((listener) => listener(event));
121
- };
122
- addEventListener(event, listener) {
123
- this.#eventListeners[event]?.push(listener) || (this.#eventListeners[event] = [listener]);
124
- return () => this.removeEventListener(event, listener);
125
- }
126
- removeEventListener(event, listener) {
127
- this.#eventListeners[event] = this.#eventListeners[event]?.filter((existingListener) => listener !== existingListener);
128
- }
129
- #injectHTML() {
130
- // Check if already injected by checking if shadow DOM exists
131
- if (this.dom) {
132
- return;
133
- }
134
- // Create a container for the modal
135
- this.#root = document.createElement('div');
136
- this.#root.id = 'mobile-wallet-adapter-embedded-root-ui';
137
- this.#root.innerHTML = modalHtml$1;
138
- this.#root.style.display = 'none';
139
- // Apply styles
140
- const styles = document.createElement('style');
141
- styles.id = 'mobile-wallet-adapter-embedded-modal-styles';
142
- styles.textContent = css$6;
143
- // Create a shadow DOM to encapsulate the modal
144
- const host = document.createElement('div');
145
- this.dom = host.attachShadow({ mode: 'closed' });
146
- // Pass the CSS variable to the Shadow DOM
147
- host.style.setProperty('--spinner-color', '#FFFFFF');
148
- this.dom.appendChild(styles);
149
- this.dom.appendChild(this.#root);
150
- // Append the shadow DOM host to the body
151
- document.body.appendChild(host);
152
- }
153
- #attachEventListeners() {
154
- if (!this.#root || this.#listenersAttached)
155
- return;
156
- const closers = [...this.#root.querySelectorAll('[data-modal-close]')];
157
- closers.forEach(closer => closer?.addEventListener('click', (event) => { this.close(event); }));
158
- window.addEventListener('load', this.close);
159
- document.addEventListener('keydown', this.#handleKeyDown);
160
- this.#listenersAttached = true;
161
- }
162
- #removeEventListeners() {
163
- if (!this.#listenersAttached)
164
- return;
165
- window.removeEventListener('load', this.close);
166
- document.removeEventListener('keydown', this.#handleKeyDown);
167
- if (!this.#root)
168
- return;
169
- const closers = [...this.#root.querySelectorAll('[data-modal-close]')];
170
- closers.forEach(closer => closer?.removeEventListener('click', this.close));
171
- this.#listenersAttached = false;
172
- }
173
- #handleKeyDown = (event) => {
174
- if (event.key === 'Escape')
175
- this.close(event);
176
- };
177
- }
178
-
117
+ var EmbeddedLoadingSpinner = class {
118
+ #root = null;
119
+ #eventListeners = {};
120
+ #listenersAttached = false;
121
+ dom = null;
122
+ constructor() {
123
+ this.init = this.init.bind(this);
124
+ this.#root = document.getElementById("mobile-wallet-adapter-embedded-root-ui");
125
+ }
126
+ async init() {
127
+ console.log("Injecting modal");
128
+ this.#injectHTML();
129
+ }
130
+ open = () => {
131
+ console.debug("Modal open");
132
+ this.#attachEventListeners();
133
+ if (this.#root) this.#root.style.display = "flex";
134
+ };
135
+ close = (event = void 0) => {
136
+ console.debug("Modal close");
137
+ this.#removeEventListeners();
138
+ if (this.#root) this.#root.style.display = "none";
139
+ this.#eventListeners["close"]?.forEach((listener) => listener(event));
140
+ };
141
+ addEventListener(event, listener) {
142
+ this.#eventListeners[event]?.push(listener) || (this.#eventListeners[event] = [listener]);
143
+ return () => this.removeEventListener(event, listener);
144
+ }
145
+ removeEventListener(event, listener) {
146
+ this.#eventListeners[event] = this.#eventListeners[event]?.filter((existingListener) => listener !== existingListener);
147
+ }
148
+ #injectHTML() {
149
+ if (this.dom) return;
150
+ this.#root = document.createElement("div");
151
+ this.#root.id = "mobile-wallet-adapter-embedded-root-ui";
152
+ this.#root.innerHTML = modalHtml$1;
153
+ this.#root.style.display = "none";
154
+ const styles = document.createElement("style");
155
+ styles.id = "mobile-wallet-adapter-embedded-modal-styles";
156
+ styles.textContent = css$6;
157
+ const host = document.createElement("div");
158
+ this.dom = host.attachShadow({ mode: "closed" });
159
+ host.style.setProperty("--spinner-color", "#FFFFFF");
160
+ this.dom.appendChild(styles);
161
+ this.dom.appendChild(this.#root);
162
+ document.body.appendChild(host);
163
+ }
164
+ #attachEventListeners() {
165
+ if (!this.#root || this.#listenersAttached) return;
166
+ [...this.#root.querySelectorAll("[data-modal-close]")].forEach((closer) => closer?.addEventListener("click", (event) => {
167
+ this.close(event);
168
+ }));
169
+ window.addEventListener("load", this.close);
170
+ document.addEventListener("keydown", this.#handleKeyDown);
171
+ this.#listenersAttached = true;
172
+ }
173
+ #removeEventListeners() {
174
+ if (!this.#listenersAttached) return;
175
+ window.removeEventListener("load", this.close);
176
+ document.removeEventListener("keydown", this.#handleKeyDown);
177
+ if (!this.#root) return;
178
+ [...this.#root.querySelectorAll("[data-modal-close]")].forEach((closer) => closer?.removeEventListener("click", this.close));
179
+ this.#listenersAttached = false;
180
+ }
181
+ #handleKeyDown = (event) => {
182
+ if (event.key === "Escape") this.close(event);
183
+ };
184
+ };
185
+ //#endregion
186
+ //#region src/embedded-modal/modal.ts
179
187
  const modalHtml = `
180
188
  <div class="mobile-wallet-adapter-embedded-modal-container" role="dialog" aria-modal="true" aria-labelledby="modal-title">
181
189
  <div data-modal-close style="position: absolute; width: 100%; height: 100%;"></div>
@@ -197,7 +205,7 @@ const css$5 = `
197
205
  justify-content: center; /* Center horizontally */
198
206
  align-items: center; /* Center vertically */
199
207
  position: fixed; /* Stay in place */
200
- z-index: 1; /* Sit on top */
208
+ z-index: 2147483647; /* Sit on top */
201
209
  left: 0;
202
210
  top: 0;
203
211
  width: 100%; /* Full width */
@@ -253,124 +261,100 @@ const fonts = `
253
261
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
254
262
  <link href="https://fonts.googleapis.com/css2?family=Inter+Tight:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
255
263
  `;
256
- class EmbeddedModal {
257
- #root = null;
258
- #eventListeners = {};
259
- #listenersAttached = false;
260
- dom = null;
261
- constructor() {
262
- // Bind methods to ensure `this` context is correct
263
- this.init = this.init.bind(this);
264
- this.#root = document.getElementById('mobile-wallet-adapter-embedded-root-ui');
265
- }
266
- async init() {
267
- console.log('Injecting modal');
268
- this.#injectHTML();
269
- }
270
- open = () => {
271
- console.debug('Modal open');
272
- this.#attachEventListeners();
273
- if (this.#root) {
274
- this.#root.style.display = 'flex';
275
- }
276
- };
277
- close = (event = undefined) => {
278
- console.debug('Modal close');
279
- this.#removeEventListeners();
280
- if (this.#root) {
281
- this.#root.style.display = 'none';
282
- }
283
- this.#eventListeners['close']?.forEach((listener) => listener(event));
284
- };
285
- addEventListener(event, listener) {
286
- this.#eventListeners[event]?.push(listener) || (this.#eventListeners[event] = [listener]);
287
- return () => this.removeEventListener(event, listener);
288
- }
289
- removeEventListener(event, listener) {
290
- this.#eventListeners[event] = this.#eventListeners[event]?.filter((existingListener) => listener !== existingListener);
291
- }
292
- #injectHTML() {
293
- // Check if the HTML has already been injected
294
- if (document.getElementById('mobile-wallet-adapter-embedded-root-ui')) {
295
- if (!this.#root)
296
- this.#root = document.getElementById('mobile-wallet-adapter-embedded-root-ui');
297
- return;
298
- }
299
- // Create a container for the modal
300
- this.#root = document.createElement('div');
301
- this.#root.id = 'mobile-wallet-adapter-embedded-root-ui';
302
- this.#root.innerHTML = modalHtml;
303
- this.#root.style.display = 'none';
304
- // Add modal content
305
- const content = this.#root.querySelector('.mobile-wallet-adapter-embedded-modal-content');
306
- if (content)
307
- content.innerHTML = this.contentHtml;
308
- // Apply styles
309
- const styles = document.createElement('style');
310
- styles.id = 'mobile-wallet-adapter-embedded-modal-styles';
311
- styles.textContent = css$5 + this.contentStyles;
312
- // Create a shadow DOM to encapsulate the modal
313
- const host = document.createElement('div');
314
- host.innerHTML = fonts;
315
- this.dom = host.attachShadow({ mode: 'closed' });
316
- this.dom.appendChild(styles);
317
- this.dom.appendChild(this.#root);
318
- // Append the shadow DOM host to the body
319
- document.body.appendChild(host);
320
- }
321
- #attachEventListeners() {
322
- if (!this.#root || this.#listenersAttached)
323
- return;
324
- const closers = [...this.#root.querySelectorAll('[data-modal-close]')];
325
- closers.forEach(closer => closer?.addEventListener('click', this.close));
326
- window.addEventListener('load', this.close);
327
- document.addEventListener('keydown', this.#handleKeyDown);
328
- this.#listenersAttached = true;
329
- }
330
- #removeEventListeners() {
331
- if (!this.#listenersAttached)
332
- return;
333
- window.removeEventListener('load', this.close);
334
- document.removeEventListener('keydown', this.#handleKeyDown);
335
- if (!this.#root)
336
- return;
337
- const closers = [...this.#root.querySelectorAll('[data-modal-close]')];
338
- closers.forEach(closer => closer?.removeEventListener('click', this.close));
339
- this.#listenersAttached = false;
340
- }
341
- #handleKeyDown = (event) => {
342
- if (event.key === 'Escape')
343
- this.close(event);
344
- };
345
- }
346
-
347
- class RemoteConnectionModal extends EmbeddedModal {
348
- contentStyles = css$4;
349
- contentHtml = QRCodeHtml;
350
- async initWithQR(qrCode) {
351
- super.init();
352
- this.populateQRCode(qrCode);
353
- }
354
- async populateQRCode(qrUrl) {
355
- const qrcodeContainer = this.dom?.getElementById('mobile-wallet-adapter-embedded-modal-qr-code-container');
356
- if (qrcodeContainer) {
357
- const qrCodeElement = await QRCode.toCanvas(qrUrl, { width: 200, margin: 0 });
358
- if (qrcodeContainer.firstElementChild !== null) {
359
- qrcodeContainer.replaceChild(qrCodeElement, qrcodeContainer.firstElementChild);
360
- }
361
- else
362
- qrcodeContainer.appendChild(qrCodeElement);
363
- // remove the loading placeholder for cleanup
364
- const qrPlaceholder = this.dom?.getElementById('mobile-wallet-adapter-embedded-modal-qr-placeholder');
365
- if (qrPlaceholder) {
366
- qrPlaceholder.style.display = 'none';
367
- }
368
- }
369
- else {
370
- console.error('QRCode Container not found');
371
- }
372
- }
373
- }
264
+ var EmbeddedModal = class {
265
+ #root = null;
266
+ #eventListeners = {};
267
+ #listenersAttached = false;
268
+ dom = null;
269
+ constructor() {
270
+ this.init = this.init.bind(this);
271
+ this.#root = document.getElementById("mobile-wallet-adapter-embedded-root-ui");
272
+ }
273
+ async init() {
274
+ console.log("Injecting modal");
275
+ this.#injectHTML();
276
+ }
277
+ open = () => {
278
+ console.debug("Modal open");
279
+ this.#attachEventListeners();
280
+ if (this.#root) this.#root.style.display = "flex";
281
+ };
282
+ close = (event = void 0) => {
283
+ console.debug("Modal close");
284
+ this.#removeEventListeners();
285
+ if (this.#root) this.#root.style.display = "none";
286
+ this.#eventListeners["close"]?.forEach((listener) => listener(event));
287
+ };
288
+ addEventListener(event, listener) {
289
+ this.#eventListeners[event]?.push(listener) || (this.#eventListeners[event] = [listener]);
290
+ return () => this.removeEventListener(event, listener);
291
+ }
292
+ removeEventListener(event, listener) {
293
+ this.#eventListeners[event] = this.#eventListeners[event]?.filter((existingListener) => listener !== existingListener);
294
+ }
295
+ #injectHTML() {
296
+ if (document.getElementById("mobile-wallet-adapter-embedded-root-ui")) {
297
+ if (!this.#root) this.#root = document.getElementById("mobile-wallet-adapter-embedded-root-ui");
298
+ return;
299
+ }
300
+ this.#root = document.createElement("div");
301
+ this.#root.id = "mobile-wallet-adapter-embedded-root-ui";
302
+ this.#root.innerHTML = modalHtml;
303
+ this.#root.style.display = "none";
304
+ const content = this.#root.querySelector(".mobile-wallet-adapter-embedded-modal-content");
305
+ if (content) content.innerHTML = this.contentHtml;
306
+ const styles = document.createElement("style");
307
+ styles.id = "mobile-wallet-adapter-embedded-modal-styles";
308
+ styles.textContent = css$5 + this.contentStyles;
309
+ const host = document.createElement("div");
310
+ host.innerHTML = fonts;
311
+ this.dom = host.attachShadow({ mode: "closed" });
312
+ this.dom.appendChild(styles);
313
+ this.dom.appendChild(this.#root);
314
+ document.body.appendChild(host);
315
+ }
316
+ #attachEventListeners() {
317
+ if (!this.#root || this.#listenersAttached) return;
318
+ [...this.#root.querySelectorAll("[data-modal-close]")].forEach((closer) => closer?.addEventListener("click", this.close));
319
+ window.addEventListener("load", this.close);
320
+ document.addEventListener("keydown", this.#handleKeyDown);
321
+ this.#listenersAttached = true;
322
+ }
323
+ #removeEventListeners() {
324
+ if (!this.#listenersAttached) return;
325
+ window.removeEventListener("load", this.close);
326
+ document.removeEventListener("keydown", this.#handleKeyDown);
327
+ if (!this.#root) return;
328
+ [...this.#root.querySelectorAll("[data-modal-close]")].forEach((closer) => closer?.removeEventListener("click", this.close));
329
+ this.#listenersAttached = false;
330
+ }
331
+ #handleKeyDown = (event) => {
332
+ if (event.key === "Escape") this.close(event);
333
+ };
334
+ };
335
+ //#endregion
336
+ //#region src/embedded-modal/remoteConnectionModal.ts
337
+ var RemoteConnectionModal = class extends EmbeddedModal {
338
+ contentStyles = css$4;
339
+ contentHtml = QRCodeHtml;
340
+ async initWithQR(qrCode) {
341
+ super.init();
342
+ this.populateQRCode(qrCode);
343
+ }
344
+ async populateQRCode(qrUrl) {
345
+ const qrcodeContainer = this.dom?.getElementById("mobile-wallet-adapter-embedded-modal-qr-code-container");
346
+ if (qrcodeContainer) {
347
+ const qrCodeElement = await qrcode.default.toCanvas(qrUrl, {
348
+ width: 200,
349
+ margin: 0
350
+ });
351
+ if (qrcodeContainer.firstElementChild !== null) qrcodeContainer.replaceChild(qrCodeElement, qrcodeContainer.firstElementChild);
352
+ else qrcodeContainer.appendChild(qrCodeElement);
353
+ const qrPlaceholder = this.dom?.getElementById("mobile-wallet-adapter-embedded-modal-qr-placeholder");
354
+ if (qrPlaceholder) qrPlaceholder.style.display = "none";
355
+ } else console.error("QRCode Container not found");
356
+ }
357
+ };
374
358
  const QRCodeHtml = `
375
359
  <div class="mobile-wallet-adapter-embedded-modal-qr-content">
376
360
  <div>
@@ -630,26 +614,25 @@ const css$4 = `
630
614
  animation: spinRight 2.5s cubic-bezier(.2,0,.8,1) infinite;
631
615
  }
632
616
  `;
633
-
634
- const icon = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03IDIuNUgxN0MxNy44Mjg0IDIuNSAxOC41IDMuMTcxNTcgMTguNSA0VjIwQzE4LjUgMjAuODI4NCAxNy44Mjg0IDIxLjUgMTcgMjEuNUg3QzYuMTcxNTcgMjEuNSA1LjUgMjAuODI4NCA1LjUgMjBWNEM1LjUgMy4xNzE1NyA2LjE3MTU3IDIuNSA3IDIuNVpNMyA0QzMgMS43OTA4NiA0Ljc5MDg2IDAgNyAwSDE3QzE5LjIwOTEgMCAyMSAxLjc5MDg2IDIxIDRWMjBDMjEgMjIuMjA5MSAxOS4yMDkxIDI0IDE3IDI0SDdDNC43OTA4NiAyNCAzIDIyLjIwOTEgMyAyMFY0Wk0xMSA0LjYxNTM4QzEwLjQ0NzcgNC42MTUzOCAxMCA1LjA2MzEgMTAgNS42MTUzOFY2LjM4NDYyQzEwIDYuOTM2OSAxMC40NDc3IDcuMzg0NjIgMTEgNy4zODQ2MkgxM0MxMy41NTIzIDcuMzg0NjIgMTQgNi45MzY5IDE0IDYuMzg0NjJWNS42MTUzOEMxNCA1LjA2MzEgMTMuNTUyMyA0LjYxNTM4IDEzIDQuNjE1MzhIMTFaIiBmaWxsPSIjRENCOEZGIi8+Cjwvc3ZnPgo=';
635
-
636
- class LocalConnectionModal extends EmbeddedModal {
637
- contentStyles = css$3;
638
- contentHtml = ErrorDialogHtml$3;
639
- initWithCallback(callback) {
640
- super.init();
641
- this.#prepareLaunchAction(callback);
642
- }
643
- #prepareLaunchAction(callback) {
644
- const launchButton = this.dom?.getElementById("mobile-wallet-adapter-launch-action");
645
- const listener = async () => {
646
- launchButton?.removeEventListener('click', listener);
647
- this.close();
648
- callback();
649
- };
650
- launchButton?.addEventListener('click', listener);
651
- }
652
- }
617
+ //#endregion
618
+ //#region src/embedded-modal/localConnectionModal.ts
619
+ var LocalConnectionModal = class extends EmbeddedModal {
620
+ contentStyles = css$3;
621
+ contentHtml = ErrorDialogHtml$3;
622
+ initWithCallback(callback) {
623
+ super.init();
624
+ this.#prepareLaunchAction(callback);
625
+ }
626
+ #prepareLaunchAction(callback) {
627
+ const launchButton = this.dom?.getElementById("mobile-wallet-adapter-launch-action");
628
+ const listener = async () => {
629
+ launchButton?.removeEventListener("click", listener);
630
+ this.close();
631
+ callback();
632
+ };
633
+ launchButton?.addEventListener("click", listener);
634
+ }
635
+ };
653
636
  const ErrorDialogHtml$3 = `
654
637
  <svg class="mobile-wallet-adapter-embedded-modal-launch-icon" width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
655
638
  <path d="M21.6 48C7.2 48 0 40.8 0 26.4V21.6C0 7.2 7.2 0 21.6 0H26.4C40.8 0 48 7.2 48 21.6V26.4C48 40.8 40.8 48 26.4 48H21.6Z" fill="#15994E"/>
@@ -707,28 +690,27 @@ const css$3 = `
707
690
  }
708
691
  }
709
692
  `;
710
-
711
- class LoopbackPermissionBlockedModal extends EmbeddedModal {
712
- contentStyles = css$2;
713
- get contentHtml() {
714
- const instructions = getIsPwaLaunchedAsApp()
715
- ? 'Long press the app icon on your home screen to open site settings'
716
- : 'Tap the lock or settings icon in the address bar to open site settings';
717
- return ErrorDialogHtml$2.replace('{{PERMISSION_INSTRUCTION_DETAIL}}', instructions);
718
- }
719
- async init() {
720
- super.init();
721
- this.#prepareLaunchAction();
722
- }
723
- #prepareLaunchAction() {
724
- const launchButton = this.dom?.getElementById("mobile-wallet-adapter-launch-action");
725
- const listener = async (event) => {
726
- launchButton?.removeEventListener('click', listener);
727
- this.close(event);
728
- };
729
- launchButton?.addEventListener('click', listener);
730
- }
731
- }
693
+ //#endregion
694
+ //#region src/embedded-modal/loopbackBlockedModal.ts
695
+ var LoopbackPermissionBlockedModal = class extends EmbeddedModal {
696
+ contentStyles = css$2;
697
+ get contentHtml() {
698
+ const instructions = getIsPwaLaunchedAsApp() ? "Long press the app icon on your home screen to open site settings" : "Tap the lock or settings icon in the address bar to open site settings";
699
+ return ErrorDialogHtml$2.replace("{{PERMISSION_INSTRUCTION_DETAIL}}", instructions);
700
+ }
701
+ async init() {
702
+ super.init();
703
+ this.#prepareLaunchAction();
704
+ }
705
+ #prepareLaunchAction() {
706
+ const launchButton = this.dom?.getElementById("mobile-wallet-adapter-launch-action");
707
+ const listener = async (event) => {
708
+ launchButton?.removeEventListener("click", listener);
709
+ this.close(event);
710
+ };
711
+ launchButton?.addEventListener("click", listener);
712
+ }
713
+ };
732
714
  const ErrorDialogHtml$2 = `
733
715
  <div class="mobile-wallet-adapter-embedded-modal-header">
734
716
  Local Wallet Connection
@@ -869,28 +851,27 @@ const css$2 = `
869
851
  }
870
852
  }
871
853
  `;
872
-
873
- class LoopbackPermissionModal extends EmbeddedModal {
874
- contentStyles = css$1;
875
- contentHtml = ErrorDialogHtml$1;
876
- async init() {
877
- super.init();
878
- this.#prepareLaunchAction();
879
- }
880
- #prepareLaunchAction() {
881
- const launchButton = this.dom?.getElementById("mobile-wallet-adapter-launch-action");
882
- const listener = async () => {
883
- launchButton?.removeEventListener('click', listener);
884
- try {
885
- // Trigger LNA permission prompting
886
- await fetch('http://localhost');
887
- }
888
- catch (e) { /* Ignore errors from fetch */ }
889
- this.close();
890
- };
891
- launchButton?.addEventListener('click', listener);
892
- }
893
- }
854
+ //#endregion
855
+ //#region src/embedded-modal/loopbackPermissionModal.ts
856
+ var LoopbackPermissionModal = class extends EmbeddedModal {
857
+ contentStyles = css$1;
858
+ contentHtml = ErrorDialogHtml$1;
859
+ async init() {
860
+ super.init();
861
+ this.#prepareLaunchAction();
862
+ }
863
+ #prepareLaunchAction() {
864
+ const launchButton = this.dom?.getElementById("mobile-wallet-adapter-launch-action");
865
+ const listener = async () => {
866
+ launchButton?.removeEventListener("click", listener);
867
+ try {
868
+ await fetch("http://localhost");
869
+ } catch {}
870
+ this.close();
871
+ };
872
+ launchButton?.addEventListener("click", listener);
873
+ }
874
+ };
894
875
  const ErrorDialogHtml$1 = `
895
876
  <div class="mobile-wallet-adapter-embedded-modal-title">Allow connections to your wallet</div>
896
877
  <div id="mobile-wallet-adapter-local-launch-message" class="mobile-wallet-adapter-embedded-modal-subtitle">
@@ -964,1015 +945,842 @@ const css$1 = `
964
945
  }
965
946
  }
966
947
  `;
967
-
948
+ //#endregion
949
+ //#region src/getIsSupported.ts
968
950
  function getIsLocalAssociationSupported() {
969
- return (typeof window !== 'undefined' &&
970
- window.isSecureContext &&
971
- typeof document !== 'undefined' &&
972
- /android/i.test(navigator.userAgent));
951
+ return typeof window !== "undefined" && window.isSecureContext && typeof document !== "undefined" && /android/i.test(navigator.userAgent);
973
952
  }
974
953
  function getIsRemoteAssociationSupported() {
975
- return (typeof window !== 'undefined' &&
976
- window.isSecureContext &&
977
- typeof document !== 'undefined' &&
978
- !/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent));
954
+ return typeof window !== "undefined" && window.isSecureContext && typeof document !== "undefined" && !/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
979
955
  }
980
- // Source: https://github.com/anza-xyz/wallet-adapter/blob/master/packages/core/react/src/getEnvironment.ts#L14
981
- // This is the same implementation that gated MWA in the Anza wallet-adapter-react library.
982
956
  function isWebView(userAgentString) {
983
- return /(WebView|Version\/.+(Chrome)\/(\d+)\.(\d+)\.(\d+)\.(\d+)|; wv\).+(Chrome)\/(\d+)\.(\d+)\.(\d+)\.(\d+))/i.test(userAgentString);
957
+ return /(WebView|Version\/.+(Chrome)\/(\d+)\.(\d+)\.(\d+)\.(\d+)|; wv\).+(Chrome)\/(\d+)\.(\d+)\.(\d+)\.(\d+))/i.test(userAgentString);
958
+ }
959
+ function isSolanaMobileWebShell(userAgentString) {
960
+ return userAgentString.includes("Solana Mobile Web Shell");
984
961
  }
985
- // Source: https://web.dev/learn/pwa/detection/
986
962
  function getIsPwaLaunchedAsApp() {
987
- // Check for Android TWA
988
- const isAndroidTwa = typeof document !== 'undefined' && document.referrer.startsWith('android-app://');
989
- // Check for display-mode: standalone, fullscreen, or minimal-ui
990
- if (typeof window == 'undefined')
991
- return isAndroidTwa;
992
- const isStandalone = window.matchMedia('(display-mode: standalone)').matches;
993
- const isFullscreen = window.matchMedia('(display-mode: fullscreen)').matches;
994
- const isMinimalUI = window.matchMedia('(display-mode: minimal-ui)').matches;
995
- // App mode if any of these conditions are true
996
- return isAndroidTwa || isStandalone || isFullscreen || isMinimalUI;
963
+ const isAndroidTwa = typeof document !== "undefined" && document.referrer.startsWith("android-app://");
964
+ if (typeof window == "undefined") return isAndroidTwa;
965
+ const isStandalone = window.matchMedia("(display-mode: standalone)").matches;
966
+ const isFullscreen = window.matchMedia("(display-mode: fullscreen)").matches;
967
+ const isMinimalUI = window.matchMedia("(display-mode: minimal-ui)").matches;
968
+ return isAndroidTwa || isStandalone || isFullscreen || isMinimalUI;
997
969
  }
998
970
  async function checkLocalNetworkAccessPermission() {
999
- try {
1000
- let lnaPermission = await navigator.permissions.query({ name: "loopback-network" });
1001
- if (lnaPermission.state === "granted") {
1002
- // LNA permission already granted, continuing
1003
- return;
1004
- }
1005
- else if (lnaPermission.state === "denied") {
1006
- // LNA permission denied, aborting
1007
- const modal = new LoopbackPermissionBlockedModal();
1008
- modal.init();
1009
- modal.open();
1010
- throw new mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError(mobileWalletAdapterProtocol.SolanaMobileWalletAdapterErrorCode.ERROR_LOOPBACK_ACCESS_BLOCKED, 'Local Network Access permission denied');
1011
- }
1012
- else if (lnaPermission.state === "prompt") {
1013
- // Show permission explainer to user, and wait for the permission to change
1014
- const modal = new LoopbackPermissionModal();
1015
- const updatedState = await new Promise((resolve, reject) => {
1016
- modal.addEventListener('close', (event) => {
1017
- if (event) {
1018
- reject(new mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError(mobileWalletAdapterProtocol.SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_CANCELLED, 'Wallet connection cancelled by user', { event }));
1019
- }
1020
- });
1021
- lnaPermission.onchange = () => {
1022
- lnaPermission.onchange = null; // cleanup
1023
- resolve(lnaPermission.state);
1024
- };
1025
- modal.init();
1026
- modal.open();
1027
- });
1028
- if (updatedState === "granted") {
1029
- // User has granted the permission, now we need another click to continue
1030
- // Note: this is required to avoid being blocked by the browsers pop-up blocker
1031
- const modal = new LocalConnectionModal();
1032
- await new Promise((resolve, reject) => {
1033
- modal.addEventListener('close', (event) => {
1034
- if (event) {
1035
- reject(new mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError(mobileWalletAdapterProtocol.SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_CANCELLED, 'Wallet connection cancelled by user', { event }));
1036
- }
1037
- });
1038
- modal.initWithCallback(async () => {
1039
- resolve(true);
1040
- });
1041
- modal.open();
1042
- });
1043
- return;
1044
- }
1045
- else {
1046
- // recurse, to avoid duplicating above logic
1047
- return await checkLocalNetworkAccessPermission();
1048
- }
1049
- }
1050
- // Shouldn't ever get here
1051
- throw new mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError(mobileWalletAdapterProtocol.SolanaMobileWalletAdapterErrorCode.ERROR_LOOPBACK_ACCESS_BLOCKED, 'Local Network Access permission unknown');
1052
- }
1053
- catch (e) {
1054
- if (e instanceof TypeError &&
1055
- (e.message.includes('loopback-network') ||
1056
- e.message.includes('local-network-access'))) {
1057
- // LNA permission API not found, continuing
1058
- return;
1059
- }
1060
- // Re-throw existing adapter errors as-is
1061
- if (e instanceof mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError) {
1062
- throw e;
1063
- }
1064
- // An unknown error occurred, wrap it
1065
- throw new mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError(mobileWalletAdapterProtocol.SolanaMobileWalletAdapterErrorCode.ERROR_LOOPBACK_ACCESS_BLOCKED, e instanceof Error ? e.message : 'Local Network Access permission unknown');
1066
- }
1067
- }
1068
-
1069
- const SolanaMobileWalletAdapterWalletName = 'Mobile Wallet Adapter';
1070
- const SolanaMobileWalletAdapterRemoteWalletName = 'Remote Mobile Wallet Adapter';
971
+ if (typeof navigator !== "undefined" && isSolanaMobileWebShell(navigator.userAgent)) return;
972
+ try {
973
+ const lnaPermission = await navigator.permissions.query({ name: "loopback-network" });
974
+ if (lnaPermission.state === "granted") return;
975
+ else if (lnaPermission.state === "denied") {
976
+ const modal = new LoopbackPermissionBlockedModal();
977
+ modal.init();
978
+ modal.open();
979
+ throw new _solana_mobile_mobile_wallet_adapter_protocol.SolanaMobileWalletAdapterError(_solana_mobile_mobile_wallet_adapter_protocol.SolanaMobileWalletAdapterErrorCode.ERROR_LOOPBACK_ACCESS_BLOCKED, "Local Network Access permission denied");
980
+ } else if (lnaPermission.state === "prompt") {
981
+ const modal = new LoopbackPermissionModal();
982
+ if (await new Promise((resolve, reject) => {
983
+ modal.addEventListener("close", (event) => {
984
+ if (event) reject(new _solana_mobile_mobile_wallet_adapter_protocol.SolanaMobileWalletAdapterError(_solana_mobile_mobile_wallet_adapter_protocol.SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_CANCELLED, "Wallet connection cancelled by user", { event }));
985
+ });
986
+ lnaPermission.onchange = () => {
987
+ lnaPermission.onchange = null;
988
+ resolve(lnaPermission.state);
989
+ };
990
+ modal.init();
991
+ modal.open();
992
+ }) === "granted") {
993
+ const modal = new LocalConnectionModal();
994
+ await new Promise((resolve, reject) => {
995
+ modal.addEventListener("close", (event) => {
996
+ if (event) reject(new _solana_mobile_mobile_wallet_adapter_protocol.SolanaMobileWalletAdapterError(_solana_mobile_mobile_wallet_adapter_protocol.SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_CANCELLED, "Wallet connection cancelled by user", { event }));
997
+ });
998
+ modal.initWithCallback(async () => {
999
+ resolve(true);
1000
+ });
1001
+ modal.open();
1002
+ });
1003
+ return;
1004
+ } else return await checkLocalNetworkAccessPermission();
1005
+ }
1006
+ throw new _solana_mobile_mobile_wallet_adapter_protocol.SolanaMobileWalletAdapterError(_solana_mobile_mobile_wallet_adapter_protocol.SolanaMobileWalletAdapterErrorCode.ERROR_LOOPBACK_ACCESS_BLOCKED, "Local Network Access permission unknown");
1007
+ } catch (e) {
1008
+ if (e instanceof TypeError && (e.message.includes("loopback-network") || e.message.includes("local-network-access"))) return;
1009
+ if (e instanceof _solana_mobile_mobile_wallet_adapter_protocol.SolanaMobileWalletAdapterError) throw e;
1010
+ throw new _solana_mobile_mobile_wallet_adapter_protocol.SolanaMobileWalletAdapterError(_solana_mobile_mobile_wallet_adapter_protocol.SolanaMobileWalletAdapterErrorCode.ERROR_LOOPBACK_ACCESS_BLOCKED, e instanceof Error ? e.message : "Local Network Access permission unknown");
1011
+ }
1012
+ }
1013
+ //#endregion
1014
+ //#region src/icon.ts
1015
+ const icon = "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03IDIuNUgxN0MxNy44Mjg0IDIuNSAxOC41IDMuMTcxNTcgMTguNSA0VjIwQzE4LjUgMjAuODI4NCAxNy44Mjg0IDIxLjUgMTcgMjEuNUg3QzYuMTcxNTcgMjEuNSA1LjUgMjAuODI4NCA1LjUgMjBWNEM1LjUgMy4xNzE1NyA2LjE3MTU3IDIuNSA3IDIuNVpNMyA0QzMgMS43OTA4NiA0Ljc5MDg2IDAgNyAwSDE3QzE5LjIwOTEgMCAyMSAxLjc5MDg2IDIxIDRWMjBDMjEgMjIuMjA5MSAxOS4yMDkxIDI0IDE3IDI0SDdDNC43OTA4NiAyNCAzIDIyLjIwOTEgMyAyMFY0Wk0xMSA0LjYxNTM4QzEwLjQ0NzcgNC42MTUzOCAxMCA1LjA2MzEgMTAgNS42MTUzOFY2LjM4NDYyQzEwIDYuOTM2OSAxMC40NDc3IDcuMzg0NjIgMTEgNy4zODQ2MkgxM0MxMy41NTIzIDcuMzg0NjIgMTQgNi45MzY5IDE0IDYuMzg0NjJWNS42MTUzOEMxNCA1LjA2MzEgMTMuNTUyMyA0LjYxNTM4IDEzIDQuNjE1MzhIMTFaIiBmaWxsPSIjRENCOEZGIi8+Cjwvc3ZnPgo=";
1016
+ //#endregion
1017
+ //#region src/wallet.ts
1018
+ const SolanaMobileWalletAdapterWalletName = "Mobile Wallet Adapter";
1019
+ const SolanaMobileWalletAdapterRemoteWalletName = "Remote Mobile Wallet Adapter";
1071
1020
  const SIGNATURE_LENGTH_IN_BYTES = 64;
1072
- const DEFAULT_FEATURES = [walletStandardFeatures.SolanaSignAndSendTransaction, walletStandardFeatures.SolanaSignTransaction, walletStandardFeatures.SolanaSignMessage, walletStandardFeatures.SolanaSignIn];
1073
- const WALLET_ASSOCIATION_TIMEOUT = 30_000;
1074
- class LocalSolanaMobileWalletAdapterWallet {
1075
- #listeners = {};
1076
- #version = '1.0.0'; // wallet-standard version
1077
- #name = SolanaMobileWalletAdapterWalletName;
1078
- #url = 'https://solanamobile.com/wallets';
1079
- #icon = icon;
1080
- #appIdentity;
1081
- #authorization;
1082
- #authorizationCache;
1083
- #connecting = false;
1084
- /**
1085
- * Every time the connection is recycled in some way (eg. `disconnect()` is called)
1086
- * increment this and use it to make sure that `transact` calls from the previous
1087
- * 'generation' don't continue to do work and throw exceptions.
1088
- */
1089
- #connectionGeneration = 0;
1090
- #chains = [];
1091
- #chainSelector;
1092
- #optionalFeatures;
1093
- #onWalletNotFound;
1094
- get version() {
1095
- return this.#version;
1096
- }
1097
- get name() {
1098
- return this.#name;
1099
- }
1100
- get url() {
1101
- return this.#url;
1102
- }
1103
- get icon() {
1104
- return this.#icon;
1105
- }
1106
- get chains() {
1107
- return this.#chains;
1108
- }
1109
- get features() {
1110
- return {
1111
- [features.StandardConnect]: {
1112
- version: '1.0.0',
1113
- connect: this.#connect,
1114
- },
1115
- [features.StandardDisconnect]: {
1116
- version: '1.0.0',
1117
- disconnect: this.#disconnect,
1118
- },
1119
- [features.StandardEvents]: {
1120
- version: '1.0.0',
1121
- on: this.#on,
1122
- },
1123
- [walletStandardFeatures.SolanaSignMessage]: {
1124
- version: '1.0.0',
1125
- signMessage: this.#signMessage,
1126
- },
1127
- [walletStandardFeatures.SolanaSignIn]: {
1128
- version: '1.0.0',
1129
- signIn: this.#signIn,
1130
- },
1131
- ...this.#optionalFeatures,
1132
- };
1133
- }
1134
- get accounts() {
1135
- return this.#authorization?.accounts ?? [];
1136
- }
1137
- constructor(config) {
1138
- this.#authorizationCache = config.authorizationCache;
1139
- this.#appIdentity = config.appIdentity;
1140
- this.#chains = config.chains;
1141
- this.#chainSelector = config.chainSelector;
1142
- this.#onWalletNotFound = config.onWalletNotFound;
1143
- this.#optionalFeatures = {
1144
- // In MWA 1.0, signAndSend is optional and signTransaction is mandatory. Whereas in MWA 2.0+,
1145
- // signAndSend is mandatory and signTransaction is optional (and soft deprecated). As of mid
1146
- // 2025, all MWA wallets support both signAndSendTransaction and signTransaction so its safe
1147
- // assume both are supported here. The features will be updated based on the actual connected
1148
- // wallets capabilities during connection regardless, so this is safe.
1149
- [walletStandardFeatures.SolanaSignAndSendTransaction]: {
1150
- version: '1.0.0',
1151
- supportedTransactionVersions: ['legacy', 0],
1152
- signAndSendTransaction: this.#signAndSendTransaction,
1153
- },
1154
- [walletStandardFeatures.SolanaSignTransaction]: {
1155
- version: '1.0.0',
1156
- supportedTransactionVersions: ['legacy', 0],
1157
- signTransaction: this.#signTransaction,
1158
- },
1159
- };
1160
- }
1161
- get connected() {
1162
- return !!this.#authorization;
1163
- }
1164
- get isAuthorized() {
1165
- return !!this.#authorization;
1166
- }
1167
- get currentAuthorization() {
1168
- return this.#authorization;
1169
- }
1170
- get cachedAuthorizationResult() {
1171
- return this.#authorizationCache.get();
1172
- }
1173
- #on = (event, listener) => {
1174
- this.#listeners[event]?.push(listener) || (this.#listeners[event] = [listener]);
1175
- return () => this.#off(event, listener);
1176
- };
1177
- #emit(event, ...args) {
1178
- // eslint-disable-next-line prefer-spread
1179
- this.#listeners[event]?.forEach((listener) => listener.apply(null, args));
1180
- }
1181
- #off(event, listener) {
1182
- this.#listeners[event] = this.#listeners[event]?.filter((existingListener) => listener !== existingListener);
1183
- }
1184
- #connect = async ({ silent } = {}) => {
1185
- if (this.#connecting || this.connected) {
1186
- return { accounts: this.accounts };
1187
- }
1188
- this.#connecting = true;
1189
- try {
1190
- if (silent) {
1191
- const cachedAuthorization = await this.#authorizationCache.get();
1192
- if (cachedAuthorization) {
1193
- await this.#handleWalletCapabilitiesResult(cachedAuthorization.capabilities);
1194
- await this.#handleAuthorizationResult(cachedAuthorization);
1195
- }
1196
- else {
1197
- return { accounts: this.accounts };
1198
- }
1199
- }
1200
- else {
1201
- await this.#performAuthorization();
1202
- }
1203
- }
1204
- catch (e) {
1205
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1206
- }
1207
- finally {
1208
- this.#connecting = false;
1209
- }
1210
- return { accounts: this.accounts };
1211
- };
1212
- #performAuthorization = async (signInPayload) => {
1213
- try {
1214
- const cachedAuthorizationResult = await this.#authorizationCache.get();
1215
- if (cachedAuthorizationResult) {
1216
- // TODO: Evaluate whether there's any threat to not `awaiting` this expression
1217
- this.#handleAuthorizationResult(cachedAuthorizationResult);
1218
- return cachedAuthorizationResult;
1219
- }
1220
- const selectedChain = await this.#chainSelector.select(this.#chains);
1221
- return await this.#transact(async (wallet) => {
1222
- const [capabilities, mwaAuthorizationResult] = await Promise.all([
1223
- wallet.getCapabilities(),
1224
- wallet.authorize({
1225
- chain: selectedChain,
1226
- identity: this.#appIdentity,
1227
- sign_in_payload: signInPayload,
1228
- })
1229
- ]);
1230
- const accounts = this.#accountsToWalletStandardAccounts(mwaAuthorizationResult.accounts);
1231
- const authorization = { ...mwaAuthorizationResult,
1232
- accounts, chain: selectedChain, capabilities: capabilities };
1233
- // TODO: Evaluate whether there's any threat to not `awaiting` this expression
1234
- Promise.all([
1235
- this.#handleWalletCapabilitiesResult(capabilities),
1236
- this.#authorizationCache.set(authorization),
1237
- this.#handleAuthorizationResult(authorization),
1238
- ]);
1239
- return authorization;
1240
- });
1241
- }
1242
- catch (e) {
1243
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1244
- }
1245
- };
1246
- #handleAuthorizationResult = async (authorization) => {
1247
- const didPublicKeysChange =
1248
- // Case 1: We started from having no authorization.
1249
- this.#authorization == null ||
1250
- // Case 2: The number of authorized accounts changed.
1251
- this.#authorization?.accounts.length !== authorization.accounts.length ||
1252
- // Case 3: The new list of addresses isn't exactly the same as the old list, in the same order.
1253
- this.#authorization.accounts.some((account, ii) => account.address !== authorization.accounts[ii].address);
1254
- this.#authorization = authorization;
1255
- if (didPublicKeysChange) {
1256
- this.#emit('change', { accounts: this.accounts });
1257
- }
1258
- };
1259
- #handleWalletCapabilitiesResult = async (capabilities) => {
1260
- // TODO: investigate why using SolanaSignTransactions constant breaks treeshaking
1261
- const supportsSignTransaction = capabilities.features.includes('solana:signTransactions'); //SolanaSignTransactions);
1262
- const supportsSignAndSendTransaction = capabilities.supports_sign_and_send_transactions;
1263
- const didCapabilitiesChange = walletStandardFeatures.SolanaSignAndSendTransaction in this.features !== supportsSignAndSendTransaction ||
1264
- walletStandardFeatures.SolanaSignTransaction in this.features !== supportsSignTransaction;
1265
- this.#optionalFeatures = {
1266
- ...((supportsSignAndSendTransaction || (!supportsSignAndSendTransaction && !supportsSignTransaction)) && {
1267
- [walletStandardFeatures.SolanaSignAndSendTransaction]: {
1268
- version: '1.0.0',
1269
- supportedTransactionVersions: ['legacy', 0],
1270
- signAndSendTransaction: this.#signAndSendTransaction,
1271
- },
1272
- }),
1273
- ...(supportsSignTransaction && {
1274
- [walletStandardFeatures.SolanaSignTransaction]: {
1275
- version: '1.0.0',
1276
- supportedTransactionVersions: ['legacy', 0],
1277
- signTransaction: this.#signTransaction,
1278
- },
1279
- }),
1280
- };
1281
- if (didCapabilitiesChange) {
1282
- this.#emit('change', { features: this.features });
1283
- }
1284
- };
1285
- #performReauthorization = async (wallet, authToken, chain) => {
1286
- try {
1287
- const [capabilities, mwaAuthorizationResult] = await Promise.all([
1288
- this.#authorization?.capabilities ?? await wallet.getCapabilities(),
1289
- wallet.authorize({
1290
- auth_token: authToken,
1291
- identity: this.#appIdentity,
1292
- chain: chain
1293
- })
1294
- ]);
1295
- const accounts = this.#accountsToWalletStandardAccounts(mwaAuthorizationResult.accounts);
1296
- const authorization = { ...mwaAuthorizationResult,
1297
- accounts: accounts, chain: chain, capabilities: capabilities
1298
- };
1299
- // TODO: Evaluate whether there's any threat to not `awaiting` this expression
1300
- Promise.all([
1301
- this.#authorizationCache.set(authorization),
1302
- this.#handleAuthorizationResult(authorization),
1303
- ]);
1304
- }
1305
- catch (e) {
1306
- this.#disconnect();
1307
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1308
- }
1309
- };
1310
- #disconnect = async () => {
1311
- this.#authorizationCache.clear(); // TODO: Evaluate whether there's any threat to not `awaiting` this expression
1312
- this.#connecting = false;
1313
- this.#connectionGeneration++;
1314
- this.#authorization = undefined;
1315
- this.#emit('change', { accounts: this.accounts });
1316
- };
1317
- #transact = async (callback) => {
1318
- const walletUriBase = this.#authorization?.wallet_uri_base;
1319
- const config = walletUriBase ? { baseUri: walletUriBase } : undefined;
1320
- const currentConnectionGeneration = this.#connectionGeneration;
1321
- const loadingSpinner = new EmbeddedLoadingSpinner();
1322
- try {
1323
- // check that we have permissions for local app connections, then run
1324
- // wallet association (transact). In case the user manually cancels
1325
- // the wallet association, cancel the connection after a timeout.
1326
- let associating = true;
1327
- let timeout = undefined;
1328
- const result = await Promise.race([
1329
- checkLocalNetworkAccessPermission()
1330
- .then(async () => {
1331
- // Begin local connection, show loading spinner while we connect
1332
- loadingSpinner.init();
1333
- const { wallet, close } = await mobileWalletAdapterProtocol.startScenario(config);
1334
- loadingSpinner.addEventListener('close', (event) => { if (event)
1335
- close(); });
1336
- loadingSpinner.open();
1337
- const result = await callback(await wallet);
1338
- loadingSpinner.close();
1339
- close();
1340
- return result;
1341
- }),
1342
- new Promise((_, reject) => {
1343
- timeout = setTimeout(() => {
1344
- if (associating) { // only timeout during association
1345
- reject(new mobileWalletAdapterProtocol.SolanaMobileWalletAdapterError(mobileWalletAdapterProtocol.SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_CANCELLED, 'Wallet connection timed out', { event: undefined }));
1346
- }
1347
- }, WALLET_ASSOCIATION_TIMEOUT);
1348
- })
1349
- ]);
1350
- clearTimeout(timeout);
1351
- return result;
1352
- }
1353
- catch (e) {
1354
- loadingSpinner.close();
1355
- if (this.#connectionGeneration !== currentConnectionGeneration) {
1356
- await new Promise(() => { }); // Never resolve.
1357
- }
1358
- if (e instanceof Error &&
1359
- e.name === 'SolanaMobileWalletAdapterError' &&
1360
- e.code === 'ERROR_WALLET_NOT_FOUND') {
1361
- await this.#onWalletNotFound(this);
1362
- }
1363
- throw e;
1364
- }
1365
- };
1366
- #assertIsAuthorized = () => {
1367
- if (!this.#authorization)
1368
- throw new Error('Wallet not connected');
1369
- return { authToken: this.#authorization.auth_token, chain: this.#authorization.chain };
1370
- };
1371
- #accountsToWalletStandardAccounts = (accounts) => {
1372
- return accounts.map((account) => {
1373
- const publicKey = jsBase64.toUint8Array(account.address);
1374
- return {
1375
- address: base58.encode(publicKey),
1376
- publicKey,
1377
- label: account.label,
1378
- icon: account.icon,
1379
- chains: account.chains ?? this.#chains,
1380
- // TODO: get supported features from getCapabilities API
1381
- features: account.features ?? DEFAULT_FEATURES
1382
- };
1383
- });
1384
- };
1385
- #performSignTransactions = async (transactions) => {
1386
- const { authToken, chain } = this.#assertIsAuthorized();
1387
- try {
1388
- const base64Transactions = transactions.map((tx) => { return jsBase64.fromUint8Array(tx); });
1389
- return await this.#transact(async (wallet) => {
1390
- await this.#performReauthorization(wallet, authToken, chain);
1391
- const signedTransactions = (await wallet.signTransactions({
1392
- payloads: base64Transactions,
1393
- })).signed_payloads.map(jsBase64.toUint8Array);
1394
- return signedTransactions;
1395
- });
1396
- }
1397
- catch (e) {
1398
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1399
- }
1400
- };
1401
- #performSignAndSendTransaction = async (transaction, options) => {
1402
- const { authToken, chain } = this.#assertIsAuthorized();
1403
- try {
1404
- return await this.#transact(async (wallet) => {
1405
- const [capabilities, _1] = await Promise.all([
1406
- wallet.getCapabilities(),
1407
- this.#performReauthorization(wallet, authToken, chain)
1408
- ]);
1409
- if (capabilities.supports_sign_and_send_transactions) {
1410
- const base64Transaction = jsBase64.fromUint8Array(transaction);
1411
- const signatures = (await wallet.signAndSendTransactions({
1412
- ...options,
1413
- payloads: [base64Transaction],
1414
- })).signatures.map(jsBase64.toUint8Array);
1415
- return signatures[0];
1416
- }
1417
- else {
1418
- throw new Error('connected wallet does not support signAndSendTransaction');
1419
- }
1420
- });
1421
- }
1422
- catch (e) {
1423
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1424
- }
1425
- };
1426
- #signAndSendTransaction = async (...inputs) => {
1427
- const outputs = [];
1428
- for (const input of inputs) {
1429
- const signature = await this.#performSignAndSendTransaction(input.transaction, input.options);
1430
- outputs.push({ signature });
1431
- }
1432
- return outputs;
1433
- };
1434
- #signTransaction = async (...inputs) => {
1435
- return (await this.#performSignTransactions(inputs.map(({ transaction }) => transaction)))
1436
- .map((signedTransaction) => {
1437
- return { signedTransaction };
1438
- });
1439
- };
1440
- #signMessage = async (...inputs) => {
1441
- const { authToken, chain } = this.#assertIsAuthorized();
1442
- const addresses = inputs.map(({ account }) => jsBase64.fromUint8Array(new Uint8Array(account.publicKey)));
1443
- const messages = inputs.map(({ message }) => jsBase64.fromUint8Array(message));
1444
- try {
1445
- return await this.#transact(async (wallet) => {
1446
- await this.#performReauthorization(wallet, authToken, chain);
1447
- const signedMessages = (await wallet.signMessages({
1448
- addresses: addresses,
1449
- payloads: messages,
1450
- })).signed_payloads.map(jsBase64.toUint8Array);
1451
- return signedMessages.map((signedMessage) => {
1452
- return { signedMessage: signedMessage, signature: signedMessage.slice(-SIGNATURE_LENGTH_IN_BYTES) };
1453
- });
1454
- });
1455
- }
1456
- catch (e) {
1457
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1458
- }
1459
- };
1460
- #signIn = async (...inputs) => {
1461
- const outputs = [];
1462
- if (inputs.length > 1) {
1463
- for (const input of inputs) {
1464
- outputs.push(await this.#performSignIn(input));
1465
- }
1466
- }
1467
- else {
1468
- return [await this.#performSignIn(inputs[0])];
1469
- }
1470
- return outputs;
1471
- };
1472
- #performSignIn = async (input) => {
1473
- this.#connecting = true;
1474
- try {
1475
- const authorizationResult = await this.#performAuthorization({
1476
- ...input,
1477
- domain: input?.domain ?? window.location.host
1478
- });
1479
- if (!authorizationResult.sign_in_result) {
1480
- throw new Error("Sign in failed, no sign in result returned by wallet");
1481
- }
1482
- const signedInAddress = authorizationResult.sign_in_result.address;
1483
- const signedInAccount = authorizationResult.accounts.find(acc => acc.address == signedInAddress);
1484
- return {
1485
- account: {
1486
- ...signedInAccount ?? {
1487
- address: base58.encode(jsBase64.toUint8Array(signedInAddress))
1488
- },
1489
- publicKey: jsBase64.toUint8Array(signedInAddress),
1490
- chains: signedInAccount?.chains ?? this.#chains,
1491
- features: signedInAccount?.features ?? authorizationResult.capabilities.features
1492
- },
1493
- signedMessage: jsBase64.toUint8Array(authorizationResult.sign_in_result.signed_message),
1494
- signature: jsBase64.toUint8Array(authorizationResult.sign_in_result.signature)
1495
- };
1496
- }
1497
- catch (e) {
1498
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1499
- }
1500
- finally {
1501
- this.#connecting = false;
1502
- }
1503
- };
1504
- }
1505
- class RemoteSolanaMobileWalletAdapterWallet {
1506
- #listeners = {};
1507
- #version = '1.0.0'; // wallet-standard version
1508
- #name = SolanaMobileWalletAdapterRemoteWalletName;
1509
- #url = 'https://solanamobile.com/wallets';
1510
- #icon = icon;
1511
- #appIdentity;
1512
- #authorization;
1513
- #authorizationCache;
1514
- #connecting = false;
1515
- /**
1516
- * Every time the connection is recycled in some way (eg. `disconnect()` is called)
1517
- * increment this and use it to make sure that `transact` calls from the previous
1518
- * 'generation' don't continue to do work and throw exceptions.
1519
- */
1520
- #connectionGeneration = 0;
1521
- #chains = [];
1522
- #chainSelector;
1523
- #optionalFeatures;
1524
- #onWalletNotFound;
1525
- #hostAuthority;
1526
- #session;
1527
- get version() {
1528
- return this.#version;
1529
- }
1530
- get name() {
1531
- return this.#name;
1532
- }
1533
- get url() {
1534
- return this.#url;
1535
- }
1536
- get icon() {
1537
- return this.#icon;
1538
- }
1539
- get chains() {
1540
- return this.#chains;
1541
- }
1542
- get features() {
1543
- return {
1544
- [features.StandardConnect]: {
1545
- version: '1.0.0',
1546
- connect: this.#connect,
1547
- },
1548
- [features.StandardDisconnect]: {
1549
- version: '1.0.0',
1550
- disconnect: this.#disconnect,
1551
- },
1552
- [features.StandardEvents]: {
1553
- version: '1.0.0',
1554
- on: this.#on,
1555
- },
1556
- [walletStandardFeatures.SolanaSignMessage]: {
1557
- version: '1.0.0',
1558
- signMessage: this.#signMessage,
1559
- },
1560
- [walletStandardFeatures.SolanaSignIn]: {
1561
- version: '1.0.0',
1562
- signIn: this.#signIn,
1563
- },
1564
- ...this.#optionalFeatures,
1565
- };
1566
- }
1567
- get accounts() {
1568
- return this.#authorization?.accounts ?? [];
1569
- }
1570
- constructor(config) {
1571
- this.#authorizationCache = config.authorizationCache;
1572
- this.#appIdentity = config.appIdentity;
1573
- this.#chains = config.chains;
1574
- this.#chainSelector = config.chainSelector;
1575
- this.#hostAuthority = config.remoteHostAuthority;
1576
- this.#onWalletNotFound = config.onWalletNotFound;
1577
- this.#optionalFeatures = {
1578
- // In MWA 1.0, signAndSend is optional and signTransaction is mandatory. Whereas in MWA 2.0+,
1579
- // signAndSend is mandatory and signTransaction is optional (and soft deprecated). As of mid
1580
- // 2025, all MWA wallets support both signAndSendTransaction and signTransaction so its safe
1581
- // assume both are supported here. The features will be updated based on the actual connected
1582
- // wallets capabilities during connection regardless, so this is safe.
1583
- [walletStandardFeatures.SolanaSignAndSendTransaction]: {
1584
- version: '1.0.0',
1585
- supportedTransactionVersions: ['legacy', 0],
1586
- signAndSendTransaction: this.#signAndSendTransaction,
1587
- },
1588
- [walletStandardFeatures.SolanaSignTransaction]: {
1589
- version: '1.0.0',
1590
- supportedTransactionVersions: ['legacy', 0],
1591
- signTransaction: this.#signTransaction,
1592
- },
1593
- };
1594
- }
1595
- get connected() {
1596
- return !!this.#session && !!this.#authorization;
1597
- }
1598
- get isAuthorized() {
1599
- return !!this.#authorization;
1600
- }
1601
- get currentAuthorization() {
1602
- return this.#authorization;
1603
- }
1604
- get cachedAuthorizationResult() {
1605
- return this.#authorizationCache.get();
1606
- }
1607
- #on = (event, listener) => {
1608
- this.#listeners[event]?.push(listener) || (this.#listeners[event] = [listener]);
1609
- return () => this.#off(event, listener);
1610
- };
1611
- #emit(event, ...args) {
1612
- // eslint-disable-next-line prefer-spread
1613
- this.#listeners[event]?.forEach((listener) => listener.apply(null, args));
1614
- }
1615
- #off(event, listener) {
1616
- this.#listeners[event] = this.#listeners[event]?.filter((existingListener) => listener !== existingListener);
1617
- }
1618
- #connect = async ({ silent } = {}) => {
1619
- if (this.#connecting || this.connected) {
1620
- return { accounts: this.accounts };
1621
- }
1622
- this.#connecting = true;
1623
- try {
1624
- await this.#performAuthorization();
1625
- }
1626
- catch (e) {
1627
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1628
- }
1629
- finally {
1630
- this.#connecting = false;
1631
- }
1632
- return { accounts: this.accounts };
1633
- };
1634
- #performAuthorization = async (signInPayload) => {
1635
- try {
1636
- const cachedAuthorizationResult = await this.#authorizationCache.get();
1637
- if (cachedAuthorizationResult) {
1638
- // TODO: Evaluate whether there's any threat to not `awaiting` this expression
1639
- this.#handleAuthorizationResult(cachedAuthorizationResult);
1640
- return cachedAuthorizationResult;
1641
- }
1642
- if (this.#session)
1643
- this.#session = undefined;
1644
- const selectedChain = await this.#chainSelector.select(this.#chains);
1645
- return await this.#transact(async (wallet) => {
1646
- const [capabilities, mwaAuthorizationResult] = await Promise.all([
1647
- wallet.getCapabilities(),
1648
- wallet.authorize({
1649
- chain: selectedChain,
1650
- identity: this.#appIdentity,
1651
- sign_in_payload: signInPayload,
1652
- })
1653
- ]);
1654
- const accounts = this.#accountsToWalletStandardAccounts(mwaAuthorizationResult.accounts);
1655
- const authorizationResult = { ...mwaAuthorizationResult,
1656
- accounts, chain: selectedChain, capabilities: capabilities };
1657
- // TODO: Evaluate whether there's any threat to not `awaiting` this expression
1658
- Promise.all([
1659
- this.#handleWalletCapabilitiesResult(capabilities),
1660
- this.#authorizationCache.set(authorizationResult),
1661
- this.#handleAuthorizationResult(authorizationResult),
1662
- ]);
1663
- return authorizationResult;
1664
- });
1665
- }
1666
- catch (e) {
1667
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1668
- }
1669
- };
1670
- #handleAuthorizationResult = async (authorization) => {
1671
- const didPublicKeysChange =
1672
- // Case 1: We started from having no authorization.
1673
- this.#authorization == null ||
1674
- // Case 2: The number of authorized accounts changed.
1675
- this.#authorization?.accounts.length !== authorization.accounts.length ||
1676
- // Case 3: The new list of addresses isn't exactly the same as the old list, in the same order.
1677
- this.#authorization.accounts.some((account, ii) => account.address !== authorization.accounts[ii].address);
1678
- this.#authorization = authorization;
1679
- if (didPublicKeysChange) {
1680
- this.#emit('change', { accounts: this.accounts });
1681
- }
1682
- };
1683
- #handleWalletCapabilitiesResult = async (capabilities) => {
1684
- // TODO: investigate why using SolanaSignTransactions constant breaks treeshaking
1685
- const supportsSignTransaction = capabilities.features.includes('solana:signTransactions'); //SolanaSignTransactions);
1686
- const supportsSignAndSendTransaction = capabilities.supports_sign_and_send_transactions ||
1687
- capabilities.features.includes('solana:signAndSendTransaction');
1688
- const didCapabilitiesChange = walletStandardFeatures.SolanaSignAndSendTransaction in this.features !== supportsSignAndSendTransaction ||
1689
- walletStandardFeatures.SolanaSignTransaction in this.features !== supportsSignTransaction;
1690
- this.#optionalFeatures = {
1691
- ...(supportsSignAndSendTransaction && {
1692
- [walletStandardFeatures.SolanaSignAndSendTransaction]: {
1693
- version: '1.0.0',
1694
- supportedTransactionVersions: capabilities.supported_transaction_versions,
1695
- signAndSendTransaction: this.#signAndSendTransaction,
1696
- },
1697
- }),
1698
- ...(supportsSignTransaction && {
1699
- [walletStandardFeatures.SolanaSignTransaction]: {
1700
- version: '1.0.0',
1701
- supportedTransactionVersions: capabilities.supported_transaction_versions,
1702
- signTransaction: this.#signTransaction,
1703
- },
1704
- }),
1705
- };
1706
- if (didCapabilitiesChange) {
1707
- this.#emit('change', { features: this.features });
1708
- }
1709
- };
1710
- #performReauthorization = async (wallet, authToken, chain) => {
1711
- try {
1712
- const [capabilities, mwaAuthorizationResult] = await Promise.all([
1713
- this.#authorization?.capabilities ?? await wallet.getCapabilities(),
1714
- wallet.authorize({
1715
- auth_token: authToken,
1716
- identity: this.#appIdentity,
1717
- chain: chain
1718
- })
1719
- ]);
1720
- const accounts = this.#accountsToWalletStandardAccounts(mwaAuthorizationResult.accounts);
1721
- const authorization = { ...mwaAuthorizationResult,
1722
- accounts: accounts, chain: chain, capabilities: capabilities };
1723
- // TODO: Evaluate whether there's any threat to not `awaiting` this expression
1724
- Promise.all([
1725
- this.#authorizationCache.set(authorization),
1726
- this.#handleAuthorizationResult(authorization),
1727
- ]);
1728
- }
1729
- catch (e) {
1730
- this.#disconnect();
1731
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1732
- }
1733
- };
1734
- #disconnect = async () => {
1735
- this.#session?.close();
1736
- this.#authorizationCache.clear(); // TODO: Evaluate whether there's any threat to not `awaiting` this expression
1737
- this.#connecting = false;
1738
- this.#connectionGeneration++;
1739
- this.#authorization = undefined;
1740
- this.#session = undefined;
1741
- this.#emit('change', { accounts: this.accounts });
1742
- };
1743
- #transact = async (callback) => {
1744
- const walletUriBase = this.#authorization?.wallet_uri_base;
1745
- const baseConfig = walletUriBase ? { baseUri: walletUriBase } : undefined;
1746
- const remoteConfig = { ...baseConfig, remoteHostAuthority: this.#hostAuthority };
1747
- const currentConnectionGeneration = this.#connectionGeneration;
1748
- const modal = new RemoteConnectionModal();
1749
- if (this.#session) {
1750
- return callback(this.#session.wallet);
1751
- }
1752
- try {
1753
- // Begin remote connection, show modal with loading anim while we connect
1754
- modal.init();
1755
- modal.open();
1756
- const { associationUrl, close, wallet } = await mobileWalletAdapterProtocol.startRemoteScenario(remoteConfig);
1757
- // Reflector is now connected, update the connection modal with qr code
1758
- const removeCloseListener = modal.addEventListener('close', (event) => {
1759
- if (event)
1760
- close();
1761
- });
1762
- modal.populateQRCode(associationUrl.toString());
1763
- // Wait for the wallet to be connected, then close the connection modal and proceed
1764
- this.#session = { close, wallet: await wallet };
1765
- removeCloseListener();
1766
- modal.close();
1767
- return await callback(this.#session.wallet);
1768
- }
1769
- catch (e) {
1770
- modal.close();
1771
- if (this.#connectionGeneration !== currentConnectionGeneration) {
1772
- await new Promise(() => { }); // Never resolve.
1773
- }
1774
- if (e instanceof Error &&
1775
- e.name === 'SolanaMobileWalletAdapterError' &&
1776
- e.code === 'ERROR_WALLET_NOT_FOUND') {
1777
- await this.#onWalletNotFound(this);
1778
- }
1779
- throw e;
1780
- }
1781
- };
1782
- #assertIsAuthorized = () => {
1783
- if (!this.#authorization)
1784
- throw new Error('Wallet not connected');
1785
- return { authToken: this.#authorization.auth_token, chain: this.#authorization.chain };
1786
- };
1787
- #accountsToWalletStandardAccounts = (accounts) => {
1788
- return accounts.map((account) => {
1789
- const publicKey = jsBase64.toUint8Array(account.address);
1790
- return {
1791
- address: base58.encode(publicKey),
1792
- publicKey,
1793
- label: account.label,
1794
- icon: account.icon,
1795
- chains: account.chains ?? this.#chains,
1796
- // TODO: get supported features from getCapabilities API
1797
- features: account.features ?? DEFAULT_FEATURES
1798
- };
1799
- });
1800
- };
1801
- #performSignTransactions = async (transactions) => {
1802
- const { authToken, chain } = this.#assertIsAuthorized();
1803
- try {
1804
- return await this.#transact(async (wallet) => {
1805
- await this.#performReauthorization(wallet, authToken, chain);
1806
- const signedTransactions = (await wallet.signTransactions({
1807
- payloads: transactions.map(jsBase64.fromUint8Array),
1808
- })).signed_payloads.map(jsBase64.toUint8Array);
1809
- return signedTransactions;
1810
- });
1811
- }
1812
- catch (e) {
1813
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1814
- }
1815
- };
1816
- #performSignAndSendTransaction = async (transaction, options) => {
1817
- const { authToken, chain } = this.#assertIsAuthorized();
1818
- try {
1819
- return await this.#transact(async (wallet) => {
1820
- const [capabilities, _1] = await Promise.all([
1821
- wallet.getCapabilities(),
1822
- this.#performReauthorization(wallet, authToken, chain)
1823
- ]);
1824
- if (capabilities.supports_sign_and_send_transactions) {
1825
- const signatures = (await wallet.signAndSendTransactions({
1826
- ...options,
1827
- payloads: [jsBase64.fromUint8Array(transaction)],
1828
- })).signatures.map(jsBase64.toUint8Array);
1829
- return signatures[0];
1830
- }
1831
- else {
1832
- throw new Error('connected wallet does not support signAndSendTransaction');
1833
- }
1834
- });
1835
- }
1836
- catch (e) {
1837
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1838
- }
1839
- };
1840
- #signAndSendTransaction = async (...inputs) => {
1841
- const outputs = [];
1842
- for (const input of inputs) {
1843
- const signature = (await this.#performSignAndSendTransaction(input.transaction, input.options));
1844
- outputs.push({ signature });
1845
- }
1846
- return outputs;
1847
- };
1848
- #signTransaction = async (...inputs) => {
1849
- return (await this.#performSignTransactions(inputs.map(({ transaction }) => transaction)))
1850
- .map((signedTransaction) => {
1851
- return { signedTransaction };
1852
- });
1853
- };
1854
- #signMessage = async (...inputs) => {
1855
- const { authToken, chain } = this.#assertIsAuthorized();
1856
- const addresses = inputs.map(({ account }) => jsBase64.fromUint8Array(new Uint8Array(account.publicKey)));
1857
- const messages = inputs.map(({ message }) => jsBase64.fromUint8Array(message));
1858
- try {
1859
- return await this.#transact(async (wallet) => {
1860
- await this.#performReauthorization(wallet, authToken, chain);
1861
- const signedMessages = (await wallet.signMessages({
1862
- addresses: addresses,
1863
- payloads: messages,
1864
- })).signed_payloads.map(jsBase64.toUint8Array);
1865
- return signedMessages.map((signedMessage) => {
1866
- return { signedMessage: signedMessage, signature: signedMessage.slice(-SIGNATURE_LENGTH_IN_BYTES) };
1867
- });
1868
- });
1869
- }
1870
- catch (e) {
1871
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1872
- }
1873
- };
1874
- #signIn = async (...inputs) => {
1875
- const outputs = [];
1876
- if (inputs.length > 1) {
1877
- for (const input of inputs) {
1878
- outputs.push(await this.#performSignIn(input));
1879
- }
1880
- }
1881
- else {
1882
- return [await this.#performSignIn(inputs[0])];
1883
- }
1884
- return outputs;
1885
- };
1886
- #performSignIn = async (input) => {
1887
- this.#connecting = true;
1888
- try {
1889
- const authorizationResult = await this.#performAuthorization({
1890
- ...input,
1891
- domain: input?.domain ?? window.location.host
1892
- });
1893
- if (!authorizationResult.sign_in_result) {
1894
- throw new Error("Sign in failed, no sign in result returned by wallet");
1895
- }
1896
- const signedInAddress = authorizationResult.sign_in_result.address;
1897
- const signedInAccount = authorizationResult.accounts.find(acc => acc.address == signedInAddress);
1898
- return {
1899
- account: {
1900
- ...signedInAccount ?? {
1901
- address: base58.encode(jsBase64.toUint8Array(signedInAddress))
1902
- },
1903
- publicKey: jsBase64.toUint8Array(signedInAddress),
1904
- chains: signedInAccount?.chains ?? this.#chains,
1905
- features: signedInAccount?.features ?? authorizationResult.capabilities.features
1906
- },
1907
- signedMessage: jsBase64.toUint8Array(authorizationResult.sign_in_result.signed_message),
1908
- signature: jsBase64.toUint8Array(authorizationResult.sign_in_result.signature)
1909
- };
1910
- }
1911
- catch (e) {
1912
- throw new Error((e instanceof Error && e.message) || 'Unknown error');
1913
- }
1914
- finally {
1915
- this.#connecting = false;
1916
- }
1917
- };
1918
- }
1919
-
1021
+ const DEFAULT_FEATURES = [
1022
+ _solana_wallet_standard_features.SolanaSignAndSendTransaction,
1023
+ _solana_wallet_standard_features.SolanaSignTransaction,
1024
+ _solana_wallet_standard_features.SolanaSignMessage,
1025
+ _solana_wallet_standard_features.SolanaSignIn
1026
+ ];
1027
+ const WALLET_ASSOCIATION_TIMEOUT = 3e4;
1028
+ function getErrorMessage(error) {
1029
+ return error instanceof Error ? error.message : "Unknown error";
1030
+ }
1031
+ var LocalSolanaMobileWalletAdapterWallet = class {
1032
+ #listeners = {};
1033
+ #version = "1.0.0";
1034
+ #name = SolanaMobileWalletAdapterWalletName;
1035
+ #url = "https://solanamobile.com/wallets";
1036
+ #icon = icon;
1037
+ #appIdentity;
1038
+ #authorization;
1039
+ #authorizationCache;
1040
+ #connecting = false;
1041
+ /**
1042
+ * Every time the connection is recycled in some way (eg. `disconnect()` is called)
1043
+ * increment this and use it to make sure that `transact` calls from the previous
1044
+ * 'generation' don't continue to do work and throw exceptions.
1045
+ */
1046
+ #connectionGeneration = 0;
1047
+ #chains = [];
1048
+ #chainSelector;
1049
+ #optionalFeatures;
1050
+ #onWalletNotFound;
1051
+ get version() {
1052
+ return this.#version;
1053
+ }
1054
+ get name() {
1055
+ return this.#name;
1056
+ }
1057
+ get url() {
1058
+ return this.#url;
1059
+ }
1060
+ get icon() {
1061
+ return this.#icon;
1062
+ }
1063
+ get chains() {
1064
+ return this.#chains;
1065
+ }
1066
+ get features() {
1067
+ return {
1068
+ [_wallet_standard_features.StandardConnect]: {
1069
+ version: "1.0.0",
1070
+ connect: this.#connect
1071
+ },
1072
+ [_wallet_standard_features.StandardDisconnect]: {
1073
+ version: "1.0.0",
1074
+ disconnect: this.#disconnect
1075
+ },
1076
+ [_wallet_standard_features.StandardEvents]: {
1077
+ version: "1.0.0",
1078
+ on: this.#on
1079
+ },
1080
+ [_solana_wallet_standard_features.SolanaSignMessage]: {
1081
+ version: "1.0.0",
1082
+ signMessage: this.#signMessage
1083
+ },
1084
+ [_solana_wallet_standard_features.SolanaSignIn]: {
1085
+ version: "1.0.0",
1086
+ signIn: this.#signIn
1087
+ },
1088
+ ...this.#optionalFeatures
1089
+ };
1090
+ }
1091
+ get accounts() {
1092
+ return this.#authorization?.accounts ?? [];
1093
+ }
1094
+ constructor(config) {
1095
+ this.#authorizationCache = config.authorizationCache;
1096
+ this.#appIdentity = config.appIdentity;
1097
+ this.#chains = config.chains;
1098
+ this.#chainSelector = config.chainSelector;
1099
+ this.#onWalletNotFound = config.onWalletNotFound;
1100
+ this.#optionalFeatures = {
1101
+ [_solana_wallet_standard_features.SolanaSignAndSendTransaction]: {
1102
+ version: "1.0.0",
1103
+ supportedTransactionVersions: ["legacy", 0],
1104
+ signAndSendTransaction: this.#signAndSendTransaction
1105
+ },
1106
+ [_solana_wallet_standard_features.SolanaSignTransaction]: {
1107
+ version: "1.0.0",
1108
+ supportedTransactionVersions: ["legacy", 0],
1109
+ signTransaction: this.#signTransaction
1110
+ }
1111
+ };
1112
+ }
1113
+ get connected() {
1114
+ return !!this.#authorization;
1115
+ }
1116
+ get isAuthorized() {
1117
+ return !!this.#authorization;
1118
+ }
1119
+ get currentAuthorization() {
1120
+ return this.#authorization;
1121
+ }
1122
+ get cachedAuthorizationResult() {
1123
+ return this.#authorizationCache.get();
1124
+ }
1125
+ #on = (event, listener) => {
1126
+ this.#listeners[event]?.push(listener) || (this.#listeners[event] = [listener]);
1127
+ return () => this.#off(event, listener);
1128
+ };
1129
+ #emit(event, ...args) {
1130
+ this.#listeners[event]?.forEach((listener) => listener.apply(null, args));
1131
+ }
1132
+ #off(event, listener) {
1133
+ this.#listeners[event] = this.#listeners[event]?.filter((existingListener) => listener !== existingListener);
1134
+ }
1135
+ #connect = async ({ silent } = {}) => {
1136
+ if (this.#connecting || this.connected) return { accounts: this.accounts };
1137
+ this.#connecting = true;
1138
+ try {
1139
+ if (silent) {
1140
+ const cachedAuthorization = await this.#authorizationCache.get();
1141
+ if (cachedAuthorization) {
1142
+ await this.#handleWalletCapabilitiesResult(cachedAuthorization.capabilities);
1143
+ await this.#handleAuthorizationResult(cachedAuthorization);
1144
+ } else return { accounts: this.accounts };
1145
+ } else await this.#performAuthorization();
1146
+ } catch (e) {
1147
+ throw new Error(getErrorMessage(e), { cause: e });
1148
+ } finally {
1149
+ this.#connecting = false;
1150
+ }
1151
+ return { accounts: this.accounts };
1152
+ };
1153
+ #performAuthorization = async (signInPayload) => {
1154
+ try {
1155
+ const cachedAuthorizationResult = await this.#authorizationCache.get();
1156
+ if (cachedAuthorizationResult) {
1157
+ this.#handleAuthorizationResult(cachedAuthorizationResult);
1158
+ return cachedAuthorizationResult;
1159
+ }
1160
+ const selectedChain = await this.#chainSelector.select(this.#chains);
1161
+ return await this.#transact(async (wallet) => {
1162
+ const [capabilities, mwaAuthorizationResult] = await Promise.all([wallet.getCapabilities(), wallet.authorize({
1163
+ chain: selectedChain,
1164
+ identity: this.#appIdentity,
1165
+ sign_in_payload: signInPayload
1166
+ })]);
1167
+ const accounts = this.#accountsToWalletStandardAccounts(mwaAuthorizationResult.accounts);
1168
+ const authorization = {
1169
+ ...mwaAuthorizationResult,
1170
+ accounts,
1171
+ chain: selectedChain,
1172
+ capabilities
1173
+ };
1174
+ Promise.all([
1175
+ this.#handleWalletCapabilitiesResult(capabilities),
1176
+ this.#authorizationCache.set(authorization),
1177
+ this.#handleAuthorizationResult(authorization)
1178
+ ]);
1179
+ return authorization;
1180
+ });
1181
+ } catch (e) {
1182
+ throw new Error(getErrorMessage(e), { cause: e });
1183
+ }
1184
+ };
1185
+ #handleAuthorizationResult = async (authorization) => {
1186
+ const didPublicKeysChange = this.#authorization == null || this.#authorization?.accounts.length !== authorization.accounts.length || this.#authorization.accounts.some((account, ii) => account.address !== authorization.accounts[ii].address);
1187
+ this.#authorization = authorization;
1188
+ if (didPublicKeysChange) this.#emit("change", { accounts: this.accounts });
1189
+ };
1190
+ #handleWalletCapabilitiesResult = async (capabilities) => {
1191
+ const supportsSignTransaction = capabilities.features.includes("solana:signTransactions");
1192
+ const supportsSignAndSendTransaction = capabilities.supports_sign_and_send_transactions;
1193
+ const didCapabilitiesChange = _solana_wallet_standard_features.SolanaSignAndSendTransaction in this.features !== supportsSignAndSendTransaction || _solana_wallet_standard_features.SolanaSignTransaction in this.features !== supportsSignTransaction;
1194
+ this.#optionalFeatures = {
1195
+ ...(supportsSignAndSendTransaction || !supportsSignAndSendTransaction && !supportsSignTransaction) && { [_solana_wallet_standard_features.SolanaSignAndSendTransaction]: {
1196
+ version: "1.0.0",
1197
+ supportedTransactionVersions: ["legacy", 0],
1198
+ signAndSendTransaction: this.#signAndSendTransaction
1199
+ } },
1200
+ ...supportsSignTransaction && { [_solana_wallet_standard_features.SolanaSignTransaction]: {
1201
+ version: "1.0.0",
1202
+ supportedTransactionVersions: ["legacy", 0],
1203
+ signTransaction: this.#signTransaction
1204
+ } }
1205
+ };
1206
+ if (didCapabilitiesChange) this.#emit("change", { features: this.features });
1207
+ };
1208
+ #performReauthorization = async (wallet, authToken, chain) => {
1209
+ try {
1210
+ const [capabilities, mwaAuthorizationResult] = await Promise.all([this.#authorization?.capabilities ?? await wallet.getCapabilities(), wallet.authorize({
1211
+ auth_token: authToken,
1212
+ identity: this.#appIdentity,
1213
+ chain
1214
+ })]);
1215
+ const accounts = this.#accountsToWalletStandardAccounts(mwaAuthorizationResult.accounts);
1216
+ const authorization = {
1217
+ ...mwaAuthorizationResult,
1218
+ accounts,
1219
+ chain,
1220
+ capabilities
1221
+ };
1222
+ Promise.all([this.#authorizationCache.set(authorization), this.#handleAuthorizationResult(authorization)]);
1223
+ } catch (e) {
1224
+ this.#disconnect();
1225
+ throw new Error(getErrorMessage(e), { cause: e });
1226
+ }
1227
+ };
1228
+ #disconnect = async () => {
1229
+ this.#authorizationCache.clear();
1230
+ this.#connecting = false;
1231
+ this.#connectionGeneration++;
1232
+ this.#authorization = void 0;
1233
+ this.#emit("change", { accounts: this.accounts });
1234
+ };
1235
+ #transact = async (callback) => {
1236
+ const walletUriBase = this.#authorization?.wallet_uri_base;
1237
+ const config = walletUriBase ? { baseUri: walletUriBase } : void 0;
1238
+ const currentConnectionGeneration = this.#connectionGeneration;
1239
+ const loadingSpinner = new EmbeddedLoadingSpinner();
1240
+ try {
1241
+ let associating = true;
1242
+ let timeout = void 0;
1243
+ const result = await Promise.race([checkLocalNetworkAccessPermission().then(async () => {
1244
+ loadingSpinner.init();
1245
+ const { wallet, close } = await (0, _solana_mobile_mobile_wallet_adapter_protocol.startScenario)(config);
1246
+ associating = false;
1247
+ loadingSpinner.addEventListener("close", (event) => {
1248
+ if (event) close();
1249
+ });
1250
+ loadingSpinner.open();
1251
+ const result = await callback(await wallet);
1252
+ loadingSpinner.close();
1253
+ close();
1254
+ return result;
1255
+ }), new Promise((_, reject) => {
1256
+ timeout = setTimeout(() => {
1257
+ if (associating) reject(new _solana_mobile_mobile_wallet_adapter_protocol.SolanaMobileWalletAdapterError(_solana_mobile_mobile_wallet_adapter_protocol.SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_CANCELLED, "Wallet connection timed out", { event: void 0 }));
1258
+ }, WALLET_ASSOCIATION_TIMEOUT);
1259
+ })]);
1260
+ clearTimeout(timeout);
1261
+ return result;
1262
+ } catch (e) {
1263
+ loadingSpinner.close();
1264
+ if (this.#connectionGeneration !== currentConnectionGeneration) await new Promise(() => {});
1265
+ if (e instanceof Error && e.name === "SolanaMobileWalletAdapterError" && e.code === "ERROR_WALLET_NOT_FOUND") await this.#onWalletNotFound(this);
1266
+ throw e;
1267
+ }
1268
+ };
1269
+ #assertIsAuthorized = () => {
1270
+ if (!this.#authorization) throw new Error("Wallet not connected");
1271
+ return {
1272
+ authToken: this.#authorization.auth_token,
1273
+ chain: this.#authorization.chain
1274
+ };
1275
+ };
1276
+ #accountsToWalletStandardAccounts = (accounts) => {
1277
+ return accounts.map((account) => {
1278
+ const publicKey = (0, js_base64.toUint8Array)(account.address);
1279
+ return {
1280
+ address: bs58.default.encode(publicKey),
1281
+ publicKey,
1282
+ label: account.label,
1283
+ icon: account.icon,
1284
+ chains: account.chains ?? this.#chains,
1285
+ features: account.features ?? DEFAULT_FEATURES
1286
+ };
1287
+ });
1288
+ };
1289
+ #performSignTransactions = async (transactions) => {
1290
+ const { authToken, chain } = this.#assertIsAuthorized();
1291
+ try {
1292
+ const base64Transactions = transactions.map((tx) => {
1293
+ return (0, js_base64.fromUint8Array)(tx);
1294
+ });
1295
+ return await this.#transact(async (wallet) => {
1296
+ await this.#performReauthorization(wallet, authToken, chain);
1297
+ return (await wallet.signTransactions({ payloads: base64Transactions })).signed_payloads.map(js_base64.toUint8Array);
1298
+ });
1299
+ } catch (e) {
1300
+ throw new Error(getErrorMessage(e), { cause: e });
1301
+ }
1302
+ };
1303
+ #performSignAndSendTransaction = async (transaction, options) => {
1304
+ const { authToken, chain } = this.#assertIsAuthorized();
1305
+ try {
1306
+ return await this.#transact(async (wallet) => {
1307
+ const [capabilities] = await Promise.all([wallet.getCapabilities(), this.#performReauthorization(wallet, authToken, chain)]);
1308
+ if (capabilities.supports_sign_and_send_transactions) {
1309
+ const base64Transaction = (0, js_base64.fromUint8Array)(transaction);
1310
+ return (await wallet.signAndSendTransactions({
1311
+ ...options,
1312
+ payloads: [base64Transaction]
1313
+ })).signatures.map(js_base64.toUint8Array)[0];
1314
+ } else throw new Error("connected wallet does not support signAndSendTransaction");
1315
+ });
1316
+ } catch (e) {
1317
+ throw new Error(getErrorMessage(e), { cause: e });
1318
+ }
1319
+ };
1320
+ #signAndSendTransaction = async (...inputs) => {
1321
+ const outputs = [];
1322
+ for (const input of inputs) {
1323
+ const signature = await this.#performSignAndSendTransaction(input.transaction, input.options);
1324
+ outputs.push({ signature });
1325
+ }
1326
+ return outputs;
1327
+ };
1328
+ #signTransaction = async (...inputs) => {
1329
+ return (await this.#performSignTransactions(inputs.map(({ transaction }) => transaction))).map((signedTransaction) => {
1330
+ return { signedTransaction };
1331
+ });
1332
+ };
1333
+ #signMessage = async (...inputs) => {
1334
+ const { authToken, chain } = this.#assertIsAuthorized();
1335
+ const addresses = inputs.map(({ account }) => (0, js_base64.fromUint8Array)(new Uint8Array(account.publicKey)));
1336
+ const messages = inputs.map(({ message }) => (0, js_base64.fromUint8Array)(message));
1337
+ try {
1338
+ return await this.#transact(async (wallet) => {
1339
+ await this.#performReauthorization(wallet, authToken, chain);
1340
+ return (await wallet.signMessages({
1341
+ addresses,
1342
+ payloads: messages
1343
+ })).signed_payloads.map(js_base64.toUint8Array).map((signedMessage) => {
1344
+ return {
1345
+ signedMessage,
1346
+ signature: signedMessage.slice(-SIGNATURE_LENGTH_IN_BYTES)
1347
+ };
1348
+ });
1349
+ });
1350
+ } catch (e) {
1351
+ throw new Error(getErrorMessage(e), { cause: e });
1352
+ }
1353
+ };
1354
+ #signIn = async (...inputs) => {
1355
+ const outputs = [];
1356
+ if (inputs.length > 1) for (const input of inputs) outputs.push(await this.#performSignIn(input));
1357
+ else return [await this.#performSignIn(inputs[0])];
1358
+ return outputs;
1359
+ };
1360
+ #performSignIn = async (input) => {
1361
+ this.#connecting = true;
1362
+ try {
1363
+ const authorizationResult = await this.#performAuthorization({
1364
+ ...input,
1365
+ domain: input?.domain ?? window.location.host
1366
+ });
1367
+ if (!authorizationResult.sign_in_result) throw new Error("Sign in failed, no sign in result returned by wallet");
1368
+ const signedInAddress = authorizationResult.sign_in_result.address;
1369
+ const signedInAccount = authorizationResult.accounts.find((acc) => acc.address == signedInAddress);
1370
+ return {
1371
+ account: {
1372
+ ...signedInAccount ?? { address: bs58.default.encode((0, js_base64.toUint8Array)(signedInAddress)) },
1373
+ publicKey: (0, js_base64.toUint8Array)(signedInAddress),
1374
+ chains: signedInAccount?.chains ?? this.#chains,
1375
+ features: signedInAccount?.features ?? authorizationResult.capabilities.features
1376
+ },
1377
+ signedMessage: (0, js_base64.toUint8Array)(authorizationResult.sign_in_result.signed_message),
1378
+ signature: (0, js_base64.toUint8Array)(authorizationResult.sign_in_result.signature)
1379
+ };
1380
+ } catch (e) {
1381
+ throw new Error(getErrorMessage(e), { cause: e });
1382
+ } finally {
1383
+ this.#connecting = false;
1384
+ }
1385
+ };
1386
+ };
1387
+ var RemoteSolanaMobileWalletAdapterWallet = class {
1388
+ #listeners = {};
1389
+ #version = "1.0.0";
1390
+ #name = SolanaMobileWalletAdapterRemoteWalletName;
1391
+ #url = "https://solanamobile.com/wallets";
1392
+ #icon = icon;
1393
+ #appIdentity;
1394
+ #authorization;
1395
+ #authorizationCache;
1396
+ #connecting = false;
1397
+ /**
1398
+ * Every time the connection is recycled in some way (eg. `disconnect()` is called)
1399
+ * increment this and use it to make sure that `transact` calls from the previous
1400
+ * 'generation' don't continue to do work and throw exceptions.
1401
+ */
1402
+ #connectionGeneration = 0;
1403
+ #chains = [];
1404
+ #chainSelector;
1405
+ #optionalFeatures;
1406
+ #onWalletNotFound;
1407
+ #hostAuthority;
1408
+ #session;
1409
+ get version() {
1410
+ return this.#version;
1411
+ }
1412
+ get name() {
1413
+ return this.#name;
1414
+ }
1415
+ get url() {
1416
+ return this.#url;
1417
+ }
1418
+ get icon() {
1419
+ return this.#icon;
1420
+ }
1421
+ get chains() {
1422
+ return this.#chains;
1423
+ }
1424
+ get features() {
1425
+ return {
1426
+ [_wallet_standard_features.StandardConnect]: {
1427
+ version: "1.0.0",
1428
+ connect: this.#connect
1429
+ },
1430
+ [_wallet_standard_features.StandardDisconnect]: {
1431
+ version: "1.0.0",
1432
+ disconnect: this.#disconnect
1433
+ },
1434
+ [_wallet_standard_features.StandardEvents]: {
1435
+ version: "1.0.0",
1436
+ on: this.#on
1437
+ },
1438
+ [_solana_wallet_standard_features.SolanaSignMessage]: {
1439
+ version: "1.0.0",
1440
+ signMessage: this.#signMessage
1441
+ },
1442
+ [_solana_wallet_standard_features.SolanaSignIn]: {
1443
+ version: "1.0.0",
1444
+ signIn: this.#signIn
1445
+ },
1446
+ ...this.#optionalFeatures
1447
+ };
1448
+ }
1449
+ get accounts() {
1450
+ return this.#authorization?.accounts ?? [];
1451
+ }
1452
+ constructor(config) {
1453
+ this.#authorizationCache = config.authorizationCache;
1454
+ this.#appIdentity = config.appIdentity;
1455
+ this.#chains = config.chains;
1456
+ this.#chainSelector = config.chainSelector;
1457
+ this.#hostAuthority = config.remoteHostAuthority;
1458
+ this.#onWalletNotFound = config.onWalletNotFound;
1459
+ this.#optionalFeatures = {
1460
+ [_solana_wallet_standard_features.SolanaSignAndSendTransaction]: {
1461
+ version: "1.0.0",
1462
+ supportedTransactionVersions: ["legacy", 0],
1463
+ signAndSendTransaction: this.#signAndSendTransaction
1464
+ },
1465
+ [_solana_wallet_standard_features.SolanaSignTransaction]: {
1466
+ version: "1.0.0",
1467
+ supportedTransactionVersions: ["legacy", 0],
1468
+ signTransaction: this.#signTransaction
1469
+ }
1470
+ };
1471
+ }
1472
+ get connected() {
1473
+ return !!this.#session && !!this.#authorization;
1474
+ }
1475
+ get isAuthorized() {
1476
+ return !!this.#authorization;
1477
+ }
1478
+ get currentAuthorization() {
1479
+ return this.#authorization;
1480
+ }
1481
+ get cachedAuthorizationResult() {
1482
+ return this.#authorizationCache.get();
1483
+ }
1484
+ #on = (event, listener) => {
1485
+ this.#listeners[event]?.push(listener) || (this.#listeners[event] = [listener]);
1486
+ return () => this.#off(event, listener);
1487
+ };
1488
+ #emit(event, ...args) {
1489
+ this.#listeners[event]?.forEach((listener) => listener.apply(null, args));
1490
+ }
1491
+ #off(event, listener) {
1492
+ this.#listeners[event] = this.#listeners[event]?.filter((existingListener) => listener !== existingListener);
1493
+ }
1494
+ #connect = async (_input = {}) => {
1495
+ if (this.#connecting || this.connected) return { accounts: this.accounts };
1496
+ this.#connecting = true;
1497
+ try {
1498
+ await this.#performAuthorization();
1499
+ } catch (e) {
1500
+ throw new Error(getErrorMessage(e), { cause: e });
1501
+ } finally {
1502
+ this.#connecting = false;
1503
+ }
1504
+ return { accounts: this.accounts };
1505
+ };
1506
+ #performAuthorization = async (signInPayload) => {
1507
+ try {
1508
+ const cachedAuthorizationResult = await this.#authorizationCache.get();
1509
+ if (cachedAuthorizationResult) {
1510
+ this.#handleAuthorizationResult(cachedAuthorizationResult);
1511
+ return cachedAuthorizationResult;
1512
+ }
1513
+ if (this.#session) this.#session = void 0;
1514
+ const selectedChain = await this.#chainSelector.select(this.#chains);
1515
+ return await this.#transact(async (wallet) => {
1516
+ const [capabilities, mwaAuthorizationResult] = await Promise.all([wallet.getCapabilities(), wallet.authorize({
1517
+ chain: selectedChain,
1518
+ identity: this.#appIdentity,
1519
+ sign_in_payload: signInPayload
1520
+ })]);
1521
+ const accounts = this.#accountsToWalletStandardAccounts(mwaAuthorizationResult.accounts);
1522
+ const authorizationResult = {
1523
+ ...mwaAuthorizationResult,
1524
+ accounts,
1525
+ chain: selectedChain,
1526
+ capabilities
1527
+ };
1528
+ Promise.all([
1529
+ this.#handleWalletCapabilitiesResult(capabilities),
1530
+ this.#authorizationCache.set(authorizationResult),
1531
+ this.#handleAuthorizationResult(authorizationResult)
1532
+ ]);
1533
+ return authorizationResult;
1534
+ });
1535
+ } catch (e) {
1536
+ throw new Error(getErrorMessage(e), { cause: e });
1537
+ }
1538
+ };
1539
+ #handleAuthorizationResult = async (authorization) => {
1540
+ const didPublicKeysChange = this.#authorization == null || this.#authorization?.accounts.length !== authorization.accounts.length || this.#authorization.accounts.some((account, ii) => account.address !== authorization.accounts[ii].address);
1541
+ this.#authorization = authorization;
1542
+ if (didPublicKeysChange) this.#emit("change", { accounts: this.accounts });
1543
+ };
1544
+ #handleWalletCapabilitiesResult = async (capabilities) => {
1545
+ const supportsSignTransaction = capabilities.features.includes("solana:signTransactions");
1546
+ const supportsSignAndSendTransaction = capabilities.supports_sign_and_send_transactions || capabilities.features.includes("solana:signAndSendTransaction");
1547
+ const didCapabilitiesChange = _solana_wallet_standard_features.SolanaSignAndSendTransaction in this.features !== supportsSignAndSendTransaction || _solana_wallet_standard_features.SolanaSignTransaction in this.features !== supportsSignTransaction;
1548
+ this.#optionalFeatures = {
1549
+ ...supportsSignAndSendTransaction && { [_solana_wallet_standard_features.SolanaSignAndSendTransaction]: {
1550
+ version: "1.0.0",
1551
+ supportedTransactionVersions: capabilities.supported_transaction_versions,
1552
+ signAndSendTransaction: this.#signAndSendTransaction
1553
+ } },
1554
+ ...supportsSignTransaction && { [_solana_wallet_standard_features.SolanaSignTransaction]: {
1555
+ version: "1.0.0",
1556
+ supportedTransactionVersions: capabilities.supported_transaction_versions,
1557
+ signTransaction: this.#signTransaction
1558
+ } }
1559
+ };
1560
+ if (didCapabilitiesChange) this.#emit("change", { features: this.features });
1561
+ };
1562
+ #performReauthorization = async (wallet, authToken, chain) => {
1563
+ try {
1564
+ const [capabilities, mwaAuthorizationResult] = await Promise.all([this.#authorization?.capabilities ?? await wallet.getCapabilities(), wallet.authorize({
1565
+ auth_token: authToken,
1566
+ identity: this.#appIdentity,
1567
+ chain
1568
+ })]);
1569
+ const accounts = this.#accountsToWalletStandardAccounts(mwaAuthorizationResult.accounts);
1570
+ const authorization = {
1571
+ ...mwaAuthorizationResult,
1572
+ accounts,
1573
+ chain,
1574
+ capabilities
1575
+ };
1576
+ Promise.all([this.#authorizationCache.set(authorization), this.#handleAuthorizationResult(authorization)]);
1577
+ } catch (e) {
1578
+ this.#disconnect();
1579
+ throw new Error(getErrorMessage(e), { cause: e });
1580
+ }
1581
+ };
1582
+ #disconnect = async () => {
1583
+ this.#session?.close();
1584
+ this.#authorizationCache.clear();
1585
+ this.#connecting = false;
1586
+ this.#connectionGeneration++;
1587
+ this.#authorization = void 0;
1588
+ this.#session = void 0;
1589
+ this.#emit("change", { accounts: this.accounts });
1590
+ };
1591
+ #transact = async (callback) => {
1592
+ const walletUriBase = this.#authorization?.wallet_uri_base;
1593
+ const remoteConfig = {
1594
+ ...walletUriBase ? { baseUri: walletUriBase } : void 0,
1595
+ remoteHostAuthority: this.#hostAuthority
1596
+ };
1597
+ const currentConnectionGeneration = this.#connectionGeneration;
1598
+ const modal = new RemoteConnectionModal();
1599
+ if (this.#session) return callback(this.#session.wallet);
1600
+ try {
1601
+ modal.init();
1602
+ modal.open();
1603
+ const { associationUrl, close, wallet } = await (0, _solana_mobile_mobile_wallet_adapter_protocol.startRemoteScenario)(remoteConfig);
1604
+ const removeCloseListener = modal.addEventListener("close", (event) => {
1605
+ if (event) close();
1606
+ });
1607
+ modal.populateQRCode(associationUrl.toString());
1608
+ this.#session = {
1609
+ close,
1610
+ wallet: await wallet
1611
+ };
1612
+ removeCloseListener();
1613
+ modal.close();
1614
+ return await callback(this.#session.wallet);
1615
+ } catch (e) {
1616
+ modal.close();
1617
+ if (this.#connectionGeneration !== currentConnectionGeneration) await new Promise(() => {});
1618
+ if (e instanceof Error && e.name === "SolanaMobileWalletAdapterError" && e.code === "ERROR_WALLET_NOT_FOUND") await this.#onWalletNotFound(this);
1619
+ throw e;
1620
+ }
1621
+ };
1622
+ #assertIsAuthorized = () => {
1623
+ if (!this.#authorization) throw new Error("Wallet not connected");
1624
+ return {
1625
+ authToken: this.#authorization.auth_token,
1626
+ chain: this.#authorization.chain
1627
+ };
1628
+ };
1629
+ #accountsToWalletStandardAccounts = (accounts) => {
1630
+ return accounts.map((account) => {
1631
+ const publicKey = (0, js_base64.toUint8Array)(account.address);
1632
+ return {
1633
+ address: bs58.default.encode(publicKey),
1634
+ publicKey,
1635
+ label: account.label,
1636
+ icon: account.icon,
1637
+ chains: account.chains ?? this.#chains,
1638
+ features: account.features ?? DEFAULT_FEATURES
1639
+ };
1640
+ });
1641
+ };
1642
+ #performSignTransactions = async (transactions) => {
1643
+ const { authToken, chain } = this.#assertIsAuthorized();
1644
+ try {
1645
+ return await this.#transact(async (wallet) => {
1646
+ await this.#performReauthorization(wallet, authToken, chain);
1647
+ return (await wallet.signTransactions({ payloads: transactions.map(js_base64.fromUint8Array) })).signed_payloads.map(js_base64.toUint8Array);
1648
+ });
1649
+ } catch (e) {
1650
+ throw new Error(getErrorMessage(e), { cause: e });
1651
+ }
1652
+ };
1653
+ #performSignAndSendTransaction = async (transaction, options) => {
1654
+ const { authToken, chain } = this.#assertIsAuthorized();
1655
+ try {
1656
+ return await this.#transact(async (wallet) => {
1657
+ const [capabilities] = await Promise.all([wallet.getCapabilities(), this.#performReauthorization(wallet, authToken, chain)]);
1658
+ if (capabilities.supports_sign_and_send_transactions) return (await wallet.signAndSendTransactions({
1659
+ ...options,
1660
+ payloads: [(0, js_base64.fromUint8Array)(transaction)]
1661
+ })).signatures.map(js_base64.toUint8Array)[0];
1662
+ else throw new Error("connected wallet does not support signAndSendTransaction");
1663
+ });
1664
+ } catch (e) {
1665
+ throw new Error(getErrorMessage(e), { cause: e });
1666
+ }
1667
+ };
1668
+ #signAndSendTransaction = async (...inputs) => {
1669
+ const outputs = [];
1670
+ for (const input of inputs) {
1671
+ const signature = await this.#performSignAndSendTransaction(input.transaction, input.options);
1672
+ outputs.push({ signature });
1673
+ }
1674
+ return outputs;
1675
+ };
1676
+ #signTransaction = async (...inputs) => {
1677
+ return (await this.#performSignTransactions(inputs.map(({ transaction }) => transaction))).map((signedTransaction) => {
1678
+ return { signedTransaction };
1679
+ });
1680
+ };
1681
+ #signMessage = async (...inputs) => {
1682
+ const { authToken, chain } = this.#assertIsAuthorized();
1683
+ const addresses = inputs.map(({ account }) => (0, js_base64.fromUint8Array)(new Uint8Array(account.publicKey)));
1684
+ const messages = inputs.map(({ message }) => (0, js_base64.fromUint8Array)(message));
1685
+ try {
1686
+ return await this.#transact(async (wallet) => {
1687
+ await this.#performReauthorization(wallet, authToken, chain);
1688
+ return (await wallet.signMessages({
1689
+ addresses,
1690
+ payloads: messages
1691
+ })).signed_payloads.map(js_base64.toUint8Array).map((signedMessage) => {
1692
+ return {
1693
+ signedMessage,
1694
+ signature: signedMessage.slice(-SIGNATURE_LENGTH_IN_BYTES)
1695
+ };
1696
+ });
1697
+ });
1698
+ } catch (e) {
1699
+ throw new Error(getErrorMessage(e), { cause: e });
1700
+ }
1701
+ };
1702
+ #signIn = async (...inputs) => {
1703
+ const outputs = [];
1704
+ if (inputs.length > 1) for (const input of inputs) outputs.push(await this.#performSignIn(input));
1705
+ else return [await this.#performSignIn(inputs[0])];
1706
+ return outputs;
1707
+ };
1708
+ #performSignIn = async (input) => {
1709
+ this.#connecting = true;
1710
+ try {
1711
+ const authorizationResult = await this.#performAuthorization({
1712
+ ...input,
1713
+ domain: input?.domain ?? window.location.host
1714
+ });
1715
+ if (!authorizationResult.sign_in_result) throw new Error("Sign in failed, no sign in result returned by wallet");
1716
+ const signedInAddress = authorizationResult.sign_in_result.address;
1717
+ const signedInAccount = authorizationResult.accounts.find((acc) => acc.address == signedInAddress);
1718
+ return {
1719
+ account: {
1720
+ ...signedInAccount ?? { address: bs58.default.encode((0, js_base64.toUint8Array)(signedInAddress)) },
1721
+ publicKey: (0, js_base64.toUint8Array)(signedInAddress),
1722
+ chains: signedInAccount?.chains ?? this.#chains,
1723
+ features: signedInAccount?.features ?? authorizationResult.capabilities.features
1724
+ },
1725
+ signedMessage: (0, js_base64.toUint8Array)(authorizationResult.sign_in_result.signed_message),
1726
+ signature: (0, js_base64.toUint8Array)(authorizationResult.sign_in_result.signature)
1727
+ };
1728
+ } catch (e) {
1729
+ throw new Error(getErrorMessage(e), { cause: e });
1730
+ } finally {
1731
+ this.#connecting = false;
1732
+ }
1733
+ };
1734
+ };
1735
+ //#endregion
1736
+ //#region src/initialize.ts
1920
1737
  function registerMwa(config) {
1921
- if (typeof window === 'undefined') {
1922
- console.warn(`MWA not registered: no window object`);
1923
- return;
1924
- }
1925
- if (!window.isSecureContext) {
1926
- console.warn(`MWA not registered: secure context required (https)`);
1927
- return;
1928
- }
1929
- // Local association technically is possible in a webview, but we prevent registration
1930
- // by default because it usually fails in the most common cases (e.g wallet browsers).
1931
- if (getIsLocalAssociationSupported() && !isWebView(navigator.userAgent)) {
1932
- wallet.registerWallet(new LocalSolanaMobileWalletAdapterWallet(config));
1933
- }
1934
- else if (getIsRemoteAssociationSupported() && config.remoteHostAuthority !== undefined) {
1935
- wallet.registerWallet(new RemoteSolanaMobileWalletAdapterWallet({ ...config, remoteHostAuthority: config.remoteHostAuthority }));
1936
- }
1937
- else ;
1938
- }
1939
-
1940
- const WALLET_NOT_FOUND_ERROR_MESSAGE = 'To use mobile wallet adapter, you must have a compatible mobile wallet application installed on your device.';
1941
- const BROWSER_NOT_SUPPORTED_ERROR_MESSAGE = 'This browser appears to be incompatible with mobile wallet adapter. Open this page in a compatible mobile browser app and try again.';
1942
- class ErrorModal extends EmbeddedModal {
1943
- contentStyles = css;
1944
- contentHtml = ErrorDialogHtml;
1945
- initWithError(error) {
1946
- super.init();
1947
- this.populateError(error);
1948
- }
1949
- populateError(error) {
1950
- const errorMessageElement = this.dom?.getElementById('mobile-wallet-adapter-error-message');
1951
- const actionBtn = this.dom?.getElementById('mobile-wallet-adapter-error-action');
1952
- if (errorMessageElement) {
1953
- if (error.name === 'SolanaMobileWalletAdapterError') {
1954
- switch (error.code) {
1955
- case 'ERROR_WALLET_NOT_FOUND':
1956
- errorMessageElement.innerHTML = WALLET_NOT_FOUND_ERROR_MESSAGE;
1957
- if (actionBtn)
1958
- actionBtn.addEventListener('click', () => {
1959
- window.location.href = 'https://solanamobile.com/wallets';
1960
- });
1961
- return;
1962
- case 'ERROR_BROWSER_NOT_SUPPORTED':
1963
- errorMessageElement.innerHTML = BROWSER_NOT_SUPPORTED_ERROR_MESSAGE;
1964
- if (actionBtn)
1965
- actionBtn.style.display = 'none';
1966
- return;
1967
- }
1968
- }
1969
- errorMessageElement.innerHTML = `An unexpected error occurred: ${error.message}`;
1970
- }
1971
- else {
1972
- console.log('Failed to locate error dialog element');
1973
- }
1974
- }
1975
- }
1738
+ if (typeof window === "undefined") {
1739
+ console.warn(`MWA not registered: no window object`);
1740
+ return;
1741
+ }
1742
+ if (!window.isSecureContext) {
1743
+ console.warn(`MWA not registered: secure context required (https)`);
1744
+ return;
1745
+ }
1746
+ const userAgent = navigator.userAgent;
1747
+ if (getIsLocalAssociationSupported() && (!isWebView(userAgent) || isSolanaMobileWebShell(userAgent))) (0, _wallet_standard_wallet.registerWallet)(new LocalSolanaMobileWalletAdapterWallet(config));
1748
+ else if (getIsRemoteAssociationSupported() && config.remoteHostAuthority !== void 0) (0, _wallet_standard_wallet.registerWallet)(new RemoteSolanaMobileWalletAdapterWallet({
1749
+ ...config,
1750
+ remoteHostAuthority: config.remoteHostAuthority
1751
+ }));
1752
+ }
1753
+ //#endregion
1754
+ //#region src/embedded-modal/errorModal.ts
1755
+ const WALLET_NOT_FOUND_ERROR_MESSAGE = "To use mobile wallet adapter, you must have a compatible mobile wallet application installed on your device.";
1756
+ const BROWSER_NOT_SUPPORTED_ERROR_MESSAGE = "This browser appears to be incompatible with mobile wallet adapter. Open this page in a compatible mobile browser app and try again.";
1757
+ var ErrorModal = class extends EmbeddedModal {
1758
+ contentStyles = css;
1759
+ contentHtml = ErrorDialogHtml;
1760
+ initWithError(error) {
1761
+ super.init();
1762
+ this.populateError(error);
1763
+ }
1764
+ populateError(error) {
1765
+ const errorMessageElement = this.dom?.getElementById("mobile-wallet-adapter-error-message");
1766
+ const actionBtn = this.dom?.getElementById("mobile-wallet-adapter-error-action");
1767
+ if (errorMessageElement) {
1768
+ if (error.name === "SolanaMobileWalletAdapterError") switch (error.code) {
1769
+ case "ERROR_WALLET_NOT_FOUND":
1770
+ errorMessageElement.innerHTML = WALLET_NOT_FOUND_ERROR_MESSAGE;
1771
+ if (actionBtn) actionBtn.addEventListener("click", () => {
1772
+ window.location.href = "https://solanamobile.com/wallets";
1773
+ });
1774
+ return;
1775
+ case "ERROR_BROWSER_NOT_SUPPORTED":
1776
+ errorMessageElement.innerHTML = BROWSER_NOT_SUPPORTED_ERROR_MESSAGE;
1777
+ if (actionBtn) actionBtn.style.display = "none";
1778
+ return;
1779
+ }
1780
+ errorMessageElement.innerHTML = `An unexpected error occurred: ${error.message}`;
1781
+ } else console.log("Failed to locate error dialog element");
1782
+ }
1783
+ };
1976
1784
  const ErrorDialogHtml = `
1977
1785
  <svg class="mobile-wallet-adapter-embedded-modal-error-icon" xmlns="http://www.w3.org/2000/svg" height="50px" viewBox="0 -960 960 960" width="50px" fill="#000000"><path d="M 280,-80 Q 197,-80 138.5,-138.5 80,-197 80,-280 80,-363 138.5,-421.5 197,-480 280,-480 q 83,0 141.5,58.5 58.5,58.5 58.5,141.5 0,83 -58.5,141.5 Q 363,-80 280,-80 Z M 824,-120 568,-376 Q 556,-389 542.5,-402.5 529,-416 516,-428 q 38,-24 61,-64 23,-40 23,-88 0,-75 -52.5,-127.5 Q 495,-760 420,-760 345,-760 292.5,-707.5 240,-655 240,-580 q 0,6 0.5,11.5 0.5,5.5 1.5,11.5 -18,2 -39.5,8 -21.5,6 -38.5,14 -2,-11 -3,-22 -1,-11 -1,-23 0,-109 75.5,-184.5 Q 311,-840 420,-840 q 109,0 184.5,75.5 75.5,75.5 75.5,184.5 0,43 -13.5,81.5 Q 653,-460 629,-428 l 251,252 z m -615,-61 71,-71 70,71 29,-28 -71,-71 71,-71 -28,-28 -71,71 -71,-71 -28,28 71,71 -71,71 z"/></svg>
1978
1786
  <div class="mobile-wallet-adapter-embedded-modal-title">We can't find a wallet.</div>
@@ -2032,102 +1840,74 @@ const css = `
2032
1840
  }
2033
1841
  }
2034
1842
  `;
2035
-
1843
+ //#endregion
1844
+ //#region src/createDefaultWalletNotFoundHandler.ts
2036
1845
  async function defaultErrorModalWalletNotFoundHandler() {
2037
- if (typeof window !== 'undefined') {
2038
- const userAgent = window.navigator.userAgent.toLowerCase();
2039
- const errorDialog = new ErrorModal();
2040
- if (userAgent.includes('wv')) { // Android WebView
2041
- // MWA is not supported in this browser so we inform the user
2042
- // errorDialog.initWithError(
2043
- // new SolanaMobileWalletAdapterError(
2044
- // SolanaMobileWalletAdapterErrorCode.ERROR_BROWSER_NOT_SUPPORTED,
2045
- // ''
2046
- // )
2047
- // );
2048
- // TODO: investigate why instantiating a new SolanaMobileWalletAdapterError here breaks treeshaking
2049
- errorDialog.initWithError({
2050
- name: 'SolanaMobileWalletAdapterError',
2051
- code: 'ERROR_BROWSER_NOT_SUPPORTED',
2052
- message: ''
2053
- });
2054
- }
2055
- else { // Browser, user does not have a wallet installed.
2056
- // errorDialog.initWithError(
2057
- // new SolanaMobileWalletAdapterError(
2058
- // SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND,
2059
- // ''
2060
- // )
2061
- // );
2062
- // TODO: investigate why instantiating a new SolanaMobileWalletAdapterError here breaks treeshaking
2063
- errorDialog.initWithError({
2064
- name: 'SolanaMobileWalletAdapterError',
2065
- code: 'ERROR_WALLET_NOT_FOUND',
2066
- message: ''
2067
- });
2068
- }
2069
- errorDialog.open();
2070
- }
1846
+ if (typeof window !== "undefined") {
1847
+ const userAgent = window.navigator.userAgent.toLowerCase();
1848
+ const errorDialog = new ErrorModal();
1849
+ if (userAgent.includes("wv")) errorDialog.initWithError({
1850
+ name: "SolanaMobileWalletAdapterError",
1851
+ code: "ERROR_BROWSER_NOT_SUPPORTED",
1852
+ message: ""
1853
+ });
1854
+ else errorDialog.initWithError({
1855
+ name: "SolanaMobileWalletAdapterError",
1856
+ code: "ERROR_WALLET_NOT_FOUND",
1857
+ message: ""
1858
+ });
1859
+ errorDialog.open();
1860
+ }
2071
1861
  }
2072
1862
  function createDefaultWalletNotFoundHandler() {
2073
- return async () => { defaultErrorModalWalletNotFoundHandler(); };
1863
+ return async () => {
1864
+ defaultErrorModalWalletNotFoundHandler();
1865
+ };
2074
1866
  }
2075
-
2076
- const CACHE_KEY = 'SolanaMobileWalletAdapterWalletStandardDefaultAuthorizationCache';
1867
+ //#endregion
1868
+ //#region src/__forks__/react-native/createDefaultAuthorizationCache.ts
1869
+ const CACHE_KEY = "SolanaMobileWalletAdapterWalletStandardDefaultAuthorizationCache";
2077
1870
  function createDefaultAuthorizationCache() {
2078
- return {
2079
- async clear() {
2080
- try {
2081
- await AsyncStorage.removeItem(CACHE_KEY);
2082
- // eslint-disable-next-line no-empty
2083
- }
2084
- catch { }
2085
- },
2086
- async get() {
2087
- try {
2088
- const parsed = JSON.parse((await AsyncStorage.getItem(CACHE_KEY)));
2089
- if (parsed && parsed.accounts) {
2090
- const parsedAccounts = parsed.accounts.map((account) => {
2091
- return {
2092
- ...account,
2093
- publicKey: 'publicKey' in account
2094
- ? new Uint8Array(Object.values(account.publicKey)) // Rebuild publicKey for WalletAccount
2095
- : base58.decode(account.address), // Fallback, get publicKey from address
2096
- };
2097
- });
2098
- return { ...parsed, accounts: parsedAccounts };
2099
- }
2100
- else
2101
- return parsed || undefined;
2102
- // eslint-disable-next-line no-empty
2103
- }
2104
- catch { }
2105
- },
2106
- async set(authorizationResult) {
2107
- try {
2108
- await AsyncStorage.setItem(CACHE_KEY, JSON.stringify(authorizationResult));
2109
- // eslint-disable-next-line no-empty
2110
- }
2111
- catch { }
2112
- },
2113
- };
2114
- }
2115
-
1871
+ return {
1872
+ async clear() {
1873
+ try {
1874
+ await _react_native_async_storage_async_storage.default.removeItem(CACHE_KEY);
1875
+ } catch {}
1876
+ },
1877
+ async get() {
1878
+ try {
1879
+ const parsed = JSON.parse(await _react_native_async_storage_async_storage.default.getItem(CACHE_KEY));
1880
+ if (parsed && parsed.accounts) {
1881
+ const parsedAccounts = parsed.accounts.map((account) => {
1882
+ return {
1883
+ ...account,
1884
+ publicKey: "publicKey" in account ? new Uint8Array(Object.values(account.publicKey)) : bs58.default.decode(account.address)
1885
+ };
1886
+ });
1887
+ return {
1888
+ ...parsed,
1889
+ accounts: parsedAccounts
1890
+ };
1891
+ } else return parsed || void 0;
1892
+ } catch {}
1893
+ },
1894
+ async set(authorizationResult) {
1895
+ try {
1896
+ await _react_native_async_storage_async_storage.default.setItem(CACHE_KEY, JSON.stringify(authorizationResult));
1897
+ } catch {}
1898
+ }
1899
+ };
1900
+ }
1901
+ //#endregion
1902
+ //#region src/createDefaultChainSelector.ts
2116
1903
  function createDefaultChainSelector() {
2117
- return {
2118
- async select(chains) {
2119
- if (chains.length === 1) {
2120
- return chains[0];
2121
- }
2122
- else if (chains.includes(walletStandardChains.SOLANA_MAINNET_CHAIN)) {
2123
- return walletStandardChains.SOLANA_MAINNET_CHAIN;
2124
- }
2125
- else
2126
- return chains[0];
2127
- },
2128
- };
1904
+ return { async select(chains) {
1905
+ if (chains.length === 1) return chains[0];
1906
+ else if (chains.includes(_solana_wallet_standard_chains.SOLANA_MAINNET_CHAIN)) return _solana_wallet_standard_chains.SOLANA_MAINNET_CHAIN;
1907
+ else return chains[0];
1908
+ } };
2129
1909
  }
2130
-
1910
+ //#endregion
2131
1911
  exports.LocalSolanaMobileWalletAdapterWallet = LocalSolanaMobileWalletAdapterWallet;
2132
1912
  exports.RemoteSolanaMobileWalletAdapterWallet = RemoteSolanaMobileWalletAdapterWallet;
2133
1913
  exports.SolanaMobileWalletAdapterRemoteWalletName = SolanaMobileWalletAdapterRemoteWalletName;
@@ -2137,3 +1917,5 @@ exports.createDefaultChainSelector = createDefaultChainSelector;
2137
1917
  exports.createDefaultWalletNotFoundHandler = createDefaultWalletNotFoundHandler;
2138
1918
  exports.defaultErrorModalWalletNotFoundHandler = defaultErrorModalWalletNotFoundHandler;
2139
1919
  exports.registerMwa = registerMwa;
1920
+
1921
+ //# sourceMappingURL=index.native.js.map