@pooflabs/web 0.0.81-rc5 → 0.0.81

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.
Files changed (81) hide show
  1. package/dist/auth/index.d.ts +10 -1
  2. package/dist/auth/providers/phantom-wallet-provider.d.ts +20 -21
  3. package/dist/global.d.ts +3 -1
  4. package/dist/{index-Fjyk5jYL.js → index-B2WGCssJ.js} +346 -490
  5. package/dist/index-B2WGCssJ.js.map +1 -0
  6. package/dist/{index-DB9nDInp.esm.js → index-CjHbp7Dq.esm.js} +3697 -562
  7. package/dist/index-CjHbp7Dq.esm.js.map +1 -0
  8. package/dist/{index-D_ta2S2c.js → index-DXPkkq81.js} +3698 -563
  9. package/dist/index-DXPkkq81.js.map +1 -0
  10. package/dist/{index-Bg_ApFIo.js → index-D_DiP8XQ.js} +3698 -563
  11. package/dist/index-D_DiP8XQ.js.map +1 -0
  12. package/dist/{index-CZhJBWap.esm.js → index-dcJIjFrs.esm.js} +3697 -562
  13. package/dist/index-dcJIjFrs.esm.js.map +1 -0
  14. package/dist/{index-Bkr4BRoP.esm.js → index-nt_HQVrk.esm.js} +344 -490
  15. package/dist/index-nt_HQVrk.esm.js.map +1 -0
  16. package/dist/{index.browser-iqs5DlRU.esm.js → index.browser-BNdFfyIg.esm.js} +1571 -1368
  17. package/dist/index.browser-BNdFfyIg.esm.js.map +1 -0
  18. package/dist/{index.browser-DHi7UhqF.js → index.browser-CT6PUv9G.js} +1571 -1368
  19. package/dist/index.browser-CT6PUv9G.js.map +1 -0
  20. package/dist/index.browser-Cy21yaX0.esm.js +1096 -0
  21. package/dist/index.browser-Cy21yaX0.esm.js.map +1 -0
  22. package/dist/index.browser-OvGNsMPu.esm.js +1002 -0
  23. package/dist/index.browser-OvGNsMPu.esm.js.map +1 -0
  24. package/dist/index.browser-ZD7Tz2bn.js +1099 -0
  25. package/dist/index.browser-ZD7Tz2bn.js.map +1 -0
  26. package/dist/index.browser-d0PlOXpF.js +105 -0
  27. package/dist/index.browser-d0PlOXpF.js.map +1 -0
  28. package/dist/index.browser-pE1s68e9.esm.js +102 -0
  29. package/dist/index.browser-pE1s68e9.esm.js.map +1 -0
  30. package/dist/index.browser-vuTr40so.js +1008 -0
  31. package/dist/index.browser-vuTr40so.js.map +1 -0
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.esm.js +1 -1
  34. package/dist/index.js +1 -1
  35. package/dist/{index.native-DYgJWWY4.esm.js → index.native-BqYr--vb.esm.js} +202 -178
  36. package/dist/index.native-BqYr--vb.esm.js.map +1 -0
  37. package/dist/{index.native-DJWuqJTZ.js → index.native-CyA-RdvW.js} +204 -178
  38. package/dist/index.native-CyA-RdvW.js.map +1 -0
  39. package/dist/index.native.esm.js +1 -1
  40. package/dist/index.native.js +1 -1
  41. package/dist/{phantom-wallet-provider-fofd8BMo.js → phantom-wallet-provider-DWCaMkyz.js} +147 -238
  42. package/dist/phantom-wallet-provider-DWCaMkyz.js.map +1 -0
  43. package/dist/{phantom-wallet-provider-DSFGWSOJ.esm.js → phantom-wallet-provider-K2V96G-G.esm.js} +147 -238
  44. package/dist/phantom-wallet-provider-K2V96G-G.esm.js.map +1 -0
  45. package/dist/{privy-wallet-provider-Csv34Kcc.js → privy-wallet-provider-BMg_S_d0.js} +4 -4
  46. package/dist/privy-wallet-provider-BMg_S_d0.js.map +1 -0
  47. package/dist/{privy-wallet-provider-TRToDe4Q.esm.js → privy-wallet-provider-DoX8q99w.esm.js} +4 -4
  48. package/dist/privy-wallet-provider-DoX8q99w.esm.js.map +1 -0
  49. package/dist/{solana-mobile-wallet-provider-L7nRuxhv.esm.js → solana-mobile-wallet-provider-Cmphb3oB.esm.js} +3 -82
  50. package/dist/solana-mobile-wallet-provider-Cmphb3oB.esm.js.map +1 -0
  51. package/dist/{solana-mobile-wallet-provider-Cp65LfNb.js → solana-mobile-wallet-provider-t22Ie8lY.js} +3 -82
  52. package/dist/solana-mobile-wallet-provider-t22Ie8lY.js.map +1 -0
  53. package/package.json +3 -3
  54. package/dist/index-Bg_ApFIo.js.map +0 -1
  55. package/dist/index-Bkr4BRoP.esm.js.map +0 -1
  56. package/dist/index-CZhJBWap.esm.js.map +0 -1
  57. package/dist/index-DB9nDInp.esm.js.map +0 -1
  58. package/dist/index-D_ta2S2c.js.map +0 -1
  59. package/dist/index-Fjyk5jYL.js.map +0 -1
  60. package/dist/index.browser-BTlliHCf.esm.js +0 -119
  61. package/dist/index.browser-BTlliHCf.esm.js.map +0 -1
  62. package/dist/index.browser-C-_FEr5M.esm.js +0 -1134
  63. package/dist/index.browser-C-_FEr5M.esm.js.map +0 -1
  64. package/dist/index.browser-DHi7UhqF.js.map +0 -1
  65. package/dist/index.browser-DRTQuf0J.js +0 -1253
  66. package/dist/index.browser-DRTQuf0J.js.map +0 -1
  67. package/dist/index.browser-Disp7Kcb.esm.js +0 -1250
  68. package/dist/index.browser-Disp7Kcb.esm.js.map +0 -1
  69. package/dist/index.browser-DjEZSiqI.js +0 -1137
  70. package/dist/index.browser-DjEZSiqI.js.map +0 -1
  71. package/dist/index.browser-DvTeEO2r.js +0 -122
  72. package/dist/index.browser-DvTeEO2r.js.map +0 -1
  73. package/dist/index.browser-iqs5DlRU.esm.js.map +0 -1
  74. package/dist/index.native-DJWuqJTZ.js.map +0 -1
  75. package/dist/index.native-DYgJWWY4.esm.js.map +0 -1
  76. package/dist/phantom-wallet-provider-DSFGWSOJ.esm.js.map +0 -1
  77. package/dist/phantom-wallet-provider-fofd8BMo.js.map +0 -1
  78. package/dist/privy-wallet-provider-Csv34Kcc.js.map +0 -1
  79. package/dist/privy-wallet-provider-TRToDe4Q.esm.js.map +0 -1
  80. package/dist/solana-mobile-wallet-provider-Cp65LfNb.js.map +0 -1
  81. package/dist/solana-mobile-wallet-provider-L7nRuxhv.esm.js.map +0 -1
