@solana-mobile/mobile-wallet-adapter-protocol 2.1.5 → 2.1.6

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 (44) hide show
  1. package/.DS_Store +0 -0
  2. package/.gitignore +2 -0
  3. package/README.md +69 -69
  4. package/android/.gitignore +14 -0
  5. package/android/build.gradle +2 -2
  6. package/lib/cjs/index.browser.js +249 -184
  7. package/lib/cjs/index.js +249 -184
  8. package/lib/cjs/index.native.js +8 -0
  9. package/lib/esm/index.browser.js +249 -184
  10. package/lib/esm/index.js +249 -184
  11. package/lib/types/index.browser.d.ts +10 -4
  12. package/lib/types/index.browser.d.ts.map +1 -1
  13. package/lib/types/index.d.ts +10 -4
  14. package/lib/types/index.d.ts.map +1 -1
  15. package/lib/types/index.native.d.ts +10 -4
  16. package/lib/types/index.native.d.ts.map +1 -1
  17. package/package.json +2 -1
  18. package/src/__forks__/react-native/base64Utils.ts +1 -0
  19. package/src/__forks__/react-native/transact.ts +91 -0
  20. package/src/arrayBufferToBase64String.ts +10 -0
  21. package/src/associationPort.ts +19 -0
  22. package/src/base64Utils.ts +22 -0
  23. package/src/codegenSpec/NativeSolanaMobileWalletAdapter.ts +13 -0
  24. package/src/createHelloReq.ts +12 -0
  25. package/src/createMobileWalletProxy.ts +182 -0
  26. package/src/createSIWSMessage.ts +14 -0
  27. package/src/createSequenceNumberVector.ts +11 -0
  28. package/src/encryptedMessage.ts +60 -0
  29. package/src/errors.ts +101 -0
  30. package/src/generateAssociationKeypair.ts +10 -0
  31. package/src/generateECDHKeypair.ts +10 -0
  32. package/src/getAssociateAndroidIntentURL.ts +77 -0
  33. package/src/getJWS.ts +19 -0
  34. package/src/getStringWithURLUnsafeBase64CharactersReplaced.ts +11 -0
  35. package/src/index.ts +3 -0
  36. package/src/jsonRpcMessage.ts +38 -0
  37. package/src/parseHelloRsp.ts +46 -0
  38. package/src/parseSessionProps.ts +33 -0
  39. package/src/reflectorId.ts +31 -0
  40. package/src/startSession.ts +98 -0
  41. package/src/transact.ts +593 -0
  42. package/src/types.ts +201 -0
  43. package/tsconfig.cjs.json +7 -0
  44. package/tsconfig.json +8 -0
@@ -11,6 +11,7 @@ declare const SolanaMobileWalletAdapterErrorCode: {
11
11
  readonly ERROR_SESSION_TIMEOUT: "ERROR_SESSION_TIMEOUT";
12
12
  readonly ERROR_WALLET_NOT_FOUND: "ERROR_WALLET_NOT_FOUND";
13
13
  readonly ERROR_INVALID_PROTOCOL_VERSION: "ERROR_INVALID_PROTOCOL_VERSION";
14
+ readonly ERROR_BROWSER_NOT_SUPPORTED: "ERROR_BROWSER_NOT_SUPPORTED";
14
15
  };
15
16
  type SolanaMobileWalletAdapterErrorCodeEnum = (typeof SolanaMobileWalletAdapterErrorCode)[keyof typeof SolanaMobileWalletAdapterErrorCode];
