wallaby-cash 1.2.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.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +66 -0
  3. package/dist/base.d.ts +10 -0
  4. package/dist/helpers/logger.d.ts +2 -0
  5. package/dist/index.d.ts +45 -0
  6. package/dist/index.esm.js +2 -0
  7. package/dist/index.esm.js.map +1 -0
  8. package/dist/index.js +2 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/index.umd.js +2 -0
  11. package/dist/index.umd.js.map +1 -0
  12. package/dist/lib/auth/index.d.ts +54 -0
  13. package/dist/lib/index.d.ts +3 -0
  14. package/dist/lib/system/index.d.ts +32 -0
  15. package/dist/lib/transactions/index.d.ts +80 -0
  16. package/dist/lib/utils/index.d.ts +21 -0
  17. package/dist/lib/utils/utils.d.ts +68 -0
  18. package/dist/lib/wallet/index.d.ts +99 -0
  19. package/dist/localStorageMock.d.ts +7 -0
  20. package/dist/routes/auth.d.ts +33 -0
  21. package/dist/routes/index.d.ts +3 -0
  22. package/dist/routes/system.d.ts +23 -0
  23. package/dist/routes/transactions.d.ts +28 -0
  24. package/dist/routes/wallet.d.ts +53 -0
  25. package/dist/tests/data/auth.d.ts +11 -0
  26. package/dist/tests/data/config.d.ts +6 -0
  27. package/dist/tests/data/index.d.ts +4 -0
  28. package/dist/tests/data/system.d.ts +47 -0
  29. package/dist/tests/data/user.d.ts +20 -0
  30. package/dist/types/auth.d.ts +48 -0
  31. package/dist/types/common.d.ts +206 -0
  32. package/dist/types/index.d.ts +5 -0
  33. package/dist/types/merchants.d.ts +43 -0
  34. package/dist/types/transactions.d.ts +127 -0
  35. package/dist/types/wallet.d.ts +123 -0
  36. package/package.json +90 -0
  37. package/src/base.ts +95 -0
  38. package/src/helpers/logger.ts +11 -0
  39. package/src/index.ts +58 -0
  40. package/src/lib/auth/index.ts +225 -0
  41. package/src/lib/index.ts +3 -0
  42. package/src/lib/system/index.ts +104 -0
  43. package/src/lib/transactions/index.ts +259 -0
  44. package/src/lib/utils/index.ts +80 -0
  45. package/src/lib/utils/utils.ts +224 -0
  46. package/src/lib/wallet/index.ts +515 -0
  47. package/src/localStorageMock.js +23 -0
  48. package/src/routes/auth.ts +34 -0
  49. package/src/routes/index.ts +3 -0
  50. package/src/routes/system.ts +24 -0
  51. package/src/routes/transactions.ts +29 -0
  52. package/src/routes/wallet.ts +65 -0
  53. package/src/tests/__mocks__/axios.js +4 -0
  54. package/src/tests/__mocks__/localStorageMock.js +23 -0
  55. package/src/tests/auth.spec.ts +117 -0
  56. package/src/tests/data/auth.ts +49 -0
  57. package/src/tests/data/config.ts +8 -0
  58. package/src/tests/data/index.ts +4 -0
  59. package/src/tests/data/system.ts +54 -0
  60. package/src/tests/data/user.ts +25 -0
  61. package/src/tests/system.spec.ts +47 -0
  62. package/src/tests/utils.spec.ts +70 -0
  63. package/src/tests/wallet.spec.ts +44 -0
  64. package/src/types/auth.ts +57 -0
  65. package/src/types/common.ts +230 -0
  66. package/src/types/index.ts +5 -0
  67. package/src/types/merchants.ts +47 -0
  68. package/src/types/transactions.ts +139 -0
  69. package/src/types/wallet.ts +141 -0
