@solana-mobile/mobile-wallet-adapter-protocol 2.1.4 → 2.2.0-new-arch-beta

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 (41) hide show
  1. package/.gitignore +2 -0
  2. package/android/.gitignore +14 -0
  3. package/android/build.gradle +13 -1
  4. package/android/src/main/java/com/solanamobile/mobilewalletadapter/reactnative/SolanaMobileWalletAdapterModule.kt +133 -110
  5. package/android/src/main/java/com/solanamobile/mobilewalletadapter/reactnative/SolanaMobileWalletAdapterPackage.kt +35 -16
  6. package/android/src/newarch/SolanaMobileWalletAdapter.kt +7 -0
  7. package/android/src/oldarch/SolanaMobileWalletAdapter.kt +16 -0
  8. package/lib/cjs/index.browser.js +8 -4
  9. package/lib/cjs/index.js +8 -4
  10. package/lib/cjs/index.native.js +4 -2
  11. package/lib/esm/index.browser.js +8 -4
  12. package/lib/esm/index.js +8 -4
  13. package/lib/types/index.native.d.ts.map +1 -1
  14. package/package.json +9 -1
  15. package/src/__forks__/react-native/base64Utils.ts +1 -0
  16. package/src/__forks__/react-native/transact.ts +91 -0
  17. package/src/arrayBufferToBase64String.ts +10 -0
  18. package/src/associationPort.ts +19 -0
  19. package/src/base64Utils.ts +3 -0
  20. package/src/codegenSpec/NativeSolanaMobileWalletAdapter.ts +13 -0
  21. package/src/createHelloReq.ts +12 -0
  22. package/src/createMobileWalletProxy.ts +175 -0
  23. package/src/createSIWSMessage.ts +14 -0
  24. package/src/createSequenceNumberVector.ts +11 -0
  25. package/src/encryptedMessage.ts +60 -0
  26. package/src/errors.ts +99 -0
  27. package/src/generateAssociationKeypair.ts +10 -0
  28. package/src/generateECDHKeypair.ts +10 -0
  29. package/src/getAssociateAndroidIntentURL.ts +78 -0
  30. package/src/getJWS.ts +19 -0
  31. package/src/getStringWithURLUnsafeBase64CharactersReplaced.ts +11 -0
  32. package/src/index.ts +3 -0
  33. package/src/jsonRpcMessage.ts +38 -0
  34. package/src/parseHelloRsp.ts +46 -0
  35. package/src/parseSessionProps.ts +33 -0
  36. package/src/reflectorId.ts +31 -0
  37. package/src/startSession.ts +130 -0
  38. package/src/transact.ts +499 -0
  39. package/src/types.ts +192 -0
  40. package/tsconfig.cjs.json +7 -0
  41. package/tsconfig.json +8 -0
