-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathinit.ts
More file actions
1347 lines (1233 loc) · 38 KB
/
init.ts
File metadata and controls
1347 lines (1233 loc) · 38 KB
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { filesystem, print, prompt, system } from 'gluegun';
import { Args, Command, Flags } from '@oclif/core';
import { Network } from '@pinax/graph-networks-registry';
import { appendApiVersionForGraph } from '../command-helpers/compiler.js';
import { ContractService } from '../command-helpers/contracts.js';
import { resolveFile } from '../command-helpers/file-resolver.js';
import { DEFAULT_IPFS_URL } from '../command-helpers/ipfs.js';
import { initNetworksConfig } from '../command-helpers/network.js';
import { chooseNodeUrl } from '../command-helpers/node.js';
import { PromptManager } from '../command-helpers/prompt-manager.js';
import { checkForProxy } from '../command-helpers/proxy.js';
import { loadRegistry } from '../command-helpers/registry.js';
import { retryWithPrompt } from '../command-helpers/retry.js';
import { generateScaffold, writeScaffold } from '../command-helpers/scaffold.js';
import { sortWithPriority } from '../command-helpers/sort.js';
import { withSpinner } from '../command-helpers/spinner.js';
import { getSubgraphBasename } from '../command-helpers/subgraph.js';
import { GRAPH_CLI_SHARED_HEADERS } from '../constants.js';
import debugFactory from '../debug.js';
import EthereumABI from '../protocols/ethereum/abi.js';
import Protocol, { ProtocolName } from '../protocols/index.js';
import { abiEvents } from '../scaffold/schema.js';
import Schema from '../schema.js';
import { createIpfsClient, loadSubgraphSchemaFromIPFS } from '../utils.js';
import { validateContract } from '../validation/index.js';
import AddCommand from './add.js';
const protocolChoices = Array.from(Protocol.availableProtocols().keys());
const initDebugger = debugFactory('graph-cli:commands:init');
const DEFAULT_EXAMPLE_SUBGRAPH = 'ethereum-gravatar';
const DEFAULT_CONTRACT_NAME = 'Contract';
export default class InitCommand extends Command {
static description = 'Creates a new subgraph with basic scaffolding.';
static args = {
subgraphName: Args.string(),
directory: Args.string(),
};
static flags = {
help: Flags.help({
char: 'h',
}),
protocol: Flags.string({
options: protocolChoices,
}),
node: Flags.string({
summary: 'Graph node for which to initialize.',
char: 'g',
}),
'from-contract': Flags.string({
description: 'Creates a scaffold based on an existing contract.',
exclusive: ['from-example'],
}),
'from-example': Flags.string({
description: 'Creates a scaffold based on an example subgraph.',
// TODO: using a default sets the value and therefore requires not to have --from-contract
// default: 'Contract',
exclusive: ['from-contract', 'spkg'],
}),
'contract-name': Flags.string({
helpGroup: 'Scaffold from contract',
description: 'Name of the contract.',
dependsOn: ['from-contract'],
}),
'index-events': Flags.boolean({
helpGroup: 'Scaffold from contract',
description: 'Index contract events as entities.',
dependsOn: ['from-contract'],
}),
'skip-install': Flags.boolean({
summary: 'Skip installing dependencies.',
default: false,
}),
'skip-git': Flags.boolean({
summary: 'Skip initializing a Git repository.',
default: false,
}),
'start-block': Flags.string({
helpGroup: 'Scaffold from contract',
description: 'Block number to start indexing from.',
// TODO: using a default sets the value and therefore requires --from-contract
// default: '0',
dependsOn: ['from-contract'],
}),
abi: Flags.string({
summary: 'Path to the contract ABI',
// TODO: using a default sets the value and therefore requires --from-contract
// default: '*Download from Etherscan*',
dependsOn: ['from-contract'],
}),
spkg: Flags.string({
summary: 'Path to the SPKG file',
}),
network: Flags.string({
summary: 'Network the contract is deployed to.',
description:
'Refer to https://github.com/graphprotocol/networks-registry/ for supported networks',
}),
ipfs: Flags.string({
summary: 'IPFS node to use for fetching subgraph data.',
char: 'i',
default: DEFAULT_IPFS_URL,
hidden: true,
}),
};
async run() {
const {
args: { subgraphName, directory },
flags,
} = await this.parse(InitCommand);
const {
protocol,
node: nodeFlag,
'from-contract': fromContract,
'contract-name': contractName,
'from-example': fromExample,
'index-events': indexEvents,
'skip-install': skipInstall,
'skip-git': skipGit,
ipfs,
network,
abi: abiPath,
'start-block': startBlock,
spkg: spkgPath,
} = flags;
initDebugger('Flags: %O', flags);
if (skipGit) {
this.warn(
'The --skip-git flag will be removed in the next major version. By default we will stop initializing a Git repository.',
);
}
if ((fromContract || spkgPath) && !network && !fromExample) {
this.error('--network is required when using --from-contract or --spkg');
}
const { node } = chooseNodeUrl({
node: nodeFlag,
});
// Detect git
const git = system.which('git');
if (!git) {
this.error('Git was not found on your system. Please install "git" so it is in $PATH.', {
exit: 1,
});
}
// Detect Yarn and/or NPM
const yarn = system.which('yarn');
const npm = system.which('npm');
if (!yarn && !npm) {
this.error(`Neither Yarn nor NPM were found on your system. Please install one of them.`, {
exit: 1,
});
}
const commands = {
link: yarn ? 'yarn link @graphprotocol/graph-cli' : 'npm link @graphprotocol/graph-cli',
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) {
await initSubgraphFromExample.bind(this)(
{
fromExample,
directory,
subgraphName,
skipInstall,
skipGit,
},
{ commands },
);
// Exit with success
return this.exit(0);
}
// Will be assigned below if ethereum
let abi!: EthereumABI;
// If all parameters are provided from the command-line,
// go straight to creating the subgraph from an existing contract
if ((fromContract || spkgPath) && protocol && subgraphName && directory && network && node) {
const registry = await loadRegistry();
const contractService = new ContractService(registry);
const sourcifyContractInfo = await contractService.getFromSourcify(
EthereumABI,
network,
fromContract!,
);
if (!protocolChoices.includes(protocol as ProtocolName)) {
this.error(
`Protocol '${protocol}' is not supported, choose from these options: ${protocolChoices.join(
', ',
)}`,
{ exit: 1 },
);
}
const protocolInstance = new Protocol(protocol as ProtocolName);
if (protocolInstance.hasABIs()) {
const ABI = protocolInstance.getABI();
if (abiPath) {
try {
abi = loadAbiFromFile(ABI, abiPath);
} catch (e) {
this.error(`Failed to load ABI: ${e.message}`, { exit: 1 });
}
} else {
try {
abi = sourcifyContractInfo
? sourcifyContractInfo.abi
: await contractService.getABI(ABI, network, fromContract!);
} catch (e) {
this.exit(1);
}
}
}
await initSubgraphFromContract.bind(this)(
{
protocolInstance,
abi,
directory,
source: fromContract!,
indexEvents,
network,
subgraphName,
contractName: contractName || DEFAULT_CONTRACT_NAME,
node,
startBlock,
spkgPath,
skipInstall,
skipGit,
ipfsUrl: ipfs,
},
{ commands, addContract: false },
);
// Exit with success
return this.exit(0);
}
if (fromExample) {
const answers = await processFromExampleInitForm.bind(this)({
subgraphName,
directory,
});
if (!answers) {
this.exit(1);
}
await initSubgraphFromExample.bind(this)(
{
fromExample,
subgraphName: answers.subgraphName,
directory: answers.directory,
skipInstall,
skipGit,
},
{ commands },
);
} else {
// Otherwise, take the user through the interactive form
const answers = await processInitForm.bind(this)({
abi,
abiPath,
directory,
source: fromContract,
indexEvents,
fromExample,
subgraphName,
contractName,
startBlock,
spkgPath,
ipfsUrl: ipfs,
});
if (!answers) {
this.exit(1);
}
await initSubgraphFromContract.bind(this)(
{
protocolInstance: answers.protocolInstance,
subgraphName: answers.subgraphName,
directory: answers.directory,
abi: answers.abi,
network: answers.network,
source: answers.source,
indexEvents: answers.indexEvents,
contractName: answers.contractName || DEFAULT_CONTRACT_NAME,
node,
startBlock: answers.startBlock,
spkgPath: answers.spkgPath,
skipInstall,
skipGit,
ipfsUrl: answers.ipfs,
},
{ commands, addContract: true },
);
if (answers.cleanup) {
answers.cleanup();
}
}
// Exit with success
this.exit(0);
}
}
async function processFromExampleInitForm(
this: InitCommand,
{
directory: initDirectory,
subgraphName: initSubgraphName,
}: {
directory?: string;
subgraphName?: string;
},
): Promise<
| {
subgraphName: string;
directory: string;
}
| undefined
> {
try {
const { subgraphName } = await prompt.ask<{ subgraphName: string }>([
{
type: 'input',
name: 'subgraphName',
message: 'Subgraph slug',
initial: initSubgraphName,
},
]);
const { directory } = await prompt.ask<{ directory: string }>([
{
type: 'input',
name: 'directory',
message: 'Directory to create the subgraph in',
initial: () => initDirectory || getSubgraphBasename(subgraphName),
},
]);
return {
subgraphName,
directory,
};
} catch (e) {
this.error(e, { exit: 1 });
}
}
async function processInitForm(
this: InitCommand,
{
abi: initAbi,
abiPath: initAbiPath,
directory: initDirectory,
source: initContract,
indexEvents: initIndexEvents,
fromExample: initFromExample,
subgraphName: initSubgraphName,
contractName: initContractName,
startBlock: initStartBlock,
spkgPath: initSpkgPath,
ipfsUrl,
}: {
abi: EthereumABI;
abiPath?: string;
directory?: string;
source?: string;
indexEvents: boolean;
fromExample?: string | boolean;
subgraphName?: string;
contractName?: string;
startBlock?: string;
spkgPath?: string;
ipfsUrl?: string;
},
): Promise<
| {
abi: EthereumABI;
protocolInstance: Protocol;
subgraphName: string;
directory: string;
network: string;
source: string;
indexEvents: boolean;
contractName: string;
startBlock: string;
fromExample: boolean;
spkgPath: string | undefined;
ipfs: string;
cleanup: (() => void) | undefined;
}
| undefined
> {
try {
const registry = await loadRegistry();
const contractService = new ContractService(registry);
const networks = sortWithPriority(
registry.networks,
n => n.issuanceRewards,
(a, b) => registry.networks.indexOf(a) - registry.networks.indexOf(b),
);
const networkToChoice = (n: Network) => ({
name: n.id,
value: `${n.id}:${n.shortName}:${n.fullName}`.toLowerCase(),
hint: `· ${n.id}`,
message: n.fullName,
});
const formatChoices = (choices: ReturnType<typeof networkToChoice>[]) => {
const shown = choices.slice(0, 20);
const remaining = networks.length - shown.length;
if (remaining == 0) return shown;
if (shown.length === choices.length) {
shown.push({
name: 'N/A',
value: '',
hint: '· other network not on the list',
message: `Other`,
});
}
return [
...shown,
{
name: ``,
disabled: true,
hint: '',
message: `< ${remaining} more - type to filter >`,
},
];
};
let network: Network = networks[0];
let protocolInstance: Protocol = new Protocol('ethereum');
let isComposedSubgraph = false;
let isSubstreams = false;
let subgraphName = initSubgraphName ?? '';
let directory = initDirectory;
let ipfsNode: string = '';
let source = initContract;
let contractName = initContractName;
let abiFromFile: EthereumABI | undefined = undefined;
let abiFromApi: EthereumABI | undefined = undefined;
let startBlock: string | undefined = undefined;
let spkgPath: string | undefined;
let spkgCleanup: (() => void) | undefined;
let indexEvents = initIndexEvents;
const promptManager = new PromptManager();
promptManager.addStep({
type: 'autocomplete',
name: 'networkId',
required: true,
message: 'Network',
choices: formatChoices(networks.map(networkToChoice)),
format: value => {
const network = networks.find(n => n.id === value);
return network
? `${network.fullName}${print.colors.muted(` · ${network.id} · ${network.explorerUrls?.[0] ?? ''}`)}`
: value;
},
suggest: (input, _) =>
formatChoices(
networks
.map(networkToChoice)
.filter(({ value }) => (value ?? '').includes(input.toLowerCase())),
),
validate: value =>
value === 'N/A' || networks.find(n => n.id === value) ? true : 'Pick a network',
result: value => {
initDebugger.extend('processInitForm')('networkId: %O', value);
const foundNetwork = networks.find(n => n.id === value);
if (!foundNetwork) {
this.log(`
The chain list is populated from the Networks Registry:
https://github.com/graphprotocol/networks-registry
To add a chain to the registry you can create an issue or submit a PR`);
process.exit(0);
}
network = foundNetwork;
promptManager.setOptions('protocol', {
choices: [
{
message: 'Smart contract',
hint: '· default',
name: network.graphNode?.protocol ?? '',
value: 'contract',
},
{ message: 'Substreams', name: 'substreams', value: 'substreams' },
// { message: 'Subgraph', name: 'subgraph', value: 'subgraph' },
].filter(({ name }) => name),
});
return value;
},
});
promptManager.addStep({
type: 'select',
name: 'protocol',
message: 'Source',
choices: [],
validate: name => {
if (name === 'arweave') {
return 'Arweave are only supported via substreams';
}
if (name === 'cosmos') {
return 'Cosmos chains are only supported via substreams';
}
return true;
},
format: protocol => {
switch (protocol) {
case '':
return '';
case 'substreams':
return 'Substreams';
case 'subgraph':
return 'Subgraph';
default:
return `Smart Contract${print.colors.muted(` · ${protocol}`)}`;
}
},
result: protocol => {
protocolInstance = new Protocol(protocol);
isComposedSubgraph = protocolInstance.isComposedSubgraph();
isSubstreams = protocolInstance.isSubstreams();
initDebugger.extend('processInitForm')('protocol: %O', protocol);
return protocol;
},
});
promptManager.addStep({
type: 'input',
name: 'subgraphName',
message: 'Subgraph slug',
initial: initSubgraphName,
validate: value => value.length > 0 || 'Subgraph slug must not be empty',
result: value => {
initDebugger.extend('processInitForm')('subgraphName: %O', value);
subgraphName = value;
return value;
},
});
promptManager.addStep({
type: 'input',
name: 'directory',
message: 'Directory to create the subgraph in',
initial: () => initDirectory || getSubgraphBasename(subgraphName),
validate: value => value.length > 0 || 'Directory must not be empty',
result: value => {
directory = value;
initDebugger.extend('processInitForm')('directory: %O', value);
return value;
},
});
promptManager.addStep({
type: 'input',
name: 'source',
message: () =>
isComposedSubgraph
? 'Source subgraph deployment ID'
: `Contract ${protocolInstance.getContract()?.identifierName()}`,
skip: () =>
initFromExample !== undefined ||
isSubstreams ||
(!protocolInstance.hasContract() && !isComposedSubgraph),
initial: initContract,
validate: async (value: string) => {
if (isComposedSubgraph) {
return value.startsWith('Qm') ? true : 'Subgraph deployment ID must start with Qm';
}
if (initFromExample !== undefined || !protocolInstance.hasContract()) {
return true;
}
const { valid, error } = validateContract(value, protocolInstance.getContract()!);
return valid ? true : error;
},
result: async (address: string) => {
initDebugger.extend('processInitForm')("source: '%s'", address);
if (
initFromExample !== undefined ||
initAbiPath ||
protocolInstance.name !== 'ethereum' // we can only validate against Etherscan API
) {
source = address;
return address;
}
const sourcifyContractInfo = await contractService.getFromSourcify(
EthereumABI,
network.id,
address,
);
if (sourcifyContractInfo) {
initStartBlock ??= sourcifyContractInfo.startBlock;
initContractName ??= sourcifyContractInfo.name;
initAbi ??= sourcifyContractInfo.abi;
initDebugger.extend('processInitForm')(
"infoFromSourcify: '%s'/'%s'",
initStartBlock,
initContractName,
);
}
// If ABI is not provided, try to fetch it from Etherscan API
let implAddress: string | undefined = undefined;
if (protocolInstance.hasABIs() && !initAbi) {
abiFromApi = await retryWithPrompt(() =>
withSpinner(
'Fetching ABI from contract API...',
'Failed to fetch ABI',
'Warning fetching ABI',
() => contractService.getABI(protocolInstance.getABI(), network.id, address),
),
);
initDebugger.extend('processInitForm')("ABI: '%s'", abiFromApi?.name);
} else {
abiFromApi = initAbi;
}
if (abiFromApi) {
const { implementationAbi, implementationAddress } = await checkForProxy(
contractService,
network.id,
address,
abiFromApi,
);
if (implementationAddress) {
implAddress = implementationAddress;
abiFromApi = implementationAbi!;
initDebugger.extend('processInitForm')(
"Impl ABI: '%s', Impl Address: '%s'",
abiFromApi?.name,
implAddress,
);
}
}
// If startBlock is not provided, try to fetch it from Etherscan API
if (!initStartBlock) {
startBlock = await retryWithPrompt(() =>
withSpinner(
'Fetching start block from contract API...',
'Failed to fetch start block',
'Warning fetching start block',
() => contractService.getStartBlock(network.id, implAddress ?? address),
),
);
initDebugger.extend('processInitForm')("startBlockFromEtherscan: '%s'", startBlock);
}
// If contract name is not provided, try to fetch it from Etherscan API
if (!initContractName) {
contractName = await retryWithPrompt(() =>
withSpinner(
'Fetching contract name from contract API...',
'Failed to fetch contract name',
'Warning fetching contract name',
() => contractService.getContractName(network.id, implAddress ?? address),
),
);
initDebugger.extend('processInitForm')("contractNameFromEtherscan: '%s'", contractName);
}
source = address;
return address;
},
});
promptManager.addStep({
type: 'input',
name: 'ipfs',
message: `IPFS node to use for fetching subgraph manifest`,
initial: ipfsUrl,
skip: () => !isComposedSubgraph,
result: value => {
ipfsNode = value;
initDebugger.extend('processInitForm')('ipfs: %O', value);
return value;
},
});
promptManager.addStep({
type: 'input',
name: 'spkg',
message: 'Substreams SPKG (local path, IPFS hash, or URL)',
initial: () => initSpkgPath,
skip: () => !isSubstreams || !!initSpkgPath,
validate: async value => {
if (!isSubstreams || !!initSpkgPath) return true;
return await withSpinner(
`Resolving Substreams SPKG file`,
`Failed to resolve SPKG file`,
`Warnings while resolving SPKG file`,
async () => {
try {
const { path, cleanup } = await resolveFile(value, 'substreams.spkg', 10_000);
spkgPath = path;
spkgCleanup = cleanup;
initDebugger.extend('processInitForm')('spkgPath: %O', path);
return true;
} catch (e) {
return e.message;
}
},
);
},
});
promptManager.addStep({
type: 'input',
name: 'abiFromFile',
message: 'ABI file (path)',
initial: initAbiPath,
skip: () =>
!protocolInstance.hasABIs() ||
initFromExample !== undefined ||
abiFromApi !== undefined ||
isSubstreams ||
!!initAbiPath ||
isComposedSubgraph,
validate: async (value: string) => {
if (
initFromExample ||
abiFromApi ||
!protocolInstance.hasABIs() ||
isSubstreams ||
isComposedSubgraph
) {
return true;
}
const ABI = protocolInstance.getABI();
if (initAbiPath) value = initAbiPath;
try {
loadAbiFromFile(ABI, value);
return true;
} catch (e) {
return e.message;
}
},
result: async (value: string) => {
initDebugger.extend('processInitForm')('abiFromFile: %O', value);
if (initFromExample || abiFromApi || !protocolInstance.hasABIs() || isComposedSubgraph) {
return null;
}
const ABI = protocolInstance.getABI();
if (initAbiPath) value = initAbiPath;
try {
abiFromFile = loadAbiFromFile(ABI, value);
return value;
} catch (e) {
return e.message;
}
},
});
promptManager.addStep({
type: 'input',
name: 'startBlock',
message: 'Start block',
initial: () => initStartBlock || startBlock || '0',
skip: () => initFromExample !== undefined || isSubstreams,
validate: value =>
initFromExample !== undefined ||
isSubstreams ||
parseInt(value) >= 0 ||
'Invalid start block',
result: value => {
startBlock = value;
initDebugger.extend('processInitForm')('startBlock: %O', value);
return value;
},
});
promptManager.addStep({
type: 'input',
name: 'contractName',
message: 'Contract name',
initial: () => initContractName || contractName || 'Contract',
skip: () => initFromExample !== undefined || !protocolInstance.hasContract() || isSubstreams,
validate: value =>
initFromExample !== undefined ||
!protocolInstance.hasContract() ||
isSubstreams ||
value.length > 0 ||
'Contract name must not be empty',
result: value => {
contractName = value;
initDebugger.extend('processInitForm')('contractName: %O', value);
return value;
},
});
promptManager.addStep({
type: 'confirm',
name: 'indexEvents',
message: 'Index contract events as entities',
initial: true,
skip: () => !!initIndexEvents || isSubstreams || isComposedSubgraph,
result: value => {
indexEvents = String(value) === 'true';
initDebugger.extend('processInitForm')('indexEvents: %O', indexEvents);
return value;
},
});
await promptManager.executeInteractive();
return {
abi: (abiFromApi || abiFromFile)!,
protocolInstance,
subgraphName,
directory: directory!,
startBlock: startBlock!,
fromExample: !!initFromExample,
network: network.id,
contractName: contractName!,
source: source!,
indexEvents,
ipfs: ipfsNode,
spkgPath,
cleanup: spkgCleanup,
};
} catch (e) {
this.error(e, { exit: 1 });
}
}
const loadAbiFromFile = (ABI: typeof EthereumABI, filename: string) => {
const exists = 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 ABI.load('Contract', filename);
}
};
// Inspired from: https://github.com/graphprotocol/graph-tooling/issues/1450#issuecomment-1713992618
async function isInRepo() {
try {
const result = await system.run('git rev-parse --is-inside-work-tree');
// It seems like we are returning "true\n" instead of "true".
// Don't think it is great idea to check for new line character here.
// So best to just check if the result includes "true".
return result.includes('true');
} catch (err) {
if (err.stderr.includes('not a git repository')) {
return false;
}
throw Error(err.stderr);
}
}
const initRepository = async (directory: string) =>
await withSpinner(
`Initialize subgraph repository`,
`Failed to initialize subgraph repository`,
`Warnings while initializing subgraph repository`,
async () => {
// Remove .git dir in --from-example mode; in --from-contract, we're
// starting from an empty directory
const gitDir = path.join(directory, '.git');
if (filesystem.exists(gitDir)) {
filesystem.remove(gitDir);
}
if (await isInRepo()) {
await system.run('git add --all', { cwd: directory });
await system.run('git commit -m "Initialize subgraph"', {
cwd: directory,
});
} else {
await system.run('git init', { cwd: directory });
await system.run('git add --all', { cwd: directory });
await system.run('git commit -m "Initial commit"', {
cwd: directory,
});
}
return true;
},
);
const installDependencies = async (
directory: string,
commands: {
link: string;
install: string;
},
) =>
await withSpinner(
`Install dependencies with ${commands.install}`,
`Failed to install dependencies`,
`Warnings while installing dependencies`,
async () => {
if (process.env.GRAPH_CLI_TESTS) {
await system.run(commands.link, { cwd: directory });
}
await system.run(commands.install, { cwd: directory });
return true;
},
);
const runCodegen = async (directory: string, codegenCommand: string) =>
await withSpinner(
`Generate ABI and schema types with ${codegenCommand}`,
`Failed to generate code from ABI and GraphQL schema`,
`Warnings while generating code from ABI and GraphQL schema`,
async () => {
await system.run(codegenCommand, { cwd: directory });
return true;
},
);
function printNextSteps(
this: InitCommand,
{ subgraphName, directory }: { subgraphName: string; directory: string },
{
commands,
}: {
commands: {
install: string;
codegen: string;
deploy: string;
};
},
) {
const relativeDir = path.relative(process.cwd(), directory);
// Print instructions
this.log(
`
Subgraph ${subgraphName} created in ${relativeDir}
`,
);
this.log(`Next steps:
1. Run \`graph auth\` to authenticate with your deploy key.
2. Type \`cd ${relativeDir}\` to enter the subgraph.
3. Run \`${commands.deploy}\` to deploy the subgraph.
Make sure to visit the documentation on https://thegraph.com/docs/ for further information.`);
}
async function initSubgraphFromExample(
this: InitCommand,
{
fromExample,
subgraphName,
directory,
skipInstall,
skipGit,
}: {
fromExample: string | boolean;
subgraphName: string;
directory: string;