@solana-mobile/mobile-wallet-adapter-protocol 0.9.9 → 1.0.1

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 (56) hide show
  1. package/.gitignore +2 -0
  2. package/README.md +69 -62
  3. package/android/.gitignore +14 -0
  4. package/android/.gradle/4.4.1/fileChanges/last-build.bin +0 -0
  5. package/android/.gradle/4.4.1/fileHashes/fileHashes.bin +0 -0
  6. package/android/.gradle/4.4.1/fileHashes/fileHashes.lock +0 -0
  7. package/android/.gradle/7.1/dependencies-accessors/dependencies-accessors.lock +0 -0
  8. package/android/.gradle/7.1/dependencies-accessors/gc.properties +0 -0
  9. package/android/.gradle/7.1/fileChanges/last-build.bin +0 -0
  10. package/android/.gradle/7.1/fileHashes/fileHashes.lock +0 -0
  11. package/android/.gradle/7.1/gc.properties +0 -0
  12. package/android/.gradle/7.5/checksums/checksums.lock +0 -0
  13. package/android/.gradle/7.5/dependencies-accessors/dependencies-accessors.lock +0 -0
  14. package/android/.gradle/7.5/dependencies-accessors/gc.properties +0 -0
  15. package/android/.gradle/7.5/fileChanges/last-build.bin +0 -0
  16. package/android/.gradle/7.5/fileHashes/fileHashes.lock +0 -0
  17. package/android/.gradle/7.5/gc.properties +0 -0
  18. package/android/.gradle/7.5.1/checksums/checksums.lock +0 -0
  19. package/android/.gradle/7.5.1/checksums/sha1-checksums.bin +0 -0
  20. package/android/.gradle/7.5.1/dependencies-accessors/dependencies-accessors.lock +0 -0
  21. package/android/.gradle/7.5.1/dependencies-accessors/gc.properties +0 -0
  22. package/android/.gradle/7.5.1/fileChanges/last-build.bin +0 -0
  23. package/android/.gradle/7.5.1/fileHashes/fileHashes.lock +0 -0
  24. package/android/.gradle/7.5.1/gc.properties +0 -0
  25. package/android/.gradle/buildOutputCleanup/buildOutputCleanup.lock +0 -0
  26. package/android/.gradle/buildOutputCleanup/cache.properties +2 -0
  27. package/android/.gradle/checksums/checksums.lock +0 -0
  28. package/android/.gradle/checksums/md5-checksums.bin +0 -0
  29. package/android/.gradle/checksums/sha1-checksums.bin +0 -0
  30. package/android/.gradle/vcs-1/gc.properties +0 -0
  31. package/android/build.gradle +146 -146
  32. package/android/gradle/wrapper/gradle-wrapper.properties +5 -5
  33. package/android/src/main/java/com/solanamobile/mobilewalletadapter/reactnative/SolanaMobileWalletAdapterModule.kt +176 -139
  34. package/lib/types/index.browser.d.ts +1 -0
  35. package/lib/types/index.d.ts +1 -0
  36. package/lib/types/index.native.d.ts +1 -0
  37. package/package.json +2 -3
  38. package/src/__forks__/react-native/transact.ts +106 -0
  39. package/src/arrayBufferToBase64String.ts +10 -0
  40. package/src/associationPort.ts +19 -0
  41. package/src/createHelloReq.ts +12 -0
  42. package/src/createSequenceNumberVector.ts +11 -0
  43. package/src/errors.ts +93 -0
  44. package/src/generateAssociationKeypair.ts +10 -0
  45. package/src/generateECDHKeypair.ts +10 -0
  46. package/src/getAssociateAndroidIntentURL.ts +52 -0
  47. package/src/getJWS.ts +19 -0
  48. package/src/getStringWithURLUnsafeBase64CharactersReplaced.ts +11 -0
  49. package/src/index.ts +3 -0
  50. package/src/jsonRpcMessage.ts +81 -0
  51. package/src/parseHelloRsp.ts +44 -0
  52. package/src/startSession.ts +94 -0
  53. package/src/transact.ts +268 -0
  54. package/src/types.ts +111 -0
  55. package/tsconfig.cjs.json +7 -0
  56. package/tsconfig.json +8 -0
