-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathcodegen.rs
More file actions
972 lines (856 loc) · 31.1 KB
/
Copy pathcodegen.rs
File metadata and controls
972 lines (856 loc) · 31.1 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
//! Code generation command.
//!
//! Generates AssemblyScript types for a subgraph from:
//! - GraphQL schema (entity classes)
//! - Contract ABIs (event and call bindings)
//! - Data source templates
//! - Subgraph data sources (fetches schema from IPFS)
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, anyhow};
use clap::Parser;
use graph::abi::JsonAbi;
use graphql_tools::parser::schema as gql;
use semver::Version;
use crate::abi::preprocess_abi_json;
use crate::codegen::{
AbiCodeGenerator, Class, GENERATED_FILE_NOTE, ModuleImports, SchemaCodeGenerator,
Template as CodegenTemplate, TemplateCodeGenerator, TemplateKind,
};
use crate::formatter::try_format_typescript;
use crate::manifest::{DataSource, Manifest, Template, load_manifest, resolve_path};
use crate::migrations;
use crate::output::{Step, step};
use crate::services::IpfsClient;
use crate::validation::{
format_manifest_errors, format_schema_errors, validate_manifest_files, validate_schema,
};
use crate::watch::watch_and_run;
/// Default IPFS URL.
const DEFAULT_IPFS_URL: &str = "https://api.thegraph.com/ipfs/api/v0";
#[derive(Clone, Debug, Parser)]
#[clap(about = "Generate AssemblyScript types for a subgraph")]
pub struct CodegenOpt {
/// Path to the subgraph manifest
#[clap(default_value = "subgraph.yaml")]
pub manifest: PathBuf,
/// Output directory for generated types
#[clap(short = 'o', long, default_value = "generated/")]
pub output_dir: PathBuf,
/// Skip subgraph migrations
#[clap(long)]
pub skip_migrations: bool,
/// Regenerate types when subgraph files change
#[clap(short = 'w', long)]
pub watch: bool,
/// IPFS node to use for fetching subgraph data
#[clap(short = 'i', long, default_value = DEFAULT_IPFS_URL)]
pub ipfs: String,
}
/// Run the codegen command.
pub async fn run_codegen(opt: CodegenOpt) -> Result<()> {
if opt.watch {
watch_and_generate(&opt).await
} else {
generate_types(&opt).await
}
}
/// Watch subgraph files and regenerate types on changes.
async fn watch_and_generate(opt: &CodegenOpt) -> Result<()> {
// Get files to watch (need to load manifest first)
let manifest = load_manifest(&opt.manifest)?;
let files_to_watch = get_files_to_watch(&opt.manifest, &manifest);
watch_and_run(
files_to_watch,
"Watching subgraph files for changes...",
|| generate_types(opt),
)
.await
}
/// Get the list of files to watch for changes.
fn get_files_to_watch(manifest_path: &Path, manifest: &Manifest) -> Vec<PathBuf> {
let mut files = vec![manifest_path.to_path_buf()];
// Add schema file
if let Some(schema_path) = &manifest.schema {
files.push(resolve_path(manifest_path, schema_path));
}
// Add ABI files
for ds in &manifest.data_sources {
for abi in &ds.abis {
files.push(resolve_path(manifest_path, &abi.file));
}
}
files
}
/// Generate all types for the subgraph.
async fn generate_types(opt: &CodegenOpt) -> Result<()> {
// Apply migrations unless skipped
if !opt.skip_migrations {
migrations::apply_migrations(&opt.manifest)?;
}
// Load the subgraph manifest
let manifest = load_manifest(&opt.manifest)?;
// Validate manifest file references (schema, mappings, ABIs exist and are valid)
let source_dir = crate::manifest::manifest_dir(&opt.manifest).to_path_buf();
let manifest_errors = validate_manifest_files(&manifest, &source_dir);
if !manifest_errors.is_empty() {
eprintln!(
"Manifest validation errors:\n{}",
format_manifest_errors(&manifest_errors)
);
return Err(anyhow!(
"Manifest validation failed with {} error(s)",
manifest_errors.len()
));
}
// Create output directory
fs::create_dir_all(&opt.output_dir)
.with_context(|| format!("Failed to create output directory: {:?}", opt.output_dir))?;
// Generate schema types
if let Some(schema_path) = manifest.schema.as_ref() {
let schema_path = resolve_path(&opt.manifest, schema_path);
let _ = generate_schema_types(&schema_path, &opt.output_dir, &manifest.spec_version)?;
}
// Generate ABI types for each data source
for ds in &manifest.data_sources {
for abi in &ds.abis {
let abi_path = resolve_path(&opt.manifest, &abi.file);
// Output to: <output_dir>/<DataSourceName>/<AbiName>.ts
let ds_output_dir = opt.output_dir.join(&ds.name);
generate_abi_types(&abi.name, &abi_path, &ds_output_dir)?;
}
}
// Generate template types
if !manifest.templates.is_empty() {
generate_template_types(&manifest.templates, &opt.output_dir)?;
// Generate ABI types for templates
for template in &manifest.templates {
for abi in &template.abis {
let abi_path = resolve_path(&opt.manifest, &abi.file);
// Output to: <output_dir>/templates/<TemplateName>/<AbiName>.ts
let template_output_dir = opt.output_dir.join("templates").join(&template.name);
generate_abi_types(&abi.name, &abi_path, &template_output_dir)?;
}
}
}
// Generate types for subgraph data sources
let subgraph_sources: Vec<&DataSource> = manifest
.data_sources
.iter()
.filter(|ds| ds.is_subgraph_source())
.collect();
if !subgraph_sources.is_empty() {
generate_subgraph_source_types(&subgraph_sources, &opt.output_dir, &opt.ipfs).await?;
}
step(Step::Done, "Types generated successfully");
Ok(())
}
/// Generate types from the GraphQL schema.
///
/// Returns Ok(true) if types were generated successfully, Ok(false) if schema
/// validation failed and schema.ts was skipped.
fn generate_schema_types(
schema_path: &Path,
output_dir: &Path,
spec_version: &Version,
) -> Result<bool> {
step(
Step::Load,
&format!("Load GraphQL schema from {}", schema_path.display()),
);
// Run graph-node schema validation
let validation_errors = validate_schema(schema_path, spec_version)?;
if !validation_errors.is_empty() {
eprintln!(
"Schema validation errors:\n{}",
format_schema_errors(&validation_errors)
);
return Err(anyhow!(
"Schema validation failed with {} error(s)",
validation_errors.len()
));
}
let schema_str = fs::read_to_string(schema_path)
.with_context(|| format!("Failed to read schema file: {:?}", schema_path))?;
let ast: gql::Document<'_, String> = gql::parse_schema(&schema_str)
.map_err(|e| anyhow::anyhow!("Failed to parse GraphQL schema: {}", e))?;
step(Step::Generate, "Generate types for GraphQL schema");
let generator = match SchemaCodeGenerator::new(&ast) {
Ok(generator) => generator,
Err(e) => {
// Schema validation failed - skip schema.ts generation but don't fail
eprintln!("Warning: {}", e);
return Ok(false);
}
};
let imports = generator.generate_module_imports();
let entity_classes = generator.generate_types(true);
let derived_loaders = generator.generate_derived_loaders();
// Combine entity classes with derived loaders
let all_classes: Vec<Class> = entity_classes.into_iter().chain(derived_loaders).collect();
let code = generate_file(&imports, &all_classes);
let formatted = try_format_typescript(&code);
let output_file = output_dir.join("schema.ts");
step(
Step::Write,
&format!("Write types to {}", output_file.display()),
);
fs::write(&output_file, formatted)
.with_context(|| format!("Failed to write schema types: {:?}", output_file))?;
Ok(true)
}
/// Generate types from an ABI file.
fn generate_abi_types(name: &str, abi_path: &Path, output_dir: &Path) -> Result<()> {
step(Step::Load, &format!("Load ABI from {}", abi_path.display()));
let abi_str = fs::read_to_string(abi_path)
.with_context(|| format!("Failed to read ABI file: {:?}", abi_path))?;
// Preprocess ABI to normalize format and add default event param names
let processed_abi = preprocess_abi_json(&abi_str)
.with_context(|| format!("Failed to preprocess ABI: {:?}", abi_path))?;
let contract: JsonAbi = serde_json::from_str(&processed_abi)
.with_context(|| format!("Failed to parse ABI JSON: {:?}", abi_path))?;
step(Step::Generate, &format!("Generate types for ABI {}", name));
let generator = AbiCodeGenerator::new(contract, name);
let imports = generator.generate_module_imports();
let classes = generator.generate_types();
let code = generate_file(&imports, &classes);
let formatted = try_format_typescript(&code);
// Create output directory (for data source subdirectory)
fs::create_dir_all(output_dir)
.with_context(|| format!("Failed to create output directory: {:?}", output_dir))?;
let output_file = output_dir.join(format!("{}.ts", name));
step(
Step::Write,
&format!("Write types to {}", output_file.display()),
);
fs::write(&output_file, formatted)
.with_context(|| format!("Failed to write ABI types: {:?}", output_file))?;
Ok(())
}
/// Generate types for data source templates.
fn generate_template_types(templates: &[Template], output_dir: &Path) -> Result<()> {
step(Step::Generate, "Generate types for data source templates");
let codegen_templates: Vec<CodegenTemplate> = templates
.iter()
.filter_map(|t| {
TemplateKind::from_str_kind(&t.kind).map(|kind| CodegenTemplate::new(&t.name, kind))
})
.collect();
if codegen_templates.is_empty() {
return Ok(());
}
let generator = TemplateCodeGenerator::new(codegen_templates);
let imports = generator.generate_module_imports();
let classes = generator.generate_types();
let code = generate_file(&imports, &classes);
let formatted = try_format_typescript(&code);
let output_file = output_dir.join("templates.ts");
step(
Step::Write,
&format!("Write types to {}", output_file.display()),
);
fs::write(&output_file, formatted)
.with_context(|| format!("Failed to write template types: {:?}", output_file))?;
Ok(())
}
/// Generate types for subgraph data sources.
///
/// For each subgraph data source, this fetches the referenced subgraph's schema
/// from IPFS and generates entity types (without store methods).
async fn generate_subgraph_source_types(
subgraph_sources: &[&DataSource],
output_dir: &Path,
ipfs_url: &str,
) -> Result<()> {
step(Step::Generate, "Generate types for subgraph data sources");
let ipfs_client = IpfsClient::new(ipfs_url)?;
// Validate that all subgraph data source names are unique
let mut seen_names = std::collections::HashSet::new();
for source in subgraph_sources {
if !seen_names.insert(&source.name) {
return Err(anyhow!(
"Duplicate subgraph data source name '{}'. Each subgraph data source must have a unique name.",
source.name
));
}
}
for source in subgraph_sources {
// source_address is guaranteed to be Some because of is_subgraph_source() filter
let address = source.source_address.as_ref().unwrap();
step(
Step::Load,
&format!("Fetch schema for subgraph {} ({})", source.name, address),
);
// Fetch schema from IPFS using block_in_place to allow blocking in async context
let schema_str = ipfs_client.fetch_subgraph_schema(address).await?;
// Parse the schema
let ast: gql::Document<'_, String> = gql::parse_schema(&schema_str)
.map_err(|e| anyhow::anyhow!("Failed to parse subgraph schema: {}", e))?;
step(
Step::Generate,
&format!("Generate types for subgraph {} ({})", source.name, address),
);
// Generate entity types WITHOUT store methods (false = no store methods)
let generator = match SchemaCodeGenerator::new(&ast) {
Ok(generator) => generator,
Err(e) => {
eprintln!(
"Warning: Failed to create schema generator for subgraph {} ({}): {}",
source.name, address, e
);
continue;
}
};
let imports = generator.generate_module_imports();
// Pass false to generate entities without store methods
let entity_classes = generator.generate_types(false);
let code = generate_file(&imports, &entity_classes);
let formatted = try_format_typescript(&code);
// Output to: <output_dir>/subgraph-<NAME>.ts
// Using name instead of IPFS hash for stable file names
let output_file = output_dir.join(format!("subgraph-{}.ts", source.name));
step(
Step::Write,
&format!("Write types to {}", output_file.display()),
);
fs::write(&output_file, formatted)
.with_context(|| format!("Failed to write subgraph types: {:?}", output_file))?;
}
Ok(())
}
/// Generate a TypeScript file from imports and classes.
fn generate_file(imports: &[ModuleImports], classes: &[Class]) -> String {
let mut output = String::new();
// Add generated file note
output.push_str(GENERATED_FILE_NOTE);
output.push('\n');
// Add imports
for import in imports {
output.push_str(&import.to_string());
output.push('\n');
}
// Add classes
for class in classes {
output.push_str(&class.to_string());
}
output
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
#[test]
fn test_generate_file() {
let imports = vec![ModuleImports::new(
vec!["Entity".to_string()],
"@graphprotocol/graph-ts",
)];
let classes = vec![];
let output = generate_file(&imports, &classes);
assert!(output.contains("AUTOGENERATED"));
assert!(output.contains("import { Entity }"));
}
/// Test that codegen generates types in the correct directory structure.
///
/// TS CLI generates:
/// - generated/schema.ts
/// - generated/<DataSourceName>/<AbiName>.ts
/// - generated/templates/<TemplateName>/<AbiName>.ts
#[tokio::test]
async fn test_codegen_directory_structure() {
let temp_dir = TempDir::new().unwrap();
let project_dir = temp_dir.path();
let output_dir = project_dir.join("generated");
// Create manifest
let manifest_content = r#"
specVersion: 0.0.4
schema:
file: ./schema.graphql
dataSources:
- kind: ethereum/contract
name: ExampleSubgraph
network: mainnet
source:
abi: ExampleContract
mapping:
kind: ethereum/events
apiVersion: 0.0.5
language: wasm/assemblyscript
file: ./mapping.ts
entities:
- MyEntity
abis:
- name: ExampleContract
file: ./Abi.json
eventHandlers:
- event: ExampleEvent(string)
handler: handleExampleEvent
"#;
fs::write(project_dir.join("subgraph.yaml"), manifest_content).unwrap();
// Create schema
let schema_content = r#"
type MyEntity @entity(immutable: true) {
id: ID!
x: BigDecimal!
}
"#;
fs::write(project_dir.join("schema.graphql"), schema_content).unwrap();
// Create ABI
let abi_content = r#"[
{
"type": "event",
"name": "ExampleEvent",
"anonymous": false,
"inputs": [{ "type": "string", "name": "param0", "indexed": false }]
}
]"#;
fs::write(project_dir.join("Abi.json"), abi_content).unwrap();
// Create mapping (empty is fine)
fs::write(project_dir.join("mapping.ts"), "").unwrap();
// Run codegen
let opt = CodegenOpt {
manifest: project_dir.join("subgraph.yaml"),
output_dir: output_dir.clone(),
skip_migrations: true,
watch: false,
ipfs: "https://api.thegraph.com/ipfs/api/v0".to_string(),
};
generate_types(&opt).await.unwrap();
// Verify directory structure
assert!(
output_dir.join("schema.ts").exists(),
"schema.ts should exist at root of output dir"
);
assert!(
output_dir.join("ExampleSubgraph").is_dir(),
"ExampleSubgraph directory should exist"
);
assert!(
output_dir
.join("ExampleSubgraph/ExampleContract.ts")
.exists(),
"ExampleContract.ts should be in ExampleSubgraph subdirectory"
);
// Verify schema.ts content
let schema_ts = fs::read_to_string(output_dir.join("schema.ts")).unwrap();
assert!(
schema_ts.contains("export class MyEntity"),
"schema.ts should contain MyEntity class"
);
assert!(
schema_ts.contains("AUTOGENERATED"),
"schema.ts should have autogenerated note"
);
// Verify ABI types content
let abi_ts =
fs::read_to_string(output_dir.join("ExampleSubgraph/ExampleContract.ts")).unwrap();
assert!(
abi_ts.contains("export class ExampleEvent"),
"ABI types should contain ExampleEvent class"
);
assert!(
abi_ts.contains("export class ExampleContract"),
"ABI types should contain ExampleContract class"
);
}
/// Snapshot test for schema codegen output format.
///
/// Tests that schema.ts matches the expected TS CLI format for a simple entity.
/// This helps ensure byte-for-byte compatibility with the graph-cli.
#[tokio::test]
async fn test_schema_codegen_snapshot() {
let temp_dir = TempDir::new().unwrap();
let project_dir = temp_dir.path();
let output_dir = project_dir.join("generated");
// Create manifest
let manifest_content = r#"
specVersion: 0.0.4
schema:
file: ./schema.graphql
dataSources:
- kind: ethereum/contract
name: TestDataSource
network: mainnet
source:
abi: TestContract
mapping:
kind: ethereum/events
apiVersion: 0.0.5
language: wasm/assemblyscript
file: ./mapping.ts
entities:
- MyEntity
abis:
- name: TestContract
file: ./TestContract.json
eventHandlers:
- event: Transfer(address,address,uint256)
handler: handleTransfer
"#;
fs::write(project_dir.join("subgraph.yaml"), manifest_content).unwrap();
// Create a simple schema with BigDecimal field
let schema_content = r#"
type MyEntity @entity(immutable: true) {
id: ID!
x: BigDecimal!
}
"#;
fs::write(project_dir.join("schema.graphql"), schema_content).unwrap();
fs::write(project_dir.join("mapping.ts"), "").unwrap();
let abi = r#"[{
"type": "event",
"name": "Transfer",
"anonymous": false,
"inputs": [
{"name": "from", "type": "address", "indexed": true},
{"name": "to", "type": "address", "indexed": true},
{"name": "value", "type": "uint256", "indexed": false}
]
}]"#;
fs::write(project_dir.join("TestContract.json"), abi).unwrap();
// Run codegen
let opt = CodegenOpt {
manifest: project_dir.join("subgraph.yaml"),
output_dir: output_dir.clone(),
skip_migrations: true,
watch: false,
ipfs: "https://api.thegraph.com/ipfs/api/v0".to_string(),
};
generate_types(&opt).await.unwrap();
// Read generated schema.ts
let schema_ts = fs::read_to_string(output_dir.join("schema.ts")).unwrap();
// Verify key parts of the output that must match TS CLI format
assert!(
schema_ts.contains("// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY."),
"Should have standard autogenerated note"
);
assert!(schema_ts.contains("import {"), "Should have imports");
assert!(
schema_ts.contains("from \"@graphprotocol/graph-ts\""),
"Should import from @graphprotocol/graph-ts"
);
assert!(
schema_ts.contains("export class MyEntity extends Entity"),
"Should export MyEntity class extending Entity"
);
assert!(
schema_ts.contains("constructor(id: string)"),
"Should have constructor with id parameter"
);
assert!(
schema_ts.contains("save(): void"),
"Should have save method"
);
assert!(
schema_ts.contains("static loadInBlock(id: string): MyEntity | null"),
"Should have loadInBlock static method"
);
assert!(
schema_ts.contains("static load(id: string): MyEntity | null"),
"Should have load static method"
);
assert!(
schema_ts.contains("get id(): string"),
"Should have id getter"
);
assert!(
schema_ts.contains("set id(value: string)"),
"Should have id setter"
);
assert!(
schema_ts.contains("get x(): BigDecimal"),
"Should have x getter returning BigDecimal"
);
assert!(
schema_ts.contains("set x(value: BigDecimal)"),
"Should have x setter accepting BigDecimal"
);
// Verify the save method has correct entity type assertion
assert!(
schema_ts.contains("store.set(\"MyEntity\""),
"save() should call store.set with entity type name"
);
// Verify load methods use correct store methods
assert!(
schema_ts.contains("store.get(\"MyEntity\""),
"load() should call store.get with entity type name"
);
assert!(
schema_ts.contains("store.get_in_block(\"MyEntity\""),
"loadInBlock() should call store.get_in_block with entity type name"
);
}
/// Snapshot test for ABI codegen output format.
///
/// Tests that ABI types match the expected TS CLI format for events and contract class.
#[tokio::test]
async fn test_abi_codegen_snapshot() {
let temp_dir = TempDir::new().unwrap();
let project_dir = temp_dir.path();
let output_dir = project_dir.join("generated");
// Create manifest
let manifest_content = r#"
specVersion: 0.0.4
schema:
file: ./schema.graphql
dataSources:
- kind: ethereum/contract
name: ExampleSubgraph
network: mainnet
source:
abi: ExampleContract
mapping:
kind: ethereum/events
apiVersion: 0.0.5
language: wasm/assemblyscript
file: ./mapping.ts
entities:
- MyEntity
abis:
- name: ExampleContract
file: ./Abi.json
eventHandlers:
- event: ExampleEvent(string)
handler: handleExampleEvent
"#;
fs::write(project_dir.join("subgraph.yaml"), manifest_content).unwrap();
// Create schema
fs::write(
project_dir.join("schema.graphql"),
"type MyEntity @entity { id: ID! }",
)
.unwrap();
fs::write(project_dir.join("mapping.ts"), "").unwrap();
// Create ABI with event
let abi_content = r#"[
{
"type": "event",
"name": "ExampleEvent",
"anonymous": false,
"inputs": [{ "type": "string", "name": "param0", "indexed": false }]
}
]"#;
fs::write(project_dir.join("Abi.json"), abi_content).unwrap();
// Run codegen
let opt = CodegenOpt {
manifest: project_dir.join("subgraph.yaml"),
output_dir: output_dir.clone(),
skip_migrations: true,
watch: false,
ipfs: "https://api.thegraph.com/ipfs/api/v0".to_string(),
};
generate_types(&opt).await.unwrap();
// Read generated ABI types
let abi_ts =
fs::read_to_string(output_dir.join("ExampleSubgraph/ExampleContract.ts")).unwrap();
// Verify key parts of the output that must match TS CLI format
assert!(
abi_ts.contains("// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY."),
"Should have standard autogenerated note"
);
assert!(abi_ts.contains("import {"), "Should have imports");
assert!(
abi_ts.contains("from \"@graphprotocol/graph-ts\""),
"Should import from @graphprotocol/graph-ts"
);
// Event class
assert!(
abi_ts.contains("export class ExampleEvent extends ethereum.Event"),
"Should export event class extending ethereum.Event"
);
assert!(
abi_ts.contains("get params(): ExampleEvent__Params"),
"Event should have params getter"
);
// Params class
assert!(
abi_ts.contains("export class ExampleEvent__Params"),
"Should have params class"
);
assert!(
abi_ts.contains("_event: ExampleEvent"),
"Params should have _event field"
);
assert!(
abi_ts.contains("get param0(): string"),
"Params should have param0 getter"
);
// Contract class
assert!(
abi_ts.contains("export class ExampleContract extends ethereum.SmartContract"),
"Should export contract class extending ethereum.SmartContract"
);
assert!(
abi_ts.contains("static bind(address: Address): ExampleContract"),
"Contract should have static bind method"
);
}
/// Test that codegen handles a NEAR manifest: it parses `kind: near`,
/// generates schema types, and produces no ABI directories (NEAR has no
/// ABIs). This guards the schema-only codegen path for non-Ethereum
/// protocols.
#[tokio::test]
async fn test_codegen_near_schema_only() {
let temp_dir = TempDir::new().unwrap();
let project_dir = temp_dir.path();
let output_dir = project_dir.join("generated");
let manifest_content = r#"
specVersion: 0.0.5
schema:
file: ./schema.graphql
dataSources:
- kind: near
name: receipts
network: near-mainnet
source:
account: wnear.flux-dev
startBlock: 100
mapping:
apiVersion: 0.0.5
language: wasm/assemblyscript
entities:
- ExampleEntity
receiptHandlers:
- handler: handleReceipt
file: ./src/receipts.ts
"#;
fs::write(project_dir.join("subgraph.yaml"), manifest_content).unwrap();
let schema_content = r#"
type ExampleEntity @entity(immutable: true) {
id: Bytes!
count: BigInt!
}
"#;
fs::write(project_dir.join("schema.graphql"), schema_content).unwrap();
fs::create_dir_all(project_dir.join("src")).unwrap();
fs::write(project_dir.join("src/receipts.ts"), "").unwrap();
let opt = CodegenOpt {
manifest: project_dir.join("subgraph.yaml"),
output_dir: output_dir.clone(),
skip_migrations: true,
watch: false,
ipfs: "https://api.thegraph.com/ipfs/api/v0".to_string(),
};
generate_types(&opt).await.unwrap();
// Schema types are generated...
assert!(
output_dir.join("schema.ts").exists(),
"schema.ts should be generated for NEAR"
);
let schema_ts = fs::read_to_string(output_dir.join("schema.ts")).unwrap();
assert!(schema_ts.contains("export class ExampleEntity"));
// ...but no per-data-source ABI directory is created.
assert!(
!output_dir.join("receipts").exists(),
"NEAR data source must not produce an ABI directory"
);
}
/// Test that codegen fails when referenced ABI file does not exist.
///
/// Before Step 2, codegen did not validate the manifest. Now it calls
/// `validate_manifest()` which checks file existence, so a missing ABI
/// file is caught before codegen even starts generating types.
#[tokio::test]
async fn test_codegen_fails_on_missing_abi_file() {
let temp_dir = TempDir::new().unwrap();
let project_dir = temp_dir.path();
let output_dir = project_dir.join("generated");
// Manifest references an ABI file that doesn't exist
let manifest_content = r#"
specVersion: 0.0.4
schema:
file: ./schema.graphql
dataSources:
- kind: ethereum/contract
name: Token
network: mainnet
source:
abi: ERC20
mapping:
kind: ethereum/events
apiVersion: 0.0.5
language: wasm/assemblyscript
file: ./mapping.ts
entities:
- MyEntity
abis:
- name: ERC20
file: ./abis/ERC20.json
"#;
fs::write(project_dir.join("subgraph.yaml"), manifest_content).unwrap();
// Create schema and mapping, but NOT the ABI file
fs::write(
project_dir.join("schema.graphql"),
"type MyEntity @entity { id: ID! }",
)
.unwrap();
fs::write(project_dir.join("mapping.ts"), "").unwrap();
let opt = CodegenOpt {
manifest: project_dir.join("subgraph.yaml"),
output_dir,
skip_migrations: true,
watch: false,
ipfs: "https://api.thegraph.com/ipfs/api/v0".to_string(),
};
let result = generate_types(&opt).await;
assert!(
result.is_err(),
"Codegen should fail when ABI file is missing"
);
let err = format!("{:#}", result.unwrap_err());
assert!(
err.contains("validation failed"),
"Error should mention validation failure, got: {}",
err
);
}
/// Test that codegen fails when referenced schema file does not exist.
#[tokio::test]
async fn test_codegen_fails_on_missing_schema_file() {
let temp_dir = TempDir::new().unwrap();
let project_dir = temp_dir.path();
let output_dir = project_dir.join("generated");
// Manifest references a schema file that doesn't exist
let manifest_content = r#"
specVersion: 0.0.4
schema:
file: ./schema.graphql
dataSources:
- kind: ethereum/contract
name: Token
network: mainnet
source:
abi: ERC20
mapping:
kind: ethereum/events
apiVersion: 0.0.5
language: wasm/assemblyscript
file: ./mapping.ts
entities:
- MyEntity
abis: []
"#;
fs::write(project_dir.join("subgraph.yaml"), manifest_content).unwrap();
// Create mapping, but NOT the schema file
fs::write(project_dir.join("mapping.ts"), "").unwrap();
let opt = CodegenOpt {
manifest: project_dir.join("subgraph.yaml"),
output_dir,
skip_migrations: true,
watch: false,
ipfs: "https://api.thegraph.com/ipfs/api/v0".to_string(),
};
let result = generate_types(&opt).await;
assert!(
result.is_err(),
"Codegen should fail when schema file is missing"
);
let err = format!("{:#}", result.unwrap_err());
assert!(
err.contains("validation failed"),
"Error should mention validation failure, got: {}",
err
);
}
}