@solana-mobile/mobile-wallet-adapter-protocol 0.9.8 → 1.0.0

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/.gitignore ADDED
@@ -0,0 +1,2 @@
1
+ lib/
2
+ android/build
@@ -0,0 +1,14 @@
1
+ # OSX
2
+ #
3
+ .DS_Store
4
+
5
+ # Android/IJ
6
+ #
7
+ .classpath
8
+ .cxx
9
+ .gradle
10
+ .idea
11
+ .project
12
+ .settings
13
+ local.properties
14
+ android.iml
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@solana-mobile/mobile-wallet-adapter-protocol",
3
3
  "description": "An implementation of the Solana Mobile Mobile Wallet Adapter protocol. Use this to open a session with a mobile wallet app, and to issue API calls to it.",
4
- "version": "0.9.8",
4
+ "version": "1.0.0",
5
5
  "author": "Steven Luscher <steven.luscher@solanamobile.com>",
6
6
  "repository": "https://github.com/solana-mobile/mobile-wallet-adapter",
7
7
  "license": "Apache-2.0",
@@ -46,6 +46,5 @@
46
46
  },
47
47
  "peerDependencies": {
48
48
  "react-native": ">0.69"
49
- },
50
- "gitHead": "040622228152826e029bc613f7c6b4b14eefb138"
49
+ }
51
50
  }