@@ -0,0 +1,1002 @@
1
+ function createDecoder(decoder) {
2
+ return Object.freeze({
3
+ ...decoder,
4
+ decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0]
5
+ });
6
+ }
7
+
8
+ var getBaseXDecoder = (alphabet4) => {
9
+ return createDecoder({
10
+ read(rawBytes, offset) {
11
+ const bytes = offset === 0 || offset <= -rawBytes.byteLength ? rawBytes : rawBytes.slice(offset);
12
+ if (bytes.length === 0) return ["", 0];
13
+ let trailIndex = bytes.findIndex((n) => n !== 0);
14
+ trailIndex = trailIndex === -1 ? bytes.length : trailIndex;
15
+ const leadingZeroes = alphabet4[0].repeat(trailIndex);
16
+ if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];
17
+ const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
18
+ const tailChars = getBaseXFromBigInt(base10Number, alphabet4);
19
+ return [leadingZeroes + tailChars, rawBytes.length];
20
+ }
21
+ });
22
+ };
23
+ function getBaseXFromBigInt(value, alphabet4) {
24
+ const base = BigInt(alphabet4.length);
25
+ const tailChars = [];
26
+ while (value > 0n) {
27
+ tailChars.unshift(alphabet4[Number(value % base)]);
28
+ value /= base;
29
+ }
30
+ return tailChars.join("");
31
+ }
32
+
33
+ // src/base58.ts
34
+ var alphabet2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
35
+ var getBase58Decoder = () => getBaseXDecoder(alphabet2);
36
+
37
+ /**
38
+ * TODO: docs
39
+ */
40
+ function createSignInMessageText(input) {
41
+ // ${domain} wants you to sign in with your Solana account:
42
+ // ${address}
43
+ //
44
+ // ${statement}
45
+ //
46
+ // URI: ${uri}
47
+ // Version: ${version}
48
+ // Chain ID: ${chain}
49
+ // Nonce: ${nonce}
50
+ // Issued At: ${issued-at}
51
+ // Expiration Time: ${expiration-time}
52
+ // Not Before: ${not-before}
53
+ // Request ID: ${request-id}
54
+ // Resources:
55
+ // - ${resources[0]}
56
+ // - ${resources[1]}
57
+ // ...
58
+ // - ${resources[n]}
59
+ let message = `${input.domain} wants you to sign in with your Solana account:\n`;
60
+ message += `${input.address}`;
61
+ if (input.statement) {
62
+ message += `\n\n${input.statement}`;
63
+ }
64
+ const fields = [];
65
+ if (input.uri) {
66
+ fields.push(`URI: ${input.uri}`);
67
+ }
68
+ if (input.version) {
69
+ fields.push(`Version: ${input.version}`);
70
+ }
71
+ if (input.chainId) {
72
+ fields.push(`Chain ID: ${input.chainId}`);
73
+ }
74
+ if (input.nonce) {
75
+ fields.push(`Nonce: ${input.nonce}`);
76
+ }
77
+ if (input.issuedAt) {
78
+ fields.push(`Issued At: ${input.issuedAt}`);
79
+ }
80
+ if (input.expirationTime) {
81
+ fields.push(`Expiration Time: ${input.expirationTime}`);
82
+ }
83
+ if (input.notBefore) {
84
+ fields.push(`Not Before: ${input.notBefore}`);
85
+ }
86
+ if (input.requestId) {
87
+ fields.push(`Request ID: ${input.requestId}`);
88
+ }
89
+ if (input.resources) {
90
+ fields.push(`Resources:`);
91
+ for (const resource of input.resources) {
92
+ fields.push(`- ${resource}`);
93
+ }
94
+ }
95
+ if (fields.length) {
96
+ message += `\n\n${fields.join('\n')}`;
97
+ }
98
+ return message;
99
+ }
100
+
101
+ //#region src/errors.ts
102
+ const SolanaMobileWalletAdapterErrorCode = {
103
+ ERROR_ASSOCIATION_PORT_OUT_OF_RANGE: "ERROR_ASSOCIATION_PORT_OUT_OF_RANGE",
104
+ ERROR_REFLECTOR_ID_OUT_OF_RANGE: "ERROR_REFLECTOR_ID_OUT_OF_RANGE",
105
+ ERROR_FORBIDDEN_WALLET_BASE_URL: "ERROR_FORBIDDEN_WALLET_BASE_URL",
106
+ ERROR_SECURE_CONTEXT_REQUIRED: "ERROR_SECURE_CONTEXT_REQUIRED",
107
+ ERROR_SESSION_CLOSED: "ERROR_SESSION_CLOSED",
108
+ ERROR_SESSION_TIMEOUT: "ERROR_SESSION_TIMEOUT",
109
+ ERROR_WALLET_NOT_FOUND: "ERROR_WALLET_NOT_FOUND",
110
+ ERROR_INVALID_PROTOCOL_VERSION: "ERROR_INVALID_PROTOCOL_VERSION",
111
+ ERROR_BROWSER_NOT_SUPPORTED: "ERROR_BROWSER_NOT_SUPPORTED",
112
+ ERROR_LOOPBACK_ACCESS_BLOCKED: "ERROR_LOOPBACK_ACCESS_BLOCKED",
113
+ ERROR_ASSOCIATION_CANCELLED: "ERROR_ASSOCIATION_CANCELLED"
114
+ };
115
+ var SolanaMobileWalletAdapterError = class extends Error {
116
+ data;
117
+ code;
118
+ constructor(...args) {
119
+ const [code, message, data] = args;
120
+ super(message);
121
+ this.code = code;
122
+ this.data = data;
123
+ this.name = "SolanaMobileWalletAdapterError";
124
+ }
125
+ };
126
+ var SolanaMobileWalletAdapterProtocolError = class extends Error {
127
+ data;
128
+ code;
129
+ jsonRpcMessageId;
130
+ constructor(...args) {
131
+ const [jsonRpcMessageId, code, message, data] = args;
132
+ super(message);
133
+ this.code = code;
134
+ this.data = data;
135
+ this.jsonRpcMessageId = jsonRpcMessageId;
136
+ this.name = "SolanaMobileWalletAdapterProtocolError";
137
+ }
138
+ };
139
+ //#endregion
140
+ //#region src/base64Utils.ts
141
+ function encode(input) {
142
+ return window.btoa(input);
143
+ }
144
+ function fromUint8Array$1(byteArray, urlsafe) {
145
+ const base64 = window.btoa(String.fromCharCode.call(null, ...byteArray));
146
+ if (urlsafe) return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
147
+ else return base64;
148
+ }
149
+ function toUint8Array(base64EncodedByteArray) {
150
+ return new Uint8Array(window.atob(base64EncodedByteArray).split("").map((c) => c.charCodeAt(0)));
151
+ }
152
+ //#endregion
153
+ //#region src/createHelloReq.ts
154
+ async function createHelloReq(ecdhPublicKey, associationKeypairPrivateKey) {
155
+ const publicKeyBuffer = await crypto.subtle.exportKey("raw", ecdhPublicKey);
156
+ const signatureBuffer = await crypto.subtle.sign({
157
+ hash: "SHA-256",
158
+ name: "ECDSA"
159
+ }, associationKeypairPrivateKey, publicKeyBuffer);
160
+ const response = new Uint8Array(publicKeyBuffer.byteLength + signatureBuffer.byteLength);
161
+ response.set(new Uint8Array(publicKeyBuffer), 0);
162
+ response.set(new Uint8Array(signatureBuffer), publicKeyBuffer.byteLength);
163
+ return response;
164
+ }
165
+ //#endregion
166
+ //#region src/base58Utils.ts
167
+ function fromUint8Array(byteArray) {
168
+ return getBase58Decoder().decode(byteArray);
169
+ }
170
+ function base64ToBase58(base64EncodedString) {
171
+ return fromUint8Array(toUint8Array(base64EncodedString));
172
+ }
173
+ //#endregion
174
+ //#region src/createSIWSMessage.ts
175
+ function createSIWSMessage(payload) {
176
+ return createSignInMessageText(payload);
177
+ }
178
+ function createSIWSMessageBase64Url(payload) {
179
+ return encode(createSIWSMessage(payload)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
180
+ }
181
+ //#endregion
182
+ //#region src/types.ts
183
+ const SolanaSignTransactions = "solana:signTransactions";
184
+ const SolanaCloneAuthorization = "solana:cloneAuthorization";
185
+ //#endregion
186
+ //#region src/createMobileWalletProxy.ts
187
+ /**
188
+ * Creates a {@link MobileWallet} proxy that handles backwards compatibility and API to RPC conversion.
189
+ *
190
+ * @param protocolVersion the protocol version in use for this session/request
191
+ * @param protocolRequestHandler callback function that handles sending the RPC request to the wallet endpoint.
192
+ * @returns a {@link MobileWallet} proxy
193
+ */
194
+ function createMobileWalletProxy(protocolVersion, protocolRequestHandler) {
195
+ return new Proxy({}, {
196
+ get(target, p) {
197
+ if (p === "then") return null;
198
+ if (target[p] == null) target[p] = async function(inputParams) {
199
+ const { method, params } = handleMobileWalletRequest(p, inputParams, protocolVersion);
200
+ const result = await protocolRequestHandler(method, params);
201
+ if (method === "authorize" && params.sign_in_payload && !result.sign_in_result) result.sign_in_result = await signInFallback(params.sign_in_payload, result, protocolRequestHandler);
202
+ return handleMobileWalletResponse(p, result, protocolVersion);
203
+ };
204
+ return target[p];
205
+ },
206
+ defineProperty() {
207
+ return false;
208
+ },
209
+ deleteProperty() {
210
+ return false;
211
+ }
212
+ });
213
+ }
214
+ /**
215
+ * Handles all {@link MobileWallet} API requests and determines the correct MWA RPC method and params to call.
216
+ * This handles backwards compatibility, based on the provided @protocolVersion.
217
+ *
218
+ * @param methodName the name of {@link MobileWallet} method that was called
219
+ * @param methodParams the parameters that were passed to the method
220
+ * @param protocolVersion the protocol version in use for this session/request
221
+ * @returns the RPC request method and params that should be sent to the wallet endpoint
222
+ */
223
+ function handleMobileWalletRequest(methodName, methodParams, protocolVersion) {
224
+ let params = methodParams;
225
+ let method = methodName.toString().replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`).toLowerCase();
226
+ switch (methodName) {
227
+ case "authorize": {
228
+ const authorizeParams = params;
229
+ let { chain } = authorizeParams;
230
+ if (protocolVersion === "legacy") {
231
+ switch (chain) {
232
+ case "solana:testnet":
233
+ chain = "testnet";
234
+ break;
235
+ case "solana:devnet":
236
+ chain = "devnet";
237
+ break;
238
+ case "solana:mainnet":
239
+ chain = "mainnet-beta";
240
+ break;
241
+ default: chain = authorizeParams.cluster;
242
+ }
243
+ authorizeParams.cluster = chain;
244
+ params = authorizeParams;
245
+ } else {
246
+ switch (chain) {
247
+ case "testnet":
248
+ case "devnet":
249
+ chain = `solana:${chain}`;
250
+ break;
251
+ case "mainnet-beta":
252
+ chain = "solana:mainnet";
253
+ break;
254
+ }
255
+ authorizeParams.chain = chain;
256
+ params = authorizeParams;
257
+ }
258
+ }
259
+ case "reauthorize": {
260
+ const { auth_token, identity } = params;
261
+ if (auth_token) switch (protocolVersion) {
262
+ case "legacy":
263
+ method = "reauthorize";
264
+ params = {
265
+ auth_token,
266
+ identity
267
+ };
268
+ break;
269
+ default:
270
+ method = "authorize";
271
+ break;
272
+ }
273
+ break;
274
+ }
275
+ }
276
+ return {
277
+ method,
278
+ params
279
+ };
280
+ }
281
+ /**
282
+ * Handles all {@link MobileWallet} API responses and modifies the response for backwards compatibility, if needed
283
+ *
284
+ * @param method the {@link MobileWallet} method that was called
285
+ * @param response the original response that was returned by the method call
286
+ * @param protocolVersion the protocol version in use for this session/request
287
+ * @returns the possibly modified response
288
+ */
289
+ function handleMobileWalletResponse(method, response, protocolVersion) {
290
+ switch (method) {
291
+ case "getCapabilities": {
292
+ const capabilities = response;
293
+ switch (protocolVersion) {
294
+ case "legacy": {
295
+ const features = [SolanaSignTransactions];
296
+ if (capabilities.supports_clone_authorization === true) features.push(SolanaCloneAuthorization);
297
+ return {
298
+ ...capabilities,
299
+ features
300
+ };
301
+ }
302
+ case "v1": return {
303
+ ...capabilities,
304
+ supports_sign_and_send_transactions: true,
305
+ supports_clone_authorization: capabilities.features.includes(SolanaCloneAuthorization)
306
+ };
307
+ }
308
+ }
309
+ }
310
+ return response;
311
+ }
312
+ async function signInFallback(signInPayload, authorizationResult, protocolRequestHandler) {
313
+ const domain = signInPayload.domain ?? window.location.host;
314
+ const address = authorizationResult.accounts[0].address;
315
+ const siwsMessage = createSIWSMessageBase64Url({
316
+ ...signInPayload,
317
+ domain,
318
+ address: base64ToBase58(address)
319
+ });
320
+ const signedPayload = toUint8Array((await protocolRequestHandler("sign_messages", {
321
+ addresses: [address],
322
+ payloads: [siwsMessage]
323
+ })).signed_payloads[0]);
324
+ const signedMessage = fromUint8Array$1(signedPayload.slice(0, signedPayload.length - 64));
325
+ const signature = fromUint8Array$1(signedPayload.slice(signedPayload.length - 64));
326
+ return {
327
+ address,
328
+ signed_message: signedMessage.length == 0 ? siwsMessage : signedMessage,
329
+ signature
330
+ };
331
+ }
332
+ function createSequenceNumberVector(sequenceNumber) {
333
+ if (sequenceNumber >= 4294967296) throw new Error("Outbound sequence number overflow. The maximum sequence number is 32-bytes.");
334
+ const byteArray = /* @__PURE__ */ new ArrayBuffer(4);
335
+ new DataView(byteArray).setUint32(0, sequenceNumber, false);
336
+ return new Uint8Array(byteArray);
337
+ }
338
+ //#endregion
339
+ //#region src/encryptedMessage.ts
340
+ const INITIALIZATION_VECTOR_BYTES = 12;
341
+ async function encryptMessage(plaintext, sequenceNumber, sharedSecret) {
342
+ const sequenceNumberVector = createSequenceNumberVector(sequenceNumber);
343
+ const initializationVector = new Uint8Array(INITIALIZATION_VECTOR_BYTES);
344
+ crypto.getRandomValues(initializationVector);
345
+ const ciphertext = await crypto.subtle.encrypt(getAlgorithmParams(sequenceNumberVector, initializationVector), sharedSecret, new TextEncoder().encode(plaintext));
346
+ const response = new Uint8Array(sequenceNumberVector.byteLength + initializationVector.byteLength + ciphertext.byteLength);
347
+ response.set(new Uint8Array(sequenceNumberVector), 0);
348
+ response.set(new Uint8Array(initializationVector), sequenceNumberVector.byteLength);
349
+ response.set(new Uint8Array(ciphertext), sequenceNumberVector.byteLength + initializationVector.byteLength);
350
+ return response;
351
+ }
352
+ async function decryptMessage(message, sharedSecret) {
353
+ const sequenceNumberVector = message.slice(0, 4);
354
+ const initializationVector = message.slice(4, 4 + INITIALIZATION_VECTOR_BYTES);
355
+ const ciphertext = message.slice(4 + INITIALIZATION_VECTOR_BYTES);
356
+ const plaintextBuffer = await crypto.subtle.decrypt(getAlgorithmParams(sequenceNumberVector, initializationVector), sharedSecret, ciphertext);
357
+ return getUtf8Decoder().decode(plaintextBuffer);
358
+ }
359
+ function getAlgorithmParams(sequenceNumber, initializationVector) {
360
+ return {
361
+ additionalData: sequenceNumber,
362
+ iv: initializationVector,
363
+ name: "AES-GCM",
364
+ tagLength: 128
365
+ };
366
+ }
367
+ let _utf8Decoder;
368
+ function getUtf8Decoder() {
369
+ if (_utf8Decoder === void 0) _utf8Decoder = new TextDecoder("utf-8");
370
+ return _utf8Decoder;
371
+ }
372
+ //#endregion
373
+ //#region src/generateAssociationKeypair.ts
374
+ async function generateAssociationKeypair() {
375
+ return await crypto.subtle.generateKey({
376
+ name: "ECDSA",
377
+ namedCurve: "P-256"
378
+ }, false, ["sign"]);
379
+ }
380
+ //#endregion
381
+ //#region src/generateECDHKeypair.ts
382
+ async function generateECDHKeypair() {
383
+ return await crypto.subtle.generateKey({
384
+ name: "ECDH",
385
+ namedCurve: "P-256"
386
+ }, false, ["deriveKey", "deriveBits"]);
387
+ }
388
+ //#endregion
389
+ //#region src/arrayBufferToBase64String.ts
390
+ function arrayBufferToBase64String(buffer) {
391
+ let binary = "";
392
+ const bytes = new Uint8Array(buffer);
393
+ const len = bytes.byteLength;
394
+ for (let ii = 0; ii < len; ii++) binary += String.fromCharCode(bytes[ii]);
395
+ return window.btoa(binary);
396
+ }
397
+ //#endregion
398
+ //#region src/associationPort.ts
399
+ function getRandomAssociationPort() {
400
+ return assertAssociationPort(49152 + Math.floor(Math.random() * 16384));
401
+ }
402
+ function assertAssociationPort(port) {
403
+ if (port < 49152 || port > 65535) throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_PORT_OUT_OF_RANGE, `Association port number must be between 49152 and 65535. ${port} given.`, { port });
404
+ return port;
405
+ }
406
+ //#endregion
407
+ //#region src/getStringWithURLUnsafeBase64CharactersReplaced.ts
408
+ function getStringWithURLUnsafeCharactersReplaced(unsafeBase64EncodedString) {
409
+ return unsafeBase64EncodedString.replace(/[/+=]/g, (m) => ({
410
+ "/": "_",
411
+ "+": "-",
412
+ "=": "."
413
+ })[m]);
414
+ }
415
+ //#endregion
416
+ //#region src/getAssociateAndroidIntentURL.ts
417
+ const INTENT_NAME = "solana-wallet";
418
+ function getPathParts(pathString) {
419
+ return pathString.replace(/(^\/+|\/+$)/g, "").split("/");
420
+ }
421
+ function getIntentURL(methodPathname, intentUrlBase) {
422
+ let baseUrl = null;
423
+ if (intentUrlBase) {
424
+ try {
425
+ baseUrl = new URL(intentUrlBase);
426
+ } catch {}
427
+ if (baseUrl?.protocol !== "https:") throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, "Base URLs supplied by wallets must be valid `https` URLs");
428
+ }
429
+ baseUrl ||= new URL(`${INTENT_NAME}:/`);
430
+ const pathname = methodPathname.startsWith("/") ? methodPathname : [...getPathParts(baseUrl.pathname), ...getPathParts(methodPathname)].join("/");
431
+ return new URL(pathname, baseUrl);
432
+ }
433
+ async function getAssociateAndroidIntentURL(associationPublicKey, putativePort, associationURLBase, protocolVersions = ["v1"]) {
434
+ const associationPort = assertAssociationPort(putativePort);
435
+ const encodedKey = arrayBufferToBase64String(await crypto.subtle.exportKey("raw", associationPublicKey));
436
+ const url = getIntentURL("v1/associate/local", associationURLBase);
437
+ url.searchParams.set("association", getStringWithURLUnsafeCharactersReplaced(encodedKey));
438
+ url.searchParams.set("port", `${associationPort}`);
439
+ protocolVersions.forEach((version) => {
440
+ url.searchParams.set("v", version);
441
+ });
442
+ return url;
443
+ }
444
+ async function getRemoteAssociateAndroidIntentURL(associationPublicKey, hostAuthority, reflectorId, associationURLBase, protocolVersions = ["v1"]) {
445
+ const encodedKey = arrayBufferToBase64String(await crypto.subtle.exportKey("raw", associationPublicKey));
446
+ const url = getIntentURL("v1/associate/remote", associationURLBase);
447
+ url.searchParams.set("association", getStringWithURLUnsafeCharactersReplaced(encodedKey));
448
+ url.searchParams.set("reflector", `${hostAuthority}`);
449
+ url.searchParams.set("id", `${fromUint8Array$1(reflectorId, true)}`);
450
+ protocolVersions.forEach((version) => {
451
+ url.searchParams.set("v", version);
452
+ });
453
+ return url;
454
+ }
455
+ //#endregion
456
+ //#region src/jsonRpcMessage.ts
457
+ async function encryptJsonRpcMessage(jsonRpcMessage, sharedSecret) {
458
+ const plaintext = JSON.stringify(jsonRpcMessage);
459
+ const sequenceNumber = jsonRpcMessage.id;
460
+ return encryptMessage(plaintext, sequenceNumber, sharedSecret);
461
+ }
462
+ async function decryptJsonRpcMessage(message, sharedSecret) {
463
+ const plaintext = await decryptMessage(message, sharedSecret);
464
+ const jsonRpcMessage = JSON.parse(plaintext);
465
+ if (Object.hasOwnProperty.call(jsonRpcMessage, "error")) throw new SolanaMobileWalletAdapterProtocolError(jsonRpcMessage.id, jsonRpcMessage.error.code, jsonRpcMessage.error.message);
466
+ return jsonRpcMessage;
467
+ }
468
+ //#endregion
469
+ //#region src/parseHelloRsp.ts
470
+ async function parseHelloRsp(payloadBuffer, associationPublicKey, ecdhPrivateKey) {
471
+ const [associationPublicKeyBuffer, walletPublicKey] = await Promise.all([crypto.subtle.exportKey("raw", associationPublicKey), crypto.subtle.importKey("raw", payloadBuffer.slice(0, 65), {
472
+ name: "ECDH",
473
+ namedCurve: "P-256"
474
+ }, false, [])]);
475
+ const sharedSecret = await crypto.subtle.deriveBits({
476
+ name: "ECDH",
477
+ public: walletPublicKey
478
+ }, ecdhPrivateKey, 256);
479
+ const ecdhSecretKey = await crypto.subtle.importKey("raw", sharedSecret, "HKDF", false, ["deriveKey"]);
480
+ return await crypto.subtle.deriveKey({
481
+ name: "HKDF",
482
+ hash: "SHA-256",
483
+ salt: new Uint8Array(associationPublicKeyBuffer),
484
+ info: new Uint8Array()
485
+ }, ecdhSecretKey, {
486
+ name: "AES-GCM",
487
+ length: 128
488
+ }, false, ["encrypt", "decrypt"]);
489
+ }
490
+ //#endregion
491
+ //#region src/parseSessionProps.ts
492
+ async function parseSessionProps(message, sharedSecret) {
493
+ const plaintext = await decryptMessage(message, sharedSecret);
494
+ const jsonProperties = JSON.parse(plaintext);
495
+ let protocolVersion = "legacy";
496
+ if (Object.hasOwnProperty.call(jsonProperties, "v")) switch (jsonProperties.v) {
497
+ case 1:
498
+ case "1":
499
+ case "v1":
500
+ protocolVersion = "v1";
501
+ break;
502
+ case "legacy":
503
+ protocolVersion = "legacy";
504
+ break;
505
+ default: throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_INVALID_PROTOCOL_VERSION, `Unknown/unsupported protocol version: ${jsonProperties.v}`);
506
+ }
507
+ return { protocol_version: protocolVersion };
508
+ }
509
+ //#endregion
510
+ //#region src/startSession.ts
511
+ const Browser = {
512
+ Firefox: 0,
513
+ Other: 1
514
+ };
515
+ function assertUnreachable(x) {
516
+ return x;
517
+ }
518
+ function getBrowser() {
519
+ return navigator.userAgent.indexOf("Firefox/") !== -1 ? Browser.Firefox : Browser.Other;
520
+ }
521
+ function getDetectionPromise() {
522
+ return new Promise((resolve, reject) => {
523
+ function cleanup() {
524
+ clearTimeout(timeoutId);
525
+ window.removeEventListener("blur", handleBlur);
526
+ }
527
+ function handleBlur() {
528
+ cleanup();
529
+ resolve();
530
+ }
531
+ window.addEventListener("blur", handleBlur);
532
+ const timeoutId = setTimeout(() => {
533
+ cleanup();
534
+ reject();
535
+ }, 3e3);
536
+ });
537
+ }
538
+ let _frame = null;
539
+ function launchUrlThroughHiddenFrame(url) {
540
+ if (_frame == null) {
541
+ _frame = document.createElement("iframe");
542
+ _frame.style.display = "none";
543
+ document.body.appendChild(_frame);
544
+ }
545
+ _frame.contentWindow.location.href = url.toString();
546
+ }
547
+ async function launchAssociation(associationUrl) {
548
+ if (associationUrl.protocol === "https:") window.location.assign(associationUrl);
549
+ else try {
550
+ const browser = getBrowser();
551
+ switch (browser) {
552
+ case Browser.Firefox:
553
+ launchUrlThroughHiddenFrame(associationUrl);
554
+ break;
555
+ case Browser.Other: {
556
+ const detectionPromise = getDetectionPromise();
557
+ window.location.assign(associationUrl);
558
+ await detectionPromise;
559
+ break;
560
+ }
561
+ default: assertUnreachable(browser);
562
+ }
563
+ } catch {
564
+ throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND, "Found no installed wallet that supports the mobile wallet protocol.");
565
+ }
566
+ }
567
+ async function startSession(associationPublicKey, associationURLBase) {
568
+ const randomAssociationPort = getRandomAssociationPort();
569
+ await launchAssociation(await getAssociateAndroidIntentURL(associationPublicKey, randomAssociationPort, associationURLBase));
570
+ return randomAssociationPort;
571
+ }
572
+ //#endregion
573
+ //#region src/transact.ts
574
+ const WEBSOCKET_CONNECTION_CONFIG = {
575
+ retryDelayScheduleMs: [
576
+ 150,
577
+ 150,
578
+ 200,
579
+ 500,
580
+ 500,
581
+ 750,
582
+ 750,
583
+ 1e3
584
+ ],
585
+ timeoutMs: 3e4
586
+ };
587
+ const WEBSOCKET_PROTOCOL_BINARY = "com.solana.mobilewalletadapter.v1";
588
+ const WEBSOCKET_PROTOCOL_BASE64 = "com.solana.mobilewalletadapter.v1.base64";
589
+ function assertSecureContext() {
590
+ if (typeof window === "undefined" || window.isSecureContext !== true) throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SECURE_CONTEXT_REQUIRED, "The mobile wallet adapter protocol must be used in a secure context (`https`).");
591
+ }
592
+ function assertSecureEndpointSpecificURI(walletUriBase) {
593
+ let url;
594
+ try {
595
+ url = new URL(walletUriBase);
596
+ } catch {
597
+ throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, "Invalid base URL supplied by wallet");
598
+ }
599
+ if (url.protocol !== "https:") throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, "Base URLs supplied by wallets must be valid `https` URLs");
600
+ }
601
+ function getSequenceNumberFromByteArray(byteArray) {
602
+ return new DataView(byteArray).getUint32(0, false);
603
+ }
604
+ function decodeVarLong(byteArray) {
605
+ const bytes = new Uint8Array(byteArray);
606
+ const l = byteArray.byteLength;
607
+ const limit = 10;
608
+ let value = 0, offset = 0, b;
609
+ do {
610
+ if (offset >= l || offset > limit) throw new RangeError("Failed to decode varint");
611
+ b = bytes[offset++];
612
+ value |= (b & 127) << 7 * offset;
613
+ } while (b >= 128);
614
+ return {
615
+ value,
616
+ offset
617
+ };
618
+ }
619
+ function getReflectorIdFromByteArray(byteArray) {
620
+ const { value: length, offset } = decodeVarLong(byteArray);
621
+ return new Uint8Array(byteArray.slice(offset, offset + length));
622
+ }
623
+ async function transact(callback, config) {
624
+ const { wallet, close } = await startScenario(config);
625
+ try {
626
+ return await callback(await wallet);
627
+ } finally {
628
+ close();
629
+ }
630
+ }
631
+ async function startScenario(config) {
632
+ assertSecureContext();
633
+ const associationKeypair = await generateAssociationKeypair();
634
+ const websocketURL = `ws://localhost:${await startSession(associationKeypair.publicKey, config?.baseUri)}/solana-wallet`;
635
+ let connectionStartTime;
636
+ const getNextRetryDelayMs = (() => {
637
+ const schedule = [...WEBSOCKET_CONNECTION_CONFIG.retryDelayScheduleMs];
638
+ return () => schedule.length > 1 ? schedule.shift() : schedule[0];
639
+ })();
640
+ let nextJsonRpcMessageId = 1;
641
+ let lastKnownInboundSequenceNumber = 0;
642
+ let state = { __type: "disconnected" };
643
+ let socket;
644
+ let sessionEstablished = false;
645
+ let handleForceClose;
646
+ return {
647
+ close: () => {
648
+ socket.close();
649
+ handleForceClose();
650
+ },
651
+ wallet: new Promise((resolve, reject) => {
652
+ const jsonRpcResponsePromises = {};
653
+ const handleOpen = async () => {
654
+ if (state.__type !== "connecting") {
655
+ console.warn(`Expected adapter state to be \`connecting\` at the moment the websocket opens. Got \`${state.__type}\`.`);
656
+ return;
657
+ }
658
+ socket.removeEventListener("open", handleOpen);
659
+ const { associationKeypair } = state;
660
+ const ecdhKeypair = await generateECDHKeypair();
661
+ socket.send(await createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));
662
+ state = {
663
+ __type: "hello_req_sent",
664
+ associationPublicKey: associationKeypair.publicKey,
665
+ ecdhPrivateKey: ecdhKeypair.privateKey
666
+ };
667
+ };
668
+ const handleClose = (evt) => {
669
+ if (evt.wasClean) state = { __type: "disconnected" };
670
+ else reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED, `The wallet session dropped unexpectedly (${evt.code}: ${evt.reason}).`, { closeEvent: evt }));
671
+ disposeSocket();
672
+ };
673
+ const handleError = async (_evt) => {
674
+ disposeSocket();
675
+ if (Date.now() - connectionStartTime >= WEBSOCKET_CONNECTION_CONFIG.timeoutMs) reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT, `Failed to connect to the wallet websocket at ${websocketURL}.`));
676
+ else {
677
+ await new Promise((resolve) => {
678
+ const retryDelayMs = getNextRetryDelayMs();
679
+ retryWaitTimeoutId = window.setTimeout(resolve, retryDelayMs);
680
+ });
681
+ attemptSocketConnection();
682
+ }
683
+ };
684
+ const handleMessage = async (evt) => {
685
+ const responseBuffer = await evt.data.arrayBuffer();
686
+ switch (state.__type) {
687
+ case "connecting": {
688
+ if (responseBuffer.byteLength !== 0) throw new Error("Encountered unexpected message while connecting");
689
+ const ecdhKeypair = await generateECDHKeypair();
690
+ socket.send(await createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));
691
+ state = {
692
+ __type: "hello_req_sent",
693
+ associationPublicKey: associationKeypair.publicKey,
694
+ ecdhPrivateKey: ecdhKeypair.privateKey
695
+ };
696
+ break;
697
+ }
698
+ case "connected":
699
+ try {
700
+ const sequenceNumber = getSequenceNumberFromByteArray(responseBuffer.slice(0, 4));
701
+ if (sequenceNumber !== lastKnownInboundSequenceNumber + 1) throw new Error("Encrypted message has invalid sequence number");
702
+ lastKnownInboundSequenceNumber = sequenceNumber;
703
+ const jsonRpcMessage = await decryptJsonRpcMessage(responseBuffer, state.sharedSecret);
704
+ const responsePromise = jsonRpcResponsePromises[jsonRpcMessage.id];
705
+ delete jsonRpcResponsePromises[jsonRpcMessage.id];
706
+ responsePromise.resolve(jsonRpcMessage.result);
707
+ } catch (e) {
708
+ if (e instanceof SolanaMobileWalletAdapterProtocolError) {
709
+ const responsePromise = jsonRpcResponsePromises[e.jsonRpcMessageId];
710
+ delete jsonRpcResponsePromises[e.jsonRpcMessageId];
711
+ responsePromise.reject(e);
712
+ } else throw e;
713
+ }
714
+ break;
715
+ case "hello_req_sent": {
716
+ if (responseBuffer.byteLength === 0) {
717
+ const ecdhKeypair = await generateECDHKeypair();
718
+ socket.send(await createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));
719
+ state = {
720
+ __type: "hello_req_sent",
721
+ associationPublicKey: associationKeypair.publicKey,
722
+ ecdhPrivateKey: ecdhKeypair.privateKey
723
+ };
724
+ break;
725
+ }
726
+ const sharedSecret = await parseHelloRsp(responseBuffer, state.associationPublicKey, state.ecdhPrivateKey);
727
+ const sessionPropertiesBuffer = responseBuffer.slice(65);
728
+ const sessionProperties = sessionPropertiesBuffer.byteLength !== 0 ? await (async () => {
729
+ const sequenceNumber = getSequenceNumberFromByteArray(sessionPropertiesBuffer.slice(0, 4));
730
+ if (sequenceNumber !== lastKnownInboundSequenceNumber + 1) throw new Error("Encrypted message has invalid sequence number");
731
+ lastKnownInboundSequenceNumber = sequenceNumber;
732
+ return parseSessionProps(sessionPropertiesBuffer, sharedSecret);
733
+ })() : { protocol_version: "legacy" };
734
+ state = {
735
+ __type: "connected",
736
+ sharedSecret,
737
+ sessionProperties
738
+ };
739
+ const wallet = createMobileWalletProxy(sessionProperties.protocol_version, async (method, params) => {
740
+ const id = nextJsonRpcMessageId++;
741
+ socket.send(await encryptJsonRpcMessage({
742
+ id,
743
+ jsonrpc: "2.0",
744
+ method,
745
+ params: params ?? {}
746
+ }, sharedSecret));
747
+ return new Promise((resolve, reject) => {
748
+ jsonRpcResponsePromises[id] = {
749
+ resolve(result) {
750
+ switch (method) {
751
+ case "authorize":
752
+ case "reauthorize": {
753
+ const { wallet_uri_base } = result;
754
+ if (wallet_uri_base != null) try {
755
+ assertSecureEndpointSpecificURI(wallet_uri_base);
756
+ } catch (e) {
757
+ reject(e);
758
+ return;
759
+ }
760
+ break;
761
+ }
762
+ }
763
+ resolve(result);
764
+ },
765
+ reject
766
+ };
767
+ });
768
+ });
769
+ sessionEstablished = true;
770
+ try {
771
+ resolve(wallet);
772
+ } catch (e) {
773
+ reject(e);
774
+ }
775
+ break;
776
+ }
777
+ }
778
+ };
779
+ handleForceClose = () => {
780
+ socket.removeEventListener("message", handleMessage);
781
+ disposeSocket();
782
+ if (!sessionEstablished) reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED, `The wallet session was closed before connection.`, { closeEvent: new CloseEvent("socket was closed before connection") }));
783
+ };
784
+ let disposeSocket;
785
+ let retryWaitTimeoutId;
786
+ const attemptSocketConnection = () => {
787
+ if (disposeSocket) disposeSocket();
788
+ state = {
789
+ __type: "connecting",
790
+ associationKeypair
791
+ };
792
+ if (connectionStartTime === void 0) connectionStartTime = Date.now();
793
+ socket = new WebSocket(websocketURL, [WEBSOCKET_PROTOCOL_BINARY]);
794
+ socket.addEventListener("open", handleOpen);
795
+ socket.addEventListener("close", handleClose);
796
+ socket.addEventListener("error", handleError);
797
+ socket.addEventListener("message", handleMessage);
798
+ disposeSocket = () => {
799
+ window.clearTimeout(retryWaitTimeoutId);
800
+ socket.removeEventListener("open", handleOpen);
801
+ socket.removeEventListener("close", handleClose);
802
+ socket.removeEventListener("error", handleError);
803
+ socket.removeEventListener("message", handleMessage);
804
+ };
805
+ };
806
+ attemptSocketConnection();
807
+ })
808
+ };
809
+ }
810
+ async function startRemoteScenario(config) {
811
+ assertSecureContext();
812
+ const associationKeypair = await generateAssociationKeypair();
813
+ const websocketURL = `wss://${config?.remoteHostAuthority}/reflect`;
814
+ let connectionStartTime;
815
+ const getNextRetryDelayMs = (() => {
816
+ const schedule = [...WEBSOCKET_CONNECTION_CONFIG.retryDelayScheduleMs];
817
+ return () => schedule.length > 1 ? schedule.shift() : schedule[0];
818
+ })();
819
+ let nextJsonRpcMessageId = 1;
820
+ let lastKnownInboundSequenceNumber = 0;
821
+ let encoding;
822
+ let state = { __type: "disconnected" };
823
+ let socket;
824
+ let disposeSocket;
825
+ const decodeBytes = async (evt) => {
826
+ if (encoding == "base64") return toUint8Array(await evt.data).buffer;
827
+ else return await evt.data.arrayBuffer();
828
+ };
829
+ const associationUrl = await new Promise((resolve, reject) => {
830
+ const handleOpen = async () => {
831
+ if (state.__type !== "connecting") {
832
+ console.warn(`Expected adapter state to be \`connecting\` at the moment the websocket opens. Got \`${state.__type}\`.`);
833
+ return;
834
+ }
835
+ if (socket.protocol.includes(WEBSOCKET_PROTOCOL_BASE64)) encoding = "base64";
836
+ else encoding = "binary";
837
+ socket.removeEventListener("open", handleOpen);
838
+ };
839
+ const handleClose = (evt) => {
840
+ if (evt.wasClean) state = { __type: "disconnected" };
841
+ else reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED, `The wallet session dropped unexpectedly (${evt.code}: ${evt.reason}).`, { closeEvent: evt }));
842
+ disposeSocket();
843
+ };
844
+ const handleError = async (_evt) => {
845
+ disposeSocket();
846
+ if (Date.now() - connectionStartTime >= WEBSOCKET_CONNECTION_CONFIG.timeoutMs) reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT, `Failed to connect to the wallet websocket at ${websocketURL}.`));
847
+ else {
848
+ await new Promise((resolve) => {
849
+ const retryDelayMs = getNextRetryDelayMs();
850
+ retryWaitTimeoutId = window.setTimeout(resolve, retryDelayMs);
851
+ });
852
+ attemptSocketConnection();
853
+ }
854
+ };
855
+ const handleReflectorIdMessage = async (evt) => {
856
+ const responseBuffer = await decodeBytes(evt);
857
+ if (state.__type === "connecting") {
858
+ if (responseBuffer.byteLength == 0) throw new Error("Encountered unexpected message while connecting");
859
+ const reflectorId = getReflectorIdFromByteArray(responseBuffer);
860
+ state = {
861
+ __type: "reflector_id_received",
862
+ reflectorId
863
+ };
864
+ const associationUrl = await getRemoteAssociateAndroidIntentURL(associationKeypair.publicKey, config.remoteHostAuthority, reflectorId, config?.baseUri);
865
+ socket.removeEventListener("message", handleReflectorIdMessage);
866
+ resolve(associationUrl);
867
+ }
868
+ };
869
+ let retryWaitTimeoutId;
870
+ const attemptSocketConnection = () => {
871
+ if (disposeSocket) disposeSocket();
872
+ state = {
873
+ __type: "connecting",
874
+ associationKeypair
875
+ };
876
+ if (connectionStartTime === void 0) connectionStartTime = Date.now();
877
+ socket = new WebSocket(websocketURL, [WEBSOCKET_PROTOCOL_BINARY, WEBSOCKET_PROTOCOL_BASE64]);
878
+ socket.addEventListener("open", handleOpen);
879
+ socket.addEventListener("close", handleClose);
880
+ socket.addEventListener("error", handleError);
881
+ socket.addEventListener("message", handleReflectorIdMessage);
882
+ disposeSocket = () => {
883
+ window.clearTimeout(retryWaitTimeoutId);
884
+ socket.removeEventListener("open", handleOpen);
885
+ socket.removeEventListener("close", handleClose);
886
+ socket.removeEventListener("error", handleError);
887
+ socket.removeEventListener("message", handleReflectorIdMessage);
888
+ };
889
+ };
890
+ attemptSocketConnection();
891
+ });
892
+ let sessionEstablished = false;
893
+ let handleClose;
894
+ return {
895
+ associationUrl,
896
+ close: () => {
897
+ socket.close();
898
+ handleClose();
899
+ },
900
+ wallet: new Promise((resolve, reject) => {
901
+ const jsonRpcResponsePromises = {};
902
+ const handleMessage = async (evt) => {
903
+ const responseBuffer = await decodeBytes(evt);
904
+ switch (state.__type) {
905
+ case "reflector_id_received": {
906
+ if (responseBuffer.byteLength !== 0) throw new Error("Encountered unexpected message while awaiting reflection");
907
+ const ecdhKeypair = await generateECDHKeypair();
908
+ const binaryMsg = await createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey);
909
+ if (encoding == "base64") socket.send(fromUint8Array$1(binaryMsg));
910
+ else socket.send(binaryMsg);
911
+ state = {
912
+ __type: "hello_req_sent",
913
+ associationPublicKey: associationKeypair.publicKey,
914
+ ecdhPrivateKey: ecdhKeypair.privateKey
915
+ };
916
+ break;
917
+ }
918
+ case "connected":
919
+ try {
920
+ const sequenceNumber = getSequenceNumberFromByteArray(responseBuffer.slice(0, 4));
921
+ if (sequenceNumber !== lastKnownInboundSequenceNumber + 1) throw new Error("Encrypted message has invalid sequence number");
922
+ lastKnownInboundSequenceNumber = sequenceNumber;
923
+ const jsonRpcMessage = await decryptJsonRpcMessage(responseBuffer, state.sharedSecret);
924
+ const responsePromise = jsonRpcResponsePromises[jsonRpcMessage.id];
925
+ delete jsonRpcResponsePromises[jsonRpcMessage.id];
926
+ responsePromise.resolve(jsonRpcMessage.result);
927
+ } catch (e) {
928
+ if (e instanceof SolanaMobileWalletAdapterProtocolError) {
929
+ const responsePromise = jsonRpcResponsePromises[e.jsonRpcMessageId];
930
+ delete jsonRpcResponsePromises[e.jsonRpcMessageId];
931
+ responsePromise.reject(e);
932
+ } else throw e;
933
+ }
934
+ break;
935
+ case "hello_req_sent": {
936
+ const sharedSecret = await parseHelloRsp(responseBuffer, state.associationPublicKey, state.ecdhPrivateKey);
937
+ const sessionPropertiesBuffer = responseBuffer.slice(65);
938
+ const sessionProperties = sessionPropertiesBuffer.byteLength !== 0 ? await (async () => {
939
+ const sequenceNumber = getSequenceNumberFromByteArray(sessionPropertiesBuffer.slice(0, 4));
940
+ if (sequenceNumber !== lastKnownInboundSequenceNumber + 1) throw new Error("Encrypted message has invalid sequence number");
941
+ lastKnownInboundSequenceNumber = sequenceNumber;
942
+ return parseSessionProps(sessionPropertiesBuffer, sharedSecret);
943
+ })() : { protocol_version: "legacy" };
944
+ state = {
945
+ __type: "connected",
946
+ sharedSecret,
947
+ sessionProperties
948
+ };
949
+ const wallet = createMobileWalletProxy(sessionProperties.protocol_version, async (method, params) => {
950
+ const id = nextJsonRpcMessageId++;
951
+ const binaryMsg = await encryptJsonRpcMessage({
952
+ id,
953
+ jsonrpc: "2.0",
954
+ method,
955
+ params: params ?? {}
956
+ }, sharedSecret);
957
+ if (encoding == "base64") socket.send(fromUint8Array$1(binaryMsg));
958
+ else socket.send(binaryMsg);
959
+ return new Promise((resolve, reject) => {
960
+ jsonRpcResponsePromises[id] = {
961
+ resolve(result) {
962
+ switch (method) {
963
+ case "authorize":
964
+ case "reauthorize": {
965
+ const { wallet_uri_base } = result;
966
+ if (wallet_uri_base != null) try {
967
+ assertSecureEndpointSpecificURI(wallet_uri_base);
968
+ } catch (e) {
969
+ reject(e);
970
+ return;
971
+ }
972
+ break;
973
+ }
974
+ }
975
+ resolve(result);
976
+ },
977
+ reject
978
+ };
979
+ });
980
+ });
981
+ sessionEstablished = true;
982
+ try {
983
+ resolve(wallet);
984
+ } catch (e) {
985
+ reject(e);
986
+ }
987
+ break;
988
+ }
989
+ }
990
+ };
991
+ socket.addEventListener("message", handleMessage);
992
+ handleClose = () => {
993
+ socket.removeEventListener("message", handleMessage);
994
+ disposeSocket();
995
+ if (!sessionEstablished) reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED, `The wallet session was closed before connection.`, { closeEvent: new CloseEvent("socket was closed before connection") }));
996
+ };
997
+ })
998
+ };
999
+ }
1000
+
1001
+ export { SolanaMobileWalletAdapterError as S, startScenario as a, SolanaMobileWalletAdapterErrorCode as b, startRemoteScenario as s, transact as t };
1002
+ //# sourceMappingURL=index.browser-OvGNsMPu.esm.js.map