-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinaData.mjs
611 lines (507 loc) · 23.2 KB
/
MinaData.mjs
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/*
2023 MinaData
Disclaimer:
The use of this code is at your own risk. The entire code is licensed under the Apache License 2.0, which means you are granted certain rights to use, modify, and distribute the code under the terms of the license. However, please be aware that this module was created for learning purposes and testing smart contracts.
This module is intended to provide a platform for educational and testing purposes only. It may not be suitable for use in production environments or for handling real-world financial transactions. The authors or contributors shall not be liable for any damages or consequences arising from the use of this module in production or critical applications.
Before using this module in any capacity, including educational or testing purposes, it is strongly recommended to review and understand its functionality thoroughly. Furthermore, it is advised to refrain from using this module for any sensitive or production-related tasks.
By using this code, you agree to the terms of the Apache License 2.0 and acknowledge that the authors or contributors shall not be held responsible for any issues or damages that may arise from its use, including educational or testing purposes.
Please read the full Apache License 2.0 for more details on your rights and responsibilities regarding the usage of this code.
*/
import { presets as pre } from './data/presets.mjs'
import { keyPathToValue, printMessages } from './helpers/mixed.mjs'
// import fetch from 'node-fetch'
import { config } from './data/config.mjs'
/*
async function getFetch() {
const globalFetch = globalThis.fetch;
const isNodeEnv = typeof global !== 'undefined';
// do nothing if `fetch` exists
if (globalFetch) {
return globalFetch;
} else if (isNodeEnv) {
// get node polyfill
return import('node-fetch').then((d) => d.default);
} else {
// get browser polyfill
return import('whatwg-fetch').then((d) => d.fetch);
}
}
*/
export class MinaData /*extends EventTarget*/ {
#config
#state
#presets
#provider
constructor( { networkName, graphQl } ) {
// super()
this.#config = config
this.#init( { networkName, graphQl } )
return true
}
#init( { networkName, graphQl } ) {
const [ messages, comments ] = this.#validateInit( { networkName, graphQl } )
printMessages( { messages, comments } )
this.#provider = JSON.parse( JSON.stringify( this.#config['network'][ networkName ] ) )
if( graphQl !== undefined ) {
this.#provider['graphQl'] = graphQl
}
this.#state = {
'environment': true,
'nonce': 0,
'subgroups': {},
networkName
}
this.#setPresets( { 'presets': pre } )
return this
}
getPresets() {
return Object.keys( this.#presets )
}
getPreset( { key } ) {
const [ messages, comments ] = this.#validateGetPreset( { key } )
printMessages( { messages, comments } )
return this.#presets[ key ]
}
async getData( { preset, userVars, subgroup='default' } ) {
subgroup = `${subgroup}`
const startTime = performance.now()
const [ messages, comments ] = this.validateGetData( { preset, userVars } )
printMessages( { messages, comments } )
const eventId = this.#state['nonce']
this.#state['nonce']++
if( !Object.hasOwn( this.#state['subgroups'], subgroup ) ) {
this.#state['subgroups'][ subgroup ] = { startTime, 'ids': {} }
}
this.#state['subgroups'][ subgroup ]['ids'][ eventId ] = -1
const result = {
'data': null,
'status': {
'code': null,
'text': null
}
}
try {
let payload = this.#preparePayload( { preset, userVars } )
// const fetch = await getFetch()
const response = await fetch(
payload['fetch']['url'],
{
'method': payload['fetch']['method'],
'headers': payload['fetch']['headers'],
'body': payload['fetch']['data']
}
)
const tmp = await response.json()
const [ m, c ] = this.#validateGetDataResponse( { 'data': tmp['data'], preset } )
result['data'] = tmp['data']
this.#state['subgroups'][ subgroup ]['ids'][ eventId ] = 1
if( m.length === 0 ) {
result['status']['code'] = 200
result['status']['text'] = `Success (${Math.floor(performance.now() - startTime)} ms)!`
} else {
result['status']['code'] = 404
result['status']['text'] = `Data not found (${Math.floor(performance.now() - startTime)} ms)!`
}
} catch( e ) {
console.log( `Following error occured: ${e}` )
result['status']['code'] = 400
result['status']['text'] = `Error (${Math.floor( performance.now() - startTime)} ms): ${e}`
}
return result
}
#validateGetDataResponse( { preset, data } ) {
const messages = []
const comments = []
const pre = this.getPreset( { 'key': preset } )
const search = pre['output']['key']
if( !Object.hasOwn( data, search ) ) {
messages.push( `Response does not include "${search}" as a key.` )
return messages
}
const type = pre['output']['type']
switch( type ) {
case 'hash':
if(
typeof data[ search ] === 'object' &&
!Array.isArray( data[ search ] )
) {
} else {
messages.push( `Response does not include expected type of "${type}"` )
}
break
case 'array':
if( Array.isArray( data[ search ] ) ) {
} else {
messages.push( `Response does not include expected type of "${type}"` )
}
break
default:
break
}
return [ messages, comments ]
}
validateGetData( { preset, userVars } ) {
let messages = []
let comments = []
let data = null
const [ m, c ] = this.#validateGetPreset( { 'key': preset } )
messages.push( ...m )
comments.push( ...c )
if( messages.length === 0 ) {
const ps = this.getPreset( { 'key': preset } )
/*
const validNetworks = Object
.keys( ps['input']['variables'][ Object.keys( ps['input']['variables'] )[ 0 ] ]['default'] )
if( !validNetworks.includes( network ) ) {
messages.push( `Network "${network}" is not known.` )
}
*/
const type = ps['input']['query']['schema']
if( !Object.hasOwn( this.#provider['graphQl'], type ) ) {
messages.push( `Preset '${preset}' GraphQl type of '${type}' not known.` )
} else if( this.#provider['graphQl'][ type ].length === 0 ){
messages.push( `Preset is for network '${this.#state['networkName']}' not available.` )
}
if( userVars === null || typeof userVars !== 'object' || Array.isArray( userVars ) ) {
messages.push( `Key 'userVars' is not type object.` )
} else {
/*
const requiredVariables = Object
.entries( ps['input']['variables'] )
.map( a => [ a[ 0 ], a[ 1 ]['required'] ] )
.filter( a => a[ 1 ] )
if( Object.keys( userVars ).length === 0 ) {
console.log( 'here', requiredVariables )
if( !requiredVariables.some( a => a[ 1 ] ) ) {
messages.push( `Required keys ${requiredVariables.map( a => a[ 0 ] ).join( ',' )} are missing.` )
}
}
*/
}
}
if( messages.length === 0 ) {
const struct = Object
.entries( this.#presets[ preset ]['input']['variables'] )
.reduce( ( acc, a, index ) => {
const [ key, value ] = a
if( value['required'] ) {
acc['required'].push( key )
} else {
acc['default'].push( key )
}
acc['all'].push( key)
return acc
}, { 'required': [], 'default': [], 'all': [] } )
Object
.keys( userVars )
.map( key => {
const test = struct['all'].includes( key )
!test ?comments.push( `The key '${key}' is not known as valid input and will ignored.` ) : ''
} )
struct['default']
.forEach( key => {
if( !Object.hasOwn( userVars, key ) ) {
const d = this.#presets[ preset ]['input']['variables'][ key ]['default'][ this.#state['networkName'] ]
comments.push( `The key '${key}' is not set, will use default parameter '${d}' instead.` )
} else {
const test = this.#presets[ preset ]['input']['variables'][ key ]['validation']['regex']
.test( userVars[ key ] )
if( !test ) {
const msg = this.#presets[ preset ]['input']['variables'][ key ]['validation']['description']
messages.push( `The key '${key}' with the value '${userVars[ key ]} is not valid. ${msg}`)
}
}
} )
struct['required']
.forEach( key => {
if( !Object.hasOwn( userVars, key ) ) {
messages.push( `The key '${key}' is missing.` )
} else {
const test = this.#presets[ preset ]['input']['variables'][ key ]['validation']['regex']
.test( userVars[ key ] )
if( !test ) {
const msg = this.#presets[ preset ]['input']['variables'][ key ]['validation']['description']
messages.push( `The key '${key}' with the value '${userVars[ key ]}' is not valid. ${msg}`)
}
}
} )
}
return [ messages, comments, data ]
}
#setPresets( { presets } ) {
const [ messages, comments ] = this.#validatePresets( { presets } )
printMessages( { messages, comments } )
this.#presets = Object
.entries( presets['presets'] )
.reduce( ( acc, a, index ) => {
const [ key, value ] = a
acc[ key ] = value
acc[ key ]['input']['variables'] = Object
.entries( acc[ key ]['input']['variables'] )
.reduce( ( abb, b, rindex ) => {
const [ _key, _value ] = b
abb[ _key ] = _value
abb[ _key ]['validation'] = keyPathToValue( {
'data': presets,
'keyPath': abb[ _key ]['validation']
} )
return abb
}, {} )
return acc
}, {} )
return true
}
#preparePayload( { preset, userVars } ) {
const ps = this.getPreset( { 'key': preset } )
const type = ps['input']['query']['schema']
const network = this.#state['networkName']
const url = this.#provider['graphQl'][ type ][ 0 ]
const data = {}
data['query'] = this.#presets[ preset ]['input']['query']['cmd']
data['variables'] = Object
.entries( ps['input']['variables'] )
.reduce( ( acc, a, index ) => {
const [ key, value ] = a
const variable = this.#presets[ preset ]['input']['variables'][ key ]
if( Object.hasOwn( userVars, key ) ) {
switch( variable['validation']['post'] ) {
case 'string':
acc[ key ] = `${userVars[ key ]}`
break
case 'integer':
acc[ key ] = parseInt( userVars[ key ] )
break
default:
console.log( 'Something went wrong.' )
}
} else {
acc[ key ] = variable['default'][ network ]
}
return acc
}, {} )
const struct = {
'fetch': {
'method': 'post',
'maxBodyLength': Infinity,
'url': url,
'headers': {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
'data': JSON.stringify( data )
}
}
return struct
}
#validateInit( { networkName, graphQl } ) {
const messages = []
const comments = []
const networks = Object
.keys( this.#config['network'] )
if( networkName === undefined ) {
messages.push( `Key 'networkName' is type of 'undefined'.` )
} else if( typeof networkName !== 'string' ) {
messages.push( `Key 'networkName' is not type of 'string'.` )
} else if( !networks.includes( networkName ) ) {
messages.push( `Key 'networkName' with the value '${networkName}' in not valid. Choose from ${networks.map( a => `'${a}'`).join(', ') } instead.` )
}
if( graphQl === undefined ) {
// messages.push( `Key 'graphQl' is type of 'undefined'.` )
} else if( graphQl.constructor !== Object ) {
messages.push( `Key 'graphQl' with the value '${graphQl}' is not type of 'object'.` )
} else if( !Object.keys( graphQl ).includes( 'proxy') || !Object.keys( graphQl ).includes( 'standard') ) {
messages.push( `Key 'graphQl' with the keys ${Object.keys( graphQl).map( a => `'${a}'`).join( ', ' )} missing 'standard' and/or 'proxy'.` )
} else if( !Array.isArray( graphQl['proxy'] ) || !Array.isArray( graphQl['standard'] ) ) {
messages.push( `Key 'graphQl' with the keys 'standard' and 'proxy' are not type of array.` )
} else if( graphQl['proxy'].length === 0 || !graphQl['standard'].length === 0 ) {
messages.push( `Key 'graphQl' with the keys 'standard' and 'proxy' is empty.` )
} else if(
!graphQl['proxy'].map( a => typeof a === 'string' ).every( a => a )
|| !graphQl['standard'].map( a => typeof a === 'string' ).every( a => a )
) {
messages.push( `Key 'graphQl' with the keys 'standard' and 'proxy' are not type of 'array of strings'.` )
} else if(
!graphQl['proxy'].map( a => a.startsWith( 'https://' ) ).every( a => a )
|| !graphQl['standard'].map( a => a.startsWith( 'https://' ) ).every( a => a )
) {
messages.push( `Key 'graphQl' with the keys 'standard' and 'proxy' are not type of 'array of url strings'.` )
}
return [ messages, comments ]
}
#validateGetPreset( { key } ) {
const messages = []
const comments = []
const keys = this.getPresets()
if( !keys.includes( key ) ) {
messages.push( `Key "key/preset" with value "${key}" not a valid preset key. Use ${keys.join( ', ' )} instead.` )
}
return [ messages, comments ]
}
#validatePreset( { presetValue, presetKey } ) {
const isObject = ( a ) => a && typeof a === 'object' && !Array.isArray( a )
const isRegex = ( a ) => a instanceof RegExp
const validateStructure = ( obj, key, type ) => {
if( !obj.hasOwnProperty( key ) ) { return false }
if( typeof obj[ key ] !== type ) { return false }
return true
}
const messages = []
const comments = []
if( !isObject( presetValue ) ) {
messages.push( `["${presetKey}"] should be type of object.` )
} else if( !validateStructure( presetKey, 'description', 'string' ) ) {
const tests = [
[
!validateStructure( presetValue, 'description', 'string' ),
`["${presetKey}"]["description"] should be type of string.`
],
[
!validateStructure( presetValue, 'input', 'object' ),
`["${presetKey}"]["input"] should be type of object.`
],
[
!validateStructure( presetValue, 'output', 'object' ),
`["${presetKey}"]["expect"] should be type of object.`
]
]
.forEach( ( [ test, msg ] ) => test ? messages.push( msg ) : '' )
}
if( messages.length === 0 ) {
const tests = [
[
!validateStructure( presetValue['input'], 'query', 'object' ),
`["${presetKey}"]["input"]["query"] should be type of object.`
],
[
!validateStructure( presetValue['input'], 'variables', 'object' ),
`["${presetKey}"]["input"]["variables"] should be type of object.`
]
]
.forEach( ( [ test, msg ] ) => test ? messages.push( msg ) : '' )
}
if( messages.length === 0 ) {
const n = [ 'cmd', 'schema' ]
.forEach( key => {
if( typeof presetValue['input']['query'][ key ] !== 'string' ) {
messages.push( `["${presetKey}"]["input"]["query"]["${key}"] is not type of string.` )
}
if( key === 'schema' ) {
const k = Object
.keys( this.#provider['graphQl'] )
if( !k.includes( presetValue['input']['query'][ key ] ) ) {
messages.push( `["${presetKey}"]["input"]["query"]["${key}"] value is not accepted. Use ${k.join( ', ' )} instead.`)
}
}
} )
}
if( messages.length === 0 ) {
Object
.entries( presetValue['input']['variables'] )
.forEach( a => {
const [ key, variable ] = a
if( !isObject( variable ) ) {
messages.push( `["${presetKey}"]["input"]["variables"]["${key}"] should be type of object.` )
} else {
const test = [
/*
[
!validateStructure( variable, 'default', 'string' ),
`["${presetKey}"]["input"]["variables"]["${key}"]["default"] should be type of string.`
],
*/
[
!validateStructure( variable, 'description', 'string' ),
`["${presetKey}"]["input"]["variables"]["${key}"]["description"] should be type of string.`
],
/*
[
!validateStructure( variable, 'validation', 'string' ),
`["${presetKey}"]["input"]["variables"]["${key}"]["validation"] should be type of string. And contains a reference to a regex.`
],
*/
[
!validateStructure( variable, 'required', 'boolean' ),
`["${presetKey}"]["input"]["variables"]["${key}"]["required"] should be type of boolean.`
],
/*
[
!validateStructure(variable, 'type', 'string' ),
`["${presetKey}"]["input"]["variables"]["${key}"]["schema"] should be type of string.`
]
*/
]
.forEach( ( [ test, msg ] ) => test ? messages.push( msg ) : '' )
}
}
)
}
if( messages.length === 0 ) {
const n = [
[
!validateStructure( presetValue['output'], 'key', 'string' ),
`["${presetKey}"]["expect"]["key"] should be type of string.`
],
[
!validateStructure( presetValue['output'], 'type', 'string' ),
`["${presetKey}"]["expect"]["type"] should be type of string.`
]
]
.forEach( ( [ test, msg ] ) => test ? messages.push( msg ) : '' )
}
return [ messages, comments ]
}
#validatePresets( { presets } ) {
const isObject = ( a ) => a && typeof a === 'object' && !Array.isArray( a )
// const isRegex = ( a ) => a instanceof RegExp
const validateStructure = ( obj, key, type ) => {
if( !obj.hasOwnProperty( key ) ) { return false }
if( typeof obj[ key ] !== type ) { return false }
return true
}
let messages = []
let comments = []
if( !isObject( presets ) ) {
messages.push( `Presets should be an object` )
} else if( !validateStructure( presets, 'presets', 'object' ) ) {
messages.push( `Key "presets" is not type object` )
} else if( !validateStructure( presets, 'regexs', 'object' ) ) {
messages.push( `Key "regex" is not type object` )
} else {
[ messages, comments ] = Object
.entries( presets['presets'] )
.reduce( ( acc, a, index ) => {
const [ key, value ] = a
const [ m, c ] = this.#validatePreset( {
'presetValue': value,
'presetKey': key
} )
const tmp = [ m, c ]
.forEach( ( a, rindex ) => {
a.length > 0 ? acc[ rindex ].push( ...a ) : ''
} )
return acc
}, [ messages, comments ] )
}
return [ messages, comments ]
}
/*
#dispatchSubgroupEvent( { subgroup, status, data } ) {
const event = new CustomEvent(
this.#config['event']['subgroup'],
{ 'detail': { subgroup, status, data } }
)
this.dispatchEvent( event )
return true
}
*/
/*
#dispatchSingleDataEvent( { eventId, preset, status, subgroup, data } ) {
const event = new CustomEvent(
this.#config['event']['singleFetch'],
{ 'detail': { eventId, preset, subgroup, status, data } }
)
this.dispatchEvent( event )
return true
}
*/
}