@@ -0,0 +1,106 @@
1
+ import { NativeModules, Platform } from 'react-native';
2
+
3
+ import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterProtocolError } from '../../errors.js';
4
+ import { MobileWallet, WalletAssociationConfig } from '../../types.js';
5
+
6
+ type ReactNativeError = Error & { code?: string; userInfo?: Record<string, unknown> };
7
+
8
+ const LINKING_ERROR =
9
+ `The package 'solana-mobile-wallet-adapter-protocol' doesn't seem to be linked. Make sure: \n\n` +
10
+ '- You rebuilt the app after installing the package\n' +
11
+ '- If you are using Lerna workspaces\n' +
12
+ ' - You have added `@solana-mobile/mobile-wallet-adapter-protocol` as an explicit dependency, and\n' +
13
+ ' - You have added `@solana-mobile/mobile-wallet-adapter-protocol` to the `nohoist` section of your package.json\n' +
14
+ '- You are not using Expo managed workflow\n';
15
+
16
+ const SolanaMobileWalletAdapter =
17
+ Platform.OS === 'android' && NativeModules.SolanaMobileWalletAdapter
18
+ ? NativeModules.SolanaMobileWalletAdapter
19
+ : new Proxy(
20
+ {},
21
+ {
22
+ get() {
23
+ throw new Error(
24
+ Platform.OS !== 'android'
25
+ ? 'The package `solana-mobile-wallet-adapter-protocol` is only compatible with React Native Android'
26
+ : LINKING_ERROR,
27
+ );
28
+ },
29
+ },
30
+ );
31
+
32
+ function getErrorMessage(e: ReactNativeError): string {
33
+ switch (e.code) {
34
+ case 'ERROR_WALLET_NOT_FOUND':
35
+ return 'Found no installed wallet that supports the mobile wallet protocol.';
36
+ default:
37
+ return e.message;
38
+ }
39
+ }
40
+
41
+ function handleError(e: any): never {
42
+ if (e instanceof Error) {
43
+ const reactNativeError: ReactNativeError = e;
44
+ switch (reactNativeError.code) {
45
+ case undefined:
46
+ throw e;
47
+ case 'JSON_RPC_ERROR': {
48
+ const details = reactNativeError.userInfo as Readonly<{ jsonRpcErrorCode: number }>;
49
+ throw new SolanaMobileWalletAdapterProtocolError(
50
+ 0 /* jsonRpcMessageId */,
51
+ details.jsonRpcErrorCode,
52
+ e.message,
53
+ );
54
+ }
55
+ default:
56
+ throw new SolanaMobileWalletAdapterError<any>(
57
+ reactNativeError.code,
58
+ getErrorMessage(reactNativeError),
59
+ reactNativeError.userInfo,
60
+ );
61
+ }
62
+ }
63
+ throw e;
64
+ }
65
+
66
+ export async function transact<TReturn>(
67
+ callback: (wallet: MobileWallet) => TReturn,
68
+ config?: WalletAssociationConfig,
69
+ ): Promise<TReturn> {
70
+ let didSuccessfullyConnect = false;
71
+ try {
72
+ await SolanaMobileWalletAdapter.startSession(config);
73
+ didSuccessfullyConnect = true;
74
+ const wallet = new Proxy<MobileWallet>({} as MobileWallet, {
75
+ get<TMethodName extends keyof MobileWallet>(target: MobileWallet, p: TMethodName) {
76
+ if (target[p] == null) {
77
+ const method = p
78
+ .toString()
79
+ .replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)
80
+ .toLowerCase();
81
+ target[p] = async function (params: Parameters<MobileWallet[TMethodName]>[0]) {
82
+ try {
83
+ return await SolanaMobileWalletAdapter.invoke(method, params);
84
+ } catch (e) {
85
+ return handleError(e);
86
+ }
87
+ } as MobileWallet[TMethodName];
88
+ }
89
+ return target[p];
90
+ },
91
+ defineProperty() {
92
+ return false;
93
+ },
94
+ deleteProperty() {
95
+ return false;
96
+ },
97
+ });
98
+ return await callback(wallet);
99
+ } catch (e) {
100
+ return handleError(e);
101
+ } finally {
102
+ if (didSuccessfullyConnect) {
103
+ await SolanaMobileWalletAdapter.endSession();
104
+ }
105
+ }
106
+ }
@@ -0,0 +1,10 @@
1
+ // https://stackoverflow.com/a/9458996/802047
2
+ export default function arrayBufferToBase64String(buffer: ArrayBuffer) {
3
+ let binary = '';
4
+ const bytes = new Uint8Array(buffer);
5
+ const len = bytes.byteLength;
6
+ for (let ii = 0; ii < len; ii++) {
7
+ binary += String.fromCharCode(bytes[ii]);
8
+ }
9
+ return window.btoa(binary);
10
+ }
@@ -0,0 +1,19 @@
1
+ import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode } from './errors.js';
2
+
3
+ declare const tag: unique symbol;
4
+ export type AssociationPort = number & { readonly [tag]: 'AssociationPort' };
5
+
6
+ export function getRandomAssociationPort(): AssociationPort {
7
+ return assertAssociationPort(49152 + Math.floor(Math.random() * (65535 - 49152 + 1)));
8
+ }
9
+
10
+ export function assertAssociationPort(port: number): AssociationPort {
11
+ if (port < 49152 || port > 65535) {
12
+ throw new SolanaMobileWalletAdapterError(
13
+ SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_PORT_OUT_OF_RANGE,
14
+ `Association port number must be between 49152 and 65535. ${port} given.`,
15
+ { port },
16
+ );
17
+ }
18
+ return port as AssociationPort;
19
+ }
@@ -0,0 +1,12 @@
1
+ export default async function createHelloReq(ecdhPublicKey: CryptoKey, associationKeypairPrivateKey: CryptoKey) {
2
+ const publicKeyBuffer = await crypto.subtle.exportKey('raw', ecdhPublicKey);
3
+ const signatureBuffer = await crypto.subtle.sign(
4
+ { hash: 'SHA-256', name: 'ECDSA' },
5
+ associationKeypairPrivateKey,
6
+ publicKeyBuffer,
7
+ );
8
+ const response = new Uint8Array(publicKeyBuffer.byteLength + signatureBuffer.byteLength);
9
+ response.set(new Uint8Array(publicKeyBuffer), 0);
10
+ response.set(new Uint8Array(signatureBuffer), publicKeyBuffer.byteLength);
11
+ return response;
12
+ }
@@ -0,0 +1,11 @@
1
+ export const SEQUENCE_NUMBER_BYTES = 4;
2
+
3
+ export default function createSequenceNumberVector(sequenceNumber: number): Uint8Array {
4
+ if (sequenceNumber >= 4294967296) {
5
+ throw new Error('Outbound sequence number overflow. The maximum sequence number is 32-bytes.');
6
+ }
7
+ const byteArray = new ArrayBuffer(SEQUENCE_NUMBER_BYTES);
8
+ const view = new DataView(byteArray);
9
+ view.setUint32(0, sequenceNumber, /* littleEndian */ false);
10
+ return new Uint8Array(byteArray);
11
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,93 @@
1
+ // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/
2
+ export const SolanaMobileWalletAdapterErrorCode = {
3
+ ERROR_ASSOCIATION_PORT_OUT_OF_RANGE: 'ERROR_ASSOCIATION_PORT_OUT_OF_RANGE',
4
+ ERROR_FORBIDDEN_WALLET_BASE_URL: 'ERROR_FORBIDDEN_WALLET_BASE_URL',
5
+ ERROR_SECURE_CONTEXT_REQUIRED: 'ERROR_SECURE_CONTEXT_REQUIRED',
6
+ ERROR_SESSION_CLOSED: 'ERROR_SESSION_CLOSED',
7
+ ERROR_SESSION_TIMEOUT: 'ERROR_SESSION_TIMEOUT',
8
+ ERROR_WALLET_NOT_FOUND: 'ERROR_WALLET_NOT_FOUND',
9
+ } as const;
10
+ type SolanaMobileWalletAdapterErrorCodeEnum =
11
+ typeof SolanaMobileWalletAdapterErrorCode[keyof typeof SolanaMobileWalletAdapterErrorCode];
12
+
13
+ type ErrorDataTypeMap = {
14
+ [SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_PORT_OUT_OF_RANGE]: {
15
+ port: number;
16
+ };
17
+ [SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL]: undefined;
18
+ [SolanaMobileWalletAdapterErrorCode.ERROR_SECURE_CONTEXT_REQUIRED]: undefined;
19
+ [SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED]: {
20
+ closeEvent: CloseEvent;
21
+ };
22
+ [SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT]: undefined;
23
+ [SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND]: undefined;
24
+ };
25
+
26
+ export class SolanaMobileWalletAdapterError<TErrorCode extends SolanaMobileWalletAdapterErrorCodeEnum> extends Error {
27
+ data: ErrorDataTypeMap[TErrorCode] | undefined;
28
+ code: TErrorCode;
29
+ constructor(
30
+ ...args: ErrorDataTypeMap[TErrorCode] extends Record<string, unknown>
31
+ ? [code: TErrorCode, message: string, data: ErrorDataTypeMap[TErrorCode]]
32
+ : [code: TErrorCode, message: string]
33
+ ) {
34
+ const [code, message, data] = args;
35
+ super(message);
36
+ this.code = code;
37
+ this.data = data;
38
+ this.name = 'SolanaMobileWalletAdapterError';
39
+ }
40
+ }
41
+
42
+ type JSONRPCErrorCode = number;
43
+
44
+ // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/
45
+ export const SolanaMobileWalletAdapterProtocolErrorCode = {
46
+ // Keep these in sync with `mobilewalletadapter/common/ProtocolContract.java`.
47
+ ERROR_AUTHORIZATION_FAILED: -1,
48
+ ERROR_INVALID_PAYLOADS: -2,
49
+ ERROR_NOT_SIGNED: -3,
50
+ ERROR_NOT_SUBMITTED: -4,
51
+ ERROR_TOO_MANY_PAYLOADS: -5,
52
+ ERROR_ATTEST_ORIGIN_ANDROID: -100,
53
+ } as const;
54
+ type SolanaMobileWalletAdapterProtocolErrorCodeEnum =
55
+ typeof SolanaMobileWalletAdapterProtocolErrorCode[keyof typeof SolanaMobileWalletAdapterProtocolErrorCode];
56
+
57
+ type ProtocolErrorDataTypeMap = {
58
+ [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_AUTHORIZATION_FAILED]: undefined;
59
+ [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_INVALID_PAYLOADS]: undefined;
60
+ [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_NOT_SIGNED]: undefined;
61
+ [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_NOT_SUBMITTED]: undefined;
62
+ [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_TOO_MANY_PAYLOADS]: undefined;
63
+ [SolanaMobileWalletAdapterProtocolErrorCode.ERROR_ATTEST_ORIGIN_ANDROID]: {
64
+ attest_origin_uri: string;
65
+ challenge: string;
66
+ context: string;
67
+ };
68
+ };
69
+
70
+ export class SolanaMobileWalletAdapterProtocolError<
71
+ TErrorCode extends SolanaMobileWalletAdapterProtocolErrorCodeEnum,
72
+ > extends Error {
73
+ data: ProtocolErrorDataTypeMap[TErrorCode] | undefined;
74
+ code: TErrorCode | JSONRPCErrorCode;
75
+ jsonRpcMessageId: number;
76
+ constructor(
77
+ ...args: ProtocolErrorDataTypeMap[TErrorCode] extends Record<string, unknown>
78
+ ? [
79
+ jsonRpcMessageId: number,
80
+ code: TErrorCode | JSONRPCErrorCode,
81
+ message: string,
82
+ data: ProtocolErrorDataTypeMap[TErrorCode],
83
+ ]
84
+ : [jsonRpcMessageId: number, code: TErrorCode | JSONRPCErrorCode, message: string]
85
+ ) {
86
+ const [jsonRpcMessageId, code, message, data] = args;
87
+ super(message);
88
+ this.code = code;
89
+ this.data = data;
90
+ this.jsonRpcMessageId = jsonRpcMessageId;
91
+ this.name = 'SolanaMobileWalletAdapterProtocolError';
92
+ }
93
+ }
@@ -0,0 +1,10 @@
1
+ export default async function generateAssociationKeypair(): Promise<CryptoKeyPair> {
2
+ return await crypto.subtle.generateKey(
3
+ {
4
+ name: 'ECDSA',
5
+ namedCurve: 'P-256',
6
+ },
7
+ false /* extractable */,
8
+ ['sign'] /* keyUsages */,
9
+ );
10
+ }
@@ -0,0 +1,10 @@
1
+ export default async function generateECDHKeypair(): Promise<CryptoKeyPair> {
2
+ return await crypto.subtle.generateKey(
3
+ {
4
+ name: 'ECDH',
5
+ namedCurve: 'P-256',
6
+ },
7
+ false /* extractable */,
8
+ ['deriveKey', 'deriveBits'] /* keyUsages */,
9
+ );
10
+ }
@@ -0,0 +1,52 @@
1
+ import arrayBufferToBase64String from './arrayBufferToBase64String.js';
2
+ import { assertAssociationPort } from './associationPort.js';
3
+ import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode } from './errors.js';
4
+ import getStringWithURLUnsafeBase64CharactersReplaced from './getStringWithURLUnsafeBase64CharactersReplaced.js';
5
+
6
+ const INTENT_NAME = 'solana-wallet';
7
+
8
+ function getPathParts(pathString: string) {
9
+ return (
10
+ pathString
11
+ // Strip leading and trailing slashes
12
+ .replace(/(^\/+|\/+$)/g, '')
13
+ // Return an array of directories
14
+ .split('/')
15
+ );
16
+ }
17
+
18
+ function getIntentURL(methodPathname: string, intentUrlBase?: string) {
19
+ let baseUrl: URL | null = null;
20
+ if (intentUrlBase) {
21
+ try {
22
+ baseUrl = new URL(intentUrlBase);
23
+ } catch {} // eslint-disable-line no-empty
24
+ if (baseUrl?.protocol !== 'https:') {
25
+ throw new SolanaMobileWalletAdapterError(
26
+ SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL,
27
+ 'Base URLs supplied by wallets must be valid `https` URLs',
28
+ );
29
+ }
30
+ }
31
+ baseUrl ||= new URL(`${INTENT_NAME}:/`);
32
+ const pathname = methodPathname.startsWith('/')
33
+ ? // Method is an absolute path. Replace it wholesale.
34
+ methodPathname
35
+ : // Method is a relative path. Merge it with the existing one.
36
+ [...getPathParts(baseUrl.pathname), ...getPathParts(methodPathname)].join('/');
37
+ return new URL(pathname, baseUrl);
38
+ }
39
+
40
+ export default async function getAssociateAndroidIntentURL(
41
+ associationPublicKey: CryptoKey,
42
+ putativePort: number,
43
+ associationURLBase?: string,
44
+ ): Promise<URL> {
45
+ const associationPort = assertAssociationPort(putativePort);
46
+ const exportedKey = await crypto.subtle.exportKey('raw', associationPublicKey);
47
+ const encodedKey = arrayBufferToBase64String(exportedKey);
48
+ const url = getIntentURL('v1/associate/local', associationURLBase);
49
+ url.searchParams.set('association', getStringWithURLUnsafeBase64CharactersReplaced(encodedKey));
50
+ url.searchParams.set('port', `${associationPort}`);
51
+ return url;
52
+ }
package/src/getJWS.ts ADDED
@@ -0,0 +1,19 @@
1
+ import arrayBufferToBase64String from './arrayBufferToBase64String.js';
2
+
3
+ export default async function getJWS(payload: string, privateKey: CryptoKey) {
4
+ const header = { alg: 'ES256' };
5
+ const headerEncoded = window.btoa(JSON.stringify(header));
6
+ const payloadEncoded = window.btoa(payload);
7
+ const message = `${headerEncoded}.${payloadEncoded}`;
8
+ const signatureBuffer = await crypto.subtle.sign(
9
+ {
10
+ name: 'ECDSA',
11
+ hash: 'SHA-256',
12
+ },
13
+ privateKey,
14
+ new TextEncoder().encode(message),
15
+ );
16
+ const signature = arrayBufferToBase64String(signatureBuffer);
17
+ const jws = `${message}.${signature}`;
18
+ return jws;
19
+ }
@@ -0,0 +1,11 @@
1
+ export default function getStringWithURLUnsafeCharactersReplaced(unsafeBase64EncodedString: string): string {
2
+ return unsafeBase64EncodedString.replace(
3
+ /[/+=]/g,
4
+ (m) =>
5
+ ({
6
+ '/': '_',
7
+ '+': '-',
8
+ '=': '.',
9
+ }[m] as string),
10
+ );
11
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './errors.js';
2
+ export * from './transact.js';
3
+ export * from './types.js';
@@ -0,0 +1,81 @@
1
+ import createSequenceNumberVector, { SEQUENCE_NUMBER_BYTES } from './createSequenceNumberVector.js';
2
+ import { SolanaMobileWalletAdapterProtocolError } from './errors.js';
3
+ import { SharedSecret } from './parseHelloRsp.js';
4
+
5
+ const INITIALIZATION_VECTOR_BYTES = 12;
6
+
7
+ interface JSONRPCRequest<TParams> {
8
+ id: number;
9
+ jsonrpc: '2.0';
10
+ method: string;
11
+ params: TParams;
12
+ }
13
+
14
+ type JSONRPCResponse<TMessage> = {
15
+ id: number;
16
+ jsonrpc: '2.0';
17
+ result: TMessage;
18
+ };
19
+
20
+ export async function encryptJsonRpcMessage<TParams>(
21
+ jsonRpcMessage: JSONRPCRequest<TParams>,
22
+ sharedSecret: SharedSecret,
23
+ ) {
24
+ const plaintext = JSON.stringify(jsonRpcMessage);
25
+ const sequenceNumberVector = createSequenceNumberVector(jsonRpcMessage.id);
26
+ const initializationVector = new Uint8Array(INITIALIZATION_VECTOR_BYTES);
27
+ crypto.getRandomValues(initializationVector);
28
+ const ciphertext = await crypto.subtle.encrypt(
29
+ getAlgorithmParams(sequenceNumberVector, initializationVector),
30
+ sharedSecret,
31
+ new TextEncoder().encode(plaintext),
32
+ );
33
+ const response = new Uint8Array(
34
+ sequenceNumberVector.byteLength + initializationVector.byteLength + ciphertext.byteLength,
35
+ );
36
+ response.set(new Uint8Array(sequenceNumberVector), 0);
37
+ response.set(new Uint8Array(initializationVector), sequenceNumberVector.byteLength);
38
+ response.set(new Uint8Array(ciphertext), sequenceNumberVector.byteLength + initializationVector.byteLength);
39
+ return response;
40
+ }
41
+
42
+ export async function decryptJsonRpcMessage<TMessage>(message: ArrayBuffer, sharedSecret: SharedSecret) {
43
+ const sequenceNumberVector = message.slice(0, SEQUENCE_NUMBER_BYTES);
44
+ const initializationVector = message.slice(
45
+ SEQUENCE_NUMBER_BYTES,
46
+ SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES,
47
+ );
48
+ const ciphertext = message.slice(SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES);
49
+ const plaintextBuffer = await crypto.subtle.decrypt(
50
+ getAlgorithmParams(sequenceNumberVector, initializationVector),
51
+ sharedSecret,
52
+ ciphertext,
53
+ );
54
+ const plaintext = getUtf8Decoder().decode(plaintextBuffer);
55
+ const jsonRpcMessage = JSON.parse(plaintext);
56
+ if (Object.hasOwnProperty.call(jsonRpcMessage, 'error')) {
57
+ throw new SolanaMobileWalletAdapterProtocolError<typeof jsonRpcMessage.error.code>(
58
+ jsonRpcMessage.id,
59
+ jsonRpcMessage.error.code,
60
+ jsonRpcMessage.error.message,
61
+ );
62
+ }
63
+ return jsonRpcMessage as JSONRPCResponse<TMessage>;
64
+ }
65
+
66
+ function getAlgorithmParams(sequenceNumber: ArrayBuffer, initializationVector: ArrayBuffer) {
67
+ return {
68
+ additionalData: sequenceNumber,
69
+ iv: initializationVector,
70
+ name: 'AES-GCM',
71
+ tagLength: 128, // 16 byte tag => 128 bits
72
+ };
73
+ }
74
+
75
+ let _utf8Decoder: TextDecoder | undefined;
76
+ function getUtf8Decoder() {
77
+ if (_utf8Decoder === undefined) {
78
+ _utf8Decoder = new TextDecoder('utf-8');
79
+ }
80
+ return _utf8Decoder;
81
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * A secret agreed upon by the app and the wallet. Used as
3
+ * a symmetric key to encrypt and decrypt messages over an
4
+ * unsecured channel.
5
+ */
6
+ export type SharedSecret = CryptoKey;
7
+
8
+ export default async function parseHelloRsp(
9
+ payloadBuffer: ArrayBuffer, // The X9.62-encoded wallet endpoint ephemeral ECDH public keypoint.
10
+ associationPublicKey: CryptoKey,
11
+ ecdhPrivateKey: CryptoKey,
12
+ ): Promise<SharedSecret> {
13
+ const [associationPublicKeyBuffer, walletPublicKey] = await Promise.all([
14
+ crypto.subtle.exportKey('raw', associationPublicKey),
15
+ crypto.subtle.importKey(
16
+ 'raw',
17
+ payloadBuffer,
18
+ { name: 'ECDH', namedCurve: 'P-256' },
19
+ false /* extractable */,
20
+ [] /* keyUsages */,
21
+ ),
22
+ ]);
23
+ const sharedSecret = await crypto.subtle.deriveBits({ name: 'ECDH', public: walletPublicKey }, ecdhPrivateKey, 256);
24
+ const ecdhSecretKey = await crypto.subtle.importKey(
25
+ 'raw',
26
+ sharedSecret,
27
+ 'HKDF',
28
+ false /* extractable */,
29
+ ['deriveKey'] /* keyUsages */,
30
+ );
31
+ const aesKeyMaterialVal = await crypto.subtle.deriveKey(
32
+ {
33
+ name: 'HKDF',
34
+ hash: 'SHA-256',
35
+ salt: new Uint8Array(associationPublicKeyBuffer),
36
+ info: new Uint8Array(),
37
+ },
38
+ ecdhSecretKey,
39
+ { name: 'AES-GCM', length: 128 },
40
+ false /* extractable */,
41
+ ['encrypt', 'decrypt'],
42
+ );
43
+ return aesKeyMaterialVal as SharedSecret;
44
+ }
@@ -0,0 +1,94 @@
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
+ }
@@ -0,0 +1,268 @@
1
+ import createHelloReq from './createHelloReq.js';
2
+ import { SEQUENCE_NUMBER_BYTES } from './createSequenceNumberVector.js';
3
+ import {
4
+ SolanaMobileWalletAdapterError,
5
+ SolanaMobileWalletAdapterErrorCode,
6
+ SolanaMobileWalletAdapterProtocolError,
7
+ } from './errors.js';
8
+ import generateAssociationKeypair from './generateAssociationKeypair.js';
9
+ import generateECDHKeypair from './generateECDHKeypair.js';
10
+ import { decryptJsonRpcMessage, encryptJsonRpcMessage } from './jsonRpcMessage.js';
11
+ import parseHelloRsp, { SharedSecret } from './parseHelloRsp.js';
12
+ import { startSession } from './startSession.js';
13
+ import { AssociationKeypair, MobileWallet, WalletAssociationConfig } from './types.js';
14
+
15
+ const WEBSOCKET_CONNECTION_CONFIG = {
16
+ /**
17
+ * 300 milliseconds is a generally accepted threshold for what someone
18
+ * would consider an acceptable response time for a user interface
19
+ * after having performed a low-attention tapping task. We set the initial
20
+ * interval at which we wait for the wallet to set up the websocket at
21
+ * half this, as per the Nyquist frequency, with a progressive backoff
22
+ * sequence from there. The total wait time is 30s, which allows for the
23
+ * user to be presented with a disambiguation dialog, select a wallet, and
24
+ * for the wallet app to subsequently start.
25
+ */
26
+ retryDelayScheduleMs: [150, 150, 200, 500, 500, 750, 750, 1000],
27
+ timeoutMs: 30000,
28
+ } as const;
29
+ const WEBSOCKET_PROTOCOL = 'com.solana.mobilewalletadapter.v1';
30
+
31
+ type JsonResponsePromises<T> = Record<
32
+ number,
33
+ Readonly<{ resolve: (value?: T | PromiseLike<T>) => void; reject: (reason?: unknown) => void }>
34
+ >;
35
+
36
+ type State =
37
+ | { __type: 'connected'; sharedSecret: SharedSecret }
38
+ | { __type: 'connecting'; associationKeypair: AssociationKeypair }
39
+ | { __type: 'disconnected' }
40
+ | { __type: 'hello_req_sent'; associationPublicKey: CryptoKey; ecdhPrivateKey: CryptoKey };
41
+
42
+ function assertSecureContext() {
43
+ if (typeof window === 'undefined' || window.isSecureContext !== true) {
44
+ throw new SolanaMobileWalletAdapterError(
45
+ SolanaMobileWalletAdapterErrorCode.ERROR_SECURE_CONTEXT_REQUIRED,
46
+ 'The mobile wallet adapter protocol must be used in a secure context (`https`).',
47
+ );
48
+ }
49
+ }
50
+
51
+ function assertSecureEndpointSpecificURI(walletUriBase: string) {
52
+ let url: URL;
53
+ try {
54
+ url = new URL(walletUriBase);
55
+ } catch {
56
+ throw new SolanaMobileWalletAdapterError(
57
+ SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL,
58
+ 'Invalid base URL supplied by wallet',
59
+ );
60
+ }
61
+ if (url.protocol !== 'https:') {
62
+ throw new SolanaMobileWalletAdapterError(
63
+ SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL,
64
+ 'Base URLs supplied by wallets must be valid `https` URLs',
65
+ );
66
+ }
67
+ }
68
+
69
+ function getSequenceNumberFromByteArray(byteArray: ArrayBuffer): number {
70
+ const view = new DataView(byteArray);
71
+ return view.getUint32(0, /* littleEndian */ false);
72
+ }
73
+
74
+ export async function transact<TReturn>(
75
+ callback: (wallet: MobileWallet) => TReturn,
76
+ config?: WalletAssociationConfig,
77
+ ): Promise<TReturn> {
78
+ assertSecureContext();
79
+ const associationKeypair = await generateAssociationKeypair();
80
+ const sessionPort = await startSession(associationKeypair.publicKey, config?.baseUri);
81
+ const websocketURL = `ws://localhost:${sessionPort}/solana-wallet`;
82
+ let connectionStartTime: number;
83
+ const getNextRetryDelayMs = (() => {
84
+ const schedule = [...WEBSOCKET_CONNECTION_CONFIG.retryDelayScheduleMs];
85
+ return () => (schedule.length > 1 ? (schedule.shift() as number) : schedule[0]);
86
+ })();
87
+ let nextJsonRpcMessageId = 1;
88
+ let lastKnownInboundSequenceNumber = 0;
89
+ let state: State = { __type: 'disconnected' };
90
+ return new Promise((resolve, reject) => {
91
+ let socket: WebSocket;
92
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
93
+ const jsonRpcResponsePromises: JsonResponsePromises<any> = {};
94
+ const handleOpen = async () => {
95
+ if (state.__type !== 'connecting') {
96
+ console.warn(
97
+ 'Expected adapter state to be `connecting` at the moment the websocket opens. ' +
98
+ `Got \`${state.__type}\`.`,
99
+ );
100
+ return;
101
+ }
102
+ const { associationKeypair } = state;
103
+ socket.removeEventListener('open', handleOpen);
104
+ const ecdhKeypair = await generateECDHKeypair();
105
+ socket.send(await createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));
106
+ state = {
107
+ __type: 'hello_req_sent',
108
+ associationPublicKey: associationKeypair.publicKey,
109
+ ecdhPrivateKey: ecdhKeypair.privateKey,
110
+ };
111
+ };
112
+ const handleClose = (evt: CloseEvent) => {
113
+ if (evt.wasClean) {
114
+ state = { __type: 'disconnected' };
115
+ } else {
116
+ reject(
117
+ new SolanaMobileWalletAdapterError(
118
+ SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED,
119
+ `The wallet session dropped unexpectedly (${evt.code}: ${evt.reason}).`,
120
+ { closeEvent: evt },
121
+ ),
122
+ );
123
+ }
124
+ disposeSocket();
125
+ };
126
+ const handleError = async (_evt: Event) => {
127
+ disposeSocket();
128
+ if (Date.now() - connectionStartTime >= WEBSOCKET_CONNECTION_CONFIG.timeoutMs) {
129
+ reject(
130
+ new SolanaMobileWalletAdapterError(
131
+ SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT,
132
+ `Failed to connect to the wallet websocket on port ${sessionPort}.`,
133
+ ),
134
+ );
135
+ } else {
136
+ await new Promise((resolve) => {
137
+ const retryDelayMs = getNextRetryDelayMs();
138
+ retryWaitTimeoutId = window.setTimeout(resolve, retryDelayMs);
139
+ });
140
+ attemptSocketConnection();
141
+ }
142
+ };
143
+ const handleMessage = async (evt: MessageEvent<Blob>) => {
144
+ const responseBuffer = await evt.data.arrayBuffer();
145
+ switch (state.__type) {
146
+ case 'connected':
147
+ try {
148
+ const sequenceNumberVector = responseBuffer.slice(0, SEQUENCE_NUMBER_BYTES);
149
+ const sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector);
150
+ if (sequenceNumber !== (lastKnownInboundSequenceNumber + 1)) {
151
+ throw new Error('Encrypted message has invalid sequence number');
152
+ }
153
+ lastKnownInboundSequenceNumber = sequenceNumber;
154
+ const jsonRpcMessage = await decryptJsonRpcMessage(responseBuffer, state.sharedSecret);
155
+ const responsePromise = jsonRpcResponsePromises[jsonRpcMessage.id];
156
+ delete jsonRpcResponsePromises[jsonRpcMessage.id];
157
+ responsePromise.resolve(jsonRpcMessage.result);
158
+ } catch (e) {
159
+ if (e instanceof SolanaMobileWalletAdapterProtocolError) {
160
+ const responsePromise = jsonRpcResponsePromises[e.jsonRpcMessageId];
161
+ delete jsonRpcResponsePromises[e.jsonRpcMessageId];
162
+ responsePromise.reject(e);
163
+ } else {
164
+ throw e;
165
+ }
166
+ }
167
+ break;
168
+ case 'hello_req_sent': {
169
+ const sharedSecret = await parseHelloRsp(
170
+ responseBuffer,
171
+ state.associationPublicKey,
172
+ state.ecdhPrivateKey,
173
+ );
174
+ state = { __type: 'connected', sharedSecret };
175
+ const wallet = new Proxy<MobileWallet>({} as MobileWallet, {
176
+ get<TMethodName extends keyof MobileWallet>(target: MobileWallet, p: TMethodName) {
177
+ if (target[p] == null) {
178
+ const method = p
179
+ .toString()
180
+ .replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)
181
+ .toLowerCase();
182
+ target[p] = async function (params: Parameters<MobileWallet[TMethodName]>[0]) {
183
+ const id = nextJsonRpcMessageId++;
184
+ socket.send(
185
+ await encryptJsonRpcMessage(
186
+ {
187
+ id,
188
+ jsonrpc: '2.0',
189
+ method,
190
+ params: params ?? {},
191
+ },
192
+ sharedSecret,
193
+ ),
194
+ );
195
+ return new Promise((resolve, reject) => {
196
+ jsonRpcResponsePromises[id] = {
197
+ resolve(result) {
198
+ switch (p) {
199
+ case 'authorize':
200
+ case 'reauthorize': {
201
+ const { wallet_uri_base } = result as Awaited<
202
+ ReturnType<MobileWallet['authorize' | 'reauthorize']>
203
+ >;
204
+ if (wallet_uri_base != null) {
205
+ try {
206
+ assertSecureEndpointSpecificURI(wallet_uri_base);
207
+ } catch (e) {
208
+ reject(e);
209
+ return;
210
+ }
211
+ }
212
+ break;
213
+ }
214
+ }
215
+ resolve(result);
216
+ },
217
+ reject,
218
+ };
219
+ });
220
+ } as MobileWallet[TMethodName];
221
+ }
222
+ return target[p];
223
+ },
224
+ defineProperty() {
225
+ return false;
226
+ },
227
+ deleteProperty() {
228
+ return false;
229
+ },
230
+ });
231
+ try {
232
+ resolve(await callback(wallet));
233
+ } catch (e) {
234
+ reject(e);
235
+ } finally {
236
+ disposeSocket();
237
+ socket.close();
238
+ }
239
+ break;
240
+ }
241
+ }
242
+ };
243
+ let disposeSocket: () => void;
244
+ let retryWaitTimeoutId: number;
245
+ const attemptSocketConnection = () => {
246
+ if (disposeSocket) {
247
+ disposeSocket();
248
+ }
249
+ state = { __type: 'connecting', associationKeypair };
250
+ if (connectionStartTime === undefined) {
251
+ connectionStartTime = Date.now();
252
+ }
253
+ socket = new WebSocket(websocketURL, [WEBSOCKET_PROTOCOL]);
254
+ socket.addEventListener('open', handleOpen);
255
+ socket.addEventListener('close', handleClose);
256
+ socket.addEventListener('error', handleError);
257
+ socket.addEventListener('message', handleMessage);
258
+ disposeSocket = () => {
259
+ window.clearTimeout(retryWaitTimeoutId);
260
+ socket.removeEventListener('open', handleOpen);
261
+ socket.removeEventListener('close', handleClose);
262
+ socket.removeEventListener('error', handleError);
263
+ socket.removeEventListener('message', handleMessage);
264
+ };
265
+ };
266
+ attemptSocketConnection();
267
+ });
268
+ }
package/src/types.ts ADDED
@@ -0,0 +1,111 @@
1
+ import type { TransactionVersion } from '@solana/web3.js';
2
+
3
+ export type Account = Readonly<{
4
+ address: Base64EncodedAddress;
5
+ label?: string;
6
+ }>;
7
+
8
+ /**
9
+ * Properties that wallets may present to users when an app
10
+ * asks for authorization to execute privileged methods (see
11
+ * {@link PrivilegedMethods}).
12
+ */
13
+ export type AppIdentity = Readonly<{
14
+ uri?: string;
15
+ icon?: string;
16
+ name?: string;
17
+ }>;
18
+
19
+ /**
20
+ * An ephemeral elliptic-curve keypair on the P-256 curve.
21
+ * This public key is used to create the association token.
22
+ * The private key is used during session establishment.
23
+ */
24
+ export type AssociationKeypair = CryptoKeyPair;
25
+
26
+ /**
27
+ * The context returned from a wallet after having authorized a given
28
+ * account for use with a given application. You can cache this and
29
+ * use it later to invoke privileged methods.
30
+ */
31
+ export type AuthorizationResult = Readonly<{
32
+ accounts: Account[];
33
+ auth_token: AuthToken;
34
+ wallet_uri_base: string;
35
+ }>;
36
+
37
+ export type AuthToken = string;
38
+
39
+ export type Base64EncodedAddress = string;
40
+
41
+ type Base64EncodedSignature = string;
42
+
43
+ type Base64EncodedMessage = string;
44
+
45
+ type Base64EncodedSignedMessage = string;
46
+
47
+ type Base64EncodedSignedTransaction = string;
48
+
49
+ export type Base64EncodedTransaction = string;
50
+
51
+ export type Cluster = 'devnet' | 'testnet' | 'mainnet-beta';
52
+
53
+ export type Finality = 'confirmed' | 'finalized' | 'processed';
54
+
55
+ export type WalletAssociationConfig = Readonly<{
56
+ baseUri?: string;
57
+ }>;
58
+
59
+ export interface AuthorizeAPI {
60
+ authorize(params: { cluster: Cluster; identity: AppIdentity }): Promise<AuthorizationResult>;
61
+ }
62
+ export interface CloneAuthorizationAPI {
63
+ cloneAuthorization(params: { auth_token: AuthToken }): Promise<Readonly<{ auth_token: AuthToken }>>;
64
+ }
65
+ export interface DeauthorizeAPI {
66
+ deauthorize(params: { auth_token: AuthToken }): Promise<Readonly<Record<string, never>>>;
67
+ }
68
+
69
+ export interface GetCapabilitiesAPI {
70
+ getCapabilities(): Promise<
71
+ Readonly<{
72
+ supports_clone_authorization: boolean;
73
+ supports_sign_and_send_transactions: boolean;
74
+ max_transactions_per_request: boolean;
75
+ max_messages_per_request: boolean;
76
+ supported_transaction_versions: ReadonlyArray<TransactionVersion>;
77
+ }>
78
+ >;
79
+ }
80
+ export interface ReauthorizeAPI {
81
+ reauthorize(params: { auth_token: AuthToken }): Promise<AuthorizationResult>;
82
+ }
83
+ export interface SignMessagesAPI {
84
+ signMessages(params: {
85
+ addresses: Base64EncodedAddress[];
86
+ payloads: Base64EncodedMessage[];
87
+ }): Promise<Readonly<{ signed_payloads: Base64EncodedSignedMessage[] }>>;
88
+ }
89
+ export interface SignTransactionsAPI {
90
+ signTransactions(params: {
91
+ payloads: Base64EncodedTransaction[];
92
+ }): Promise<Readonly<{ signed_payloads: Base64EncodedSignedTransaction[] }>>;
93
+ }
94
+ export interface SignAndSendTransactionsAPI {
95
+ signAndSendTransactions(params: {
96
+ options?: Readonly<{
97
+ min_context_slot?: number;
98
+ }>;
99
+ payloads: Base64EncodedTransaction[];
100
+ }): Promise<Readonly<{ signatures: Base64EncodedSignature[] }>>;
101
+ }
102
+
103
+ export interface MobileWallet
104
+ extends AuthorizeAPI,
105
+ CloneAuthorizationAPI,
106
+ DeauthorizeAPI,
107
+ GetCapabilitiesAPI,
108
+ ReauthorizeAPI,
109
+ SignMessagesAPI,
110
+ SignTransactionsAPI,
111
+ SignAndSendTransactionsAPI {}
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "module": "commonjs",
5
+ "outDir": "lib/cjs"
6
+ }
7
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "include": ["src"],
4
+ "compilerOptions": {
5
+ "declarationDir": "./lib/types",
6
+ "outDir": "lib/esm"
7
+ }
8
+ }