@@ -0,0 +1,499 @@
1
+ import createHelloReq from './createHelloReq.js';
2
+ import createMobileWalletProxy from './createMobileWalletProxy.js';
3
+ import { SEQUENCE_NUMBER_BYTES } from './createSequenceNumberVector.js';
4
+ import { ENCODED_PUBLIC_KEY_LENGTH_BYTES } from './encryptedMessage.js';
5
+ import {
6
+ SolanaMobileWalletAdapterError,
7
+ SolanaMobileWalletAdapterErrorCode,
8
+ SolanaMobileWalletAdapterProtocolError,
9
+ } from './errors.js';
10
+ import generateAssociationKeypair from './generateAssociationKeypair.js';
11
+ import generateECDHKeypair from './generateECDHKeypair.js';
12
+ import { decryptJsonRpcMessage, encryptJsonRpcMessage } from './jsonRpcMessage.js';
13
+ import parseHelloRsp, { SharedSecret } from './parseHelloRsp.js';
14
+ import parseSessionProps from './parseSessionProps.js';
15
+ import { startSession, startRemoteSession, getRemoteSessionUrl } from './startSession.js';
16
+ import { AssociationKeypair, MobileWallet, RemoteMobileWallet, RemoteWalletAssociationConfig, SessionProperties, WalletAssociationConfig } from './types.js';
17
+
18
+ const WEBSOCKET_CONNECTION_CONFIG = {
19
+ /**
20
+ * 300 milliseconds is a generally accepted threshold for what someone
21
+ * would consider an acceptable response time for a user interface
22
+ * after having performed a low-attention tapping task. We set the initial
23
+ * interval at which we wait for the wallet to set up the websocket at
24
+ * half this, as per the Nyquist frequency, with a progressive backoff
25
+ * sequence from there. The total wait time is 30s, which allows for the
26
+ * user to be presented with a disambiguation dialog, select a wallet, and
27
+ * for the wallet app to subsequently start.
28
+ */
29
+ retryDelayScheduleMs: [150, 150, 200, 500, 500, 750, 750, 1000],
30
+ timeoutMs: 30000,
31
+ } as const;
32
+ const WEBSOCKET_PROTOCOL = 'com.solana.mobilewalletadapter.v1';
33
+
34
+ type JsonResponsePromises<T> = Record<
35
+ number,
36
+ Readonly<{ resolve: (value?: T | PromiseLike<T>) => void; reject: (reason?: unknown) => void }>
37
+ >;
38
+
39
+ type State =
40
+ | { __type: 'connected'; sharedSecret: SharedSecret; sessionProperties: SessionProperties }
41
+ | { __type: 'connecting'; associationKeypair: AssociationKeypair }
42
+ | { __type: 'disconnected' }
43
+ | { __type: 'hello_req_sent'; associationPublicKey: CryptoKey; ecdhPrivateKey: CryptoKey };
44
+
45
+ function assertSecureContext() {
46
+ if (typeof window === 'undefined' || window.isSecureContext !== true) {
47
+ throw new SolanaMobileWalletAdapterError(
48
+ SolanaMobileWalletAdapterErrorCode.ERROR_SECURE_CONTEXT_REQUIRED,
49
+ 'The mobile wallet adapter protocol must be used in a secure context (`https`).',
50
+ );
51
+ }
52
+ }
53
+
54
+ function assertSecureEndpointSpecificURI(walletUriBase: string) {
55
+ let url: URL;
56
+ try {
57
+ url = new URL(walletUriBase);
58
+ } catch {
59
+ throw new SolanaMobileWalletAdapterError(
60
+ SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL,
61
+ 'Invalid base URL supplied by wallet',
62
+ );
63
+ }
64
+ if (url.protocol !== 'https:') {
65
+ throw new SolanaMobileWalletAdapterError(
66
+ SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL,
67
+ 'Base URLs supplied by wallets must be valid `https` URLs',
68
+ );
69
+ }
70
+ }
71
+
72
+ function getSequenceNumberFromByteArray(byteArray: ArrayBuffer): number {
73
+ const view = new DataView(byteArray);
74
+ return view.getUint32(0, /* littleEndian */ false);
75
+ }
76
+
77
+ export async function transact<TReturn>(
78
+ callback: (wallet: MobileWallet) => TReturn,
79
+ config?: WalletAssociationConfig,
80
+ ): Promise<TReturn> {
81
+ assertSecureContext();
82
+ const associationKeypair = await generateAssociationKeypair();
83
+ const sessionPort = await startSession(associationKeypair.publicKey, config?.baseUri);
84
+ const websocketURL = `ws://localhost:${sessionPort}/solana-wallet`;
85
+ let connectionStartTime: number;
86
+ const getNextRetryDelayMs = (() => {
87
+ const schedule = [...WEBSOCKET_CONNECTION_CONFIG.retryDelayScheduleMs];
88
+ return () => (schedule.length > 1 ? (schedule.shift() as number) : schedule[0]);
89
+ })();
90
+ let nextJsonRpcMessageId = 1;
91
+ let lastKnownInboundSequenceNumber = 0;
92
+ let state: State = { __type: 'disconnected' };
93
+ return new Promise((resolve, reject) => {
94
+ let socket: WebSocket;
95
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
96
+ const jsonRpcResponsePromises: JsonResponsePromises<any> = {};
97
+ const handleOpen = async () => {
98
+ if (state.__type !== 'connecting') {
99
+ console.warn(
100
+ 'Expected adapter state to be `connecting` at the moment the websocket opens. ' +
101
+ `Got \`${state.__type}\`.`,
102
+ );
103
+ return;
104
+ }
105
+ socket.removeEventListener('open', handleOpen);
106
+
107
+ // previous versions of this library and walletlib incorrectly implemented the MWA session
108
+ // establishment protocol for local connections. The dapp is supposed to wait for the
109
+ // APP_PING message before sending the HELLO_REQ. Instead, the dapp was sending the HELLO_REQ
110
+ // immediately upon connection to the websocket server regardless of wether or not an
111
+ // APP_PING was sent by the wallet/websocket server. We must continue to support this behavior
112
+ // in case the user is using a wallet that has not updated their walletlib implementation.
113
+ const { associationKeypair } = state;
114
+ const ecdhKeypair = await generateECDHKeypair();
115
+ socket.send(await createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));
116
+ state = {
117
+ __type: 'hello_req_sent',
118
+ associationPublicKey: associationKeypair.publicKey,
119
+ ecdhPrivateKey: ecdhKeypair.privateKey,
120
+ };
121
+ };
122
+ const handleClose = (evt: CloseEvent) => {
123
+ if (evt.wasClean) {
124
+ state = { __type: 'disconnected' };
125
+ } else {
126
+ reject(
127
+ new SolanaMobileWalletAdapterError(
128
+ SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED,
129
+ `The wallet session dropped unexpectedly (${evt.code}: ${evt.reason}).`,
130
+ { closeEvent: evt },
131
+ ),
132
+ );
133
+ }
134
+ disposeSocket();
135
+ };
136
+ const handleError = async (_evt: Event) => {
137
+ disposeSocket();
138
+ if (Date.now() - connectionStartTime >= WEBSOCKET_CONNECTION_CONFIG.timeoutMs) {
139
+ reject(
140
+ new SolanaMobileWalletAdapterError(
141
+ SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT,
142
+ `Failed to connect to the wallet websocket at ${websocketURL}.`,
143
+ ),
144
+ );
145
+ } else {
146
+ await new Promise((resolve) => {
147
+ const retryDelayMs = getNextRetryDelayMs();
148
+ retryWaitTimeoutId = window.setTimeout(resolve, retryDelayMs);
149
+ });
150
+ attemptSocketConnection();
151
+ }
152
+ };
153
+ const handleMessage = async (evt: MessageEvent<Blob>) => {
154
+ const responseBuffer = await evt.data.arrayBuffer();
155
+ switch (state.__type) {
156
+ case 'connecting':
157
+ if (responseBuffer.byteLength !== 0) {
158
+ throw new Error('Encountered unexpected message while connecting');
159
+ }
160
+ const ecdhKeypair = await generateECDHKeypair();
161
+ socket.send(await createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));
162
+ state = {
163
+ __type: 'hello_req_sent',
164
+ associationPublicKey: associationKeypair.publicKey,
165
+ ecdhPrivateKey: ecdhKeypair.privateKey,
166
+ };
167
+ break;
168
+ case 'connected':
169
+ try {
170
+ const sequenceNumberVector = responseBuffer.slice(0, SEQUENCE_NUMBER_BYTES);
171
+ const sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector);
172
+ if (sequenceNumber !== (lastKnownInboundSequenceNumber + 1)) {
173
+ throw new Error('Encrypted message has invalid sequence number');
174
+ }
175
+ lastKnownInboundSequenceNumber = sequenceNumber;
176
+ const jsonRpcMessage = await decryptJsonRpcMessage(responseBuffer, state.sharedSecret);
177
+ const responsePromise = jsonRpcResponsePromises[jsonRpcMessage.id];
178
+ delete jsonRpcResponsePromises[jsonRpcMessage.id];
179
+ responsePromise.resolve(jsonRpcMessage.result);
180
+ } catch (e) {
181
+ if (e instanceof SolanaMobileWalletAdapterProtocolError) {
182
+ const responsePromise = jsonRpcResponsePromises[e.jsonRpcMessageId];
183
+ delete jsonRpcResponsePromises[e.jsonRpcMessageId];
184
+ responsePromise.reject(e);
185
+ } else {
186
+ throw e;
187
+ }
188
+ }
189
+ break;
190
+ case 'hello_req_sent': {
191
+ // if we receive an APP_PING message (empty message), resend the HELLO_REQ (see above)
192
+ if (responseBuffer.byteLength === 0) {
193
+ const ecdhKeypair = await generateECDHKeypair();
194
+ socket.send(await createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));
195
+ state = {
196
+ __type: 'hello_req_sent',
197
+ associationPublicKey: associationKeypair.publicKey,
198
+ ecdhPrivateKey: ecdhKeypair.privateKey,
199
+ };
200
+ break;
201
+ }
202
+ const sharedSecret = await parseHelloRsp(
203
+ responseBuffer,
204
+ state.associationPublicKey,
205
+ state.ecdhPrivateKey,
206
+ );
207
+ const sessionPropertiesBuffer = responseBuffer.slice(ENCODED_PUBLIC_KEY_LENGTH_BYTES);
208
+ const sessionProperties = sessionPropertiesBuffer.byteLength !== 0
209
+ ? await (async () => {
210
+ const sequenceNumberVector = sessionPropertiesBuffer.slice(0, SEQUENCE_NUMBER_BYTES);
211
+ const sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector);
212
+ if (sequenceNumber !== (lastKnownInboundSequenceNumber + 1)) {
213
+ throw new Error('Encrypted message has invalid sequence number');
214
+ }
215
+ lastKnownInboundSequenceNumber = sequenceNumber;
216
+ return parseSessionProps(sessionPropertiesBuffer, sharedSecret);
217
+ })() : <SessionProperties> { protocol_version: 'legacy' };
218
+ state = { __type: 'connected', sharedSecret, sessionProperties };
219
+ const wallet = createMobileWalletProxy(sessionProperties.protocol_version,
220
+ async (method, params) => {
221
+ const id = nextJsonRpcMessageId++;
222
+ socket.send(
223
+ await encryptJsonRpcMessage(
224
+ {
225
+ id,
226
+ jsonrpc: '2.0' as const,
227
+ method,
228
+ params: params ?? {},
229
+ },
230
+ sharedSecret,
231
+ ),
232
+ );
233
+ return new Promise((resolve, reject) => {
234
+ jsonRpcResponsePromises[id] = {
235
+ resolve(result) {
236
+ switch (method) {
237
+ case 'authorize':
238
+ case 'reauthorize': {
239
+ const { wallet_uri_base } = result as Awaited<
240
+ ReturnType<MobileWallet['authorize' | 'reauthorize']>
241
+ >;
242
+ if (wallet_uri_base != null) {
243
+ try {
244
+ assertSecureEndpointSpecificURI(wallet_uri_base);
245
+ } catch (e) {
246
+ reject(e);
247
+ return;
248
+ }
249
+ }
250
+ break;
251
+ }
252
+ }
253
+ resolve(result);
254
+ },
255
+ reject,
256
+ };
257
+ });
258
+ })
259
+ try {
260
+ resolve(await callback(wallet));
261
+ } catch (e) {
262
+ reject(e);
263
+ } finally {
264
+ disposeSocket();
265
+ socket.close();
266
+ }
267
+ break;
268
+ }
269
+ }
270
+ };
271
+ let disposeSocket: () => void;
272
+ let retryWaitTimeoutId: number;
273
+ const attemptSocketConnection = () => {
274
+ if (disposeSocket) {
275
+ disposeSocket();
276
+ }
277
+ state = { __type: 'connecting', associationKeypair };
278
+ if (connectionStartTime === undefined) {
279
+ connectionStartTime = Date.now();
280
+ }
281
+ socket = new WebSocket(websocketURL, [WEBSOCKET_PROTOCOL]);
282
+ socket.addEventListener('open', handleOpen);
283
+ socket.addEventListener('close', handleClose);
284
+ socket.addEventListener('error', handleError);
285
+ socket.addEventListener('message', handleMessage);
286
+ disposeSocket = () => {
287
+ window.clearTimeout(retryWaitTimeoutId);
288
+ socket.removeEventListener('open', handleOpen);
289
+ socket.removeEventListener('close', handleClose);
290
+ socket.removeEventListener('error', handleError);
291
+ socket.removeEventListener('message', handleMessage);
292
+ };
293
+ };
294
+ attemptSocketConnection();
295
+ });
296
+ }
297
+
298
+ export async function transactRemote<TReturn>(
299
+ callback: (wallet: RemoteMobileWallet) => TReturn,
300
+ config: RemoteWalletAssociationConfig,
301
+ ): Promise<{associationUrl: URL, result: Promise<TReturn>}> {
302
+ assertSecureContext();
303
+ const associationKeypair = await generateAssociationKeypair();
304
+ const { associationUrl, reflectorId } = await getRemoteSessionUrl(associationKeypair.publicKey, config.remoteHostAuthority, config?.baseUri);
305
+ const websocketURL = `wss://${config?.remoteHostAuthority}/reflect?id=${reflectorId}`;
306
+
307
+ let connectionStartTime: number;
308
+ const getNextRetryDelayMs = (() => {
309
+ const schedule = [...WEBSOCKET_CONNECTION_CONFIG.retryDelayScheduleMs];
310
+ return () => (schedule.length > 1 ? (schedule.shift() as number) : schedule[0]);
311
+ })();
312
+ let nextJsonRpcMessageId = 1;
313
+ let lastKnownInboundSequenceNumber = 0;
314
+ let state: State = { __type: 'disconnected' };
315
+ return { associationUrl, result: new Promise((resolve, reject) => {
316
+ let socket: WebSocket;
317
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
318
+ const jsonRpcResponsePromises: JsonResponsePromises<any> = {};
319
+ const handleOpen = async () => {
320
+ if (state.__type !== 'connecting') {
321
+ console.warn(
322
+ 'Expected adapter state to be `connecting` at the moment the websocket opens. ' +
323
+ `Got \`${state.__type}\`.`,
324
+ );
325
+ return;
326
+ }
327
+ socket.removeEventListener('open', handleOpen);
328
+ };
329
+ const handleClose = (evt: CloseEvent) => {
330
+ if (evt.wasClean) {
331
+ state = { __type: 'disconnected' };
332
+ } else {
333
+ reject(
334
+ new SolanaMobileWalletAdapterError(
335
+ SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED,
336
+ `The wallet session dropped unexpectedly (${evt.code}: ${evt.reason}).`,
337
+ { closeEvent: evt },
338
+ ),
339
+ );
340
+ }
341
+ disposeSocket();
342
+ };
343
+ const handleError = async (_evt: Event) => {
344
+ disposeSocket();
345
+ if (Date.now() - connectionStartTime >= WEBSOCKET_CONNECTION_CONFIG.timeoutMs) {
346
+ reject(
347
+ new SolanaMobileWalletAdapterError(
348
+ SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT,
349
+ `Failed to connect to the wallet websocket at ${websocketURL}.`,
350
+ ),
351
+ );
352
+ } else {
353
+ await new Promise((resolve) => {
354
+ const retryDelayMs = getNextRetryDelayMs();
355
+ retryWaitTimeoutId = window.setTimeout(resolve, retryDelayMs);
356
+ });
357
+ attemptSocketConnection();
358
+ }
359
+ };
360
+ const handleMessage = async (evt: MessageEvent<Blob>) => {
361
+ const responseBuffer = await evt.data.arrayBuffer();
362
+ switch (state.__type) {
363
+ case 'connecting':
364
+ if (responseBuffer.byteLength !== 0) {
365
+ throw new Error('Encountered unexpected message while connecting');
366
+ }
367
+ const ecdhKeypair = await generateECDHKeypair();
368
+ socket.send(await createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));
369
+ state = {
370
+ __type: 'hello_req_sent',
371
+ associationPublicKey: associationKeypair.publicKey,
372
+ ecdhPrivateKey: ecdhKeypair.privateKey,
373
+ };
374
+ break;
375
+ case 'connected':
376
+ try {
377
+ const sequenceNumberVector = responseBuffer.slice(0, SEQUENCE_NUMBER_BYTES);
378
+ const sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector);
379
+ if (sequenceNumber !== (lastKnownInboundSequenceNumber + 1)) {
380
+ throw new Error('Encrypted message has invalid sequence number');
381
+ }
382
+ lastKnownInboundSequenceNumber = sequenceNumber;
383
+ const jsonRpcMessage = await decryptJsonRpcMessage(responseBuffer, state.sharedSecret);
384
+ const responsePromise = jsonRpcResponsePromises[jsonRpcMessage.id];
385
+ delete jsonRpcResponsePromises[jsonRpcMessage.id];
386
+ responsePromise.resolve(jsonRpcMessage.result);
387
+ } catch (e) {
388
+ if (e instanceof SolanaMobileWalletAdapterProtocolError) {
389
+ const responsePromise = jsonRpcResponsePromises[e.jsonRpcMessageId];
390
+ delete jsonRpcResponsePromises[e.jsonRpcMessageId];
391
+ responsePromise.reject(e);
392
+ } else {
393
+ throw e;
394
+ }
395
+ }
396
+ break;
397
+ case 'hello_req_sent': {
398
+ const sharedSecret = await parseHelloRsp(
399
+ responseBuffer,
400
+ state.associationPublicKey,
401
+ state.ecdhPrivateKey,
402
+ );
403
+ const sessionPropertiesBuffer = responseBuffer.slice(ENCODED_PUBLIC_KEY_LENGTH_BYTES);
404
+ const sessionProperties = sessionPropertiesBuffer.byteLength !== 0
405
+ ? await (async () => {
406
+ const sequenceNumberVector = sessionPropertiesBuffer.slice(0, SEQUENCE_NUMBER_BYTES);
407
+ const sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector);
408
+ if (sequenceNumber !== (lastKnownInboundSequenceNumber + 1)) {
409
+ throw new Error('Encrypted message has invalid sequence number');
410
+ }
411
+ lastKnownInboundSequenceNumber = sequenceNumber;
412
+ return parseSessionProps(sessionPropertiesBuffer, sharedSecret);
413
+ })() : <SessionProperties> { protocol_version: 'legacy' };
414
+ state = { __type: 'connected', sharedSecret, sessionProperties };
415
+ const wallet = createMobileWalletProxy(sessionProperties.protocol_version,
416
+ async (method, params) => {
417
+ const id = nextJsonRpcMessageId++;
418
+ socket.send(
419
+ await encryptJsonRpcMessage(
420
+ {
421
+ id,
422
+ jsonrpc: '2.0' as const,
423
+ method,
424
+ params: params ?? {},
425
+ },
426
+ sharedSecret,
427
+ ),
428
+ );
429
+ return new Promise((resolve, reject) => {
430
+ jsonRpcResponsePromises[id] = {
431
+ resolve(result) {
432
+ switch (method) {
433
+ case 'authorize':
434
+ case 'reauthorize': {
435
+ const { wallet_uri_base } = result as Awaited<
436
+ ReturnType<MobileWallet['authorize' | 'reauthorize']>
437
+ >;
438
+ if (wallet_uri_base != null) {
439
+ try {
440
+ assertSecureEndpointSpecificURI(wallet_uri_base);
441
+ } catch (e) {
442
+ reject(e);
443
+ return;
444
+ }
445
+ }
446
+ break;
447
+ }
448
+ }
449
+ resolve(result);
450
+ },
451
+ reject,
452
+ };
453
+ });
454
+ })
455
+ try {
456
+ resolve(await callback(new Proxy(wallet as RemoteMobileWallet, {
457
+ get<TMethodName extends keyof RemoteMobileWallet>(target: RemoteMobileWallet, p: TMethodName) {
458
+ if (p == 'terminateSession') {
459
+ return async function () {
460
+ disposeSocket();
461
+ socket.close();
462
+ return;
463
+ };
464
+ } else return target[p];
465
+ },
466
+ })))
467
+ } catch (e) {
468
+ reject(e);
469
+ }
470
+ break;
471
+ }
472
+ }
473
+ };
474
+ let disposeSocket: () => void;
475
+ let retryWaitTimeoutId: number;
476
+ const attemptSocketConnection = () => {
477
+ if (disposeSocket) {
478
+ disposeSocket();
479
+ }
480
+ state = { __type: 'connecting', associationKeypair };
481
+ if (connectionStartTime === undefined) {
482
+ connectionStartTime = Date.now();
483
+ }
484
+ socket = new WebSocket(websocketURL, [WEBSOCKET_PROTOCOL]);
485
+ socket.addEventListener('open', handleOpen);
486
+ socket.addEventListener('close', handleClose);
487
+ socket.addEventListener('error', handleError);
488
+ socket.addEventListener('message', handleMessage);
489
+ disposeSocket = () => {
490
+ window.clearTimeout(retryWaitTimeoutId);
491
+ socket.removeEventListener('open', handleOpen);
492
+ socket.removeEventListener('close', handleClose);
493
+ socket.removeEventListener('error', handleError);
494
+ socket.removeEventListener('message', handleMessage);
495
+ };
496
+ };
497
+ attemptSocketConnection();
498
+ })};
499
+ }
package/src/types.ts ADDED
@@ -0,0 +1,192 @@
1
+ import type { TransactionVersion } from '@solana/web3.js';
2
+ import type { SolanaSignInInput } from "@solana/wallet-standard";
3
+ import type { IdentifierArray, IdentifierString, WalletAccount, WalletIcon } from '@wallet-standard/core';
4
+
5
+ export type Account = Readonly<{
6
+ address: Base64EncodedAddress;
7
+ label?: string;
8
+ icon?: WalletIcon;
9
+ chains?: IdentifierArray;
10
+ features?: IdentifierArray;
11
+ }> | WalletAccount;
12
+
13
+ /**
14
+ * Properties that wallets may present to users when an app
15
+ * asks for authorization to execute privileged methods (see
16
+ * {@link PrivilegedMethods}).
17
+ */
18
+ export type AppIdentity = Readonly<{
19
+ uri?: string;
20
+ icon?: string;
21
+ name?: string;
22
+ }>;
23
+
24
+ /**
25
+ * An ephemeral elliptic-curve keypair on the P-256 curve.
26
+ * This public key is used to create the association token.
27
+ * The private key is used during session establishment.
28
+ */
29
+ export type AssociationKeypair = CryptoKeyPair;
30
+
31
+ export type ProtocolVersion = 'v1' | 'legacy';
32
+
33
+ export type SessionProperties = Readonly<{
34
+ protocol_version: ProtocolVersion;
35
+ }>;
36
+
37
+ /**
38
+ * The context returned from a wallet after having authorized a given
39
+ * account for use with a given application. You can cache this and
40
+ * use it later to invoke privileged methods.
41
+ */
42
+ export type AuthorizationResult = Readonly<{
43
+ accounts: Account[];
44
+ auth_token: AuthToken;
45
+ wallet_uri_base: string;
46
+ sign_in_result?: SignInResult;
47
+ }>;
48
+
49
+ export type AuthToken = string;
50
+
51
+ export type Base64EncodedAddress = string;
52
+
53
+ type Base64EncodedSignature = string;
54
+
55
+ type Base64EncodedMessage = string;
56
+
57
+ type Base64EncodedSignedMessage = string;
58
+
59
+ type Base64EncodedSignedTransaction = string;
60
+
61
+ export type Base64EncodedTransaction = string;
62
+
63
+ /**
64
+ * @deprecated Replaced by the 'chain' parameter, which adds multi-chain capability as per MWA 2.0 spec.
65
+ */
66
+ export type Cluster = 'devnet' | 'testnet' | 'mainnet-beta';
67
+
68
+ export type Chain = IdentifierString | Cluster;
69
+
70
+ export type Finality = 'confirmed' | 'finalized' | 'processed';
71
+
72
+ export type WalletAssociationConfig = Readonly<{
73
+ baseUri?: string;
74
+ }>;
75
+
76
+ export type RemoteWalletAssociationConfig = WalletAssociationConfig & Readonly<{
77
+ remoteHostAuthority: string;
78
+ }>;
79
+
80
+ export interface AuthorizeAPI {
81
+ /**
82
+ * @deprecated Replaced by updated authorize() method, which adds MWA 2.0 spec support.
83
+ */
84
+ authorize(params: { cluster: Cluster; identity: AppIdentity }): Promise<AuthorizationResult>;
85
+
86
+ authorize(params: {
87
+ identity: AppIdentity;
88
+ chain?: Chain;
89
+ features?: IdentifierArray;
90
+ addresses?: string[];
91
+ auth_token?: AuthToken;
92
+ sign_in_payload?: SignInPayload;
93
+ }): Promise<AuthorizationResult>;
94
+ }
95
+ export interface CloneAuthorizationAPI {
96
+ cloneAuthorization(params: { auth_token: AuthToken }): Promise<Readonly<{ auth_token: AuthToken }>>;
97
+ }
98
+ export interface DeauthorizeAPI {
99
+ deauthorize(params: { auth_token: AuthToken }): Promise<Readonly<Record<string, never>>>;
100
+ }
101
+
102
+ export interface GetCapabilitiesAPI {
103
+ getCapabilities(): Promise<
104
+ Readonly<{
105
+ max_transactions_per_request: number;
106
+ max_messages_per_request: number;
107
+ supported_transaction_versions: ReadonlyArray<TransactionVersion>;
108
+ features: IdentifierArray;
109
+ /**
110
+ * @deprecated Replaced by features array.
111
+ */
112
+ supports_clone_authorization: boolean;
113
+ /**
114
+ * @deprecated Replaced by features array.
115
+ */
116
+ supports_sign_and_send_transactions: boolean;
117
+ }>
118
+ >;
119
+ }
120
+ export interface ReauthorizeAPI {
121
+ reauthorize(params: { auth_token: AuthToken; identity: AppIdentity }): Promise<AuthorizationResult>;
122
+ }
123
+ export interface SignMessagesAPI {
124
+ signMessages(params: {
125
+ addresses: Base64EncodedAddress[];
126
+ payloads: Base64EncodedMessage[];
127
+ }): Promise<Readonly<{ signed_payloads: Base64EncodedSignedMessage[] }>>;
128
+ }
129
+ export interface SignTransactionsAPI {
130
+ signTransactions(params: {
131
+ payloads: Base64EncodedTransaction[];
132
+ }): Promise<Readonly<{ signed_payloads: Base64EncodedSignedTransaction[] }>>;
133
+ }
134
+ export interface SignAndSendTransactionsAPI {
135
+ signAndSendTransactions(params: {
136
+ options?: Readonly<{
137
+ min_context_slot?: number;
138
+ commitment?: string;
139
+ skip_preflight?: boolean;
140
+ max_retries?: number;
141
+ wait_for_commitment_to_send_next_transaction?: boolean;
142
+ }>;
143
+ payloads: Base64EncodedTransaction[];
144
+ }): Promise<Readonly<{ signatures: Base64EncodedSignature[] }>>;
145
+ }
146
+
147
+ export interface MobileWallet
148
+ extends AuthorizeAPI,
149
+ CloneAuthorizationAPI,
150
+ DeauthorizeAPI,
151
+ GetCapabilitiesAPI,
152
+ ReauthorizeAPI,
153
+ SignMessagesAPI,
154
+ SignTransactionsAPI,
155
+ SignAndSendTransactionsAPI {}
156
+
157
+ export interface TerminateSessionAPI {
158
+ terminateSession(): void
159
+ }
160
+
161
+ export interface RemoteMobileWallet
162
+ extends MobileWallet, TerminateSessionAPI {}
163
+
164
+ // optional features
165
+ export const SolanaSignTransactions = 'solana:signTransactions'
166
+ export const SolanaCloneAuthorization = 'solana:cloneAuthorization'
167
+ export const SolanaSignInWithSolana = 'solana:signInWithSolana'
168
+
169
+ export type SignInPayload = Readonly<{
170
+ domain?: string;
171
+ address?: string;
172
+ statement?: string;
173
+ uri?: string;
174
+ version?: string;
175
+ chainId?: string;
176
+ nonce?: string;
177
+ issuedAt?: string;
178
+ expirationTime?: string;
179
+ notBefore?: string;
180
+ requestId?: string;
181
+ resources?: readonly string[];
182
+ }> | SolanaSignInInput;
183
+
184
+ export type SignInPayloadWithRequiredFields = Partial<SignInPayload> &
185
+ Required<Pick<SignInPayload, 'domain' | 'address'>>
186
+
187
+ export type SignInResult = Readonly<{
188
+ address: Base64EncodedAddress;
189
+ signed_message: Base64EncodedSignedMessage;
190
+ signature: Base64EncodedAddress;
191
+ signature_type?: string;
192
+ }>;