@graphprotocol/graph-cli 0.37.4 → 0.37.5

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