@graphprotocol/graph-cli 0.38.0-alpha-20230131175746-0102e0f → 0.38.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.
@@ -0,0 +1,817 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const fs_1 = __importDefault(require("fs"));
30
+ const os_1 = __importDefault(require("os"));
31
+ const path_1 = __importDefault(require("path"));
32
+ const chalk_1 = __importDefault(require("chalk"));
33
+ const graphCli = __importStar(require("../cli"));
34
+ const abi_1 = require("../command-helpers/abi");
35
+ const DataSourcesExtractor = __importStar(require("../command-helpers/data-sources"));
36
+ const gluegun_1 = require("../command-helpers/gluegun");
37
+ const network_1 = require("../command-helpers/network");
38
+ const node_1 = require("../command-helpers/node");
39
+ const scaffold_1 = require("../command-helpers/scaffold");
40
+ const spinner_1 = require("../command-helpers/spinner");
41
+ const studio_1 = require("../command-helpers/studio");
42
+ const subgraph_1 = require("../command-helpers/subgraph");
43
+ const debug_1 = __importDefault(require("../debug"));
44
+ const protocols_1 = __importDefault(require("../protocols"));
45
+ const schema_1 = require("../scaffold/schema");
46
+ const validation_1 = require("../validation");
47
+ const protocolChoices = Array.from(protocols_1.default.availableProtocols().keys());
48
+ const availableNetworks = protocols_1.default.availableNetworks();
49
+ const DEFAULT_EXAMPLE_SUBGRAPH = 'ethereum/gravatar';
50
+ const initDebug = (0, debug_1.default)('graph-cli:init');
51
+ const HELP = `
52
+ ${chalk_1.default.bold('graph init')} [options] [subgraph-name] [directory]
53
+
54
+ ${chalk_1.default.dim('Options:')}
55
+
56
+ --protocol <${protocolChoices.join('|')}>
57
+ --product <subgraph-studio|hosted-service>
58
+ Selects the product for which to initialize
59
+ --studio Shortcut for --product subgraph-studio
60
+ -g, --node <node> Graph node for which to initialize
61
+ --allow-simple-name Use a subgraph name without a prefix (default: false)
62
+ -h, --help Show usage information
63
+
64
+ ${chalk_1.default.dim('Choose mode with one of:')}
65
+
66
+ --from-contract <contract> Creates a scaffold based on an existing contract
67
+ --from-example [example] Creates a scaffold based on an example subgraph
68
+
69
+ ${chalk_1.default.dim('Options for --from-contract:')}
70
+
71
+ --contract-name Name of the contract (default: Contract)
72
+ --index-events Index contract events as entities
73
+ --start-block Block number to start indexing from (default: 0)
74
+
75
+ ${chalk_1.default.dim.underline('Ethereum:')}
76
+
77
+ --abi <path> Path to the contract ABI (default: download from Etherscan)
78
+ --network <${availableNetworks.get('ethereum').join('|')}>
79
+ Selects the network the contract is deployed to
80
+
81
+ ${chalk_1.default.dim.underline('NEAR:')}
82
+
83
+ --network <${availableNetworks.get('near').join('|')}>
84
+ Selects the network the contract is deployed to
85
+
86
+ ${chalk_1.default.dim.underline('Cosmos:')}
87
+
88
+ --network <${availableNetworks.get('cosmos').join('|')}>
89
+ Selects the network the contract is deployed to
90
+ `;
91
+ const processInitForm = async (toolbox, { protocol, product, studio, node, abi, allowSimpleName, directory, contract, indexEvents, fromExample, network, subgraphName, contractName, startBlock, }) => {
92
+ let abiFromEtherscan = undefined;
93
+ let abiFromFile = undefined;
94
+ let protocolInstance;
95
+ let ProtocolContract;
96
+ let ABI;
97
+ const questions = [
98
+ {
99
+ type: 'select',
100
+ name: 'protocol',
101
+ message: 'Protocol',
102
+ choices: protocolChoices,
103
+ skip: protocolChoices.includes(protocol),
104
+ result: (value) => {
105
+ protocol || (protocol = value);
106
+ protocolInstance = new protocols_1.default(protocol);
107
+ return protocol;
108
+ },
109
+ },
110
+ {
111
+ type: 'select',
112
+ name: 'product',
113
+ message: 'Product for which to initialize',
114
+ choices: ['subgraph-studio', 'hosted-service'],
115
+ skip: () => protocol === 'arweave' ||
116
+ protocol === 'cosmos' ||
117
+ protocol === 'near' ||
118
+ product === 'subgraph-studio' ||
119
+ product === 'hosted-service' ||
120
+ studio !== undefined ||
121
+ node !== undefined,
122
+ result: (value) => {
123
+ // For now we only support NEAR subgraphs in the Hosted Service
124
+ if (protocol === 'near') {
125
+ // Can be overwritten because the question will be skipped (product === undefined)
126
+ product = 'hosted-service';
127
+ return product;
128
+ }
129
+ if (value == 'subgraph-studio') {
130
+ allowSimpleName = true;
131
+ }
132
+ product = value;
133
+ return value;
134
+ },
135
+ },
136
+ {
137
+ type: 'input',
138
+ name: 'subgraphName',
139
+ message: () => (product == 'subgraph-studio' || studio ? 'Subgraph slug' : 'Subgraph name'),
140
+ initial: subgraphName,
141
+ validate: (name) => {
142
+ try {
143
+ (0, subgraph_1.validateSubgraphName)(name, { allowSimpleName });
144
+ return true;
145
+ }
146
+ catch (e) {
147
+ return `${e.message}
148
+
149
+ Examples:
150
+
151
+ $ graph init ${os_1.default.userInfo().username}/${name}
152
+ $ graph init ${name} --allow-simple-name`;
153
+ }
154
+ },
155
+ result: (value) => {
156
+ subgraphName = value;
157
+ return value;
158
+ },
159
+ },
160
+ {
161
+ type: 'input',
162
+ name: 'directory',
163
+ message: 'Directory to create the subgraph in',
164
+ initial: () => directory || (0, subgraph_1.getSubgraphBasename)(subgraphName),
165
+ validate: (value) => toolbox.filesystem.exists(value || directory || (0, subgraph_1.getSubgraphBasename)(subgraphName))
166
+ ? 'Directory already exists'
167
+ : true,
168
+ },
169
+ {
170
+ type: 'select',
171
+ name: 'network',
172
+ message: () => `${protocolInstance.displayName()} network`,
173
+ choices: () => {
174
+ initDebug('Generating list of available networks for protocol "%s" (%M)', protocol, availableNetworks.get(protocol));
175
+ return (
176
+ // @ts-expect-error TODO: wait what?
177
+ availableNetworks
178
+ .get(protocol) // Get networks related to the chosen protocol.
179
+ // @ts-expect-error TODO: wait what?
180
+ .toArray()); // Needed because of gluegun. It can't even receive a JS iterable.
181
+ },
182
+ skip: fromExample !== undefined,
183
+ initial: network || 'mainnet',
184
+ result: (value) => {
185
+ network = value;
186
+ return value;
187
+ },
188
+ },
189
+ // TODO:
190
+ //
191
+ // protocols that don't support contract
192
+ // - arweave
193
+ // - cosmos
194
+ {
195
+ type: 'input',
196
+ name: 'contract',
197
+ message: () => {
198
+ ProtocolContract = protocolInstance.getContract();
199
+ return `Contract ${ProtocolContract.identifierName()}`;
200
+ },
201
+ skip: () => fromExample !== undefined || !protocolInstance.hasContract(),
202
+ initial: contract,
203
+ validate: async (value) => {
204
+ if (fromExample !== undefined || !protocolInstance.hasContract()) {
205
+ return true;
206
+ }
207
+ // Validate whether the contract is valid
208
+ const { valid, error } = (0, validation_1.validateContract)(value, ProtocolContract);
209
+ return valid ? true : error;
210
+ },
211
+ result: async (value) => {
212
+ if (fromExample !== undefined) {
213
+ return value;
214
+ }
215
+ ABI = protocolInstance.getABI();
216
+ // Try loading the ABI from Etherscan, if none was provided
217
+ if (protocolInstance.hasABIs() && !abi) {
218
+ try {
219
+ if (network === 'poa-core') {
220
+ // TODO: this variable is never used anywhere, what happens?
221
+ // abiFromBlockScout = await loadAbiFromBlockScout(ABI, network, value)
222
+ }
223
+ else {
224
+ abiFromEtherscan = await (0, abi_1.loadAbiFromEtherscan)(ABI, network, value);
225
+ }
226
+ }
227
+ catch (e) {
228
+ // noop
229
+ }
230
+ }
231
+ return value;
232
+ },
233
+ },
234
+ {
235
+ type: 'input',
236
+ name: 'abi',
237
+ message: 'ABI file (path)',
238
+ initial: abi,
239
+ skip: () => !protocolInstance.hasABIs() || fromExample !== undefined || abiFromEtherscan !== undefined,
240
+ validate: async (value) => {
241
+ if (fromExample || abiFromEtherscan || !protocolInstance.hasABIs()) {
242
+ return true;
243
+ }
244
+ try {
245
+ abiFromFile = loadAbiFromFile(toolbox, ABI, value);
246
+ return true;
247
+ }
248
+ catch (e) {
249
+ return e.message;
250
+ }
251
+ },
252
+ },
253
+ {
254
+ type: 'input',
255
+ name: 'startBlock',
256
+ message: 'Start Block',
257
+ initial: startBlock || '0',
258
+ skip: () => fromExample !== undefined || startBlock,
259
+ validate: (value) => parseInt(value) >= 0,
260
+ result: (value) => {
261
+ startBlock = value;
262
+ return value;
263
+ },
264
+ },
265
+ {
266
+ type: 'input',
267
+ name: 'contractName',
268
+ message: 'Contract Name',
269
+ initial: contractName || 'Contract',
270
+ skip: () => fromExample !== undefined || !protocolInstance.hasContract(),
271
+ validate: (value) => value && value.length > 0,
272
+ result: (value) => {
273
+ contractName = value;
274
+ return value;
275
+ },
276
+ },
277
+ {
278
+ type: 'confirm',
279
+ name: 'indexEvents',
280
+ message: 'Index contract events as entities',
281
+ initial: true,
282
+ skip: () => !!indexEvents,
283
+ result: (value) => {
284
+ indexEvents = value;
285
+ return value;
286
+ },
287
+ },
288
+ ];
289
+ try {
290
+ const answers = await toolbox.prompt.ask(
291
+ // @ts-expect-error questions do somehow fit
292
+ questions);
293
+ return {
294
+ ...answers,
295
+ abi: (abiFromEtherscan || abiFromFile),
296
+ protocolInstance,
297
+ };
298
+ }
299
+ catch (e) {
300
+ return undefined;
301
+ }
302
+ };
303
+ const loadAbiFromFile = (toolbox, ABI, filename) => {
304
+ const exists = toolbox.filesystem.exists(filename);
305
+ if (!exists) {
306
+ throw Error('File does not exist.');
307
+ }
308
+ else if (exists === 'dir') {
309
+ throw Error('Path points to a directory, not a file.');
310
+ }
311
+ else if (exists === 'other') {
312
+ throw Error('Not sure what this path points to.');
313
+ }
314
+ else {
315
+ return ABI.load('Contract', filename);
316
+ }
317
+ };
318
+ exports.default = {
319
+ description: 'Creates a new subgraph with basic scaffolding',
320
+ run: async (toolbox) => {
321
+ // Obtain tools
322
+ const { print, system } = toolbox;
323
+ // Read CLI parameters
324
+ let { protocol, product, studio, node, g, abi, allowSimpleName, fromContract, contractName, fromExample, h, help, indexEvents, network, startBlock, } = toolbox.parameters.options;
325
+ node || (node = g);
326
+ ({ node, allowSimpleName } = (0, node_1.chooseNodeUrl)({
327
+ product,
328
+ studio,
329
+ node,
330
+ allowSimpleName,
331
+ }));
332
+ if (fromContract && fromExample) {
333
+ print.error(`Only one of --from-example and --from-contract can be used at a time.`);
334
+ process.exitCode = 1;
335
+ return;
336
+ }
337
+ let subgraphName, directory;
338
+ try {
339
+ [subgraphName, directory] = (0, gluegun_1.fixParameters)(toolbox.parameters, {
340
+ allowSimpleName,
341
+ help,
342
+ h,
343
+ indexEvents,
344
+ studio,
345
+ });
346
+ }
347
+ catch (e) {
348
+ print.error(e.message);
349
+ process.exitCode = 1;
350
+ return;
351
+ }
352
+ // Show help text if requested
353
+ if (help || h) {
354
+ print.info(HELP);
355
+ return;
356
+ }
357
+ // Detect git
358
+ const git = system.which('git');
359
+ if (git === null) {
360
+ print.error(`Git was not found on your system. Please install 'git' so it is in $PATH.`);
361
+ process.exitCode = 1;
362
+ return;
363
+ }
364
+ // Detect Yarn and/or NPM
365
+ const yarn = system.which('yarn');
366
+ const npm = system.which('npm');
367
+ if (!yarn && !npm) {
368
+ print.error(`Neither Yarn nor NPM were found on your system. Please install one of them.`);
369
+ process.exitCode = 1;
370
+ return;
371
+ }
372
+ const commands = {
373
+ install: yarn ? 'yarn' : 'npm install',
374
+ codegen: yarn ? 'yarn codegen' : 'npm run codegen',
375
+ deploy: yarn ? 'yarn deploy' : 'npm run deploy',
376
+ };
377
+ // If all parameters are provided from the command-line,
378
+ // go straight to creating the subgraph from the example
379
+ if (fromExample && subgraphName && directory) {
380
+ return await initSubgraphFromExample(toolbox, { fromExample, allowSimpleName, directory, subgraphName, studio, product }, { commands });
381
+ }
382
+ // If all parameters are provided from the command-line,
383
+ // go straight to creating the subgraph from an existing contract
384
+ if (fromContract && protocol && subgraphName && directory && network && node) {
385
+ if (!protocolChoices.includes(protocol)) {
386
+ print.error(`Protocol '${protocol}' is not supported, choose from these options: ${protocolChoices.join(', ')}`);
387
+ process.exitCode = 1;
388
+ return;
389
+ }
390
+ const protocolInstance = new protocols_1.default(protocol);
391
+ if (protocolInstance.hasABIs()) {
392
+ const ABI = protocolInstance.getABI();
393
+ if (abi) {
394
+ try {
395
+ abi = loadAbiFromFile(toolbox, ABI, abi);
396
+ }
397
+ catch (e) {
398
+ print.error(`Failed to load ABI: ${e.message}`);
399
+ process.exitCode = 1;
400
+ return;
401
+ }
402
+ }
403
+ else {
404
+ try {
405
+ if (network === 'poa-core') {
406
+ abi = await (0, abi_1.loadAbiFromBlockScout)(ABI, network, fromContract);
407
+ }
408
+ else {
409
+ abi = await (0, abi_1.loadAbiFromEtherscan)(ABI, network, fromContract);
410
+ }
411
+ }
412
+ catch (e) {
413
+ process.exitCode = 1;
414
+ return;
415
+ }
416
+ }
417
+ }
418
+ return await initSubgraphFromContract(toolbox, {
419
+ protocolInstance,
420
+ abi,
421
+ allowSimpleName,
422
+ directory,
423
+ contract: fromContract,
424
+ indexEvents,
425
+ network,
426
+ subgraphName,
427
+ contractName,
428
+ node,
429
+ studio,
430
+ product,
431
+ startBlock,
432
+ }, { commands, addContract: false });
433
+ }
434
+ // Otherwise, take the user through the interactive form
435
+ const inputs = await processInitForm(toolbox, {
436
+ protocol,
437
+ product,
438
+ studio,
439
+ node,
440
+ abi,
441
+ allowSimpleName,
442
+ directory,
443
+ contract: fromContract,
444
+ indexEvents,
445
+ fromExample,
446
+ network,
447
+ subgraphName,
448
+ contractName,
449
+ startBlock,
450
+ });
451
+ // Exit immediately when the form is cancelled
452
+ if (inputs === undefined) {
453
+ process.exit(1);
454
+ }
455
+ print.info('———');
456
+ if (fromExample) {
457
+ await initSubgraphFromExample(toolbox, {
458
+ fromExample,
459
+ subgraphName: inputs.subgraphName,
460
+ directory: inputs.directory,
461
+ studio: inputs.studio,
462
+ product: inputs.product,
463
+ }, { commands });
464
+ }
465
+ else {
466
+ ({ node, allowSimpleName } = (0, node_1.chooseNodeUrl)({
467
+ product: inputs.product,
468
+ studio,
469
+ node,
470
+ allowSimpleName,
471
+ }));
472
+ await initSubgraphFromContract(toolbox, {
473
+ protocolInstance: inputs.protocolInstance,
474
+ allowSimpleName,
475
+ subgraphName: inputs.subgraphName,
476
+ directory: inputs.directory,
477
+ abi: inputs.abi,
478
+ network: inputs.network,
479
+ contract: inputs.contract,
480
+ indexEvents: inputs.indexEvents,
481
+ contractName: inputs.contractName,
482
+ node,
483
+ studio: inputs.studio,
484
+ product: inputs.product,
485
+ startBlock: inputs.startBlock,
486
+ }, { commands, addContract: true });
487
+ }
488
+ },
489
+ };
490
+ const revalidateSubgraphName = async (toolbox, subgraphName, { allowSimpleName }) => {
491
+ // Fail if the subgraph name is invalid
492
+ try {
493
+ (0, subgraph_1.validateSubgraphName)(subgraphName, { allowSimpleName });
494
+ return true;
495
+ }
496
+ catch (e) {
497
+ toolbox.print.error(`${e.message}
498
+
499
+ Examples:
500
+
501
+ $ graph init ${os_1.default.userInfo().username}/${subgraphName}
502
+ $ graph init ${subgraphName} --allow-simple-name`);
503
+ return false;
504
+ }
505
+ };
506
+ const initRepository = async (toolbox, directory) => await (0, spinner_1.withSpinner)(`Initialize subgraph repository`, `Failed to initialize subgraph repository`, `Warnings while initializing subgraph repository`, async () => {
507
+ // Remove .git dir in --from-example mode; in --from-contract, we're
508
+ // starting from an empty directory
509
+ const gitDir = path_1.default.join(directory, '.git');
510
+ if (toolbox.filesystem.exists(gitDir)) {
511
+ toolbox.filesystem.remove(gitDir);
512
+ }
513
+ await toolbox.system.run('git init', { cwd: directory });
514
+ await toolbox.system.run('git add --all', { cwd: directory });
515
+ await toolbox.system.run('git commit -m "Initial commit"', {
516
+ cwd: directory,
517
+ });
518
+ return true;
519
+ });
520
+ // Only used for local testing / continuous integration.
521
+ //
522
+ // This requires that the command `npm link` is called
523
+ // on the root directory of this repository, as described here:
524
+ // https://docs.npmjs.com/cli/v7/commands/npm-link.
525
+ const npmLinkToLocalCli = async (toolbox, directory) => {
526
+ if (process.env.GRAPH_CLI_TESTS) {
527
+ await toolbox.system.run('npm link @graphprotocol/graph-cli', { cwd: directory });
528
+ }
529
+ };
530
+ const installDependencies = async (toolbox, directory, installCommand) => await (0, spinner_1.withSpinner)(`Install dependencies with ${toolbox.print.colors.muted(installCommand)}`, `Failed to install dependencies`, `Warnings while installing dependencies`, async () => {
531
+ // Links to local graph-cli if we're running the automated tests
532
+ await npmLinkToLocalCli(toolbox, directory);
533
+ await toolbox.system.run(installCommand, { cwd: directory });
534
+ return true;
535
+ });
536
+ const runCodegen = async (toolbox, directory, codegenCommand) => await (0, spinner_1.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 () => {
537
+ await toolbox.system.run(codegenCommand, { cwd: directory });
538
+ return true;
539
+ });
540
+ const printNextSteps = (toolbox, { subgraphName, directory }, { commands, }) => {
541
+ const { print } = toolbox;
542
+ const relativeDir = path_1.default.relative(process.cwd(), directory);
543
+ // Print instructions
544
+ print.success(`
545
+ Subgraph ${print.colors.blue(subgraphName)} created in ${print.colors.blue(relativeDir)}
546
+ `);
547
+ print.info(`Next steps:
548
+
549
+ 1. Run \`${print.colors.muted('graph auth')}\` to authenticate with your deploy key.
550
+
551
+ 2. Type \`${print.colors.muted(`cd ${relativeDir}`)}\` to enter the subgraph.
552
+
553
+ 3. Run \`${print.colors.muted(commands.deploy)}\` to deploy the subgraph.
554
+
555
+ Make sure to visit the documentation on https://thegraph.com/docs/ for further information.`);
556
+ };
557
+ const initSubgraphFromExample = async (toolbox, { fromExample, allowSimpleName, subgraphName, directory, studio, product, }, { commands, }) => {
558
+ const { filesystem, print, system } = toolbox;
559
+ // Fail if the subgraph name is invalid
560
+ if (!revalidateSubgraphName(toolbox, subgraphName, { allowSimpleName: !!allowSimpleName })) {
561
+ process.exitCode = 1;
562
+ return;
563
+ }
564
+ // Fail if the output directory already exists
565
+ if (filesystem.exists(directory)) {
566
+ print.error(`Directory or file "${directory}" already exists`);
567
+ process.exitCode = 1;
568
+ return;
569
+ }
570
+ // Clone the example subgraph repository
571
+ const cloned = await (0, spinner_1.withSpinner)(`Cloning example subgraph`, `Failed to clone example subgraph`, `Warnings while cloning example subgraph`, async () => {
572
+ // Create a temporary directory
573
+ const prefix = path_1.default.join(os_1.default.tmpdir(), 'example-subgraph-');
574
+ const tmpDir = fs_1.default.mkdtempSync(prefix);
575
+ try {
576
+ await system.run(`git clone http://github.com/graphprotocol/example-subgraphs ${tmpDir}`);
577
+ // If an example is not specified, use the default one
578
+ if (fromExample === undefined || fromExample === true) {
579
+ fromExample = DEFAULT_EXAMPLE_SUBGRAPH;
580
+ }
581
+ const exampleSubgraphPath = path_1.default.join(tmpDir, String(fromExample));
582
+ if (!filesystem.exists(exampleSubgraphPath)) {
583
+ return { result: false, error: `Example not found: ${fromExample}` };
584
+ }
585
+ filesystem.copy(exampleSubgraphPath, directory);
586
+ return true;
587
+ }
588
+ finally {
589
+ filesystem.remove(tmpDir);
590
+ }
591
+ });
592
+ if (!cloned) {
593
+ process.exitCode = 1;
594
+ return;
595
+ }
596
+ try {
597
+ // It doesn't matter if we changed the URL we clone the YAML,
598
+ // we'll check it's network anyway. If it's a studio subgraph we're dealing with.
599
+ const dataSourcesAndTemplates = await DataSourcesExtractor.fromFilePath(path_1.default.join(directory, 'subgraph.yaml'));
600
+ for (const { network } of dataSourcesAndTemplates) {
601
+ (0, studio_1.validateStudioNetwork)({ studio, product, network });
602
+ }
603
+ }
604
+ catch (e) {
605
+ print.error(e.message);
606
+ process.exitCode = 1;
607
+ return;
608
+ }
609
+ const networkConf = await (0, network_1.initNetworksConfig)(toolbox, directory, 'address');
610
+ if (networkConf !== true) {
611
+ process.exitCode = 1;
612
+ return;
613
+ }
614
+ // Update package.json to match the subgraph name
615
+ const prepared = await (0, spinner_1.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 () => {
616
+ try {
617
+ // Load package.json
618
+ const pkgJsonFilename = filesystem.path(directory, 'package.json');
619
+ const pkgJson = await filesystem.read(pkgJsonFilename, 'json');
620
+ pkgJson.name = (0, subgraph_1.getSubgraphBasename)(subgraphName);
621
+ Object.keys(pkgJson.scripts).forEach(name => {
622
+ pkgJson.scripts[name] = pkgJson.scripts[name].replace('example', subgraphName);
623
+ });
624
+ delete pkgJson['license'];
625
+ delete pkgJson['repository'];
626
+ // Remove example's cli in favor of the local one (added via `npm link`)
627
+ if (process.env.GRAPH_CLI_TESTS) {
628
+ delete pkgJson['devDependencies']['@graphprotocol/graph-cli'];
629
+ }
630
+ // Write package.json
631
+ filesystem.write(pkgJsonFilename, pkgJson, { jsonIndent: 2 });
632
+ return true;
633
+ }
634
+ catch (e) {
635
+ print.error(`Failed to preconfigure the subgraph: ${e}`);
636
+ filesystem.remove(directory);
637
+ return false;
638
+ }
639
+ });
640
+ if (!prepared) {
641
+ process.exitCode = 1;
642
+ return;
643
+ }
644
+ // Initialize a fresh Git repository
645
+ const repo = await initRepository(toolbox, directory);
646
+ if (repo !== true) {
647
+ process.exitCode = 1;
648
+ return;
649
+ }
650
+ // Install dependencies
651
+ const installed = await installDependencies(toolbox, directory, commands.install);
652
+ if (installed !== true) {
653
+ process.exitCode = 1;
654
+ return;
655
+ }
656
+ // Run code-generation
657
+ const codegen = await runCodegen(toolbox, directory, commands.codegen);
658
+ if (codegen !== true) {
659
+ process.exitCode = 1;
660
+ return;
661
+ }
662
+ printNextSteps(toolbox, { subgraphName, directory }, { commands });
663
+ };
664
+ const initSubgraphFromContract = async (toolbox, { protocolInstance, allowSimpleName, subgraphName, directory, abi, network, contract, indexEvents, contractName, node, studio, product, startBlock, }, { commands, addContract, }) => {
665
+ const { print } = toolbox;
666
+ // Fail if the subgraph name is invalid
667
+ if (!revalidateSubgraphName(toolbox, subgraphName, { allowSimpleName })) {
668
+ process.exitCode = 1;
669
+ return;
670
+ }
671
+ // Fail if the output directory already exists
672
+ if (toolbox.filesystem.exists(directory)) {
673
+ print.error(`Directory or file "${directory}" already exists`);
674
+ process.exitCode = 1;
675
+ return;
676
+ }
677
+ if (protocolInstance.hasABIs() &&
678
+ ((0, schema_1.abiEvents)(abi).size === 0 ||
679
+ // @ts-expect-error TODO: the abiEvents result is expected to be a List, how's it an array?
680
+ (0, schema_1.abiEvents)(abi).length === 0)) {
681
+ // Fail if the ABI does not contain any events
682
+ print.error(`ABI does not contain any events`);
683
+ process.exitCode = 1;
684
+ return;
685
+ }
686
+ // We can validate this before the scaffold because we receive
687
+ // the network from the form or via command line argument.
688
+ // We don't need to read the manifest in this case.
689
+ try {
690
+ (0, studio_1.validateStudioNetwork)({ studio, product, network });
691
+ }
692
+ catch (e) {
693
+ print.error(e.message);
694
+ process.exitCode = 1;
695
+ return;
696
+ }
697
+ // Scaffold subgraph
698
+ const scaffold = await (0, spinner_1.withSpinner)(`Create subgraph scaffold`, `Failed to create subgraph scaffold`, `Warnings while creating subgraph scaffold`, async (spinner) => {
699
+ const scaffold = await (0, scaffold_1.generateScaffold)({
700
+ protocolInstance,
701
+ subgraphName,
702
+ abi,
703
+ network,
704
+ contract,
705
+ indexEvents,
706
+ contractName,
707
+ startBlock,
708
+ node,
709
+ }, spinner);
710
+ await (0, scaffold_1.writeScaffold)(scaffold, directory, spinner);
711
+ return true;
712
+ });
713
+ if (scaffold !== true) {
714
+ process.exitCode = 1;
715
+ return;
716
+ }
717
+ if (protocolInstance.hasContract()) {
718
+ const identifierName = protocolInstance.getContract().identifierName();
719
+ const networkConf = await (0, network_1.initNetworksConfig)(toolbox, directory, identifierName);
720
+ if (networkConf !== true) {
721
+ process.exitCode = 1;
722
+ return;
723
+ }
724
+ }
725
+ // Initialize a fresh Git repository
726
+ const repo = await initRepository(toolbox, directory);
727
+ if (repo !== true) {
728
+ process.exitCode = 1;
729
+ return;
730
+ }
731
+ // Install dependencies
732
+ const installed = await installDependencies(toolbox, directory, commands.install);
733
+ if (installed !== true) {
734
+ process.exitCode = 1;
735
+ return;
736
+ }
737
+ // Run code-generation
738
+ const codegen = await runCodegen(toolbox, directory, commands.codegen);
739
+ if (codegen !== true) {
740
+ process.exitCode = 1;
741
+ return;
742
+ }
743
+ while (addContract) {
744
+ addContract = await addAnotherContract(toolbox, { protocolInstance, directory });
745
+ }
746
+ printNextSteps(toolbox, { subgraphName, directory }, { commands });
747
+ };
748
+ const addAnotherContract = async (toolbox, { protocolInstance, directory }) => {
749
+ const addContractConfirmation = await toolbox.prompt.confirm('Add another contract?');
750
+ if (addContractConfirmation) {
751
+ let abiFromFile = false;
752
+ const ProtocolContract = protocolInstance.getContract();
753
+ const questions = [
754
+ {
755
+ type: 'input',
756
+ name: 'contract',
757
+ message: () => `Contract ${ProtocolContract.identifierName()}`,
758
+ validate: async (value) => {
759
+ // Validate whether the contract is valid
760
+ const { valid, error } = (0, validation_1.validateContract)(value, ProtocolContract);
761
+ return valid ? true : error;
762
+ },
763
+ },
764
+ {
765
+ type: 'select',
766
+ name: 'localAbi',
767
+ message: 'Provide local ABI path?',
768
+ choices: ['yes', 'no'],
769
+ result: (value) => {
770
+ abiFromFile = value === 'yes' ? true : false;
771
+ return abiFromFile;
772
+ },
773
+ },
774
+ {
775
+ type: 'input',
776
+ name: 'abi',
777
+ message: 'ABI file (path)',
778
+ skip: () => abiFromFile === false,
779
+ },
780
+ {
781
+ type: 'input',
782
+ name: 'contractName',
783
+ message: 'Contract Name',
784
+ initial: 'Contract',
785
+ validate: (value) => value && value.length > 0,
786
+ },
787
+ ];
788
+ // Get the cwd before process.chdir in order to switch back in the end of command execution
789
+ const cwd = process.cwd();
790
+ try {
791
+ const { abi, contract, contractName } = await toolbox.prompt.ask(
792
+ // @ts-expect-error questions do somehow fit
793
+ questions);
794
+ if (fs_1.default.existsSync(directory)) {
795
+ process.chdir(directory);
796
+ }
797
+ const commandLine = ['add', contract, '--contract-name', contractName];
798
+ if (abiFromFile) {
799
+ if (abi.includes(directory)) {
800
+ commandLine.push('--abi', path_1.default.normalize(abi.replace(directory, '')));
801
+ }
802
+ else {
803
+ commandLine.push('--abi', abi);
804
+ }
805
+ }
806
+ await graphCli.run(commandLine);
807
+ }
808
+ catch (e) {
809
+ toolbox.print.error(e);
810
+ process.exit(1);
811
+ }
812
+ finally {
813
+ process.chdir(cwd);
814
+ }
815
+ }
816
+ return addContractConfirmation;
817
+ };