-
Notifications
You must be signed in to change notification settings - Fork 58
/
misc.ts
537 lines (483 loc) · 12.2 KB
/
misc.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import {
ABI_ERC20,
ILitError,
LIT_AUTH_SIG_CHAIN_KEYS,
LIT_CHAINS,
LIT_ERROR,
} from '@lit-protocol/constants';
import {
Chain,
AuthSig,
KV,
NodeClientErrorV0,
NodeClientErrorV1,
NodeErrorV0,
NodeErrorV1,
ClaimRequest,
ClaimKeyResponse,
ClaimResult,
ClaimProcessor,
MintCallback,
RelayClaimProcessor,
} from '@lit-protocol/types';
import { JsonRpcProvider } from '@ethersproject/providers';
import { Contract } from '@ethersproject/contracts';
import { version } from '@lit-protocol/constants';
const logBuffer: Array<Array<any>> = [];
/**
*
* Print error message based on Error interface
*
* @param { Error } e
* @returns { void }
*/
export const printError = (e: Error): void => {
console.log('Error Stack', e.stack);
console.log('Error Name', e.name);
console.log('Error Message', e.message);
};
/**
*
* Find the element that occurs the most in an array
*
* @param { Array<any> } arr
* @returns { any } the element that appeared the most
*/
export const mostCommonString = (arr: Array<any>): any => {
return arr
.sort(
(a: any, b: any) =>
arr.filter((v: any) => v === a).length -
arr.filter((v: any) => v === b).length
)
.pop();
};
export const throwError = (e: NodeClientErrorV0 | NodeClientErrorV1): never => {
if (isNodeClientErrorV1(e)) {
return throwErrorV1(e);
} else if (isNodeClientErrorV0(e)) {
return throwErrorV0(e);
}
return throwGenericError(e as any);
};
/**
*
* Standardized way to throw error in Lit Protocol projects
*
* @deprecated use throwErrorV1
* @param { ILitError }
* @property { string } message
* @property { string } name
* @property { string } errorCode
*/
export const throwErrorV0 = ({
message,
name,
errorCode,
error,
}: ILitError): never => {
const errConstructorFunc = function (
this: any,
message: string,
name: string,
errorCode: string
) {
this.message = message;
this.name = name;
// Map old error codes to new ones if possible.
this.errorCode = oldErrorToNewErrorMap[errorCode] ?? errorCode;
};
throw new (errConstructorFunc as any)(
message,
(name = error?.name ?? name),
(errorCode = error?.code ?? errorCode)
);
};
// Map for old error codes to new ones
const oldErrorToNewErrorMap: { [key: string]: string } = {
not_authorized: 'NodeNotAuthorized',
storage_error: 'NodeStorageError',
};
/**
*
* Standardized way to throw error in Lit Protocol projects
*
*/
export const throwErrorV1 = ({
errorKind,
details,
status,
message,
errorCode,
}: NodeClientErrorV1): never => {
const errConstructorFunc = function (
this: any,
errorKind: string,
status: number,
details: string[],
message?: string,
errorCode?: string
) {
this.message = message;
this.errorCode = errorCode;
this.errorKind = errorKind;
this.status = status;
this.details = details;
};
throw new (errConstructorFunc as any)(
errorKind,
status,
details,
message,
errorCode
);
};
export const throwGenericError = (e: any): never => {
const errConstructorFunc = function (this: any, message: string) {
this.message = message;
this.errorKind = LIT_ERROR.UNKNOWN_ERROR.name;
this.errorCode = LIT_ERROR.UNKNOWN_ERROR.code;
};
throw new (errConstructorFunc as any)(e.message ?? 'Generic Error');
};
export const isNodeClientErrorV1 = (
nodeError: NodeClientErrorV0 | NodeClientErrorV1
): nodeError is NodeClientErrorV1 => {
return (
nodeError.hasOwnProperty('errorCode') &&
nodeError.hasOwnProperty('errorKind')
);
};
export const isNodeClientErrorV0 = (
nodeError: NodeClientErrorV0 | NodeClientErrorV1
): nodeError is NodeClientErrorV0 => {
return nodeError.hasOwnProperty('errorCode');
};
export const isNodeErrorV1 = (
nodeError: NodeErrorV0 | NodeErrorV1
): nodeError is NodeErrorV1 => {
return (
nodeError.hasOwnProperty('errorCode') &&
nodeError.hasOwnProperty('errorKind')
);
};
export const isNodeErrorV0 = (
nodeError: NodeErrorV0 | NodeErrorV1
): nodeError is NodeErrorV0 => {
return nodeError.hasOwnProperty('errorCode');
};
declare global {
var litConfig: any;
var wasmExport: any;
var wasmECDSA: any;
}
export const throwRemovedFunctionError = (functionName: string) => {
throwError({
message: `This function "${functionName}" has been removed. Please use the old SDK.`,
errorKind: LIT_ERROR.REMOVED_FUNCTION_ERROR.kind,
errorCode: LIT_ERROR.REMOVED_FUNCTION_ERROR.name,
});
};
/**
*
* console.log but prepend [Lit-JS-SDK] before the message
*
* @param { any } args
*
* @returns { void }
*/
export const log = (...args: any): void => {
// append the prefix
args.unshift(`[Lit-JS-SDK v${version}]`);
if (!globalThis) {
// there is no globalThis, just print the log
console.log(...args);
return;
}
// check if config is loaded yet
if (!globalThis?.litConfig) {
// config isn't loaded yet, push into buffer
logBuffer.push(args);
return;
}
if (globalThis?.litConfig?.debug !== true) {
return;
}
// config is loaded, and debug is true
// if there are there are logs in buffer, print them first and empty the buffer.
while (logBuffer.length > 0) {
const log = logBuffer.shift() ?? '';
console.log(...log);
}
console.log(...args);
};
/**
*
* Get the type of a variable, could be an object instance type.
* eg Uint8Array instance should return 'Uint8Array` as string
* or simply a `string` or `int` type
*
* @param { any } value
* @returns { string } type
*/
export const getVarType = (value: any): string => {
return Object.prototype.toString.call(value).slice(8, -1);
};
/**
*
* Check if the given value is the given type
* If not, throw `invalidParamType` error
*
* @property { any } value
* @property { Array<String> } allowedTypes
* @property { string } paramName
* @property { string } functionName
* @property { boolean } throwOnError
*
* @returns { Boolean } true/false
*
*/
export const checkType = ({
value,
allowedTypes,
paramName,
functionName,
throwOnError = true,
}: {
value: any;
allowedTypes: Array<string> | any;
paramName: string;
functionName: string;
throwOnError?: boolean;
}): boolean => {
// -- validate
if (!allowedTypes.includes(getVarType(value))) {
const message = `Expecting ${allowedTypes.join(
' or '
)} type for parameter named ${paramName} in Lit-JS-SDK function ${functionName}(), but received "${getVarType(
value
)}" type instead. value: ${
value instanceof Object ? JSON.stringify(value) : value
}`;
if (throwOnError) {
throwError({
message,
errorKind: LIT_ERROR.INVALID_PARAM_TYPE.kind,
errorCode: LIT_ERROR.INVALID_PARAM_TYPE.name,
});
}
return false;
}
// -- else
return true;
};
/**
*
* @param { AuthSig } authSig
* @param { string } chain
* @param { string } functionName
*
* @returns { boolean }
*/
export const checkIfAuthSigRequiresChainParam = (
authSig: AuthSig,
chain: string,
functionName: string
): boolean => {
log('checkIfAuthSigRequiresChainParam');
for (const key of LIT_AUTH_SIG_CHAIN_KEYS) {
if (key in authSig) {
return true;
}
}
// if we're here, then we need the chain param
if (
!checkType({
value: chain,
allowedTypes: ['String'],
paramName: 'chain',
functionName,
})
) {
return false;
}
return true;
};
/**
* TODO: Fix "any"
* Sort object
*
* @param { any } obj
* @returns { any }
*/
export const sortedObject = (obj: any): any => {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(sortedObject);
}
const sortedKeys = Object.keys(obj).sort();
const result: any = {};
// NOTE: Use forEach instead of reduce for performance with large objects eg Wasm code
sortedKeys.forEach((key: any) => {
result[key] = sortedObject(obj[key]);
});
return result;
};
/**
*
* Convert number to hex
* @param { number } v
* @return { string } hex value prexied with 0x
*/
export const numberToHex = (v: number): string => {
return '0x' + v.toString(16);
};
/**
*
* Check if the given value is the given type
* If not, throw `invalidParamType` error
*
* @param { any } value
* @param { string } type
* @param { string } paramName
* @param { string } functionName
* @returns { Boolean } true/false
*/
export const is = (
value: any,
type: string,
paramName: string,
functionName: string,
throwOnError = true
) => {
if (getVarType(value) !== type) {
let message = `Expecting "${type}" type for parameter named ${paramName} in Lit-JS-SDK function ${functionName}(), but received "${getVarType(
value
)}" type instead. value: ${
value instanceof Object ? JSON.stringify(value) : value
}`;
if (throwOnError) {
throwError({
message,
errorKind: LIT_ERROR.INVALID_PARAM_TYPE.kind,
errorCode: LIT_ERROR.INVALID_PARAM_TYPE.name,
});
}
return false;
}
return true;
};
/**
* Convert types before sending to Lit Actions as jsParams, some JS types don't serialize well, so we will convert them before sending to the nodes
*
* @param { object } params.jsParams The jsParams you are sending
* @returns { object } The jsParams object, but with any incompatible types automatically converted
*/
export const convertLitActionsParams = (jsParams: object): object => {
// -- property
const convertedParams: KV = {};
// -- execute
for (const [key, value] of Object.entries(jsParams)) {
const _key: string = key;
const _value: any = value;
// -- get value type
const varType = getVarType(_value);
// -- case: Unit8Array
if (varType === 'Uint8Array') {
convertedParams[_key] = Array.from(_value);
// -- case: Object, recurse over any objects
} else if (varType === 'Object') {
convertedParams[_key] = convertLitActionsParams(_value);
}
// -- default
else {
convertedParams[_key] = _value;
}
}
return convertedParams;
};
export const isNode = () => {
var isNode = false;
// @ts-ignore
if (typeof process === 'object') {
// @ts-ignore
if (typeof process.versions === 'object') {
// @ts-ignore
if (typeof process.versions.node !== 'undefined') {
isNode = true;
}
}
}
return isNode;
};
export const isBrowser = () => {
return isNode() === false;
};
/**
*
* Get the number of decimal places in a token
*
* @property { string } contractAddress The token contract address
* @property { string } chain The chain on which the token is deployed
*
* @returns { number } The number of decimal places in the token
*/
export const decimalPlaces = async ({
contractAddress,
chain,
}: {
contractAddress: string;
chain: Chain;
}): Promise<number> => {
const rpcUrl = LIT_CHAINS[chain].rpcUrls[0] as string;
const web3 = new JsonRpcProvider(rpcUrl);
const contract = new Contract(contractAddress, (ABI_ERC20 as any).abi, web3);
return await contract['decimals']();
};
/**
*
* Generate a random path (for testing)
*
* @returns { string } The random path
*/
export const genRandomPath = (): string => {
return (
'/' +
Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15)
);
};
export const defaultMintClaimCallback: MintCallback<
RelayClaimProcessor
> = async (params: ClaimResult<RelayClaimProcessor>): Promise<string> => {
try {
const relayUrl = params.relayUrl
? params.relayUrl
: 'https://relayer-server-staging-cayenne.getlit.dev/auth/claim';
const response = await fetch(relayUrl, {
method: 'POST',
body: JSON.stringify(params),
headers: {
'api-key': params.relayApiKey
? params.relayApiKey
: '67e55044-10b1-426f-9247-bb680e5fe0c8_relayer',
'Content-Type': 'application/json',
},
});
if (response.status < 200 || response.status >= 400) {
let errResp = await response.json() ?? "";
let errStmt = `An error occured requesting "/auth/claim" endpoint ${JSON.stringify(
errResp
)}`;
console.warn(errStmt);
throw new Error(errStmt);
}
let body: any = await response.json();
return body.requestId;
} catch (e) {
console.error((e as Error).message);
throw e;
}
};