-
Notifications
You must be signed in to change notification settings - Fork 189
/
init.js
646 lines (574 loc) · 17.6 KB
/
init.js
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
const chalk = require('chalk')
const fetch = require('node-fetch')
const immutable = require('immutable')
const os = require('os')
const path = require('path')
const toolbox = require('gluegun/toolbox')
const {
getSubgraphBasename,
validateSubgraphName,
} = require('../command-helpers/subgraph')
const { withSpinner, step } = require('../command-helpers/spinner')
const { fixParameters } = require('../command-helpers/gluegun')
const { abiEvents, generateScaffold, writeScaffold } = require('../scaffold')
const ABI = require('../abi')
const HELP = `
${chalk.bold('graph init')} [options] [subgraph-name] [directory]
${chalk.dim('Options:')}
--allow-simple-name Use a subgraph name without a prefix (default: false)
-h, --help Show usage information
${chalk.dim('Choose mode with one of:')}
--from-contract <address> Creates a scaffold based on an existing contract
--from-example Creates a scaffold based on an example subgraph
${chalk.dim('Options for --from-contract:')}
--abi <path> Path to the contract ABI (default: download from Etherscan)
--network <mainnet|kovan|rinkeby|ropsten|goerli|poa-core>
Selects the network the contract is deployed to
--index-events Index contract events as entities
`
const processInitForm = async (
toolbox,
{ abi, address, allowSimpleName, directory, fromExample, network, subgraphName },
) => {
let networkChoices = ['mainnet', 'kovan', 'rinkeby', 'ropsten', 'goerli', 'poa-core']
let addressPattern = /^(0x)?[0-9a-fA-F]{40}$/
let abiFromEtherscan = undefined
let abiFromFile = undefined
let questions = [
{
type: 'input',
name: 'subgraphName',
message: 'Subgraph name',
initial: subgraphName,
validate: name => {
try {
validateSubgraphName(name, { allowSimpleName })
return true
} catch (e) {
return `${e.message}
Examples:
$ graph init ${os.userInfo().username}/${name}
$ graph init ${name} --allow-simple-name`
}
},
result: value => {
subgraphName = value
return value
},
},
{
type: 'input',
name: 'directory',
message: 'Directory to create the subgraph in',
initial: () => directory || getSubgraphBasename(subgraphName),
validate: value =>
toolbox.filesystem.exists(value || directory || getSubgraphBasename(subgraphName))
? 'Directory already exists'
: true,
},
{
type: 'select',
name: 'network',
message: 'Ethereum network',
choices: networkChoices,
skip: fromExample !== undefined,
initial: network || 'mainnet',
result: value => {
network = value
return value
},
},
{
type: 'input',
name: 'address',
message: 'Contract address',
skip: fromExample !== undefined,
initial: address,
validate: async value => {
if (fromExample !== undefined) {
return true
}
// Validate whether the address is valid
if (!addressPattern.test(value)) {
return `Contract address "${value}" is invalid.
Must be 40 hexadecimal characters, with an optional '0x' prefix.`
}
return true
},
result: async value => {
if (fromExample !== undefined) {
return value
}
// Try loading the ABI from Etherscan, if none was provided
if (!abi) {
try {
if (network === 'poa-core') {
abiFromBlockScout = await loadAbiFromBlockScout(network, value)
} else {
abiFromEtherscan = await loadAbiFromEtherscan(network, value)
}
} catch (e) {}
}
return value
},
},
{
type: 'input',
name: 'abi',
message: 'ABI file (path)',
initial: abi,
skip: () => fromExample !== undefined || abiFromEtherscan !== undefined,
validate: async value => {
if (fromExample || abiFromEtherscan) {
return true
}
try {
abiFromFile = await loadAbiFromFile(value)
return true
} catch (e) {
return e.message
}
},
},
]
try {
let answers = await toolbox.prompt.ask(questions)
return { ...answers, abi: abiFromEtherscan || abiFromFile }
} catch (e) {
return undefined
}
}
const loadAbiFromBlockScout = async (network, address) =>
await withSpinner(
`Fetching ABI from BlockScout`,
`Failed to fetch ABI from BlockScout`,
`Warnings while fetching ABI from BlockScout`,
async spinner => {
let result = await fetch(
`https://blockscout.com/${
network.replace('-', '/')
}/api?module=contract&action=getabi&address=${address}`,
)
let json = await result.json()
// BlockScout returns a JSON object that has a `status`, a `message` and
// a `result` field. The `status` is '0' in case of errors and '1' in
// case of success
if (json.status === '1') {
return new ABI('Contract', undefined, immutable.fromJS(JSON.parse(json.result)))
} else {
throw new Error('ABI not found, try loading it from a local file')
}
},
)
const loadAbiFromEtherscan = async (network, address) =>
await withSpinner(
`Fetching ABI from Etherscan`,
`Failed to fetch ABI from Etherscan`,
`Warnings while fetching ABI from Etherscan`,
async spinner => {
let result = await fetch(
`https://${
network === 'mainnet' ? 'api' : `api-${network}`
}.etherscan.io/api?module=contract&action=getabi&address=${address}`,
)
let json = await result.json()
// Etherscan returns a JSON object that has a `status`, a `message` and
// a `result` field. The `status` is '0' in case of errors and '1' in
// case of success
if (json.status === '1') {
return new ABI('Contract', undefined, immutable.fromJS(JSON.parse(json.result)))
} else {
throw new Error('ABI not found, try loading it from a local file')
}
},
)
const loadAbiFromFile = async filename => {
let exists = await toolbox.filesystem.exists(filename)
if (!exists) {
throw Error('File does not exist.')
} else if (exists === 'dir') {
throw Error('Path points to a directory, not a file.')
} else if (exists === 'other') {
throw Error('Not sure what this path points to.')
} else {
return await ABI.load('Contract', filename)
}
}
module.exports = {
description: 'Creates a new subgraph with basic scaffolding',
options: {
boolean: ['from-example'],
},
run: async toolbox => {
// Obtain tools
let { print, system } = toolbox
// Read CLI parameters
let {
abi,
allowSimpleName,
fromContract,
fromExample,
h,
help,
indexEvents,
network,
} = toolbox.parameters.options
if (fromContract && fromExample) {
print.error(`Only one of --from-example and --from-contract can be used at a time.`)
process.exitCode = 1
return
}
let subgraphName, directory
try {
;[subgraphName, directory] = fixParameters(toolbox.parameters, {
fromExample,
allowSimpleName,
help,
h,
indexEvents,
})
} catch (e) {
print.error(e.message)
process.exitCode = 1
return
}
// Show help text if requested
if (help || h) {
print.info(HELP)
return
}
// Detect git
let git = await system.which('git')
if (git === null) {
print.error(
`Git was not found on your system. Please install 'git' so it is in $PATH.`,
)
process.exitCode = 1
return
}
// Detect Yarn and/or NPM
let yarn = await system.which('yarn')
let npm = await system.which('npm')
if (!yarn && !npm) {
print.error(
`Neither Yarn nor NPM were found on your system. Please install one of them.`,
)
process.exitCode = 1
return
}
let commands = {
install: yarn ? 'yarn' : 'npm install',
codegen: yarn ? 'yarn codegen' : 'npm run codegen',
deploy: yarn ? 'yarn deploy' : 'npm run deploy',
}
// If all parameters are provided from the command-line,
// go straight to creating the subgraph from the example
if (fromExample && subgraphName && directory) {
return await initSubgraphFromExample(
toolbox,
{ allowSimpleName, directory, subgraphName },
{ commands },
)
}
// If all parameters are provided from the command-line,
// go straight to creating the subgraph from an existing contract
if (fromContract && subgraphName && directory && network) {
if (abi) {
try {
abi = await loadAbiFromFile(abi)
} catch (e) {
print.error(`Failed to load ABI: ${e.message}`)
process.exitCode = 1
return
}
} else {
try {
if (network === 'poa-core') {
abi = await loadAbiFromBlockScout(network, fromContract)
} else {
abi = await loadAbiFromEtherscan(network, fromContract)
}
} catch (e) {
process.exitCode = 1
return
}
}
return await initSubgraphFromContract(
toolbox,
{
abi,
allowSimpleName,
directory,
address: fromContract,
indexEvents,
network,
subgraphName,
},
{ commands },
)
}
// Otherwise, take the user through the interactive form
let inputs = await processInitForm(toolbox, {
abi,
allowSimpleName,
directory,
address: fromContract,
fromExample,
network,
subgraphName,
})
// Exit immediately when the form is cancelled
if (inputs === undefined) {
process.exit(1)
return
}
print.info('———')
if (fromExample) {
await initSubgraphFromExample(
toolbox,
{
subgraphName: inputs.subgraphName,
directory: inputs.directory,
},
{ commands },
)
} else {
await initSubgraphFromContract(
toolbox,
{
allowSimpleName,
subgraphName: inputs.subgraphName,
directory: inputs.directory,
abi: inputs.abi,
network: inputs.network,
address: inputs.address,
indexEvents,
},
{ commands },
)
}
},
}
const revalidateSubgraphName = async (toolbox, subgraphName, { allowSimpleName }) => {
// Fail if the subgraph name is invalid
try {
validateSubgraphName(subgraphName, { allowSimpleName })
return true
} catch (e) {
toolbox.print.error(`${e.message}
Examples:
$ graph init ${os.userInfo().username}/${subgraphName}
$ graph init ${subgraphName} --allow-simple-name`)
return false
}
}
const initRepository = async (toolbox, directory) =>
await withSpinner(
`Initialize subgraph repository`,
`Failed to initialize subgraph repository`,
`Warnings while initializing subgraph repository`,
async spinner => {
// Remove .git dir in --from-example mode; in --from-contract, we're
// starting from an empty directory
let gitDir = path.join(directory, '.git')
if (toolbox.filesystem.exists(gitDir)) {
await toolbox.filesystem.remove(gitDir)
}
await toolbox.system.run('git init', { cwd: directory })
await toolbox.system.run('git add --all', { cwd: directory })
await toolbox.system.run('git commit -m "Initial commit"', {
cwd: directory,
})
return true
},
)
const installDependencies = async (toolbox, directory, installCommand) =>
await withSpinner(
`Install dependencies with ${toolbox.print.colors.muted(installCommand)}`,
`Failed to install dependencies`,
`Warnings while installing dependencies`,
async spinner => {
await toolbox.system.run(installCommand, { cwd: directory })
return true
},
)
const runCodegen = async (toolbox, directory, codegenCommand) =>
await withSpinner(
`Generate ABI and schema types with ${toolbox.print.colors.muted(codegenCommand)}`,
`Failed to generate code from ABI and GraphQL schema`,
`Warnings while generating code from ABI and GraphQL schema`,
async spinner => {
await toolbox.system.run(codegenCommand, { cwd: directory })
return true
},
)
const printNextSteps = (toolbox, { subgraphName, directory }, { commands }) => {
let { print } = toolbox
let relativeDir = path.relative(process.cwd(), directory)
// Print instructions
print.success(
`
Subgraph ${print.colors.blue(subgraphName)} created in ${print.colors.blue(relativeDir)}
`,
)
print.info(`Next steps:
1. Run \`${print.colors.muted(
'graph auth https://api.thegraph.com/deploy/ <access-token>',
)}\`
to authenticate with the hosted service. You can get the access token from
https://thegraph.com/explorer/dashboard/.
2. Type \`${print.colors.muted(`cd ${relativeDir}`)}\` to enter the subgraph.
3. Run \`${print.colors.muted(commands.deploy)}\` to deploy the subgraph to
https://thegraph.com/explorer/subgraph/${subgraphName}.
Make sure to visit the documentation on https://thegraph.com/docs/ for further information.`)
}
const initSubgraphFromExample = async (
toolbox,
{ allowSimpleName, subgraphName, directory },
{ commands },
) => {
let { filesystem, print, system } = toolbox
// Fail if the subgraph name is invalid
if (!revalidateSubgraphName(toolbox, subgraphName, { allowSimpleName })) {
process.exitCode = 1
return
}
// Fail if the output directory already exists
if (filesystem.exists(directory)) {
print.error(`Directory or file "${directory}" already exists`)
process.exitCode = 1
return
}
// Clone the example subgraph repository
let cloned = await withSpinner(
`Cloning example subgraph`,
`Failed to clone example subgraph`,
`Warnings while cloning example subgraph`,
async spinner => {
await system.run(
`git clone http://github.com/graphprotocol/example-subgraph ${directory}`,
)
return true
},
)
if (!cloned) {
process.exitCode = 1
return
}
// Update package.json to match the subgraph name
let prepared = await withSpinner(
`Update subgraph name and commands in package.json`,
`Failed to update subgraph name and commands in package.json`,
`Warnings while updating subgraph name and commands in package.json`,
async spinner => {
try {
// Load package.json
let pkgJsonFilename = filesystem.path(directory, 'package.json')
let pkgJson = await filesystem.read(pkgJsonFilename, 'json')
pkgJson.name = getSubgraphBasename(subgraphName)
Object.keys(pkgJson.scripts).forEach(name => {
pkgJson.scripts[name] = pkgJson.scripts[name].replace('example', subgraphName)
})
delete pkgJson['license']
delete pkgJson['repository']
// Write package.json
await filesystem.write(pkgJsonFilename, pkgJson, { jsonIndent: 2 })
return true
} catch (e) {
print.error(`Failed to preconfigure the subgraph: ${e}`)
filesystem.remove(directory)
return false
}
},
)
if (!prepared) {
process.exitCode = 1
return
}
// Initialize a fresh Git repository
let repo = await initRepository(toolbox, directory)
if (repo !== true) {
process.exitCode = 1
return
}
// Install dependencies
let installed = await installDependencies(toolbox, directory, commands.install)
if (installed !== true) {
process.exitCode = 1
return
}
// Run code-generation
let codegen = await runCodegen(toolbox, directory, commands.codegen)
if (codegen !== true) {
process.exitCode = 1
return
}
printNextSteps(toolbox, { subgraphName, directory }, { commands })
}
const initSubgraphFromContract = async (
toolbox,
{ allowSimpleName, subgraphName, directory, abi, network, address, indexEvents },
{ commands },
) => {
let { print } = toolbox
// Fail if the subgraph name is invalid
if (!revalidateSubgraphName(toolbox, subgraphName, { allowSimpleName })) {
process.exitCode = 1
return
}
// Fail if the output directory already exists
if (toolbox.filesystem.exists(directory)) {
print.error(`Directory or file "${directory}" already exists`)
process.exitCode = 1
return
}
if (abiEvents(abi).length === 0) {
// Fail if the ABI does not contain any events
print.error(`ABI does not contain any events`)
process.exitCode = 1
return
}
// Scaffold subgraph from ABI
let scaffold = await withSpinner(
`Create subgraph scaffold`,
`Failed to create subgraph scaffold`,
`Warnings while creating subgraph scaffold`,
async spinner => {
let scaffold = await generateScaffold(
{
subgraphName,
abi,
network,
address,
indexEvents,
},
spinner,
)
await writeScaffold(scaffold, directory, spinner)
return true
},
)
if (scaffold !== true) {
process.exitCode = 1
return
}
// Initialize a fresh Git repository
let repo = await initRepository(toolbox, directory)
if (repo !== true) {
process.exitCode = 1
return
}
// Install dependencies
let installed = await installDependencies(toolbox, directory, commands.install)
if (installed !== true) {
process.exitCode = 1
return
}
// Run code-generation
let codegen = await runCodegen(toolbox, directory, commands.codegen)
if (codegen !== true) {
process.exitCode = 1
return
}
printNextSteps(toolbox, { subgraphName, directory }, { commands })
}