@pooflabs/web 0.0.80 → 0.0.81-rc1

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