@solana-mobile/mobile-wallet-adapter-protocol 2.1.3 → 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.
- package/android/build.gradle +15 -3
- package/android/gradle/wrapper/gradle-wrapper.properties +1 -1
- package/android/src/main/java/com/solanamobile/mobilewalletadapter/reactnative/SolanaMobileWalletAdapterModule.kt +133 -110
- package/android/src/main/java/com/solanamobile/mobilewalletadapter/reactnative/SolanaMobileWalletAdapterPackage.kt +35 -16
- package/android/src/newarch/SolanaMobileWalletAdapter.kt +7 -0
- package/android/src/oldarch/SolanaMobileWalletAdapter.kt +16 -0
- package/lib/cjs/index.browser.js +266 -5
- package/lib/cjs/index.js +266 -5
- package/lib/cjs/index.native.js +5 -2
- package/lib/esm/index.browser.js +266 -6
- package/lib/esm/index.js +266 -6
- package/lib/types/index.browser.d.ts +17 -1
- package/lib/types/index.browser.d.ts.map +1 -1
- package/lib/types/index.d.ts +17 -1
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/index.native.d.ts +17 -1
- package/lib/types/index.native.d.ts.map +1 -1
- package/package.json +10 -2
- package/src/__forks__/react-native/transact.ts +14 -15
- package/src/codegenSpec/NativeSolanaMobileWalletAdapter.ts +13 -0
- package/src/errors.ts +4 -0
- package/src/getAssociateAndroidIntentURL.ts +21 -0
- package/src/reflectorId.ts +31 -0
- package/src/startSession.ts +130 -94
- package/src/transact.ts +237 -4
- package/src/types.ts +11 -0
|
@@ -2,6 +2,7 @@ import arrayBufferToBase64String from './arrayBufferToBase64String.js';
|
|
|
2
2
|
import { assertAssociationPort } from './associationPort.js';
|
|
3
3
|
import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode } from './errors.js';
|
|
4
4
|
import getStringWithURLUnsafeBase64CharactersReplaced from './getStringWithURLUnsafeBase64CharactersReplaced.js';
|
|
5
|
+
import { assertReflectorId } from './reflectorId.js';
|
|
5
6
|
import { ProtocolVersion } from './types.js';
|
|
6
7
|
|
|
7
8
|
const INTENT_NAME = 'solana-wallet';
|
|
@@ -55,3 +56,23 @@ export default async function getAssociateAndroidIntentURL(
|
|
|
55
56
|
})
|
|
56
57
|
return url;
|
|
57
58
|
}
|
|
59
|
+
|
|
60
|
+
export async function getRemoteAssociateAndroidIntentURL(
|
|
61
|
+
associationPublicKey: CryptoKey,
|
|
62
|
+
hostAuthority: string,
|
|
63
|
+
putativeId: number,
|
|
64
|
+
associationURLBase?: string,
|
|
65
|
+
protocolVersions: ProtocolVersion[] = ['v1'],
|
|
66
|
+
): Promise<URL> {
|
|
67
|
+
const reflectorId = assertReflectorId(putativeId);
|
|
68
|
+
const exportedKey = await crypto.subtle.exportKey('raw', associationPublicKey);
|
|
69
|
+
const encodedKey = arrayBufferToBase64String(exportedKey);
|
|
70
|
+
const url = getIntentURL('v1/associate/remote', associationURLBase);
|
|
71
|
+
url.searchParams.set('association', getStringWithURLUnsafeBase64CharactersReplaced(encodedKey));
|
|
72
|
+
url.searchParams.set('reflector', `${hostAuthority}`);
|
|
73
|
+
url.searchParams.set('id', `${reflectorId}`);
|
|
74
|
+
protocolVersions.forEach( (version) => {
|
|
75
|
+
url.searchParams.set('v', version);
|
|
76
|
+
})
|
|
77
|
+
return url;
|
|
78
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode } from './errors.js';
|
|
2
|
+
|
|
3
|
+
declare const tag: unique symbol;
|
|
4
|
+
export type ReflectorId = number & { readonly [tag]: 'ReflectorId' };
|
|
5
|
+
|
|
6
|
+
export function getRandomReflectorId(): ReflectorId {
|
|
7
|
+
return assertReflectorId(getRandomInt(0, 9007199254740991)); // 0 < id < 2^53 - 1
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function getRandomInt(min: number, max: number) {
|
|
11
|
+
const randomBuffer = new Uint32Array(1);
|
|
12
|
+
|
|
13
|
+
window.crypto.getRandomValues(randomBuffer);
|
|
14
|
+
|
|
15
|
+
let randomNumber = randomBuffer[0] / (0xffffffff + 1);
|
|
16
|
+
|
|
17
|
+
min = Math.ceil(min);
|
|
18
|
+
max = Math.floor(max);
|
|
19
|
+
return Math.floor(randomNumber * (max - min + 1)) + min;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function assertReflectorId(id: number): ReflectorId {
|
|
23
|
+
if (id < 0 || id > 9007199254740991) { // 0 < id < 2^53 - 1
|
|
24
|
+
throw new SolanaMobileWalletAdapterError(
|
|
25
|
+
SolanaMobileWalletAdapterErrorCode.ERROR_REFLECTOR_ID_OUT_OF_RANGE,
|
|
26
|
+
`Association port number must be between 49152 and 65535. ${id} given.`,
|
|
27
|
+
{ id },
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
return id as ReflectorId;
|
|
31
|
+
}
|
package/src/startSession.ts
CHANGED
|
@@ -1,94 +1,130 @@
|
|
|
1
|
-
import { AssociationPort, getRandomAssociationPort } from './associationPort.js';
|
|
2
|
-
import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode } from './errors.js';
|
|
3
|
-
import getAssociateAndroidIntentURL from './getAssociateAndroidIntentURL.js';
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
//
|
|
23
|
-
//
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
_frame
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
1
|
+
import { AssociationPort, getRandomAssociationPort } from './associationPort.js';
|
|
2
|
+
import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode } from './errors.js';
|
|
3
|
+
import getAssociateAndroidIntentURL, { getRemoteAssociateAndroidIntentURL } from './getAssociateAndroidIntentURL.js';
|
|
4
|
+
import { assertReflectorId, getRandomReflectorId, ReflectorId } from './reflectorId.js';
|
|
5
|
+
|
|
6
|
+
// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/
|
|
7
|
+
const Browser = {
|
|
8
|
+
Firefox: 0,
|
|
9
|
+
Other: 1,
|
|
10
|
+
} as const;
|
|
11
|
+
type BrowserEnum = typeof Browser[keyof typeof Browser];
|
|
12
|
+
|
|
13
|
+
function assertUnreachable(x: never): never {
|
|
14
|
+
return x;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function getBrowser(): BrowserEnum {
|
|
18
|
+
return navigator.userAgent.indexOf('Firefox/') !== -1 ? Browser.Firefox : Browser.Other;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function getDetectionPromise() {
|
|
22
|
+
// Chrome and others silently fail if a custom protocol is not supported.
|
|
23
|
+
// For these, we wait to see if the browser is navigated away from in
|
|
24
|
+
// a reasonable amount of time (ie. the native wallet opened).
|
|
25
|
+
return new Promise<void>((resolve, reject) => {
|
|
26
|
+
function cleanup() {
|
|
27
|
+
clearTimeout(timeoutId);
|
|
28
|
+
window.removeEventListener('blur', handleBlur);
|
|
29
|
+
}
|
|
30
|
+
function handleBlur() {
|
|
31
|
+
cleanup();
|
|
32
|
+
resolve();
|
|
33
|
+
}
|
|
34
|
+
window.addEventListener('blur', handleBlur);
|
|
35
|
+
const timeoutId = setTimeout(() => {
|
|
36
|
+
cleanup();
|
|
37
|
+
reject();
|
|
38
|
+
}, 2000);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
let _frame: HTMLIFrameElement | null = null;
|
|
43
|
+
function launchUrlThroughHiddenFrame(url: URL) {
|
|
44
|
+
if (_frame == null) {
|
|
45
|
+
_frame = document.createElement('iframe');
|
|
46
|
+
_frame.style.display = 'none';
|
|
47
|
+
document.body.appendChild(_frame);
|
|
48
|
+
}
|
|
49
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
50
|
+
_frame.contentWindow!.location.href = url.toString();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function launchAssociation(associationUrl: URL) {
|
|
54
|
+
if (associationUrl.protocol === 'https:') {
|
|
55
|
+
// The association URL is an Android 'App Link' or iOS 'Universal Link'.
|
|
56
|
+
// These are regular web URLs that are designed to launch an app if it
|
|
57
|
+
// is installed or load the actual target webpage if not.
|
|
58
|
+
window.location.assign(associationUrl);
|
|
59
|
+
} else {
|
|
60
|
+
// The association URL has a custom protocol (eg. `solana-wallet:`)
|
|
61
|
+
try {
|
|
62
|
+
const browser = getBrowser();
|
|
63
|
+
switch (browser) {
|
|
64
|
+
case Browser.Firefox:
|
|
65
|
+
// If a custom protocol is not supported in Firefox, it throws.
|
|
66
|
+
launchUrlThroughHiddenFrame(associationUrl);
|
|
67
|
+
// If we reached this line, it's supported.
|
|
68
|
+
break;
|
|
69
|
+
case Browser.Other: {
|
|
70
|
+
const detectionPromise = getDetectionPromise();
|
|
71
|
+
window.location.assign(associationUrl);
|
|
72
|
+
await detectionPromise;
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
default:
|
|
76
|
+
assertUnreachable(browser);
|
|
77
|
+
}
|
|
78
|
+
} catch (e) {
|
|
79
|
+
throw new SolanaMobileWalletAdapterError(
|
|
80
|
+
SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND,
|
|
81
|
+
'Found no installed wallet that supports the mobile wallet protocol.',
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function startSession(
|
|
88
|
+
associationPublicKey: CryptoKey,
|
|
89
|
+
associationURLBase?: string,
|
|
90
|
+
): Promise<AssociationPort> {
|
|
91
|
+
const randomAssociationPort = getRandomAssociationPort();
|
|
92
|
+
const associationUrl = await getAssociateAndroidIntentURL(
|
|
93
|
+
associationPublicKey,
|
|
94
|
+
randomAssociationPort,
|
|
95
|
+
associationURLBase,
|
|
96
|
+
);
|
|
97
|
+
await launchAssociation(associationUrl);
|
|
98
|
+
return randomAssociationPort;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function startRemoteSession(
|
|
102
|
+
associationPublicKey: CryptoKey,
|
|
103
|
+
hostAuthority: string,
|
|
104
|
+
associationURLBase?: string,
|
|
105
|
+
): Promise<ReflectorId> {
|
|
106
|
+
const randomReflectorId = getRandomReflectorId();
|
|
107
|
+
const associationUrl = await getRemoteAssociateAndroidIntentURL(
|
|
108
|
+
associationPublicKey,
|
|
109
|
+
hostAuthority,
|
|
110
|
+
randomReflectorId,
|
|
111
|
+
associationURLBase,
|
|
112
|
+
);
|
|
113
|
+
await launchAssociation(associationUrl);
|
|
114
|
+
return randomReflectorId;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export async function getRemoteSessionUrl(
|
|
118
|
+
associationPublicKey: CryptoKey,
|
|
119
|
+
hostAuthority: string,
|
|
120
|
+
associationURLBase?: string,
|
|
121
|
+
): Promise<{associationUrl: URL, reflectorId: ReflectorId }> {
|
|
122
|
+
const randomReflectorId = getRandomReflectorId();
|
|
123
|
+
const associationUrl = await getRemoteAssociateAndroidIntentURL(
|
|
124
|
+
associationPublicKey,
|
|
125
|
+
hostAuthority,
|
|
126
|
+
randomReflectorId,
|
|
127
|
+
associationURLBase,
|
|
128
|
+
);
|
|
129
|
+
return { associationUrl, reflectorId: randomReflectorId };
|
|
130
|
+
}
|
package/src/transact.ts
CHANGED
|
@@ -12,8 +12,8 @@ import generateECDHKeypair from './generateECDHKeypair.js';
|
|
|
12
12
|
import { decryptJsonRpcMessage, encryptJsonRpcMessage } from './jsonRpcMessage.js';
|
|
13
13
|
import parseHelloRsp, { SharedSecret } from './parseHelloRsp.js';
|
|
14
14
|
import parseSessionProps from './parseSessionProps.js';
|
|
15
|
-
import { startSession } from './startSession.js';
|
|
16
|
-
import { AssociationKeypair, MobileWallet, SessionProperties, WalletAssociationConfig } from './types.js';
|
|
15
|
+
import { startSession, startRemoteSession, getRemoteSessionUrl } from './startSession.js';
|
|
16
|
+
import { AssociationKeypair, MobileWallet, RemoteMobileWallet, RemoteWalletAssociationConfig, SessionProperties, WalletAssociationConfig } from './types.js';
|
|
17
17
|
|
|
18
18
|
const WEBSOCKET_CONNECTION_CONFIG = {
|
|
19
19
|
/**
|
|
@@ -102,8 +102,15 @@ export async function transact<TReturn>(
|
|
|
102
102
|
);
|
|
103
103
|
return;
|
|
104
104
|
}
|
|
105
|
-
const { associationKeypair } = state;
|
|
106
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;
|
|
107
114
|
const ecdhKeypair = await generateECDHKeypair();
|
|
108
115
|
socket.send(await createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));
|
|
109
116
|
state = {
|
|
@@ -132,7 +139,7 @@ export async function transact<TReturn>(
|
|
|
132
139
|
reject(
|
|
133
140
|
new SolanaMobileWalletAdapterError(
|
|
134
141
|
SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT,
|
|
135
|
-
`Failed to connect to the wallet websocket
|
|
142
|
+
`Failed to connect to the wallet websocket at ${websocketURL}.`,
|
|
136
143
|
),
|
|
137
144
|
);
|
|
138
145
|
} else {
|
|
@@ -146,6 +153,18 @@ export async function transact<TReturn>(
|
|
|
146
153
|
const handleMessage = async (evt: MessageEvent<Blob>) => {
|
|
147
154
|
const responseBuffer = await evt.data.arrayBuffer();
|
|
148
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;
|
|
149
168
|
case 'connected':
|
|
150
169
|
try {
|
|
151
170
|
const sequenceNumberVector = responseBuffer.slice(0, SEQUENCE_NUMBER_BYTES);
|
|
@@ -169,6 +188,17 @@ export async function transact<TReturn>(
|
|
|
169
188
|
}
|
|
170
189
|
break;
|
|
171
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
|
+
}
|
|
172
202
|
const sharedSecret = await parseHelloRsp(
|
|
173
203
|
responseBuffer,
|
|
174
204
|
state.associationPublicKey,
|
|
@@ -264,3 +294,206 @@ export async function transact<TReturn>(
|
|
|
264
294
|
attemptSocketConnection();
|
|
265
295
|
});
|
|
266
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
CHANGED
|
@@ -73,6 +73,10 @@ export type WalletAssociationConfig = Readonly<{
|
|
|
73
73
|
baseUri?: string;
|
|
74
74
|
}>;
|
|
75
75
|
|
|
76
|
+
export type RemoteWalletAssociationConfig = WalletAssociationConfig & Readonly<{
|
|
77
|
+
remoteHostAuthority: string;
|
|
78
|
+
}>;
|
|
79
|
+
|
|
76
80
|
export interface AuthorizeAPI {
|
|
77
81
|
/**
|
|
78
82
|
* @deprecated Replaced by updated authorize() method, which adds MWA 2.0 spec support.
|
|
@@ -150,6 +154,13 @@ export interface MobileWallet
|
|
|
150
154
|
SignTransactionsAPI,
|
|
151
155
|
SignAndSendTransactionsAPI {}
|
|
152
156
|
|
|
157
|
+
export interface TerminateSessionAPI {
|
|
158
|
+
terminateSession(): void
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export interface RemoteMobileWallet
|
|
162
|
+
extends MobileWallet, TerminateSessionAPI {}
|
|
163
|
+
|
|
153
164
|
// optional features
|
|
154
165
|
export const SolanaSignTransactions = 'solana:signTransactions'
|
|
155
166
|
export const SolanaCloneAuthorization = 'solana:cloneAuthorization'
|