16
17
  type ErrorDataTypeMap = {
@@ -28,6 +29,7 @@ type ErrorDataTypeMap = {
28
29
  [SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT]: undefined;
29
30
  [SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND]: undefined;
30
31
  [SolanaMobileWalletAdapterErrorCode.ERROR_INVALID_PROTOCOL_VERSION]: undefined;
32
+ [SolanaMobileWalletAdapterErrorCode.ERROR_BROWSER_NOT_SUPPORTED]: undefined;
31
33
  };
32
34
  declare class SolanaMobileWalletAdapterError<TErrorCode extends SolanaMobileWalletAdapterErrorCodeEnum> extends Error {
33
35
  data: ErrorDataTypeMap[TErrorCode] | undefined;
@@ -248,10 +250,14 @@ type SignInResult = Readonly<{
248
250
  signature: Base64EncodedAddress;
249
251
  signature_type?: string;
250
252
  }>;
251
- declare function transact<TReturn>(callback: (wallet: MobileWallet) => TReturn, config?: WalletAssociationConfig): Promise<TReturn>;
252
- declare function transactRemote<TReturn>(callback: (wallet: RemoteMobileWallet) => TReturn, config: RemoteWalletAssociationConfig): Promise<{
253
+ type Scenario = Readonly<{
254
+ wallet: Promise<MobileWallet>;
255
+ close: () => void;
256
+ }>;
257
+ type RemoteScenario = Scenario & Readonly<{
253
258
  associationUrl: URL;
254
- result: Promise<TReturn>;
255
259
  }>;
256
- export { SolanaMobileWalletAdapterErrorCode, SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterProtocolErrorCode, SolanaMobileWalletAdapterProtocolError, transact, transactRemote, Account, AppIdentity, AssociationKeypair, ProtocolVersion, SessionProperties, AuthorizationResult, AuthToken, Base64EncodedAddress, Base64EncodedTransaction, Cluster, Chain, Finality, WalletAssociationConfig, RemoteWalletAssociationConfig, AuthorizeAPI, CloneAuthorizationAPI, DeauthorizeAPI, GetCapabilitiesAPI, ReauthorizeAPI, SignMessagesAPI, SignTransactionsAPI, SignAndSendTransactionsAPI, MobileWallet, TerminateSessionAPI, RemoteMobileWallet, SolanaSignTransactions, SolanaCloneAuthorization, SolanaSignInWithSolana, SignInPayload, SignInPayloadWithRequiredFields, SignInResult };
260
+ declare function transact<TReturn>(callback: (wallet: MobileWallet) => TReturn, config?: WalletAssociationConfig): Promise<TReturn>;
261
+ declare function startRemoteScenario(config: RemoteWalletAssociationConfig): Promise<RemoteScenario>;
262
+ export { SolanaMobileWalletAdapterErrorCode, SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterProtocolErrorCode, SolanaMobileWalletAdapterProtocolError, transact, startRemoteScenario, Account, AppIdentity, AssociationKeypair, ProtocolVersion, SessionProperties, AuthorizationResult, AuthToken, Base64EncodedAddress, Base64EncodedTransaction, Cluster, Chain, Finality, WalletAssociationConfig, RemoteWalletAssociationConfig, AuthorizeAPI, CloneAuthorizationAPI, DeauthorizeAPI, GetCapabilitiesAPI, ReauthorizeAPI, SignMessagesAPI, SignTransactionsAPI, SignAndSendTransactionsAPI, MobileWallet, TerminateSessionAPI, RemoteMobileWallet, SolanaSignTransactions, SolanaCloneAuthorization, SolanaSignInWithSolana, SignInPayload, SignInPayloadWithRequiredFields, SignInResult, Scenario, RemoteScenario };
257
263
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts","../../src/errors.ts","../../src/createHelloReq.ts","../../src/types.ts","../../src/base64Utils.ts","../../src/createSIWSMessage.ts","../../src/createMobileWalletProxy.ts","../../src/createSequenceNumberVector.ts","../../src/parseHelloRsp.ts","../../src/encryptedMessage.ts","../../src/generateAssociationKeypair.ts","../../src/generateECDHKeypair.ts","../../src/jsonRpcMessage.ts","../../src/parseSessionProps.ts","../../src/associationPort.ts","../../src/arrayBufferToBase64String.ts","../../src/getStringWithURLUnsafeBase64CharactersReplaced.ts","../../src/reflectorId.ts","../../src/getAssociateAndroidIntentURL.ts","../../src/startSession.ts","../../src/transact.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts","../../src/errors.ts","../../src/base64Utils.ts","../../src/createHelloReq.ts","../../src/types.ts","../../src/createSIWSMessage.ts","../../src/createMobileWalletProxy.ts","../../src/createSequenceNumberVector.ts","../../src/parseHelloRsp.ts","../../src/encryptedMessage.ts","../../src/generateAssociationKeypair.ts","../../src/generateECDHKeypair.ts","../../src/arrayBufferToBase64String.ts","../../src/associationPort.ts","../../src/getStringWithURLUnsafeBase64CharactersReplaced.ts","../../src/getAssociateAndroidIntentURL.ts","../../src/jsonRpcMessage.ts","../../src/parseSessionProps.ts","../../src/startSession.ts","../../src/transact.ts"],"names":[],"mappings":""}
@@ -11,6 +11,7 @@ declare const SolanaMobileWalletAdapterErrorCode: {
11
11
  readonly ERROR_SESSION_TIMEOUT: "ERROR_SESSION_TIMEOUT";
12
12
  readonly ERROR_WALLET_NOT_FOUND: "ERROR_WALLET_NOT_FOUND";
13
13
  readonly ERROR_INVALID_PROTOCOL_VERSION: "ERROR_INVALID_PROTOCOL_VERSION";
14
+ readonly ERROR_BROWSER_NOT_SUPPORTED: "ERROR_BROWSER_NOT_SUPPORTED";
14
15
  };
15
16
  type SolanaMobileWalletAdapterErrorCodeEnum = (typeof SolanaMobileWalletAdapterErrorCode)[keyof typeof SolanaMobileWalletAdapterErrorCode];
16
17
  type ErrorDataTypeMap = {
@@ -28,6 +29,7 @@ type ErrorDataTypeMap = {
28
29
  [SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT]: undefined;
29
30
  [SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND]: undefined;
30
31
  [SolanaMobileWalletAdapterErrorCode.ERROR_INVALID_PROTOCOL_VERSION]: undefined;
32
+ [SolanaMobileWalletAdapterErrorCode.ERROR_BROWSER_NOT_SUPPORTED]: undefined;
31
33
  };
32
34
  declare class SolanaMobileWalletAdapterError<TErrorCode extends SolanaMobileWalletAdapterErrorCodeEnum> extends Error {
33
35
  data: ErrorDataTypeMap[TErrorCode] | undefined;
@@ -248,10 +250,14 @@ type SignInResult = Readonly<{
248
250
  signature: Base64EncodedAddress;
249
251
  signature_type?: string;
250
252
  }>;
251
- declare function transact<TReturn>(callback: (wallet: MobileWallet) => TReturn, config?: WalletAssociationConfig): Promise<TReturn>;
252
- declare function transactRemote<TReturn>(callback: (wallet: RemoteMobileWallet) => TReturn, config: RemoteWalletAssociationConfig): Promise<{
253
+ type Scenario = Readonly<{
254
+ wallet: Promise<MobileWallet>;
255
+ close: () => void;
256
+ }>;
257
+ type RemoteScenario = Scenario & Readonly<{
253
258
  associationUrl: URL;
254
- result: Promise<TReturn>;
255
259
  }>;
256
- export { SolanaMobileWalletAdapterErrorCode, SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterProtocolErrorCode, SolanaMobileWalletAdapterProtocolError, transact, transactRemote, Account, AppIdentity, AssociationKeypair, ProtocolVersion, SessionProperties, AuthorizationResult, AuthToken, Base64EncodedAddress, Base64EncodedTransaction, Cluster, Chain, Finality, WalletAssociationConfig, RemoteWalletAssociationConfig, AuthorizeAPI, CloneAuthorizationAPI, DeauthorizeAPI, GetCapabilitiesAPI, ReauthorizeAPI, SignMessagesAPI, SignTransactionsAPI, SignAndSendTransactionsAPI, MobileWallet, TerminateSessionAPI, RemoteMobileWallet, SolanaSignTransactions, SolanaCloneAuthorization, SolanaSignInWithSolana, SignInPayload, SignInPayloadWithRequiredFields, SignInResult };
260
+ declare function transact<TReturn>(callback: (wallet: MobileWallet) => TReturn, config?: WalletAssociationConfig): Promise<TReturn>;
261
+ declare function startRemoteScenario(config: RemoteWalletAssociationConfig): Promise<RemoteScenario>;
262
+ export { SolanaMobileWalletAdapterErrorCode, SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterProtocolErrorCode, SolanaMobileWalletAdapterProtocolError, transact, startRemoteScenario, Account, AppIdentity, AssociationKeypair, ProtocolVersion, SessionProperties, AuthorizationResult, AuthToken, Base64EncodedAddress, Base64EncodedTransaction, Cluster, Chain, Finality, WalletAssociationConfig, RemoteWalletAssociationConfig, AuthorizeAPI, CloneAuthorizationAPI, DeauthorizeAPI, GetCapabilitiesAPI, ReauthorizeAPI, SignMessagesAPI, SignTransactionsAPI, SignAndSendTransactionsAPI, MobileWallet, TerminateSessionAPI, RemoteMobileWallet, SolanaSignTransactions, SolanaCloneAuthorization, SolanaSignInWithSolana, SignInPayload, SignInPayloadWithRequiredFields, SignInResult, Scenario, RemoteScenario };
257
263
  //# sourceMappingURL=index.native.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.native.d.ts","sourceRoot":"","sources":["../../src/index.ts","../../src/errors.ts","../../src/createHelloReq.ts","../../src/types.ts","../../src/base64Utils.ts","../../src/createSIWSMessage.ts","../../src/createMobileWalletProxy.ts","../../src/createSequenceNumberVector.ts","../../src/parseHelloRsp.ts","../../src/encryptedMessage.ts","../../src/generateAssociationKeypair.ts","../../src/generateECDHKeypair.ts","../../src/jsonRpcMessage.ts","../../src/parseSessionProps.ts","../../src/associationPort.ts","../../src/arrayBufferToBase64String.ts","../../src/getStringWithURLUnsafeBase64CharactersReplaced.ts","../../src/reflectorId.ts","../../src/getAssociateAndroidIntentURL.ts","../../src/startSession.ts","../../src/transact.ts","../../src/codegenSpec/NativeSolanaMobileWalletAdapter.ts","../../src/__forks__/react-native/transact.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"index.native.d.ts","sourceRoot":"","sources":["../../src/index.ts","../../src/errors.ts","../../src/base64Utils.ts","../../src/createHelloReq.ts","../../src/types.ts","../../src/createSIWSMessage.ts","../../src/createMobileWalletProxy.ts","../../src/createSequenceNumberVector.ts","../../src/parseHelloRsp.ts","../../src/encryptedMessage.ts","../../src/generateAssociationKeypair.ts","../../src/generateECDHKeypair.ts","../../src/arrayBufferToBase64String.ts","../../src/associationPort.ts","../../src/getStringWithURLUnsafeBase64CharactersReplaced.ts","../../src/getAssociateAndroidIntentURL.ts","../../src/jsonRpcMessage.ts","../../src/parseSessionProps.ts","../../src/startSession.ts","../../src/transact.ts","../../src/codegenSpec/NativeSolanaMobileWalletAdapter.ts","../../src/__forks__/react-native/transact.ts"],"names":[],"mappings":""}
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": "2.1.5",
4
+ "version": "2.1.6",
5
5
  "author": "Steven Luscher <steven.luscher@solanamobile.com>",
6
6
  "repository": {
7
7
  "type": "git",
@@ -28,6 +28,7 @@
28
28
  },
29
29
  "files": [
30
30
  "android",
31
+ "src/codegenSpec",
31
32
  "!android/build",
32
33
  "lib",
33
34
  "LICENSE"
@@ -0,0 +1 @@
1
+ export { encode, fromUint8Array, toUint8Array } from 'js-base64';
@@ -0,0 +1,91 @@
1
+ import { Platform } from 'react-native';
2
+
3
+ import NativeSolanaMobileWalletAdapter from '../../codegenSpec/NativeSolanaMobileWalletAdapter.js';
4
+ import createMobileWalletProxy from '../../createMobileWalletProxy.js';
5
+ import { SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterProtocolError } from '../../errors.js';
6
+ import { MobileWallet, SessionProperties, WalletAssociationConfig } from '../../types.js';
7
+
8
+ type ReactNativeError = Error & { code?: string; userInfo?: Record<string, unknown> };
9
+
10
+ const LINKING_ERROR =
11
+ `The package 'solana-mobile-wallet-adapter-protocol' doesn't seem to be linked. Make sure: \n\n` +
12
+ '- You rebuilt the app after installing the package\n' +
13
+ '- If you are using Lerna workspaces\n' +
14
+ ' - You have added `@solana-mobile/mobile-wallet-adapter-protocol` as an explicit dependency, and\n' +
15
+ ' - You have added `@solana-mobile/mobile-wallet-adapter-protocol` to the `nohoist` section of your package.json\n' +
16
+ '- You are not using Expo managed workflow\n';
17
+
18
+ const SolanaMobileWalletAdapter =
19
+ Platform.OS === 'android' && NativeSolanaMobileWalletAdapter
20
+ ? NativeSolanaMobileWalletAdapter
21
+ : (new Proxy(
22
+ {},
23
+ {
24
+ get() {
25
+ throw new Error(
26
+ Platform.OS !== 'android'
27
+ ? 'The package `solana-mobile-wallet-adapter-protocol` is only compatible with React Native Android'
28
+ : LINKING_ERROR,
29
+ );
30
+ },
31
+ },
32
+ ) as typeof NativeSolanaMobileWalletAdapter);
33
+
34
+ function getErrorMessage(e: ReactNativeError): string {
35
+ switch (e.code) {
36
+ case 'ERROR_WALLET_NOT_FOUND':
37
+ return 'Found no installed wallet that supports the mobile wallet protocol.';
38
+ default:
39
+ return e.message;
40
+ }
41
+ }
42
+
43
+ function handleError(e: any): never {
44
+ if (e instanceof Error) {
45
+ const reactNativeError: ReactNativeError = e;
46
+ switch (reactNativeError.code) {
47
+ case undefined:
48
+ throw e;
49
+ case 'JSON_RPC_ERROR': {
50
+ const details = reactNativeError.userInfo as Readonly<{ jsonRpcErrorCode: number }>;
51
+ throw new SolanaMobileWalletAdapterProtocolError(
52
+ 0 /* jsonRpcMessageId */,
53
+ details.jsonRpcErrorCode,
54
+ e.message,
55
+ );
56
+ }
57
+ default:
58
+ throw new SolanaMobileWalletAdapterError<any>(
59
+ reactNativeError.code,
60
+ getErrorMessage(reactNativeError),
61
+ reactNativeError.userInfo,
62
+ );
63
+ }
64
+ }
65
+ throw e;
66
+ }
67
+
68
+ export async function transact<TReturn>(
69
+ callback: (wallet: MobileWallet) => TReturn,
70
+ config?: WalletAssociationConfig,
71
+ ): Promise<TReturn> {
72
+ let didSuccessfullyConnect = false;
73
+ try {
74
+ const sessionProperties: SessionProperties = await SolanaMobileWalletAdapter.startSession(config);
75
+ didSuccessfullyConnect = true;
76
+ const wallet = createMobileWalletProxy(sessionProperties.protocol_version, async (method, params) => {
77
+ try {
78
+ return SolanaMobileWalletAdapter.invoke(method, params);
79
+ } catch (e) {
80
+ return handleError(e);
81
+ }
82
+ });
83
+ return await callback(wallet);
84
+ } catch (e) {
85
+ return handleError(e);
86
+ } finally {
87
+ if (didSuccessfullyConnect) {
88
+ await SolanaMobileWalletAdapter.endSession();
89
+ }
90
+ }
91
+ }
@@ -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,22 @@
1
+ export function encode(input: string): string {
2
+ return window.btoa(input);
3
+ }
4
+
5
+ export function fromUint8Array(byteArray: Uint8Array, urlsafe?: boolean): string {
6
+ const base64 = window.btoa(String.fromCharCode.call(null, ...byteArray));
7
+ if (urlsafe) {
8
+ return base64
9
+ .replace(/\+/g, '-')
10
+ .replace(/\//g, '_')
11
+ .replace(/=+$/, '');
12
+ } else return base64;
13
+ }
14
+
15
+ export function toUint8Array(base64EncodedByteArray: string): Uint8Array {
16
+ return new Uint8Array(
17
+ window
18
+ .atob(base64EncodedByteArray)
19
+ .split('')
20
+ .map((c) => c.charCodeAt(0)),
21
+ );
22
+ }
@@ -0,0 +1,13 @@
1
+ import { TurboModule, TurboModuleRegistry } from 'react-native';
2
+
3
+ export interface Spec extends TurboModule {
4
+ startSession(config?: { baseUri?: string }): Promise<{
5
+ protocol_version: 'legacy' | 'v1';
6
+ }>;
7
+
8
+ invoke(method: string, params: Object | undefined): Promise<Object>;
9
+
10
+ endSession(): Promise<boolean>;
11
+ }
12
+
13
+ export default TurboModuleRegistry.getEnforcing<Spec>('SolanaMobileWalletAdapter') as Spec;
@@ -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,182 @@
1
+ import { createSIWSMessageBase64 } from "./createSIWSMessage";
2
+ import {
3
+ AuthorizationResult,
4
+ MobileWallet,
5
+ ProtocolVersion,
6
+ SignInPayload,
7
+ SignInResult,
8
+ SolanaCloneAuthorization,
9
+ SolanaSignTransactions
10
+ } from "./types";
11
+ import type { IdentifierArray } from "@wallet-standard/core";
12
+
13
+ /**
14
+ * Creates a {@link MobileWallet} proxy that handles backwards compatibility and API to RPC conversion.
15
+ *
16
+ * @param protocolVersion the protocol version in use for this session/request
17
+ * @param protocolRequestHandler callback function that handles sending the RPC request to the wallet endpoint.
18
+ * @returns a {@link MobileWallet} proxy
19
+ */
20
+ export default function createMobileWalletProxy<
21
+ TMethodName extends keyof MobileWallet,
22
+ TReturn extends Awaited<ReturnType<MobileWallet[TMethodName]>>
23
+ >(
24
+ protocolVersion: ProtocolVersion,
25
+ protocolRequestHandler: (method: string, params: Parameters<MobileWallet[TMethodName]>[0]) => Promise<any>
26
+ ): MobileWallet {
27
+ return new Proxy<MobileWallet>({} as MobileWallet, {
28
+ get<TMethodName extends keyof MobileWallet>(target: MobileWallet, p: TMethodName) {
29
+ // Wrapping a Proxy in a promise results in the Proxy being asked for a 'then' property so must
30
+ // return null if 'then' is called on this proxy to let the 'resolve()' call know this is not a promise.
31
+ // see: https://stackoverflow.com/a/53890904
32
+ //@ts-ignore
33
+ if (p === 'then') {
34
+ return null;
35
+ }
36
+ if (target[p] == null) {
37
+ target[p] = async function (inputParams: Parameters<MobileWallet[TMethodName]>[0]) {
38
+ const { method, params } = handleMobileWalletRequest(p, inputParams, protocolVersion);
39
+ const result = await protocolRequestHandler(method, params) as Awaited<ReturnType<MobileWallet[TMethodName]>>;
40
+ // if the request tried to sign in but the wallet did not return a sign in result, fallback on message signing
41
+ if (method === 'authorize' && (params as any).sign_in_payload && !(result as any).sign_in_result) {
42
+ (result as any)['sign_in_result'] = await signInFallback(
43
+ (params as Parameters<MobileWallet['authorize']>[0]).sign_in_payload as SignInPayload,
44
+ result as Awaited<ReturnType<MobileWallet['authorize']>>,
45
+ protocolRequestHandler
46
+ );
47
+ }
48
+ return handleMobileWalletResponse(p, result, protocolVersion) as TReturn;
49
+ } as MobileWallet[TMethodName];
50
+ }
51
+ return target[p];
52
+ },
53
+ defineProperty() {
54
+ return false;
55
+ },
56
+ deleteProperty() {
57
+ return false;
58
+ },
59
+ });
60
+ };
61
+
62
+ /**
63
+ * Handles all {@link MobileWallet} API requests and determines the correct MWA RPC method and params to call.
64
+ * This handles backwards compatibility, based on the provided @protocolVersion.
65
+ *
66
+ * @param methodName the name of {@link MobileWallet} method that was called
67
+ * @param methodParams the parameters that were passed to the method
68
+ * @param protocolVersion the protocol version in use for this session/request
69
+ * @returns the RPC request method and params that should be sent to the wallet endpoint
70
+ */
71
+ function handleMobileWalletRequest<TMethodName extends keyof MobileWallet>(
72
+ methodName: TMethodName,
73
+ methodParams: Parameters<MobileWallet[TMethodName]>[0],
74
+ protocolVersion: ProtocolVersion
75
+ ) {
76
+ let params = methodParams;
77
+ let method: string = methodName
78
+ .toString()
79
+ .replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)
80
+ .toLowerCase();
81
+ switch (methodName) {
82
+ case 'authorize': {
83
+ let { chain } = params as Parameters<MobileWallet['authorize']>[0];
84
+ if (protocolVersion === 'legacy') {
85
+ switch (chain) {
86
+ case 'solana:testnet': { chain = 'testnet'; break; }
87
+ case 'solana:devnet': { chain = 'devnet'; break; }
88
+ case 'solana:mainnet': { chain = 'mainnet-beta'; break; }
89
+ default: { chain = (params as any).cluster; }
90
+ }
91
+ (params as any).cluster = chain;
92
+ } else {
93
+ switch (chain) {
94
+ case 'testnet':
95
+ case 'devnet': { chain = `solana:${chain}`; break; }
96
+ case 'mainnet-beta': { chain = 'solana:mainnet'; break; }
97
+ }
98
+ (params as Parameters<MobileWallet['authorize']>[0]).chain = chain;
99
+ }
100
+ }
101
+ case 'reauthorize': {
102
+ const { auth_token, identity } = params as Parameters<MobileWallet['authorize' | 'reauthorize']>[0];
103
+ if (auth_token) {
104
+ switch (protocolVersion) {
105
+ case 'legacy': {
106
+ method = 'reauthorize';
107
+ params = { auth_token: auth_token, identity: identity };
108
+ break;
109
+ }
110
+ default: {
111
+ method = 'authorize';
112
+ break;
113
+ }
114
+ }
115
+ }
116
+ break;
117
+ }
118
+ }
119
+ return { method, params }
120
+ };
121
+
122
+ /**
123
+ * Handles all {@link MobileWallet} API responses and modifies the response for backwards compatibility, if needed
124
+ *
125
+ * @param method the {@link MobileWallet} method that was called
126
+ * @param response the original response that was returned by the method call
127
+ * @param protocolVersion the protocol version in use for this session/request
128
+ * @returns the possibly modified response
129
+ */
130
+ function handleMobileWalletResponse<TMethodName extends keyof MobileWallet>(
131
+ method: TMethodName,
132
+ response: Awaited<ReturnType<MobileWallet[TMethodName]>>,
133
+ protocolVersion: ProtocolVersion
134
+ ): Awaited<ReturnType<MobileWallet[TMethodName]>> {
135
+ switch (method) {
136
+ case 'getCapabilities': {
137
+ const capabilities = response as Awaited<ReturnType<MobileWallet['getCapabilities']>>
138
+ switch (protocolVersion) {
139
+ case 'legacy': {
140
+ const features: `${string}:${string}`[] = [ SolanaSignTransactions ];
141
+ if (capabilities.supports_clone_authorization === true) {
142
+ features.push(SolanaCloneAuthorization);
143
+ }
144
+ return {
145
+ ...capabilities,
146
+ features: features as IdentifierArray,
147
+ } as Awaited<ReturnType<MobileWallet[TMethodName]>>;
148
+ }
149
+ case 'v1': {
150
+ return {
151
+ ...capabilities,
152
+ supports_sign_and_send_transactions: true,
153
+ supports_clone_authorization: capabilities.features.includes(SolanaCloneAuthorization)
154
+ } as Awaited<ReturnType<MobileWallet[TMethodName]>>;
155
+ }
156
+ }
157
+ }
158
+ }
159
+ return response;
160
+ };
161
+
162
+ async function signInFallback(
163
+ signInPayload: SignInPayload,
164
+ authorizationResult: Awaited<ReturnType<MobileWallet['authorize']>>,
165
+ protocolRequestHandler: (method: string, params: Parameters<MobileWallet['signMessages']>[0]) => Promise<unknown>
166
+ ) {
167
+ const domain = signInPayload.domain ?? window.location.host;
168
+ const address = (authorizationResult as AuthorizationResult).accounts[0].address;
169
+ const siwsMessage = createSIWSMessageBase64({ ...signInPayload, domain, address })
170
+ const signMessageResult = await (protocolRequestHandler('sign_messages',
171
+ {
172
+ addresses: [ address ],
173
+ payloads: [ siwsMessage ]
174
+ }
175
+ ) as ReturnType<MobileWallet['signMessages']>);
176
+ const signInResult: SignInResult = {
177
+ address: address,
178
+ signed_message: siwsMessage,
179
+ signature: signMessageResult.signed_payloads[0].slice(siwsMessage.length)
180
+ };
181
+ return signInResult;
182
+ }
@@ -0,0 +1,14 @@
1
+ import {
2
+ SolanaSignInInputWithRequiredFields,
3
+ createSignInMessageText,
4
+ } from '@solana/wallet-standard-util';
5
+ import { SignInPayload } from './types';
6
+ import { encode } from './base64Utils';
7
+
8
+ export function createSIWSMessage(payload: SolanaSignInInputWithRequiredFields & SignInPayload): string {
9
+ return createSignInMessageText(payload);
10
+ }
11
+
12
+ export function createSIWSMessageBase64(payload: SolanaSignInInputWithRequiredFields & SignInPayload): string {
13
+ return encode(createSIWSMessage(payload));
14
+ }
@@ -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
+ }
@@ -0,0 +1,60 @@
1
+ import createSequenceNumberVector, { SEQUENCE_NUMBER_BYTES } from './createSequenceNumberVector.js';
2
+ import { SharedSecret } from './parseHelloRsp.js';
3
+
4
+ const INITIALIZATION_VECTOR_BYTES = 12;
5
+ export const ENCODED_PUBLIC_KEY_LENGTH_BYTES = 65;
6
+
7
+ export async function encryptMessage(
8
+ plaintext: string,
9
+ sequenceNumber: number,
10
+ sharedSecret: SharedSecret,
11
+ ) {
12
+ const sequenceNumberVector = createSequenceNumberVector(sequenceNumber);
13
+ const initializationVector = new Uint8Array(INITIALIZATION_VECTOR_BYTES);
14
+ crypto.getRandomValues(initializationVector);
15
+ const ciphertext = await crypto.subtle.encrypt(
16
+ getAlgorithmParams(sequenceNumberVector, initializationVector),
17
+ sharedSecret,
18
+ new TextEncoder().encode(plaintext),
19
+ );
20
+ const response = new Uint8Array(
21
+ sequenceNumberVector.byteLength + initializationVector.byteLength + ciphertext.byteLength,
22
+ );
23
+ response.set(new Uint8Array(sequenceNumberVector), 0);
24
+ response.set(new Uint8Array(initializationVector), sequenceNumberVector.byteLength);
25
+ response.set(new Uint8Array(ciphertext), sequenceNumberVector.byteLength + initializationVector.byteLength);
26
+ return response;
27
+ }
28
+
29
+ export async function decryptMessage(message: ArrayBuffer, sharedSecret: SharedSecret) {
30
+ const sequenceNumberVector = message.slice(0, SEQUENCE_NUMBER_BYTES);
31
+ const initializationVector = message.slice(
32
+ SEQUENCE_NUMBER_BYTES,
33
+ SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES,
34
+ );
35
+ const ciphertext = message.slice(SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES);
36
+ const plaintextBuffer = await crypto.subtle.decrypt(
37
+ getAlgorithmParams(sequenceNumberVector, initializationVector),
38
+ sharedSecret,
39
+ ciphertext,
40
+ );
41
+ const plaintext = getUtf8Decoder().decode(plaintextBuffer);
42
+ return plaintext
43
+ }
44
+
45
+ function getAlgorithmParams(sequenceNumber: ArrayBuffer, initializationVector: ArrayBuffer) {
46
+ return {
47
+ additionalData: sequenceNumber,
48
+ iv: initializationVector,
49
+ name: 'AES-GCM',
50
+ tagLength: 128, // 16 byte tag => 128 bits
51
+ };
52
+ }
53
+
54
+ let _utf8Decoder: TextDecoder | undefined;
55
+ function getUtf8Decoder() {
56
+ if (_utf8Decoder === undefined) {
57
+ _utf8Decoder = new TextDecoder('utf-8');
58
+ }
59
+ return _utf8Decoder;
60
+ }