@@ -1,139 +1,176 @@
1
- package com.solanamobile.mobilewalletadapter.reactnative
2
-
3
- import android.content.ActivityNotFoundException
4
- import android.net.Uri
5
- import android.util.Log
6
- import com.facebook.react.bridge.*
7
- import com.solana.mobilewalletadapter.clientlib.protocol.JsonRpc20Client
8
- import com.solana.mobilewalletadapter.clientlib.protocol.MobileWalletAdapterClient
9
- import com.solana.mobilewalletadapter.clientlib.scenario.LocalAssociationIntentCreator
10
- import com.solana.mobilewalletadapter.clientlib.scenario.LocalAssociationScenario
11
- import com.solanamobile.mobilewalletadapter.reactnative.JSONSerializationUtils.convertJsonToMap
12
- import com.solanamobile.mobilewalletadapter.reactnative.JSONSerializationUtils.convertMapToJson
13
- import kotlinx.coroutines.*
14
- import kotlinx.coroutines.sync.Mutex
15
- import org.json.JSONObject
16
- import java.util.concurrent.ExecutionException
17
- import java.util.concurrent.TimeUnit
18
- import java.util.concurrent.TimeoutException
19
-
20
- class SolanaMobileWalletAdapterModule(reactContext: ReactApplicationContext) :
21
- ReactContextBaseJavaModule(reactContext), CoroutineScope {
22
-
23
- data class SessionState(
24
- val client: MobileWalletAdapterClient,
25
- val localAssociation: LocalAssociationScenario,
26
- )
27
-
28
- override val coroutineContext =
29
- Dispatchers.IO + CoroutineName("SolanaMobileWalletAdapterModuleScope") + SupervisorJob()
30
-
31
- companion object {
32
- private const val ASSOCIATION_TIMEOUT_MS = 10000
33
- private const val CLIENT_TIMEOUT_MS = 90000
34
-
35
- // Used to ensure that you can't start more than one session at a time.
36
- private val mutex: Mutex = Mutex()
37
- private var sessionState: SessionState? = null
38
- }
39
-
40
- override fun getName(): String {
41
- return "SolanaMobileWalletAdapter"
42
- }
43
-
44
- @ReactMethod
45
- fun startSession(config: ReadableMap?, promise: Promise) = launch {
46
- mutex.lock()
47
- Log.d(name, "startSession with config $config")
48
- try {
49
- val uriPrefix = config?.getString("baseUri")?.let { Uri.parse(it) }
50
- val localAssociation = LocalAssociationScenario(
51
- CLIENT_TIMEOUT_MS,
52
- )
53
- val intent = LocalAssociationIntentCreator.createAssociationIntent(
54
- uriPrefix,
55
- localAssociation.port,
56
- localAssociation.session
57
- )
58
- currentActivity?.startActivityForResult(intent, 0)
59
- ?: throw NullPointerException("Could not find a current activity from which to launch a local association")
60
- val client =
61
- localAssociation.start().get(ASSOCIATION_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS)
62
- sessionState = SessionState(client, localAssociation)
63
- promise.resolve(true)
64
- } catch (e: ActivityNotFoundException) {
65
- Log.e(name, "Found no installed wallet that supports the mobile wallet protocol", e)
66
- cleanup()
67
- promise.reject("ERROR_WALLET_NOT_FOUND", e)
68
- } catch (e: TimeoutException) {
69
- Log.e(name, "Timed out waiting for local association to be ready", e)
70
- cleanup()
71
- promise.reject("Timed out waiting for local association to be ready", e)
72
- } catch (e: InterruptedException) {
73
- Log.w(name, "Interrupted while waiting for local association to be ready", e)
74
- cleanup()
75
- promise.reject(e)
76
- } catch (e: ExecutionException) {
77
- Log.e(name, "Failed establishing local association with wallet", e.cause)
78
- cleanup()
79
- promise.reject(e)
80
- } catch (e: Throwable) {
81
- Log.e(name, "Failed to start session", e)
82
- cleanup()
83
- promise.reject(e)
84
- }
85
- }
86
-
87
- @ReactMethod
88
- fun invoke(method: String, params: ReadableMap, promise: Promise) = sessionState?.let {
89
- Log.d(name, "invoke `$method` with params $params")
90
- try {
91
- val result = it.client.methodCall(
92
- method,
93
- convertMapToJson(params),
94
- CLIENT_TIMEOUT_MS
95
- ).get() as JSONObject
96
- promise.resolve(convertJsonToMap(result))
97
- } catch (e: ExecutionException) {
98
- val cause = e.cause
99
- if (cause is JsonRpc20Client.JsonRpc20RemoteException) {
100
- val userInfo = Arguments.createMap()
101
- userInfo.putInt("jsonRpcErrorCode", cause.code)
102
- promise.reject("JSON_RPC_ERROR", cause, userInfo)
103
- } else {
104
- throw e
105
- }
106
- } catch (e: Throwable) {
107
- Log.e(name, "Failed to invoke `$method` with params $params", e)
108
- promise.reject(e)
109
- }
110
- } ?: throw NullPointerException("Tried to invoke `$method` without an active session")
111
-
112
- @ReactMethod
113
- fun endSession(promise: Promise) = sessionState?.let {
114
- launch {
115
- Log.d(name, "endSession")
116
- try {
117
- it.localAssociation.close()
118
- .get(ASSOCIATION_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS)
119
- cleanup()
120
- promise.resolve(true)
121
- } catch (e: TimeoutException) {
122
- Log.e(name, "Timed out waiting for local association to close", e)
123
- cleanup()
124
- promise.reject("Failed to end session", e)
125
- } catch (e: Throwable) {
126
- Log.e(name, "Failed to end session", e)
127
- cleanup()
128
- promise.reject("Failed to end session", e)
129
- }
130
- }
131
- } ?: throw NullPointerException("Tried to end a session without an active session")
132
-
133
- private fun cleanup() {
134
- sessionState = null
135
- if (mutex.isLocked) {
136
- mutex.unlock()
137
- }
138
- }
139
- }
1
+ package com.solanamobile.mobilewalletadapter.reactnative
2
+
3
+ import android.app.Activity
4
+ import android.content.ActivityNotFoundException
5
+ import android.content.Intent
6
+ import android.net.Uri
7
+ import android.util.Log
8
+ import com.facebook.react.bridge.*
9
+ import com.solana.mobilewalletadapter.clientlib.protocol.JsonRpc20Client
10
+ import com.solana.mobilewalletadapter.clientlib.protocol.MobileWalletAdapterClient
11
+ import com.solana.mobilewalletadapter.clientlib.scenario.LocalAssociationIntentCreator
12
+ import com.solana.mobilewalletadapter.clientlib.scenario.LocalAssociationScenario
13
+ import com.solanamobile.mobilewalletadapter.reactnative.JSONSerializationUtils.convertJsonToMap
14
+ import com.solanamobile.mobilewalletadapter.reactnative.JSONSerializationUtils.convertMapToJson
15
+ import kotlinx.coroutines.*
16
+ import kotlinx.coroutines.sync.Mutex
17
+ import org.json.JSONObject
18
+ import java.util.concurrent.ExecutionException
19
+ import java.util.concurrent.TimeUnit
20
+ import java.util.concurrent.TimeoutException
21
+
22
+ class SolanaMobileWalletAdapterModule(reactContext: ReactApplicationContext) :
23
+ ReactContextBaseJavaModule(reactContext), CoroutineScope {
24
+
25
+ data class SessionState(
26
+ val client: MobileWalletAdapterClient,
27
+ val localAssociation: LocalAssociationScenario,
28
+ )
29
+
30
+ override val coroutineContext =
31
+ Dispatchers.IO + CoroutineName("SolanaMobileWalletAdapterModuleScope") + SupervisorJob()
32
+
33
+ companion object {
34
+ private const val ASSOCIATION_TIMEOUT_MS = 10000
35
+ private const val CLIENT_TIMEOUT_MS = 90000
36
+ private const val REQUEST_LOCAL_ASSOCIATION = 0
37
+
38
+ // Used to ensure that you can't start more than one session at a time.
39
+ private val mutex: Mutex = Mutex()
40
+ private var sessionState: SessionState? = null
41
+ }
42
+
43
+ private val mActivityEventCallbacks = mutableMapOf<Int, (Int, Intent?) -> (Unit)>()
44
+ private val mActivityEventListener: ActivityEventListener =
45
+ object : BaseActivityEventListener() {
46
+ override fun onActivityResult(
47
+ activity: Activity?,
48
+ requestCode: Int,
49
+ resultCode: Int,
50
+ data: Intent?
51
+ ) {
52
+ mActivityEventCallbacks[requestCode]?.let { callback ->
53
+ callback(resultCode, data)
54
+ mActivityEventCallbacks.remove(requestCode)
55
+ }
56
+ }
57
+ }
58
+
59
+ init {
60
+ reactContext.addActivityEventListener(mActivityEventListener)
61
+ }
62
+
63
+ override fun getName(): String {
64
+ return "SolanaMobileWalletAdapter"
65
+ }
66
+
67
+ @ReactMethod
68
+ fun startSession(config: ReadableMap?, promise: Promise) = launch {
69
+ mutex.lock()
70
+ Log.d(name, "startSession with config $config")
71
+ try {
72
+ val uriPrefix = config?.getString("baseUri")?.let { Uri.parse(it) }
73
+ val localAssociation = LocalAssociationScenario(
74
+ CLIENT_TIMEOUT_MS,
75
+ )
76
+ val intent = LocalAssociationIntentCreator.createAssociationIntent(
77
+ uriPrefix,
78
+ localAssociation.port,
79
+ localAssociation.session
80
+ )
81
+ launchIntent(intent, REQUEST_LOCAL_ASSOCIATION) { resultCode, _ ->
82
+ if (resultCode == Activity.RESULT_CANCELED) {
83
+ Log.d(name, "Local association cancelled by user, ending session")
84
+ promise.reject("Session not established: Local association cancelled by user",
85
+ LocalAssociationScenario.ConnectionFailedException("Local association cancelled by user"))
86
+ localAssociation.close()
87
+ }
88
+ }
89
+ val client =
90
+ localAssociation.start().get(ASSOCIATION_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS)
91
+ sessionState = SessionState(client, localAssociation)
92
+ promise.resolve(true)
93
+ } catch (e: ActivityNotFoundException) {
94
+ Log.e(name, "Found no installed wallet that supports the mobile wallet protocol", e)
95
+ cleanup()
96
+ promise.reject("ERROR_WALLET_NOT_FOUND", e)
97
+ } catch (e: TimeoutException) {
98
+ Log.e(name, "Timed out waiting for local association to be ready", e)
99
+ cleanup()
100
+ promise.reject("Timed out waiting for local association to be ready", e)
101
+ } catch (e: InterruptedException) {
102
+ Log.w(name, "Interrupted while waiting for local association to be ready", e)
103
+ cleanup()
104
+ promise.reject(e)
105
+ } catch (e: ExecutionException) {
106
+ Log.e(name, "Failed establishing local association with wallet", e.cause)
107
+ cleanup()
108
+ promise.reject(e)
109
+ } catch (e: Throwable) {
110
+ Log.e(name, "Failed to start session", e)
111
+ cleanup()
112
+ promise.reject(e)
113
+ }
114
+ }
115
+
116
+ @ReactMethod
117
+ fun invoke(method: String, params: ReadableMap, promise: Promise) = sessionState?.let {
118
+ Log.d(name, "invoke `$method` with params $params")
119
+ try {
120
+ val result = it.client.methodCall(
121
+ method,
122
+ convertMapToJson(params),
123
+ CLIENT_TIMEOUT_MS
124
+ ).get() as JSONObject
125
+ promise.resolve(convertJsonToMap(result))
126
+ } catch (e: ExecutionException) {
127
+ val cause = e.cause
128
+ if (cause is JsonRpc20Client.JsonRpc20RemoteException) {
129
+ val userInfo = Arguments.createMap()
130
+ userInfo.putInt("jsonRpcErrorCode", cause.code)
131
+ promise.reject("JSON_RPC_ERROR", cause, userInfo)
132
+ } else {
133
+ throw e
134
+ }
135
+ } catch (e: Throwable) {
136
+ Log.e(name, "Failed to invoke `$method` with params $params", e)
137
+ promise.reject(e)
138
+ }
139
+ } ?: throw NullPointerException("Tried to invoke `$method` without an active session")
140
+
141
+ @ReactMethod
142
+ fun endSession(promise: Promise) = sessionState?.let {
143
+ launch {
144
+ Log.d(name, "endSession")
145
+ try {
146
+ it.localAssociation.close()
147
+ .get(ASSOCIATION_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS)
148
+ cleanup()
149
+ promise.resolve(true)
150
+ } catch (e: TimeoutException) {
151
+ Log.e(name, "Timed out waiting for local association to close", e)
152
+ cleanup()
153
+ promise.reject("Failed to end session", e)
154
+ } catch (e: Throwable) {
155
+ Log.e(name, "Failed to end session", e)
156
+ cleanup()
157
+ promise.reject("Failed to end session", e)
158
+ }
159
+ }
160
+ } ?: throw NullPointerException("Tried to end a session without an active session")
161
+
162
+ private fun launchIntent(intent: Intent, requestCode: Int, callback: (Int, Intent?) -> (Unit)) {
163
+ mActivityEventCallbacks[requestCode] = callback
164
+ currentActivity?.startActivityForResult(intent, REQUEST_LOCAL_ASSOCIATION) ?: run {
165
+ mActivityEventCallbacks.remove(requestCode)
166
+ throw NullPointerException("Could not find a current activity from which to launch a local association")
167
+ }
168
+ }
169
+
170
+ private fun cleanup() {
171
+ sessionState = null
172
+ if (mutex.isLocked) {
173
+ mutex.unlock()
174
+ }
175
+ }
176
+ }
@@ -143,6 +143,7 @@ interface GetCapabilitiesAPI {
143
143
  interface ReauthorizeAPI {
144
144
  reauthorize(params: {
145
145
  auth_token: AuthToken;
146
+ identity: AppIdentity;
146
147
  }): Promise<AuthorizationResult>;
147
148
  }
148
149
  interface SignMessagesAPI {
@@ -143,6 +143,7 @@ interface GetCapabilitiesAPI {
143
143
  interface ReauthorizeAPI {
144
144
  reauthorize(params: {
145
145
  auth_token: AuthToken;
146
+ identity: AppIdentity;
146
147
  }): Promise<AuthorizationResult>;
147
148
  }
148
149
  interface SignMessagesAPI {
@@ -143,6 +143,7 @@ interface GetCapabilitiesAPI {
143
143
  interface ReauthorizeAPI {
144
144
  reauthorize(params: {
145
145
  auth_token: AuthToken;
146
+ identity: AppIdentity;
146
147
  }): Promise<AuthorizationResult>;
147
148
  }
148
149
  interface SignMessagesAPI {
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.9",
4
+ "version": "1.0.1",
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": "d03adeaa47d752aaac815300572d1157e2362758"
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
+ }