@solana-mobile/mobile-wallet-adapter-protocol 2.1.3 → 2.1.4
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 +3 -3
- package/android/gradle/wrapper/gradle-wrapper.properties +1 -1
- package/lib/cjs/index.browser.js +262 -5
- package/lib/cjs/index.js +262 -5
- package/lib/cjs/index.native.js +1 -0
- package/lib/esm/index.browser.js +262 -6
- package/lib/esm/index.js +262 -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 +2 -2
- package/.gitignore +0 -2
- package/android/.gitignore +0 -14
- package/src/__forks__/react-native/base64Utils.ts +0 -1
- package/src/__forks__/react-native/transact.ts +0 -92
- package/src/arrayBufferToBase64String.ts +0 -10
- package/src/associationPort.ts +0 -19
- package/src/base64Utils.ts +0 -3
- package/src/createHelloReq.ts +0 -12
- package/src/createMobileWalletProxy.ts +0 -175
- package/src/createSIWSMessage.ts +0 -14
- package/src/createSequenceNumberVector.ts +0 -11
- package/src/encryptedMessage.ts +0 -60
- package/src/errors.ts +0 -95
- package/src/generateAssociationKeypair.ts +0 -10
- package/src/generateECDHKeypair.ts +0 -10
- package/src/getAssociateAndroidIntentURL.ts +0 -57
- package/src/getJWS.ts +0 -19
- package/src/getStringWithURLUnsafeBase64CharactersReplaced.ts +0 -11
- package/src/index.ts +0 -3
- package/src/jsonRpcMessage.ts +0 -38
- package/src/parseHelloRsp.ts +0 -46
- package/src/parseSessionProps.ts +0 -33
- package/src/startSession.ts +0 -94
- package/src/transact.ts +0 -266
- package/src/types.ts +0 -181
- package/tsconfig.cjs.json +0 -7
- package/tsconfig.json +0 -8
package/src/parseHelloRsp.ts
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { ENCODED_PUBLIC_KEY_LENGTH_BYTES } from "./encryptedMessage";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* A secret agreed upon by the app and the wallet. Used as
|
|
5
|
-
* a symmetric key to encrypt and decrypt messages over an
|
|
6
|
-
* unsecured channel.
|
|
7
|
-
*/
|
|
8
|
-
export type SharedSecret = CryptoKey;
|
|
9
|
-
|
|
10
|
-
export default async function parseHelloRsp(
|
|
11
|
-
payloadBuffer: ArrayBuffer, // The X9.62-encoded wallet endpoint ephemeral ECDH public keypoint.
|
|
12
|
-
associationPublicKey: CryptoKey,
|
|
13
|
-
ecdhPrivateKey: CryptoKey,
|
|
14
|
-
): Promise<SharedSecret> {
|
|
15
|
-
const [associationPublicKeyBuffer, walletPublicKey] = await Promise.all([
|
|
16
|
-
crypto.subtle.exportKey('raw', associationPublicKey),
|
|
17
|
-
crypto.subtle.importKey(
|
|
18
|
-
'raw',
|
|
19
|
-
payloadBuffer.slice(0, ENCODED_PUBLIC_KEY_LENGTH_BYTES),
|
|
20
|
-
{ name: 'ECDH', namedCurve: 'P-256' },
|
|
21
|
-
false /* extractable */,
|
|
22
|
-
[] /* keyUsages */,
|
|
23
|
-
),
|
|
24
|
-
]);
|
|
25
|
-
const sharedSecret = await crypto.subtle.deriveBits({ name: 'ECDH', public: walletPublicKey }, ecdhPrivateKey, 256);
|
|
26
|
-
const ecdhSecretKey = await crypto.subtle.importKey(
|
|
27
|
-
'raw',
|
|
28
|
-
sharedSecret,
|
|
29
|
-
'HKDF',
|
|
30
|
-
false /* extractable */,
|
|
31
|
-
['deriveKey'] /* keyUsages */,
|
|
32
|
-
);
|
|
33
|
-
const aesKeyMaterialVal = await crypto.subtle.deriveKey(
|
|
34
|
-
{
|
|
35
|
-
name: 'HKDF',
|
|
36
|
-
hash: 'SHA-256',
|
|
37
|
-
salt: new Uint8Array(associationPublicKeyBuffer),
|
|
38
|
-
info: new Uint8Array(),
|
|
39
|
-
},
|
|
40
|
-
ecdhSecretKey,
|
|
41
|
-
{ name: 'AES-GCM', length: 128 },
|
|
42
|
-
false /* extractable */,
|
|
43
|
-
['encrypt', 'decrypt'],
|
|
44
|
-
);
|
|
45
|
-
return aesKeyMaterialVal as SharedSecret;
|
|
46
|
-
}
|
package/src/parseSessionProps.ts
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import { decryptMessage } from "./encryptedMessage";
|
|
2
|
-
import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode } from "./errors";
|
|
3
|
-
import { SharedSecret } from "./parseHelloRsp";
|
|
4
|
-
import { ProtocolVersion, SessionProperties } from "./types";
|
|
5
|
-
|
|
6
|
-
export default async function parseSessionProps(
|
|
7
|
-
message: ArrayBuffer,
|
|
8
|
-
sharedSecret: SharedSecret
|
|
9
|
-
): Promise<SessionProperties> {
|
|
10
|
-
const plaintext = await decryptMessage(message, sharedSecret);
|
|
11
|
-
const jsonProperties = JSON.parse(plaintext);
|
|
12
|
-
let protocolVersion: ProtocolVersion = 'legacy';
|
|
13
|
-
if (Object.hasOwnProperty.call(jsonProperties, 'v')) {
|
|
14
|
-
switch (jsonProperties.v) {
|
|
15
|
-
case 1:
|
|
16
|
-
case '1':
|
|
17
|
-
case 'v1':
|
|
18
|
-
protocolVersion = 'v1'
|
|
19
|
-
break;
|
|
20
|
-
case 'legacy':
|
|
21
|
-
protocolVersion = 'legacy'
|
|
22
|
-
break;
|
|
23
|
-
default:
|
|
24
|
-
throw new SolanaMobileWalletAdapterError(
|
|
25
|
-
SolanaMobileWalletAdapterErrorCode.ERROR_INVALID_PROTOCOL_VERSION,
|
|
26
|
-
`Unknown/unsupported protocol version: ${jsonProperties.v}`
|
|
27
|
-
);
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
return <SessionProperties>({
|
|
31
|
-
protocol_version: protocolVersion
|
|
32
|
-
})
|
|
33
|
-
}
|
package/src/startSession.ts
DELETED
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
import { AssociationPort, getRandomAssociationPort } from './associationPort.js';
|
|
2
|
-
import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode } from './errors.js';
|
|
3
|
-
import getAssociateAndroidIntentURL from './getAssociateAndroidIntentURL.js';
|
|
4
|
-
|
|
5
|
-
// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/
|
|
6
|
-
const Browser = {
|
|
7
|
-
Firefox: 0,
|
|
8
|
-
Other: 1,
|
|
9
|
-
} as const;
|
|
10
|
-
type BrowserEnum = typeof Browser[keyof typeof Browser];
|
|
11
|
-
|
|
12
|
-
function assertUnreachable(x: never): never {
|
|
13
|
-
return x;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
function getBrowser(): BrowserEnum {
|
|
17
|
-
return navigator.userAgent.indexOf('Firefox/') !== -1 ? Browser.Firefox : Browser.Other;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function getDetectionPromise() {
|
|
21
|
-
// Chrome and others silently fail if a custom protocol is not supported.
|
|
22
|
-
// For these, we wait to see if the browser is navigated away from in
|
|
23
|
-
// a reasonable amount of time (ie. the native wallet opened).
|
|
24
|
-
return new Promise<void>((resolve, reject) => {
|
|
25
|
-
function cleanup() {
|
|
26
|
-
clearTimeout(timeoutId);
|
|
27
|
-
window.removeEventListener('blur', handleBlur);
|
|
28
|
-
}
|
|
29
|
-
function handleBlur() {
|
|
30
|
-
cleanup();
|
|
31
|
-
resolve();
|
|
32
|
-
}
|
|
33
|
-
window.addEventListener('blur', handleBlur);
|
|
34
|
-
const timeoutId = setTimeout(() => {
|
|
35
|
-
cleanup();
|
|
36
|
-
reject();
|
|
37
|
-
}, 2000);
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
let _frame: HTMLIFrameElement | null = null;
|
|
42
|
-
function launchUrlThroughHiddenFrame(url: URL) {
|
|
43
|
-
if (_frame == null) {
|
|
44
|
-
_frame = document.createElement('iframe');
|
|
45
|
-
_frame.style.display = 'none';
|
|
46
|
-
document.body.appendChild(_frame);
|
|
47
|
-
}
|
|
48
|
-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
49
|
-
_frame.contentWindow!.location.href = url.toString();
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export async function startSession(
|
|
53
|
-
associationPublicKey: CryptoKey,
|
|
54
|
-
associationURLBase?: string,
|
|
55
|
-
): Promise<AssociationPort> {
|
|
56
|
-
const randomAssociationPort = getRandomAssociationPort();
|
|
57
|
-
const associationUrl = await getAssociateAndroidIntentURL(
|
|
58
|
-
associationPublicKey,
|
|
59
|
-
randomAssociationPort,
|
|
60
|
-
associationURLBase,
|
|
61
|
-
);
|
|
62
|
-
if (associationUrl.protocol === 'https:') {
|
|
63
|
-
// The association URL is an Android 'App Link' or iOS 'Universal Link'.
|
|
64
|
-
// These are regular web URLs that are designed to launch an app if it
|
|
65
|
-
// is installed or load the actual target webpage if not.
|
|
66
|
-
window.location.assign(associationUrl);
|
|
67
|
-
} else {
|
|
68
|
-
// The association URL has a custom protocol (eg. `solana-wallet:`)
|
|
69
|
-
try {
|
|
70
|
-
const browser = getBrowser();
|
|
71
|
-
switch (browser) {
|
|
72
|
-
case Browser.Firefox:
|
|
73
|
-
// If a custom protocol is not supported in Firefox, it throws.
|
|
74
|
-
launchUrlThroughHiddenFrame(associationUrl);
|
|
75
|
-
// If we reached this line, it's supported.
|
|
76
|
-
break;
|
|
77
|
-
case Browser.Other: {
|
|
78
|
-
const detectionPromise = getDetectionPromise();
|
|
79
|
-
window.location.assign(associationUrl);
|
|
80
|
-
await detectionPromise;
|
|
81
|
-
break;
|
|
82
|
-
}
|
|
83
|
-
default:
|
|
84
|
-
assertUnreachable(browser);
|
|
85
|
-
}
|
|
86
|
-
} catch (e) {
|
|
87
|
-
throw new SolanaMobileWalletAdapterError(
|
|
88
|
-
SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND,
|
|
89
|
-
'Found no installed wallet that supports the mobile wallet protocol.',
|
|
90
|
-
);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
return randomAssociationPort;
|
|
94
|
-
}
|
package/src/transact.ts
DELETED
|
@@ -1,266 +0,0 @@
|
|
|
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 } from './startSession.js';
|
|
16
|
-
import { AssociationKeypair, MobileWallet, 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
|
-
const { associationKeypair } = state;
|
|
106
|
-
socket.removeEventListener('open', handleOpen);
|
|
107
|
-
const ecdhKeypair = await generateECDHKeypair();
|
|
108
|
-
socket.send(await createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));
|
|
109
|
-
state = {
|
|
110
|
-
__type: 'hello_req_sent',
|
|
111
|
-
associationPublicKey: associationKeypair.publicKey,
|
|
112
|
-
ecdhPrivateKey: ecdhKeypair.privateKey,
|
|
113
|
-
};
|
|
114
|
-
};
|
|
115
|
-
const handleClose = (evt: CloseEvent) => {
|
|
116
|
-
if (evt.wasClean) {
|
|
117
|
-
state = { __type: 'disconnected' };
|
|
118
|
-
} else {
|
|
119
|
-
reject(
|
|
120
|
-
new SolanaMobileWalletAdapterError(
|
|
121
|
-
SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED,
|
|
122
|
-
`The wallet session dropped unexpectedly (${evt.code}: ${evt.reason}).`,
|
|
123
|
-
{ closeEvent: evt },
|
|
124
|
-
),
|
|
125
|
-
);
|
|
126
|
-
}
|
|
127
|
-
disposeSocket();
|
|
128
|
-
};
|
|
129
|
-
const handleError = async (_evt: Event) => {
|
|
130
|
-
disposeSocket();
|
|
131
|
-
if (Date.now() - connectionStartTime >= WEBSOCKET_CONNECTION_CONFIG.timeoutMs) {
|
|
132
|
-
reject(
|
|
133
|
-
new SolanaMobileWalletAdapterError(
|
|
134
|
-
SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT,
|
|
135
|
-
`Failed to connect to the wallet websocket on port ${sessionPort}.`,
|
|
136
|
-
),
|
|
137
|
-
);
|
|
138
|
-
} else {
|
|
139
|
-
await new Promise((resolve) => {
|
|
140
|
-
const retryDelayMs = getNextRetryDelayMs();
|
|
141
|
-
retryWaitTimeoutId = window.setTimeout(resolve, retryDelayMs);
|
|
142
|
-
});
|
|
143
|
-
attemptSocketConnection();
|
|
144
|
-
}
|
|
145
|
-
};
|
|
146
|
-
const handleMessage = async (evt: MessageEvent<Blob>) => {
|
|
147
|
-
const responseBuffer = await evt.data.arrayBuffer();
|
|
148
|
-
switch (state.__type) {
|
|
149
|
-
case 'connected':
|
|
150
|
-
try {
|
|
151
|
-
const sequenceNumberVector = responseBuffer.slice(0, SEQUENCE_NUMBER_BYTES);
|
|
152
|
-
const sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector);
|
|
153
|
-
if (sequenceNumber !== (lastKnownInboundSequenceNumber + 1)) {
|
|
154
|
-
throw new Error('Encrypted message has invalid sequence number');
|
|
155
|
-
}
|
|
156
|
-
lastKnownInboundSequenceNumber = sequenceNumber;
|
|
157
|
-
const jsonRpcMessage = await decryptJsonRpcMessage(responseBuffer, state.sharedSecret);
|
|
158
|
-
const responsePromise = jsonRpcResponsePromises[jsonRpcMessage.id];
|
|
159
|
-
delete jsonRpcResponsePromises[jsonRpcMessage.id];
|
|
160
|
-
responsePromise.resolve(jsonRpcMessage.result);
|
|
161
|
-
} catch (e) {
|
|
162
|
-
if (e instanceof SolanaMobileWalletAdapterProtocolError) {
|
|
163
|
-
const responsePromise = jsonRpcResponsePromises[e.jsonRpcMessageId];
|
|
164
|
-
delete jsonRpcResponsePromises[e.jsonRpcMessageId];
|
|
165
|
-
responsePromise.reject(e);
|
|
166
|
-
} else {
|
|
167
|
-
throw e;
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
break;
|
|
171
|
-
case 'hello_req_sent': {
|
|
172
|
-
const sharedSecret = await parseHelloRsp(
|
|
173
|
-
responseBuffer,
|
|
174
|
-
state.associationPublicKey,
|
|
175
|
-
state.ecdhPrivateKey,
|
|
176
|
-
);
|
|
177
|
-
const sessionPropertiesBuffer = responseBuffer.slice(ENCODED_PUBLIC_KEY_LENGTH_BYTES);
|
|
178
|
-
const sessionProperties = sessionPropertiesBuffer.byteLength !== 0
|
|
179
|
-
? await (async () => {
|
|
180
|
-
const sequenceNumberVector = sessionPropertiesBuffer.slice(0, SEQUENCE_NUMBER_BYTES);
|
|
181
|
-
const sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector);
|
|
182
|
-
if (sequenceNumber !== (lastKnownInboundSequenceNumber + 1)) {
|
|
183
|
-
throw new Error('Encrypted message has invalid sequence number');
|
|
184
|
-
}
|
|
185
|
-
lastKnownInboundSequenceNumber = sequenceNumber;
|
|
186
|
-
return parseSessionProps(sessionPropertiesBuffer, sharedSecret);
|
|
187
|
-
})() : <SessionProperties> { protocol_version: 'legacy' };
|
|
188
|
-
state = { __type: 'connected', sharedSecret, sessionProperties };
|
|
189
|
-
const wallet = createMobileWalletProxy(sessionProperties.protocol_version,
|
|
190
|
-
async (method, params) => {
|
|
191
|
-
const id = nextJsonRpcMessageId++;
|
|
192
|
-
socket.send(
|
|
193
|
-
await encryptJsonRpcMessage(
|
|
194
|
-
{
|
|
195
|
-
id,
|
|
196
|
-
jsonrpc: '2.0' as const,
|
|
197
|
-
method,
|
|
198
|
-
params: params ?? {},
|
|
199
|
-
},
|
|
200
|
-
sharedSecret,
|
|
201
|
-
),
|
|
202
|
-
);
|
|
203
|
-
return new Promise((resolve, reject) => {
|
|
204
|
-
jsonRpcResponsePromises[id] = {
|
|
205
|
-
resolve(result) {
|
|
206
|
-
switch (method) {
|
|
207
|
-
case 'authorize':
|
|
208
|
-
case 'reauthorize': {
|
|
209
|
-
const { wallet_uri_base } = result as Awaited<
|
|
210
|
-
ReturnType<MobileWallet['authorize' | 'reauthorize']>
|
|
211
|
-
>;
|
|
212
|
-
if (wallet_uri_base != null) {
|
|
213
|
-
try {
|
|
214
|
-
assertSecureEndpointSpecificURI(wallet_uri_base);
|
|
215
|
-
} catch (e) {
|
|
216
|
-
reject(e);
|
|
217
|
-
return;
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
break;
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
resolve(result);
|
|
224
|
-
},
|
|
225
|
-
reject,
|
|
226
|
-
};
|
|
227
|
-
});
|
|
228
|
-
})
|
|
229
|
-
try {
|
|
230
|
-
resolve(await callback(wallet));
|
|
231
|
-
} catch (e) {
|
|
232
|
-
reject(e);
|
|
233
|
-
} finally {
|
|
234
|
-
disposeSocket();
|
|
235
|
-
socket.close();
|
|
236
|
-
}
|
|
237
|
-
break;
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
};
|
|
241
|
-
let disposeSocket: () => void;
|
|
242
|
-
let retryWaitTimeoutId: number;
|
|
243
|
-
const attemptSocketConnection = () => {
|
|
244
|
-
if (disposeSocket) {
|
|
245
|
-
disposeSocket();
|
|
246
|
-
}
|
|
247
|
-
state = { __type: 'connecting', associationKeypair };
|
|
248
|
-
if (connectionStartTime === undefined) {
|
|
249
|
-
connectionStartTime = Date.now();
|
|
250
|
-
}
|
|
251
|
-
socket = new WebSocket(websocketURL, [WEBSOCKET_PROTOCOL]);
|
|
252
|
-
socket.addEventListener('open', handleOpen);
|
|
253
|
-
socket.addEventListener('close', handleClose);
|
|
254
|
-
socket.addEventListener('error', handleError);
|
|
255
|
-
socket.addEventListener('message', handleMessage);
|
|
256
|
-
disposeSocket = () => {
|
|
257
|
-
window.clearTimeout(retryWaitTimeoutId);
|
|
258
|
-
socket.removeEventListener('open', handleOpen);
|
|
259
|
-
socket.removeEventListener('close', handleClose);
|
|
260
|
-
socket.removeEventListener('error', handleError);
|
|
261
|
-
socket.removeEventListener('message', handleMessage);
|
|
262
|
-
};
|
|
263
|
-
};
|
|
264
|
-
attemptSocketConnection();
|
|
265
|
-
});
|
|
266
|
-
}
|
package/src/types.ts
DELETED
|
@@ -1,181 +0,0 @@
|
|
|
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 interface AuthorizeAPI {
|
|
77
|
-
/**
|
|
78
|
-
* @deprecated Replaced by updated authorize() method, which adds MWA 2.0 spec support.
|
|
79
|
-
*/
|
|
80
|
-
authorize(params: { cluster: Cluster; identity: AppIdentity }): Promise<AuthorizationResult>;
|
|
81
|
-
|
|
82
|
-
authorize(params: {
|
|
83
|
-
identity: AppIdentity;
|
|
84
|
-
chain?: Chain;
|
|
85
|
-
features?: IdentifierArray;
|
|
86
|
-
addresses?: string[];
|
|
87
|
-
auth_token?: AuthToken;
|
|
88
|
-
sign_in_payload?: SignInPayload;
|
|
89
|
-
}): Promise<AuthorizationResult>;
|
|
90
|
-
}
|
|
91
|
-
export interface CloneAuthorizationAPI {
|
|
92
|
-
cloneAuthorization(params: { auth_token: AuthToken }): Promise<Readonly<{ auth_token: AuthToken }>>;
|
|
93
|
-
}
|
|
94
|
-
export interface DeauthorizeAPI {
|
|
95
|
-
deauthorize(params: { auth_token: AuthToken }): Promise<Readonly<Record<string, never>>>;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export interface GetCapabilitiesAPI {
|
|
99
|
-
getCapabilities(): Promise<
|
|
100
|
-
Readonly<{
|
|
101
|
-
max_transactions_per_request: number;
|
|
102
|
-
max_messages_per_request: number;
|
|
103
|
-
supported_transaction_versions: ReadonlyArray<TransactionVersion>;
|
|
104
|
-
features: IdentifierArray;
|
|
105
|
-
/**
|
|
106
|
-
* @deprecated Replaced by features array.
|
|
107
|
-
*/
|
|
108
|
-
supports_clone_authorization: boolean;
|
|
109
|
-
/**
|
|
110
|
-
* @deprecated Replaced by features array.
|
|
111
|
-
*/
|
|
112
|
-
supports_sign_and_send_transactions: boolean;
|
|
113
|
-
}>
|
|
114
|
-
>;
|
|
115
|
-
}
|
|
116
|
-
export interface ReauthorizeAPI {
|
|
117
|
-
reauthorize(params: { auth_token: AuthToken; identity: AppIdentity }): Promise<AuthorizationResult>;
|
|
118
|
-
}
|
|
119
|
-
export interface SignMessagesAPI {
|
|
120
|
-
signMessages(params: {
|
|
121
|
-
addresses: Base64EncodedAddress[];
|
|
122
|
-
payloads: Base64EncodedMessage[];
|
|
123
|
-
}): Promise<Readonly<{ signed_payloads: Base64EncodedSignedMessage[] }>>;
|
|
124
|
-
}
|
|
125
|
-
export interface SignTransactionsAPI {
|
|
126
|
-
signTransactions(params: {
|
|
127
|
-
payloads: Base64EncodedTransaction[];
|
|
128
|
-
}): Promise<Readonly<{ signed_payloads: Base64EncodedSignedTransaction[] }>>;
|
|
129
|
-
}
|
|
130
|
-
export interface SignAndSendTransactionsAPI {
|
|
131
|
-
signAndSendTransactions(params: {
|
|
132
|
-
options?: Readonly<{
|
|
133
|
-
min_context_slot?: number;
|
|
134
|
-
commitment?: string;
|
|
135
|
-
skip_preflight?: boolean;
|
|
136
|
-
max_retries?: number;
|
|
137
|
-
wait_for_commitment_to_send_next_transaction?: boolean;
|
|
138
|
-
}>;
|
|
139
|
-
payloads: Base64EncodedTransaction[];
|
|
140
|
-
}): Promise<Readonly<{ signatures: Base64EncodedSignature[] }>>;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
export interface MobileWallet
|
|
144
|
-
extends AuthorizeAPI,
|
|
145
|
-
CloneAuthorizationAPI,
|
|
146
|
-
DeauthorizeAPI,
|
|
147
|
-
GetCapabilitiesAPI,
|
|
148
|
-
ReauthorizeAPI,
|
|
149
|
-
SignMessagesAPI,
|
|
150
|
-
SignTransactionsAPI,
|
|
151
|
-
SignAndSendTransactionsAPI {}
|
|
152
|
-
|
|
153
|
-
// optional features
|
|
154
|
-
export const SolanaSignTransactions = 'solana:signTransactions'
|
|
155
|
-
export const SolanaCloneAuthorization = 'solana:cloneAuthorization'
|
|
156
|
-
export const SolanaSignInWithSolana = 'solana:signInWithSolana'
|
|
157
|
-
|
|
158
|
-
export type SignInPayload = Readonly<{
|
|
159
|
-
domain?: string;
|
|
160
|
-
address?: string;
|
|
161
|
-
statement?: string;
|
|
162
|
-
uri?: string;
|
|
163
|
-
version?: string;
|
|
164
|
-
chainId?: string;
|
|
165
|
-
nonce?: string;
|
|
166
|
-
issuedAt?: string;
|
|
167
|
-
expirationTime?: string;
|
|
168
|
-
notBefore?: string;
|
|
169
|
-
requestId?: string;
|
|
170
|
-
resources?: readonly string[];
|
|
171
|
-
}> | SolanaSignInInput;
|
|
172
|
-
|
|
173
|
-
export type SignInPayloadWithRequiredFields = Partial<SignInPayload> &
|
|
174
|
-
Required<Pick<SignInPayload, 'domain' | 'address'>>
|
|
175
|
-
|
|
176
|
-
export type SignInResult = Readonly<{
|
|
177
|
-
address: Base64EncodedAddress;
|
|
178
|
-
signed_message: Base64EncodedSignedMessage;
|
|
179
|
-
signature: Base64EncodedAddress;
|
|
180
|
-
signature_type?: string;
|
|
181
|
-
}>;
|
package/tsconfig.cjs.json
DELETED