package/src/base.ts ADDED
@@ -0,0 +1,95 @@
1
+ import axios, { AxiosError } from 'axios';
2
+ import { WallabyConfig, RequestMothod, RequestOptions, RequestRoute } from './types';
3
+ import { getAccessToken } from './lib/utils/utils';
4
+ import logger from './helpers/logger';
5
+
6
+ export abstract class Base {
7
+ private apiKey: string;
8
+ private baseUrl: string;
9
+ public userId: string;
10
+ public jwt?: string;
11
+
12
+ constructor(config: WallabyConfig) {
13
+ this.apiKey = config.apiKey;
14
+ this.baseUrl = config.baseUrl;
15
+ this.userId = config.userId;
16
+ this.jwt = config.jwt;
17
+ }
18
+
19
+ protected async request<T>(route: RequestRoute, options?: RequestOptions): Promise<T | any> {
20
+ try {
21
+ let url;
22
+ if (typeof route.fullPath !== 'string') {
23
+ url = route.fullPath(options?.payload);
24
+ } else {
25
+ url = route.fullPath;
26
+ }
27
+ const headers = this.getRequestHeaders(route.accessTokenRequired);
28
+
29
+ const http = axios.create({
30
+ url: url,
31
+ baseURL: this.baseUrl,
32
+ headers: headers,
33
+ });
34
+
35
+ http.interceptors.response.use(
36
+ (response) => response,
37
+ (error) => {
38
+ if (error?.response?.data) {
39
+ logger('SDK::Base::Interceptor::error.response.data', error.response.data);
40
+ return Promise.reject(error.response.data);
41
+ }
42
+ logger('SDK::Base::Interceptor::error', error);
43
+ return Promise.reject(error);
44
+ },
45
+ );
46
+
47
+ switch (route.method) {
48
+ case RequestMothod.Get:
49
+ try {
50
+ const result = await http.get(url);
51
+ logger('SDK::Base::RequestMothod.Get::result', result);
52
+ return result.data;
53
+ } catch (error: AxiosError | any) {
54
+ logger('SDK::Base::RequestMothod.Get::error', error);
55
+ throw new Error(error?.message);
56
+ }
57
+ case RequestMothod.Post:
58
+ try {
59
+ const result = await http.post(url, JSON.stringify(options?.payload));
60
+ logger('SDK::Base::RequestMothod.Post::result', result);
61
+ return result.data;
62
+ } catch (error: AxiosError | any) {
63
+ logger('SDK::Base::RequestMothod.Post::error', error);
64
+ throw new Error(error?.message);
65
+ }
66
+ case RequestMothod.Put:
67
+ try {
68
+ const result = await http.put(url, JSON.stringify(options?.payload) ?? null);
69
+
70
+ return result.data;
71
+ } catch (error: AxiosError | any) {
72
+ throw new Error(error?.message);
73
+ }
74
+ }
75
+ } catch (error) {
76
+ logger('SDK::Base::request::error', error);
77
+ return Promise.reject(error);
78
+ }
79
+ }
80
+
81
+ protected getRequestHeaders(accessTokenRequired: boolean) {
82
+ let headers: any = {
83
+ 'Content-Type': 'application/json',
84
+ 'x-api-key': this.apiKey,
85
+ 'x-client-jwt': this.jwt,
86
+ };
87
+ if (accessTokenRequired && this.userId) {
88
+ headers = {
89
+ ...headers,
90
+ Authorization: 'Bearer ' + getAccessToken(this.userId),
91
+ };
92
+ }
93
+ return headers;
94
+ }
95
+ }
@@ -0,0 +1,11 @@
1
+ import debug from 'debug';
2
+
3
+ const logger = (message: string, data?: any) => {
4
+ if (process.env.NODE_ENV === 'production') {
5
+ return;
6
+ }
7
+ const log = debug('NCW-SDK-JS');
8
+ return log(message, data);
9
+ };
10
+
11
+ export default logger;
package/src/index.ts ADDED
@@ -0,0 +1,58 @@
1
+ import { WallabyConfig } from './types';
2
+ import { Auth, Wallet, Utils } from './lib';
3
+ import { System } from './lib/system';
4
+ import { Transactions } from './lib/transactions';
5
+
6
+ /**
7
+ * The Wallaby SDK client. This class is the main entry point into Wallaby's
8
+ * APIs and separates functionality into different domains.
9
+ *
10
+ * @public
11
+ */
12
+ export default class Wallaby {
13
+ /**
14
+ * The `auth` domain contains functions to authenticate user in Wallany's system.
15
+ * @public
16
+ */
17
+ public readonly auth: Auth;
18
+
19
+ /**
20
+ * Thi `system` domain contains functions that get system specific data like available blockchains, or available token.
21
+ * @public
22
+ */
23
+ public readonly system: System;
24
+
25
+ /**
26
+ * The `Utils` domain contains helper functions for interacting with local storage.
27
+ * @public
28
+ */
29
+ public readonly utils: Utils;
30
+
31
+ /**
32
+ * The `wallet` domain contains all wallet calls to Wallaby's APIs.
33
+ * @public
34
+ */
35
+ public readonly wallet: Wallet;
36
+
37
+ /**
38
+ * The `transactions` domain contains all transactions calls to Wallaby's APIs.
39
+ */
40
+ public readonly transactinos: Transactions;
41
+
42
+ /**
43
+ * @param {string} [config.apiKey] - The API key to use for Wallaby
44
+ * @param {string} [config.baseUrl] - The baseUrl for the API endpoints
45
+ * @param {string} [config.userId] - The client user ID
46
+ * @param {string} [config.jwt] - A web token generated by the client for authorization
47
+ * @public
48
+ */
49
+ constructor(config: WallabyConfig) {
50
+ this.wallet = new Wallet(config);
51
+ this.utils = new Utils(config);
52
+ this.auth = new Auth(config);
53
+ this.system = new System(config);
54
+ this.transactinos = new Transactions(config);
55
+ }
56
+ }
57
+
58
+ export * from './types';
@@ -0,0 +1,225 @@
1
+ import { Base } from '../../base';
2
+ import * as Utils from '../utils/utils';
3
+ import { AuthRoutes } from '../../routes';
4
+ import {
5
+ SignatureMessageRequest,
6
+ SignatureMessageResponse,
7
+ SignInRequest,
8
+ SignInResponse,
9
+ SignUpRequest,
10
+ SignUpResponse,
11
+ WallabyError,
12
+ WallabyConfig,
13
+ ClientAuthPubKeyRequest,
14
+ RefreshAccessTokenResponse,
15
+ ClientAuthPubKeyResponse,
16
+ } from '../../types';
17
+ import { createIdentity, hash, publicKeyByPrivateKey, sign } from 'eth-crypto';
18
+ import logger from '../../helpers/logger';
19
+
20
+ export class Auth extends Base {
21
+ constructor(config: WallabyConfig) {
22
+ super(config);
23
+ }
24
+
25
+ /**
26
+ *
27
+ * @public
28
+ * @description The returned message will be used to authorize the user to sign operations
29
+ * @param {string} hashKey
30
+ * @param {string} userId
31
+ * @returns {SignatureMessageResponse} The returned message will be used for sign up and sign in signature
32
+ */
33
+ async signatureMessage({ hashKey, userId }: SignatureMessageRequest): Promise<SignatureMessageResponse | undefined> {
34
+ try {
35
+ if (!hashKey) {
36
+ return undefined;
37
+ }
38
+
39
+ let clientAuthPubKey = undefined;
40
+ let decryptedClientAuthPrivKey = undefined;
41
+
42
+ // If local storage doesn't already have data for the user, we create new key pair and save it
43
+ decryptedClientAuthPrivKey = Utils.getDecryptedPrivateKey(userId, hashKey);
44
+ if (!decryptedClientAuthPrivKey) {
45
+ logger('if statement')
46
+ const { publicKey, privateKey } = createIdentity();
47
+ clientAuthPubKey = publicKey;
48
+ decryptedClientAuthPrivKey = privateKey;
49
+ } else {
50
+ clientAuthPubKey = publicKeyByPrivateKey(decryptedClientAuthPrivKey);
51
+ }
52
+
53
+ const response: Pick<SignatureMessageResponse, 'message' | 'error'> = await this.request(AuthRoutes.signatureMessage, {
54
+ method: AuthRoutes.signatureMessage.method,
55
+ payload: { clientAuthPubKey },
56
+ });
57
+
58
+ if (response.error) {
59
+ throw new Error(response.error);
60
+ }
61
+
62
+ const { message } = response;
63
+ const hashedMessage = hash.keccak256(message);
64
+ const signature = sign(decryptedClientAuthPrivKey, hashedMessage);
65
+
66
+ return { message, hashedMessage, signature, decryptedClientAuthPrivKey, clientAuthPubKey };
67
+ } catch (error) {
68
+ logger('SDK::Auth::signatureMessage::error', error);
69
+ return Promise.reject(error);
70
+ }
71
+ }
72
+
73
+ /**
74
+ *
75
+ * @public
76
+ * @description Users will be able to sign in by providing a signature and message. Use the same key pair used on sign up'
77
+ * @param {string} hashKey
78
+ * @param {string} firstName
79
+ * @param {string} lastName
80
+ * @param {string} email
81
+ * @returns {SignUpResponse}
82
+ */
83
+ async signUp({ hashKey, firstName, lastName, email }: SignUpRequest): Promise<SignUpResponse | undefined> {
84
+ try {
85
+ const signatureMessage = await this.signatureMessage({ hashKey, userId: this.userId });
86
+
87
+ if (!signatureMessage || signatureMessage.error) {
88
+ throw new Error(signatureMessage?.error);
89
+ }
90
+
91
+ const { message, signature, decryptedClientAuthPrivKey, clientAuthPubKey } = signatureMessage;
92
+
93
+ const response: SignUpResponse = await this.request(AuthRoutes.signUp, {
94
+ method: AuthRoutes.signUp.method,
95
+ payload: { clientAuthPubKey, signature, message, firstName, lastName, email, externalUserId: this.userId },
96
+ });
97
+ if (!response || response.error) {
98
+ throw new Error();
99
+ }
100
+
101
+ const { accessToken, user } = response;
102
+ Utils.setAccessToken(this.userId, accessToken);
103
+ Utils.setWallabyAuthPubKey(this.userId, user.wallabyAuthPubKey);
104
+ Utils.setEncryptedPrivateKey(this.userId, decryptedClientAuthPrivKey, hashKey);
105
+
106
+ return response;
107
+ } catch (error) {
108
+ logger('SDK::Auth::singUp::error', error);
109
+ return Promise.reject(error);
110
+ }
111
+ }
112
+
113
+ /**
114
+ *
115
+ * @public
116
+ * @description Users will be able to sign in by providing a signature and message. Use the same key pair used on sign up'
117
+ * @param {string} hashKey
118
+ * @returns {SignInResponse}
119
+ */
120
+ async signIn({ hashKey }: SignInRequest): Promise<SignInResponse | undefined> {
121
+ try {
122
+ const signatureMessage = await this.signatureMessage({ hashKey, userId: this.userId });
123
+ if (!signatureMessage || signatureMessage.error) {
124
+ throw new Error(signatureMessage?.error);
125
+ }
126
+
127
+ const { message, signature, clientAuthPubKey } = signatureMessage;
128
+
129
+ const response: SignInResponse = await this.request(AuthRoutes.signIn, {
130
+ method: AuthRoutes.signUp.method,
131
+ payload: { clientAuthPubKey, signature, message },
132
+ });
133
+
134
+ if (response && response.error) {
135
+ throw new Error(response.error);
136
+ }
137
+
138
+ const { accessToken, user } = response;
139
+ const wallabyAuthPubKey = Utils.getWallabyAuthPubKey(this.userId);
140
+
141
+ if (!wallabyAuthPubKey) {
142
+ Utils.setWallabyAuthPubKey(this.userId, user.wallabyAuthPubKey);
143
+ }
144
+ Utils.setAccessToken(this.userId, accessToken);
145
+
146
+ return response;
147
+ } catch (error) {
148
+ logger('SDK::Auth::signIn::error', error);
149
+ return Promise.reject(error);
150
+ }
151
+ }
152
+
153
+ /**
154
+ *
155
+ * @public
156
+ * @description Users will be able to sign up by providing a signature and message. Use the same pair keys used on sign up
157
+ * @param {null}
158
+ * @returns {string} Access token
159
+ */
160
+ async refreshAccessToken({}): Promise<RefreshAccessTokenResponse | undefined> {
161
+ try {
162
+ const response: RefreshAccessTokenResponse = await this.request(AuthRoutes.refreshAcessToken);
163
+ if (response.error) {
164
+ throw new Error(response.error);
165
+ }
166
+
167
+ const { accessToken } = response;
168
+ Utils.setAccessToken(this.userId, accessToken);
169
+
170
+ return response;
171
+ } catch (error) {
172
+ logger('SDK::Auth::RefreshAccessToken::error', error);
173
+ return Promise.reject(error);
174
+ }
175
+ }
176
+
177
+ /**
178
+ * @description Change user authentication public key
179
+ * @param {string} hashKey
180
+ * @param {string} userId
181
+ * @returns {User} User object
182
+ */
183
+ async updateClientAuthPubKey({
184
+ hashKey,
185
+ userId,
186
+ }: Pick<ClientAuthPubKeyRequest, 'hashKey' | 'userId'>): Promise<ClientAuthPubKeyResponse | undefined> {
187
+ try {
188
+ const signatureMessage = await this.signatureMessage({ hashKey, userId: this.userId });
189
+ if (!signatureMessage || signatureMessage.error) {
190
+ throw new Error(signatureMessage?.error);
191
+ }
192
+
193
+ const { message, signature, clientAuthPubKey } = signatureMessage;
194
+
195
+ const { publicKey, privateKey } = createIdentity();
196
+
197
+ const response: ClientAuthPubKeyResponse = await this.request(AuthRoutes.clientAuthPubKey, {
198
+ method: AuthRoutes.clientAuthPubKey.method,
199
+ payload: {
200
+ message,
201
+ clientAuthPubKey,
202
+ signature,
203
+ newClientAuthPubKey: publicKey,
204
+ },
205
+ });
206
+ if (response.error) {
207
+ throw new Error(response.error);
208
+ }
209
+ // Updating private key from the newly generate key pair.
210
+ Utils.setEncryptedPrivateKey(userId, privateKey, hashKey);
211
+ return response;
212
+ } catch (error) {
213
+ logger('SDK::Auth::clientAuthPubKey::error', error);
214
+ return Promise.reject(error);
215
+ }
216
+ }
217
+
218
+ /**
219
+ * @description
220
+ * @param {string} clientAuthPubKey
221
+ * @returns {WallabyAuthPubKeyResponse} Returns user's Wallaby WallabyAuthPubKey
222
+ */
223
+ async getWallabyAuthPublicKey() {}
224
+ }
225
+ 1;
@@ -0,0 +1,3 @@
1
+ export * from './wallet';
2
+ export * from './auth';
3
+ export * from './utils';
@@ -0,0 +1,104 @@
1
+ import { Base } from '../../base';
2
+ import { WallabyConfig, Blockchain, AssetConfig, User } from '../../types';
3
+ import { SystemRoutes } from '../../routes';
4
+ import logger from '../../helpers/logger';
5
+
6
+ export class System extends Base {
7
+ constructor(config: WallabyConfig) {
8
+ super(config);
9
+ }
10
+
11
+ /**
12
+ * @public
13
+ * @description Get all supported chains
14
+ * @param {null}
15
+ * @returns {Array<Blockchain>} Array of supported chains
16
+ */
17
+ async getSupportedBlockchains(): Promise<Array<Blockchain> | undefined> {
18
+ try {
19
+ logger('SDK::System::getSupportedBlockchains:: before response');
20
+ const response = await this.request(SystemRoutes.getSupportedBlockchains, {
21
+ method: SystemRoutes.getSupportedBlockchains.method,
22
+ payload: {},
23
+ });
24
+
25
+ logger('SDK::System::getSupportedBlockchains::response', response);
26
+ if (!response || response.error) {
27
+ logger('SDK::System::getSupportedBlockchains::no response');
28
+ // logger('SDK::System::getSupportedBlockchains::response.error', response.error);
29
+ throw new Error('There is no response');
30
+ }
31
+ return response.chains;
32
+ } catch (error: any) {
33
+ logger('SDK::System::getSupportedBlockchains::error', error);
34
+ return Promise.reject(error);
35
+ }
36
+ }
37
+
38
+ /**
39
+ * @public
40
+ * @description Get all supported assets configuration
41
+ * @param {null}
42
+ * @returns {Array<AssetConfig>} Array of supported tokens
43
+ */
44
+ async getSupportedTokens(): Promise<AssetConfig[] | undefined> {
45
+ try {
46
+ const response = await this.request(SystemRoutes.getSupportedTokens, {
47
+ method: SystemRoutes.getSupportedTokens.method,
48
+ payload: {},
49
+ });
50
+
51
+ if (!response || response.error) {
52
+ throw new Error();
53
+ }
54
+ return response.assets;
55
+ } catch (error) {
56
+ logger('SDK::System::getSupportedTokens::error', error);
57
+ return Promise.reject(error);
58
+ }
59
+ }
60
+
61
+ /**
62
+ * @public
63
+ * @param {string} userId
64
+ * @returns {User} Returns user public data
65
+ */
66
+ async getUserData(userId: string): Promise<User | undefined> {
67
+ try {
68
+ const response = await this.request(SystemRoutes.getUserData, {
69
+ method: SystemRoutes.getUserData.method,
70
+ payload: { userId },
71
+ });
72
+ if (!response || response.error) {
73
+ throw new Error();
74
+ }
75
+ return response.user;
76
+ } catch (error) {
77
+ logger('SDK::System::getUserData::error', error);
78
+ return Promise.reject(error);
79
+ }
80
+ }
81
+
82
+ /**
83
+ * @public
84
+ * @description This returns essential data by the external user ID provided at sign up.
85
+ * @param {string} externalUserId
86
+ * @returns {User} Returns user public data
87
+ */
88
+ async getUserByExternalUserId(externalUserId: string): Promise<User | undefined> {
89
+ try {
90
+ const response = await this.request(SystemRoutes.getUserByExternalUserId, {
91
+ method: SystemRoutes.getUserByExternalUserId.method,
92
+ payload: { externalUserId },
93
+ });
94
+
95
+ if (!response || response.error) {
96
+ throw new Error();
97
+ }
98
+ return response.user;
99
+ } catch (error) {
100
+ logger('SDK::System::getUserByExternalUserId::error', error);
101
+ return Promise.reject(error);
102
+ }
103
+ }
104
+ }