-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathmanifest.rs
1895 lines (1737 loc) · 51.6 KB
/
manifest.rs
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
use std::collections::HashMap;
use std::num::NonZeroU32;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use graph::blockchain::DataSource;
use graph::components::store::BLOCK_NUMBER_MAX;
use graph::data::store::scalar::Bytes;
use graph::data::store::Value;
use graph::data::subgraph::schema::SubgraphError;
use graph::data::subgraph::{
Prune, LATEST_VERSION, SPEC_VERSION_0_0_4, SPEC_VERSION_0_0_7, SPEC_VERSION_0_0_8,
SPEC_VERSION_0_0_9, SPEC_VERSION_1_0_0, SPEC_VERSION_1_2_0, SPEC_VERSION_1_3_0,
};
use graph::data_source::offchain::OffchainDataSourceKind;
use graph::data_source::{DataSourceEnum, DataSourceTemplate};
use graph::entity;
use graph::env::ENV_VARS;
use graph::prelude::web3::types::H256;
use graph::prelude::{
anyhow, async_trait, serde_yaml, tokio, BigDecimal, BigInt, DeploymentHash, Link, Logger,
SubgraphManifest, SubgraphManifestResolveError, SubgraphManifestValidationError, SubgraphStore,
UnvalidatedSubgraphManifest,
};
use graph::{
blockchain::NodeCapabilities as _,
components::link_resolver::{JsonValueStream, LinkResolver as LinkResolverTrait},
data::subgraph::SubgraphFeature,
};
use graph::semver::Version;
use graph_chain_ethereum::{BlockHandlerFilter, Chain, NodeCapabilities};
use test_store::LOGGER;
const GQL_SCHEMA: &str = r#"
type Thing @entity { id: ID! }
type TestEntity @entity { id: ID! }
"#;
const GQL_SCHEMA_FULLTEXT: &str = include_str!("full-text.graphql");
const SOURCE_SUBGRAPH_MANIFEST: &str = "
dataSources: []
schema:
file:
/: /ipfs/QmSourceSchema
specVersion: 1.3.0
";
const SOURCE_SUBGRAPH_SCHEMA: &str = "
type TestEntity @entity { id: ID! }
type User @entity { id: ID! }
type Profile @entity { id: ID! }
type TokenData @entity(timeseries: true) {
id: Int8!
timestamp: Timestamp!
amount: BigDecimal!
}
type TokenStats @aggregation(intervals: [\"hour\", \"day\"], source: \"TokenData\") {
id: Int8!
timestamp: Timestamp!
totalAmount: BigDecimal! @aggregate(fn: \"sum\", arg: \"amount\")
}
";
const MAPPING_WITH_IPFS_FUNC_WASM: &[u8] = include_bytes!("ipfs-on-ethereum-contracts.wasm");
const ABI: &str = "[{\"type\":\"function\", \"inputs\": [{\"name\": \"i\",\"type\": \"uint256\"}],\"name\":\"get\",\"outputs\": [{\"type\": \"address\",\"name\": \"o\"}]}]";
const FILE: &str = "{}";
const FILE_CID: &str = "bafkreigkhuldxkyfkoaye4rgcqcwr45667vkygd45plwq6hawy7j4rbdky";
#[derive(Default, Debug, Clone)]
struct TextResolver {
texts: HashMap<String, Vec<u8>>,
}
impl TextResolver {
fn add(&mut self, link: &str, text: &impl AsRef<[u8]>) {
self.texts.insert(link.to_owned(), text.as_ref().to_vec());
}
}
#[async_trait]
impl LinkResolverTrait for TextResolver {
fn with_timeout(&self, _timeout: Duration) -> Box<dyn LinkResolverTrait> {
Box::new(self.clone())
}
fn with_retries(&self) -> Box<dyn LinkResolverTrait> {
Box::new(self.clone())
}
async fn cat(&self, _logger: &Logger, link: &Link) -> Result<Vec<u8>, anyhow::Error> {
self.texts
.get(&link.link)
.ok_or(anyhow!("No text for {}", &link.link))
.map(Clone::clone)
}
async fn get_block(&self, _logger: &Logger, _link: &Link) -> Result<Vec<u8>, anyhow::Error> {
unimplemented!()
}
async fn json_stream(
&self,
_logger: &Logger,
_link: &Link,
) -> Result<JsonValueStream, anyhow::Error> {
unimplemented!()
}
}
async fn try_resolve_manifest(
text: &str,
max_spec_version: Version,
) -> Result<SubgraphManifest<graph_chain_ethereum::Chain>, anyhow::Error> {
let mut resolver = TextResolver::default();
let id = DeploymentHash::new("Qmmanifest").unwrap();
resolver.add(id.as_str(), &text);
resolver.add("/ipfs/Qmschema", &GQL_SCHEMA);
resolver.add("/ipfs/Qmabi", &ABI);
resolver.add("/ipfs/Qmmapping", &MAPPING_WITH_IPFS_FUNC_WASM);
resolver.add("/ipfs/QmSource", &SOURCE_SUBGRAPH_MANIFEST);
resolver.add("/ipfs/QmSource2", &SOURCE_SUBGRAPH_MANIFEST);
resolver.add("/ipfs/QmSourceSchema", &SOURCE_SUBGRAPH_SCHEMA);
resolver.add(FILE_CID, &FILE);
let resolver: Arc<dyn LinkResolverTrait> = Arc::new(resolver);
let raw = serde_yaml::from_str(text)?;
Ok(SubgraphManifest::resolve_from_raw(id, raw, &resolver, &LOGGER, max_spec_version).await?)
}
async fn resolve_manifest(
text: &str,
max_spec_version: Version,
) -> SubgraphManifest<graph_chain_ethereum::Chain> {
try_resolve_manifest(text, max_spec_version)
.await
.expect("Parsing simple manifest works")
}
async fn resolve_unvalidated(text: &str) -> UnvalidatedSubgraphManifest<Chain> {
let mut resolver = TextResolver::default();
let id = DeploymentHash::new("Qmmanifest").unwrap();
resolver.add(id.as_str(), &text);
resolver.add("/ipfs/Qmschema", &GQL_SCHEMA);
let resolver: Arc<dyn LinkResolverTrait> = Arc::new(resolver);
let raw = serde_yaml::from_str(text).unwrap();
UnvalidatedSubgraphManifest::resolve(id, raw, &resolver, &LOGGER, SPEC_VERSION_0_0_4.clone())
.await
.expect("Parsing simple manifest works")
}
// Some of these manifest tests should be made chain-independent, but for
// now we just run them for the ethereum `Chain`
#[tokio::test]
async fn simple_manifest() {
const YAML: &str = "
dataSources: []
schema:
file:
/: /ipfs/Qmschema
specVersion: 0.0.2
";
let manifest = resolve_manifest(YAML, SPEC_VERSION_0_0_4).await;
assert_eq!("Qmmanifest", manifest.id.as_str());
assert!(manifest.graft.is_none());
}
#[tokio::test]
async fn ipfs_manifest() {
let yaml = "
schema:
file:
/: /ipfs/Qmschema
dataSources: []
templates:
- name: IpfsSource
kind: file/ipfs
mapping:
apiVersion: 0.0.6
language: wasm/assemblyscript
entities:
- TestEntity
file:
/: /ipfs/Qmmapping
handler: handleFile
specVersion: 0.0.7
";
let manifest = resolve_manifest(yaml, SPEC_VERSION_0_0_7).await;
assert_eq!("Qmmanifest", manifest.id.as_str());
assert_eq!(manifest.data_sources.len(), 0);
let data_source = match &manifest.templates[0] {
DataSourceTemplate::Offchain(ds) => ds,
DataSourceTemplate::Onchain(_) => unreachable!(),
DataSourceTemplate::Subgraph(_) => unreachable!(),
};
assert_eq!(data_source.kind, OffchainDataSourceKind::Ipfs);
}
#[tokio::test]
async fn subgraph_ds_manifest() {
let yaml = "
schema:
file:
/: /ipfs/Qmschema
dataSources:
- name: SubgraphSource
kind: subgraph
entities:
- Gravatar
network: mainnet
source:
address: 'QmSource'
startBlock: 9562480
mapping:
apiVersion: 0.0.6
language: wasm/assemblyscript
entities:
- TestEntity
file:
/: /ipfs/Qmmapping
handlers:
- handler: handleEntity
entity: TestEntity
specVersion: 1.3.0
";
let manifest = resolve_manifest(yaml, SPEC_VERSION_1_3_0).await;
assert_eq!("Qmmanifest", manifest.id.as_str());
assert_eq!(manifest.data_sources.len(), 1);
let data_source = &manifest.data_sources[0];
match data_source {
DataSourceEnum::Subgraph(ds) => {
assert_eq!(ds.name, "SubgraphSource");
assert_eq!(ds.kind, "subgraph");
assert_eq!(ds.source.start_block, 9562480);
}
_ => panic!("Expected a subgraph data source"),
}
}
#[tokio::test]
async fn subgraph_ds_manifest_aggregations_should_fail() {
let yaml = "
schema:
file:
/: /ipfs/Qmschema
dataSources:
- name: SubgraphSource
kind: subgraph
entities:
- Gravatar
network: mainnet
source:
address: 'QmSource'
startBlock: 9562480
mapping:
apiVersion: 0.0.6
language: wasm/assemblyscript
entities:
- TestEntity
file:
/: /ipfs/Qmmapping
handlers:
- handler: handleEntity
entity: TokenStats # This is an aggregation and should fail
specVersion: 1.3.0
";
let result = try_resolve_manifest(yaml, SPEC_VERSION_1_3_0).await;
assert!(result.is_err());
let err = result.unwrap_err();
assert!(err
.to_string()
.contains("Entity TokenStats is an aggregation and cannot be used as a mapping entity"));
}
#[tokio::test]
async fn multiple_subgraph_ds_manifest() {
let yaml = "
schema:
file:
/: /ipfs/Qmschema
dataSources:
- name: SubgraphSource1
kind: subgraph
entities:
- Gravatar
network: mainnet
source:
address: 'QmSource'
startBlock: 9562480
mapping:
apiVersion: 0.0.6
language: wasm/assemblyscript
entities:
- TestEntity
file:
/: /ipfs/Qmmapping
handlers:
- handler: handleEntity
entity: User
- name: SubgraphSource2
kind: subgraph
entities:
- Profile
network: mainnet
source:
address: 'QmSource2'
startBlock: 9562500
mapping:
apiVersion: 0.0.6
language: wasm/assemblyscript
entities:
- TestEntity2
file:
/: /ipfs/Qmmapping
handlers:
- handler: handleProfile
entity: Profile
specVersion: 1.3.0
";
let manifest = resolve_manifest(yaml, SPEC_VERSION_1_3_0).await;
assert_eq!("Qmmanifest", manifest.id.as_str());
assert_eq!(manifest.data_sources.len(), 2);
// Validate first data source
match &manifest.data_sources[0] {
DataSourceEnum::Subgraph(ds) => {
assert_eq!(ds.name, "SubgraphSource1");
assert_eq!(ds.kind, "subgraph");
assert_eq!(ds.source.start_block, 9562480);
}
_ => panic!("Expected a subgraph data source"),
}
// Validate second data source
match &manifest.data_sources[1] {
DataSourceEnum::Subgraph(ds) => {
assert_eq!(ds.name, "SubgraphSource2");
assert_eq!(ds.kind, "subgraph");
assert_eq!(ds.source.start_block, 9562500);
}
_ => panic!("Expected a subgraph data source"),
}
}
#[tokio::test]
async fn graft_manifest() {
const YAML: &str = "
dataSources: []
schema:
file:
/: /ipfs/Qmschema
graft:
base: Qmbase
block: 12345
specVersion: 0.0.2
";
let manifest = resolve_manifest(YAML, SPEC_VERSION_0_0_4).await;
assert_eq!("Qmmanifest", manifest.id.as_str());
let graft = manifest.graft.expect("The manifest has a graft base");
assert_eq!("Qmbase", graft.base.as_str());
assert_eq!(12345, graft.block);
}
#[tokio::test]
async fn parse_indexer_hints() {
const YAML: &str = "
dataSources: []
schema:
file:
/: /ipfs/Qmschema
graft:
base: Qmbase
block: 12345
specVersion: 1.0.0
indexerHints:
prune: 100
";
let manifest = resolve_manifest(YAML, SPEC_VERSION_1_0_0).await;
assert_eq!(manifest.history_blocks(), 100);
let yaml: &str = "
dataSources: []
schema:
file:
/: /ipfs/Qmschema
graft:
base: Qmbase
block: 12345
specVersion: 1.0.0
indexerHints:
prune: auto
";
let manifest = resolve_manifest(yaml, SPEC_VERSION_1_0_0).await;
Prune::Auto.history_blocks();
assert_eq!(manifest.history_blocks(), ENV_VARS.min_history_blocks);
let yaml: &str = "
dataSources: []
schema:
file:
/: /ipfs/Qmschema
graft:
base: Qmbase
block: 12345
specVersion: 1.0.0
indexerHints:
prune: never
";
let manifest = resolve_manifest(yaml, SPEC_VERSION_1_0_0).await;
assert_eq!(manifest.history_blocks(), BLOCK_NUMBER_MAX);
}
#[test]
fn graft_failed_subgraph() {
const YAML: &str = "
dataSources: []
schema:
file:
/: /ipfs/Qmschema
graft:
base: Qmbase
block: 0
specVersion: 0.0.2
";
test_store::run_test_sequentially(|store| async move {
let subgraph_store = store.subgraph_store();
let unvalidated = resolve_unvalidated(YAML).await;
let subgraph = DeploymentHash::new("Qmbase").unwrap();
// Creates base subgraph at block 0 (genesis).
let deployment = test_store::create_test_subgraph(&subgraph, GQL_SCHEMA).await;
let schema = store
.subgraph_store()
.input_schema(&deployment.hash)
.unwrap();
// Adds an example entity.
let thing = entity! { schema => id: "datthing" };
test_store::insert_entities(
&deployment,
vec![(schema.entity_type("Thing").unwrap(), thing)],
)
.await
.unwrap();
let error = SubgraphError {
subgraph_id: deployment.hash.clone(),
message: "deterministic error".to_string(),
block_ptr: Some(test_store::BLOCKS[1].clone()),
handler: None,
deterministic: true,
};
// Fails the base subgraph at block 1 (and advances the pointer).
test_store::transact_errors(
&store,
&deployment,
test_store::BLOCKS[1].clone(),
vec![error],
false,
)
.await
.unwrap();
// Make sure there are no GraftBaseInvalid errors.
//
// This is allowed because:
// - base: failed at block 1
// - graft: starts at block 0
//
// Meaning that the graft will fail just like it's parent
// but it started at a valid previous block.
assert!(
!unvalidated
.validate(subgraph_store.clone(), true)
.await
.expect_err("Validation must fail")
.into_iter()
.any(|e| matches!(&e, SubgraphManifestValidationError::GraftBaseInvalid(_))),
"There shouldn't be a GraftBaseInvalid error"
);
// Resolve the graft normally.
let manifest = resolve_manifest(YAML, SPEC_VERSION_0_0_4).await;
assert_eq!("Qmmanifest", manifest.id.as_str());
let graft = manifest.graft.expect("The manifest has a graft base");
assert_eq!("Qmbase", graft.base.as_str());
assert_eq!(0, graft.block);
})
}
#[test]
fn graft_invalid_manifest() {
const YAML: &str = "
dataSources: []
schema:
file:
/: /ipfs/Qmschema
graft:
base: Qmbase
block: 1
specVersion: 0.0.2
";
test_store::run_test_sequentially(|store| async move {
let subgraph_store = store.subgraph_store();
let unvalidated = resolve_unvalidated(YAML).await;
let subgraph = DeploymentHash::new("Qmbase").unwrap();
//
// Validation against subgraph that hasn't synced anything fails
//
let deployment = test_store::create_test_subgraph(&subgraph, GQL_SCHEMA).await;
let schema = store
.subgraph_store()
.input_schema(&deployment.hash)
.unwrap();
// This check is awkward since the test manifest has other problems
// that the validation complains about as setting up a valid manifest
// would be a bit more work; we just want to make sure that
// graft-related checks work
let msg = unvalidated
.validate(subgraph_store.clone(), true)
.await
.expect_err("Validation must fail")
.into_iter()
.find(|e| matches!(e, SubgraphManifestValidationError::GraftBaseInvalid(_)))
.expect("There must be a GraftBaseInvalid error")
.to_string();
assert_eq!(
"the graft base is invalid: failed to graft onto `Qmbase` since \
it has not processed any blocks",
msg
);
let thing = entity! { schema => id: "datthing" };
test_store::insert_entities(
&deployment,
vec![(schema.entity_type("Thing").unwrap(), thing)],
)
.await
.unwrap();
// Validation against subgraph that has not reached the graft point fails
let unvalidated = resolve_unvalidated(YAML).await;
let msg = unvalidated
.validate(subgraph_store.clone(), true)
.await
.expect_err("Validation must fail")
.into_iter()
.find(|e| matches!(e, SubgraphManifestValidationError::GraftBaseInvalid(_)))
.expect("There must be a GraftBaseInvalid error")
.to_string();
assert_eq!(
"the graft base is invalid: failed to graft onto `Qmbase` \
at block 1 since it has only processed block 0",
msg
);
let error = SubgraphError {
subgraph_id: deployment.hash.clone(),
message: "deterministic error".to_string(),
block_ptr: Some(test_store::BLOCKS[1].clone()),
handler: None,
deterministic: true,
};
test_store::transact_errors(
&store,
&deployment,
test_store::BLOCKS[1].clone(),
vec![error],
false,
)
.await
.unwrap();
// This check is bit awkward, but we just want to be sure there is a
// GraftBaseInvalid error.
//
// The validation error happens because:
// - base: failed at block 1
// - graft: starts at block 1
//
// Since we start grafts at N + 1, we can't allow a graft to be created
// at the failed block. They (developers) should choose a previous valid
// block.
let unvalidated = resolve_unvalidated(YAML).await;
let msg = unvalidated
.validate(subgraph_store, true)
.await
.expect_err("Validation must fail")
.into_iter()
.find(|e| matches!(e, SubgraphManifestValidationError::GraftBaseInvalid(_)))
.expect("There must be a GraftBaseInvalid error")
.to_string();
assert_eq!(
"the graft base is invalid: failed to graft onto `Qmbase` \
at block 1 since it's not healthy. You can graft it starting at block 0 backwards",
msg
);
})
}
#[tokio::test]
async fn parse_data_source_context() {
const YAML: &str = "
dataSources:
- kind: ethereum/contract
name: Factory
network: mainnet
context:
bool_example:
type: Bool
data: true
int8_example:
type: Int8
data: 64
big_decimal_example:
type: BigDecimal
data: 10.99
bytes_example:
type: Bytes
data: \"0x68656c6c6f\"
list_example:
type: List
data:
- type: Int
data: 1
- type: Int
data: 2
- type: Int
data: 3
big_int_example:
type: BigInt
data: \"1000000000000000000000000\"
string_example:
type: String
data: \"bar\"
int_example:
type: Int
data: 42
source:
address: \"0x0000000000000000000000000000000000000000\"
abi: Factory
startBlock: 9562480
mapping:
kind: ethereum/events
apiVersion: 0.0.4
language: wasm/assemblyscript
entities:
- TestEntity
file:
/: /ipfs/Qmmapping
abis:
- name: Factory
file:
/: /ipfs/Qmabi
blockHandlers:
- handler: handleBlock
schema:
file:
/: /ipfs/Qmschema
specVersion: 0.0.8
";
let manifest = resolve_manifest(YAML, SPEC_VERSION_0_0_8).await;
let data_source = manifest
.data_sources
.iter()
.find_map(|ds| ds.as_onchain().cloned())
.unwrap();
let context = data_source.context.as_ref().clone().unwrap();
let sorted = context.sorted();
assert_eq!(sorted.len(), 8);
assert_eq!(
sorted[0],
(
"big_decimal_example".into(),
Value::BigDecimal(BigDecimal::from(10.99))
)
);
assert_eq!(
sorted[1],
(
"big_int_example".into(),
Value::BigInt(BigInt::from_str("1000000000000000000000000").unwrap())
)
);
assert_eq!(sorted[2], ("bool_example".into(), Value::Bool(true)));
assert_eq!(
sorted[3],
(
"bytes_example".into(),
Value::Bytes(Bytes::from_str("0x68656c6c6f").unwrap())
)
);
assert_eq!(sorted[4], ("int8_example".into(), Value::Int8(64)));
assert_eq!(sorted[5], ("int_example".into(), Value::Int(42)));
assert_eq!(
sorted[6],
(
"list_example".into(),
Value::List(vec![Value::Int(1), Value::Int(2), Value::Int(3)])
)
);
assert_eq!(
sorted[7],
("string_example".into(), Value::String("bar".into()))
);
}
#[tokio::test]
async fn parse_event_handlers_with_topics() {
const YAML: &str = "
dataSources:
- kind: ethereum/contract
name: Factory
network: mainnet
source:
abi: Factory
startBlock: 9562480
endBlock: 9562481
mapping:
kind: ethereum/events
apiVersion: 0.0.4
language: wasm/assemblyscript
entities:
- TestEntity
file:
/: /ipfs/Qmmapping
abis:
- name: Factory
file:
/: /ipfs/Qmabi
eventHandlers:
- event: Test(address,string)
handler: handleTest
topic1: [\"0x0000000000000000000000000000000000000000000000000000000000000000\", \"0x0000000000000000000000000000000000000000000000000000000000000001\", \"0x0000000000000000000000000000000000000000000000000000000000000002\" ]
topic2: [\"0x0000000000000000000000000000000000000000000000000000000000000001\"]
topic3: [\"0x0000000000000000000000000000000000000000000000000000000000000002\"]
schema:
file:
/: /ipfs/Qmschema
specVersion: 1.2.0
";
let manifest = resolve_manifest(YAML, SPEC_VERSION_1_2_0).await;
// Check if end block is parsed correctly
let data_source = manifest.data_sources.first().unwrap();
let topic1 = &data_source.as_onchain().unwrap().mapping.event_handlers[0].topic1;
let topic2 = &data_source.as_onchain().unwrap().mapping.event_handlers[0].topic2;
let topic3 = &data_source.as_onchain().unwrap().mapping.event_handlers[0].topic3;
assert_eq!(
Some(vec![
H256::from_str("0000000000000000000000000000000000000000000000000000000000000000")
.unwrap(),
H256::from_str("0000000000000000000000000000000000000000000000000000000000000001")
.unwrap(),
H256::from_str("0000000000000000000000000000000000000000000000000000000000000002")
.unwrap()
]),
topic1.clone()
);
assert_eq!(
Some(vec![H256::from_str(
"0000000000000000000000000000000000000000000000000000000000000001"
)
.unwrap()]),
topic2.clone()
);
assert_eq!(
Some(vec![H256::from_str(
"0000000000000000000000000000000000000000000000000000000000000002"
)
.unwrap()]),
topic3.clone()
);
}
#[tokio::test]
async fn parse_block_handlers_with_polling_filter() {
const YAML: &str = "
dataSources:
- kind: ethereum/contract
name: Factory
network: mainnet
source:
address: \"0x0000000000000000000000000000000000000000\"
abi: Factory
startBlock: 9562480
mapping:
kind: ethereum/events
apiVersion: 0.0.4
language: wasm/assemblyscript
entities:
- TestEntity
file:
/: /ipfs/Qmmapping
abis:
- name: Factory
file:
/: /ipfs/Qmabi
blockHandlers:
- handler: handleBlock
filter:
kind: polling
every: 10
schema:
file:
/: /ipfs/Qmschema
specVersion: 0.0.8
";
let manifest = resolve_manifest(YAML, SPEC_VERSION_0_0_8).await;
let onchain_data_sources = manifest
.data_sources
.iter()
.filter_map(|ds| ds.as_onchain().cloned())
.collect::<Vec<_>>();
let data_source = onchain_data_sources.get(0).unwrap();
let validation_errors = data_source.validate(&LATEST_VERSION);
let filter = data_source.mapping.block_handlers[0].filter.clone();
assert_eq!(0, validation_errors.len());
assert_eq!(
BlockHandlerFilter::Polling {
every: NonZeroU32::new(10).unwrap()
},
filter.unwrap()
);
assert_eq!("Qmmanifest", manifest.id.as_str());
}
#[tokio::test]
async fn parse_data_source_with_end_block() {
const YAML: &str = "
dataSources:
- kind: ethereum/contract
name: Factory
network: mainnet
source:
abi: Factory
startBlock: 9562480
endBlock: 9562481
mapping:
kind: ethereum/events
apiVersion: 0.0.4
language: wasm/assemblyscript
entities:
- TestEntity
file:
/: /ipfs/Qmmapping
abis:
- name: Factory
file:
/: /ipfs/Qmabi
schema:
file:
/: /ipfs/Qmschema
specVersion: 0.0.9
";
let manifest = resolve_manifest(YAML, SPEC_VERSION_0_0_9).await;
// Check if end block is parsed correctly
let data_source = manifest.data_sources.first().unwrap();
let end_block = data_source.as_onchain().unwrap().end_block;
assert_eq!(Some(9562481), end_block);
}
#[tokio::test]
async fn parse_block_handlers_with_both_polling_and_once_filter() {
const YAML: &str = "
dataSources:
- kind: ethereum/contract
name: Factory
network: mainnet
source:
address: \"0x0000000000000000000000000000000000000000\"
abi: Factory
startBlock: 9562480
mapping:
kind: ethereum/events
apiVersion: 0.0.4
language: wasm/assemblyscript
entities:
- TestEntity
file:
/: /ipfs/Qmmapping
abis:
- name: Factory
file:
/: /ipfs/Qmabi
blockHandlers:
- handler: intitialize
filter:
kind: once
- handler: handleBlock
filter:
kind: polling
every: 10
schema:
file:
/: /ipfs/Qmschema
specVersion: 0.0.8
";
let manifest = resolve_manifest(YAML, SPEC_VERSION_0_0_8).await;
let onchain_data_sources = manifest
.data_sources
.iter()
.filter_map(|ds| ds.as_onchain().cloned())
.collect::<Vec<_>>();
let data_source = onchain_data_sources.get(0).unwrap();
let validation_errors = data_source.validate(LATEST_VERSION);
let filters = data_source
.mapping
.block_handlers
.iter()
.map(|h| h.filter.clone())
.collect::<Vec<_>>();
assert_eq!(0, validation_errors.len());
assert_eq!(
vec![
Some(BlockHandlerFilter::Once),
Some(BlockHandlerFilter::Polling {
every: NonZeroU32::new(10).unwrap()
})
],
filters
);
assert_eq!("Qmmanifest", manifest.id.as_str());
}
#[tokio::test]
async fn should_not_parse_block_handlers_with_both_filtered_and_non_filtered_handlers() {
const YAML: &str = "
dataSources:
- kind: ethereum/contract
name: Factory
network: mainnet
source:
address: \"0x0000000000000000000000000000000000000000\"
abi: Factory
startBlock: 9562480
mapping:
kind: ethereum/events
apiVersion: 0.0.4
language: wasm/assemblyscript
entities:
- TestEntity
file:
/: /ipfs/Qmmapping
abis:
- name: Factory
file:
/: /ipfs/Qmabi
blockHandlers:
- handler: handleBlock
- handler: handleBlockPolling
filter: