-
Notifications
You must be signed in to change notification settings - Fork 66
/
indexer.rs
1037 lines (909 loc) · 40 KB
/
indexer.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 crate::{
helpers::*, parse::IndexerConfig, schema::process_graphql_schema,
wasm::handler_block_wasm,
};
use fuel_abi_types::abi::program::TypeDeclaration;
use fuel_indexer_lib::{
constants::*, manifest::ContractIds, manifest::Manifest,
utils::workspace_manifest_prefix,
};
use fuel_indexer_types::{type_id, FUEL_TYPES_NAMESPACE};
use fuels::{core::codec::resolve_fn_selector, types::param_types::ParamType};
use fuels_code_gen::{Abigen, AbigenTarget, ProgramType};
use proc_macro::TokenStream;
use quote::quote;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use syn::{parse_macro_input, FnArg, Item, ItemMod, PatType, Type};
fn additional_declarations() -> proc_macro2::TokenStream {
quote! {
// Miscellaneous types that can be included in ABI JSON
type b256 = [u8; 32];
type Bytes = Vec<u8>;
type B512 = [u8; 64];
}
}
fn process_fn_items(
manifest: &Manifest,
abi_path: Option<String>,
indexer_module: ItemMod,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
if indexer_module.content.is_none()
|| indexer_module
.content
.as_ref()
.expect("Could not parse function input contents.")
.1
.is_empty()
{
proc_macro_error::abort_call_site!(
"No module body, must specify at least one handler function."
)
}
let abi = get_json_abi(abi_path).unwrap_or_default();
let mut decoded_type_snippets = HashSet::new();
let mut decoded_log_match_arms = HashSet::new();
let mut decoded_type_fields = HashSet::new();
let mut abi_dispatchers = Vec::new();
let funcs = abi.clone().functions;
let abi_types: Vec<TypeDeclaration> = abi
.clone()
.types
.iter()
.map(|t| strip_callpath_from_type_field(t.clone()))
.collect();
let abi_log_types = abi.clone().logged_types.unwrap_or_default();
let abi_msg_types = abi.clone().messages_types.unwrap_or_default();
let fuel_types = FUEL_PRIMITIVES
.iter()
.map(|x| {
let type_id = type_id(FUEL_TYPES_NAMESPACE, x) as usize;
let typ = TypeDeclaration {
type_id,
type_field: x.to_string(),
components: None,
type_parameters: None,
};
(typ.type_id, typ)
})
.collect::<HashMap<usize, TypeDeclaration>>();
let _tuple_types_tyid = abi_types
.iter()
.filter_map(|typ| {
if is_tuple_type(typ) {
return Some((typ.type_id, typ.clone()));
}
None
})
.collect::<HashMap<usize, TypeDeclaration>>();
// Used to do a reverse lookup of typed path names to ABI type IDs.
let mut type_ids = RESERVED_TYPEDEF_NAMES
.iter()
.map(|x| (x.to_string(), type_id(FUEL_TYPES_NAMESPACE, x) as usize))
.collect::<HashMap<String, usize>>();
let mut abi_types_tyid = abi_types
.iter()
.map(|typ| (typ.type_id, typ.clone()))
.collect::<HashMap<usize, TypeDeclaration>>();
let message_types_decoders = abi_msg_types
.iter()
.map(|typ| {
let message_type_id = typ.message_id;
let ty_id = typ.application.type_id;
quote! {
#message_type_id => {
self.decode_type(#ty_id, data)?;
}
}
})
.chain(vec![quote! {
u64::MAX => {
{}
}
}])
.collect::<Vec<proc_macro2::TokenStream>>();
// Take a second pass over `abi_types` in order to update an `TypeDeclarations` that need to
// be updated with more information for the codegen process.
let abi_types = abi_types
.iter()
.map(|typ| {
// If this is an array type we have to manually update it's type field to include its inner
// type so that the rest of the codegen will work with minimal changes.
if is_array_type(typ) {
let inner = typ
.components
.as_ref()
.expect("Array type expects inner components")
.first()
.expect("Array type expects at least one inner component")
.type_id;
let size = typ
.type_field
.split(' ')
.last()
.expect(
"Array type has unexpected type field format. Expected [u8; 32]",
)
.trim_end_matches(']')
.parse::<usize>()
.expect("Array type size could not be determined.");
let inner = abi_types_tyid
.get(&inner)
.expect("Array type inner not found in ABI types.");
let name = format!("[{}; {}]", inner.name(), size);
let typ = TypeDeclaration {
type_field: name,
..typ.clone()
};
abi_types_tyid.insert(typ.type_id, typ.clone());
typ
} else {
typ.to_owned()
}
})
.collect::<Vec<TypeDeclaration>>();
let abi_type_decoders = abi_types
.iter()
.filter_map(|typ| {
if is_non_decodable_type(typ) {
return None;
}
if is_fuel_primitive(typ) {
proc_macro_error::abort_call_site!(
"'{}' is a reserved Fuel type.",
typ.name()
)
}
if is_generic_type(typ) {
let gt = GenericType::from(typ);
match gt {
GenericType::Vec | GenericType::Option => {
let ab_types = abi_types_tyid.clone();
let inner_typs = derive_generic_inner_typedefs(
typ,
&funcs,
&abi_log_types,
&ab_types,
);
return Some(
inner_typs
.iter()
.filter_map(|inner_typ| {
let (typ_name, type_tokens) = typed_path_components(
typ,
inner_typ,
&abi_types_tyid,
);
let ty_id =
type_id(FUEL_TYPES_NAMESPACE, &typ_name) as usize;
let typ = TypeDeclaration {
type_id: ty_id,
type_field: typ_name.clone(),
..typ.clone()
};
if decoded_type_snippets.contains(&ty_id) {
return None;
}
abi_types_tyid.insert(ty_id, typ.clone());
type_ids.insert(typ_name.clone(), ty_id);
decoded_type_snippets.insert(ty_id);
Some(decode_snippet(&type_tokens, &typ))
})
.collect::<Vec<proc_macro2::TokenStream>>(),
);
}
_ => unimplemented!("Unsupported decoder generic type: {:?}", gt),
}
} else {
let type_tokens = typ.rust_tokens();
type_ids.insert(type_tokens.to_string(), typ.type_id);
decoded_type_snippets.insert(typ.type_id);
Some(vec![decode_snippet(&type_tokens, typ)])
}
})
.flatten()
.collect::<Vec<proc_macro2::TokenStream>>();
let fuel_type_decoders = fuel_types
.values()
.map(|typ| {
let type_tokens = typ.rust_tokens();
type_ids.insert(type_tokens.to_string(), typ.type_id);
decoded_type_snippets.insert(typ.type_id);
decode_snippet(&type_tokens, typ)
})
.collect::<Vec<proc_macro2::TokenStream>>();
let decoders = [fuel_type_decoders, abi_type_decoders].concat();
let abi_struct_fields = abi_types
.iter()
.filter_map(|typ| {
if is_non_decodable_type(typ) {
return None;
}
if is_fuel_primitive(typ) {
proc_macro_error::abort_call_site!(
"'{}' is a reserved Fuel type.",
typ.name()
)
}
if is_generic_type(typ) {
let inner_typs = derive_generic_inner_typedefs(
typ,
&funcs,
&abi_log_types,
&abi_types_tyid,
);
return Some(
inner_typs
.iter()
.filter_map(|inner_typ| {
let (typ_name, type_tokens) =
typed_path_components(typ, inner_typ, &abi_types_tyid);
let ty_id = type_id(FUEL_TYPES_NAMESPACE, &typ_name) as usize;
if decoded_type_fields.contains(&ty_id) {
return None;
}
let typ = TypeDeclaration {
type_id: ty_id,
type_field: typ_name.clone(),
..typ.clone()
};
let ident = typ.decoder_field_ident();
type_ids.insert(typ_name.clone(), ty_id);
decoded_type_fields.insert(ty_id);
Some(quote! {
#ident: Vec<#type_tokens>
})
})
.collect::<Vec<proc_macro2::TokenStream>>(),
);
} else {
let ident = typ.decoder_field_ident();
let type_tokens = typ.rust_tokens();
type_ids.insert(typ.rust_tokens().to_string(), typ.type_id);
decoded_type_fields.insert(typ.type_id);
Some(vec![quote! {
#ident: Vec<#type_tokens>
}])
}
})
.flatten()
.collect::<Vec<proc_macro2::TokenStream>>();
let fuel_struct_fields = fuel_types
.iter()
.filter_map(|(_ty_id, typ)| {
if is_non_decodable_type(typ) {
return None;
}
let name = typ.decoder_field_ident();
let ty = typ.rust_tokens();
type_ids.insert(ty.to_string(), typ.type_id);
decoded_type_snippets.insert(typ.type_id);
if decoded_type_fields.contains(&typ.type_id) {
return None;
}
Some(quote! {
#name: Vec<#ty>
})
})
.collect::<Vec<proc_macro2::TokenStream>>();
let decoder_struct_fields = [abi_struct_fields, fuel_struct_fields].concat();
// Since log type decoders use `TypeDeclaration`s that were manually created specifically
// for generics, we parsed log types after other ABI types.
let log_type_decoders = abi_log_types
.iter()
.filter_map(|log| {
let ty_id = log.application.type_id;
let log_id = log.log_id as usize;
let typ = abi_types_tyid
.get(&log.application.type_id)
.expect("Could not get log type reference from ABI types.");
if is_non_decodable_type(typ) {
return None;
}
if is_generic_type(typ) {
let gt = GenericType::from(typ);
match gt {
GenericType::Vec | GenericType::Option => {
let inner_typ =
derive_log_generic_inner_typedefs(log, &abi, &abi_types_tyid);
let (typ_name, _) =
typed_path_components(typ, inner_typ, &abi_types_tyid);
let ty_id = type_id(FUEL_TYPES_NAMESPACE, &typ_name) as usize;
let _typ = abi_types_tyid.get(&ty_id).expect(
"Could not get generic log type reference from ABI types.",
);
decoded_log_match_arms.insert(log_id);
Some(quote! {
#log_id => {
self.decode_type(#ty_id, data)?;
}
})
}
_ => unimplemented!("Unsupported decoder generic type: {:?}", gt),
}
} else {
decoded_log_match_arms.insert(log_id);
Some(quote! {
#log_id => {
self.decode_type(#ty_id, data)?;
}
})
}
})
.collect::<Vec<proc_macro2::TokenStream>>();
let abi_selectors = funcs
.iter()
.map(|function| {
let params: Vec<ParamType> = function
.inputs
.iter()
.map(|x| {
ParamType::try_from_type_application(x, &abi_types_tyid)
.expect("Could not derive TypeApplication param types.")
})
.collect();
let sig = resolve_fn_selector(&function.name, ¶ms[..]);
let selector = u64::from_be_bytes(sig);
let ty_id = function_output_type_id(function, &abi_types_tyid);
quote! {
#selector => #ty_id,
}
})
.collect::<Vec<proc_macro2::TokenStream>>();
let abi_selectors_to_fn_names = funcs
.iter()
.map(|function| {
let params: Vec<ParamType> = function
.inputs
.iter()
.map(|x| {
ParamType::try_from_type_application(x, &abi_types_tyid)
.expect("Could not derive TypeApplication param types.")
})
.collect();
let sig = resolve_fn_selector(&function.name, ¶ms[..]);
let fn_name = function.name.clone();
let selector = u64::from_be_bytes(sig);
quote! {
#selector => #fn_name.to_string(),
}
})
.collect::<Vec<proc_macro2::TokenStream>>();
let contents = indexer_module
.content
.expect("Could not parse input content.")
.1;
let mut handler_fns = Vec::with_capacity(contents.len());
let start_block = match manifest.start_block() {
Some(start_block) => {
quote! {
if block.height < #start_block {
return Ok(());
}
}
}
None => quote! {},
};
let subscribed_contract_ids = match &manifest.contract_id() {
ContractIds::Single(_) => quote! {},
ContractIds::Multiple(contract_ids) => {
let contract_ids = contract_ids
.iter()
.map(|id| {
quote! {
Bech32ContractId::from_str(#id).unwrap_or_else(|_| {
let contract_id = ContractId::from_str(&#id).expect("Failed to parse manifest 'contract_id'");
Bech32ContractId::from(contract_id)
})
}
})
.collect::<Vec<proc_macro2::TokenStream>>();
quote! {
let contract_ids = HashSet::from([#(#contract_ids),*]);
}
}
};
let check_if_subscribed_to_contract = match &manifest.contract_id() {
ContractIds::Single(contract_id) => match contract_id {
Some(contract_id) => {
quote! {
let id_bytes = <[u8; 32]>::try_from(id).expect("Could not convert contract ID into bytes");
let bech32_id = Bech32ContractId::new("fuel", id_bytes);
let manifest_contract_id = Bech32ContractId::from_str(#contract_id).unwrap_or_else(|_| {
let contract_id = ContractId::from_str(&#contract_id).expect("Failed to parse manifest 'contract_id'");
Bech32ContractId::from(contract_id)
});
if bech32_id != manifest_contract_id {
debug!("Not subscribed to this contract. Will skip this receipt event. <('-'<)");
continue;
}
}
}
None => quote! {},
},
ContractIds::Multiple(_) => {
quote! {
let id_bytes = <[u8; 32]>::try_from(id).expect("Could not convert contract ID into bytes");
let bech32_id = Bech32ContractId::new("fuel", id_bytes);
if !contract_ids.contains(&bech32_id) {
debug!("Not subscribed to this contract. Will skip this receipt event. <('-'<)");
continue;
}
}
}
};
for item in contents {
match item {
Item::Fn(fn_item) => {
let mut input_checks = Vec::new();
let mut arg_list = Vec::new();
for inp in &fn_item.sig.inputs {
match inp {
FnArg::Receiver(_) => {
proc_macro_error::abort_call_site!(
"`self` argument not allowed in handler function."
)
}
FnArg::Typed(PatType { ty, .. }) => {
if let Type::Path(path) = &**ty {
let path_seg = path
.path
.segments
.last()
.expect("Could not get last path segment.");
let path_type_name = typed_path_name(path);
if is_unsupported_type(&path_type_name) {
proc_macro_error::abort_call_site!(
"Type with ident '{:?}' is not currently supported.",
path_seg.ident
)
}
if !type_ids.contains_key(&path_type_name) {
proc_macro_error::abort_call_site!(
"Type with ident '{:?}' not defined in the ABI.",
path_seg.ident
);
};
let ty_id = type_ids
.get(&path_type_name)
.expect("Path type name not found in type IDs.");
let typ = match abi_types_tyid.get(ty_id) {
Some(typ) => typ,
None => fuel_types.get(ty_id).unwrap(),
};
let dispatcher_name = typ.decoder_field_ident();
input_checks
.push(quote! { self.#dispatcher_name.len() > 0 });
arg_list
.push(quote! { self.#dispatcher_name[0].clone() });
} else {
proc_macro_error::abort_call_site!(
"Arguments must be types defined in the ABI."
)
}
}
}
}
let fn_name = &fn_item.sig.ident;
let fn_name_string = fn_name.to_string();
if arg_list.is_empty() {
proc_macro_error::abort_call_site!(
"Handler function '{}' must have at least one argument.",
fn_name.to_string(),
);
}
let fn_call = if fn_item.sig.output == syn::ReturnType::Default {
quote! {
#fn_name(#(#arg_list),*)
}
} else {
quote! {
if let Err(e) = #fn_name(#(#arg_list),*).with_context(|| format!("Failed executing {}()", #fn_name_string)) {
unsafe {
if !ERROR_MESSAGE.is_empty() {
ERROR_MESSAGE += "\n\n";
}
// Piggyback on ERROR_MESSAGE to collect multiple errors.
// ERROR_MESSAGE is converted back to Error at the end of dispatch()
ERROR_MESSAGE += &format!("{e:?}");
}
}
}
};
abi_dispatchers.push(quote! {
if ( #(#input_checks)&&* ) {
#fn_call
}
});
handler_fns.push(fn_item);
}
i => {
proc_macro_error::abort_call_site!(
"Unsupported item in indexer module '{:?}'.",
i
)
}
}
}
let decoder_struct = quote! {
#[derive(Default)]
struct Decoders {
#(#decoder_struct_fields),*
}
impl Decoders {
fn selector_to_type_id(&self, sel: u64) -> usize {
match sel {
#(#abi_selectors)*
_ => {
debug!("Unknown selector; check ABI to make sure function outputs match to types");
usize::MAX
}
}
}
pub fn selector_to_fn_name(&self, sel: u64) -> String {
match sel {
#(#abi_selectors_to_fn_names)*
_ => {
debug!("Unknown selector; check ABI to make sure function outputs match to types");
"".to_string()
}
}
}
fn compute_message_id(&self, sender: &Address, recipient: &Address, nonce: Nonce, amount: Word, data: Option<Vec<u8>>) -> MessageId {
let mut raw_message_id = Sha256::new()
.chain_update(sender)
.chain_update(recipient)
.chain_update(nonce)
.chain_update(amount.to_be_bytes());
let raw_message_id = if let Some(buffer) = data {
raw_message_id
.chain_update(&buffer[..])
.finalize()
} else {
raw_message_id.finalize()
};
let message_id = <[u8; 32]>::try_from(&raw_message_id[..]).expect("Could not calculate message ID from receipt fields");
message_id.into()
}
fn decode_type(&mut self, ty_id: usize, data: Vec<u8>) -> anyhow::Result<()> {
let decoder = ABIDecoder::default();
match ty_id {
#(#decoders),*
_ => {
debug!("Unknown type ID; check ABI to make sure types are correct.");
},
}
Ok(())
}
pub fn decode_block(&mut self, data: BlockData) {
self.blockdata_decoded.push(data);
}
pub fn decode_return_type(&mut self, sel: u64, data: Vec<u8>) -> anyhow::Result<()> {
let ty_id = self.selector_to_type_id(sel);
self.decode_type(ty_id, data)?;
Ok(())
}
pub fn decode_logdata(&mut self, rb: usize, data: Vec<u8>) -> anyhow::Result<()> {
match rb {
#(#log_type_decoders),*
_ => debug!("Unknown logged type ID; check ABI to make sure that logged types are correct.")
}
Ok(())
}
pub fn decode_messagedata(&mut self, type_id: u64, data: Vec<u8>) -> anyhow::Result<()> {
match type_id {
#(#message_types_decoders),*
_ => debug!("Unknown message type ID; check ABI to make sure that message types are correct.")
}
Ok(())
}
pub fn dispatch(&self) -> anyhow::Result<()> {
#(#abi_dispatchers)*
unsafe {
if !ERROR_MESSAGE.is_empty() {
anyhow::bail!(ERROR_MESSAGE.clone());
} else {
Ok(())
}
}
}
}
};
(
quote! {
#subscribed_contract_ids
use anyhow::Context;
use fuel::TransactionData;
let mut process_transaction = |decoder: &mut Decoders, tx: TransactionData| -> anyhow::Result<()> {
let mut return_types = Vec::new();
let mut callees = HashSet::new();
for receipt in tx.receipts {
match receipt {
fuel::Receipt::Call { id: contract_id, amount, asset_id, gas, param1, to: id, .. } => {
#check_if_subscribed_to_contract
let fn_name = decoder.selector_to_fn_name(param1);
return_types.push(param1);
callees.insert(id);
let data = serialize(
&Call {
contract_id: ContractId::from(<[u8; 32]>::from(contract_id)),
to: ContractId::from(<[u8; 32]>::from(id)),
amount,
asset_id: AssetId::from(<[u8; 32]>::from(asset_id)),
gas,
fn_name
}
);
let ty_id = Call::type_id();
decoder.decode_type(ty_id, data)?;
}
fuel::Receipt::Log { id, ra, rb, .. } => {
#check_if_subscribed_to_contract
let ty_id = Log::type_id();
let data = serialize(
&Log {
contract_id: ContractId::from(<[u8; 32]>::from(id)),
ra,
rb
}
);
decoder.decode_type(ty_id, data)?;
}
fuel::Receipt::LogData { rb, data, ptr, len, id, .. } => {
#check_if_subscribed_to_contract
decoder.decode_logdata(rb as usize, data.unwrap_or(Vec::<u8>::new()))?;
}
fuel::Receipt::Return { id, val, pc, is } => {
#check_if_subscribed_to_contract
if callees.contains(&id) {
let ty_id = Return::type_id();
let data = serialize(
&Return {
contract_id: ContractId::from(<[u8; 32]>::from(id)),
val,
pc,
is
}
);
decoder.decode_type(ty_id, data)?;
}
}
fuel::Receipt::ReturnData { data, id, .. } => {
#check_if_subscribed_to_contract
if callees.contains(&id) {
let selector = return_types.pop().expect("No return type available. <('-'<)");
decoder.decode_return_type(selector, data.unwrap_or(Vec::<u8>::new()))?;
}
}
fuel::Receipt::MessageOut { sender, recipient, amount, nonce, len, digest, data, .. } => {
let sender = Address::from(<[u8; 32]>::from(sender));
let recipient = Address::from(<[u8; 32]>::from(recipient));
let message_id = decoder.compute_message_id(&sender, &recipient, nonce, amount, data.clone());
// It's possible that the data field was generated from an empty Sway `Bytes` array
// in the send_message() instruction in which case the data field in the receipt will
// have no type information or data to decode. Thus, we check for a None value or
// an empty byte vector; if either condition is present, then we decode to a unit struct instead.
let (type_id, data) = data
.map_or((u64::MAX, Vec::<u8>::new()), |buffer| {
if buffer.is_empty() {
(u64::MAX, Vec::<u8>::new())
} else {
let (type_id_bytes, data_bytes) = buffer.split_at(8);
let type_id = u64::from_be_bytes(
<[u8; 8]>::try_from(type_id_bytes)
.expect("Could not get type ID for data in MessageOut receipt")
);
let data = data_bytes.to_vec();
(type_id, data)
}
});
decoder.decode_messagedata(type_id, data.clone())?;
let ty_id = MessageOut::type_id();
let data = serialize(
&MessageOut {
message_id,
sender,
recipient,
amount,
nonce,
len,
digest,
data
}
);
decoder.decode_type(ty_id, data)?;
}
fuel::Receipt::ScriptResult { result, gas_used } => {
let ty_id = ScriptResult::type_id();
let data = serialize(&ScriptResult{ result: u64::from(result), gas_used });
decoder.decode_type(ty_id, data)?;
}
fuel::Receipt::Transfer { id, to, asset_id, amount, pc, is, .. } => {
#check_if_subscribed_to_contract
let ty_id = Transfer::type_id();
let data = serialize(
&Transfer {
contract_id: ContractId::from(<[u8; 32]>::from(id)),
to: ContractId::from(<[u8; 32]>::from(to)),
asset_id: AssetId::from(<[u8; 32]>::from(asset_id)),
amount,
pc,
is
}
);
decoder.decode_type(ty_id, data)?;
}
fuel::Receipt::TransferOut { id, to, asset_id, amount, pc, is, .. } => {
#check_if_subscribed_to_contract
let ty_id = TransferOut::type_id();
let data = serialize(
&TransferOut {
contract_id: ContractId::from(<[u8; 32]>::from(id)),
to: Address::from(<[u8; 32]>::from(to)),
asset_id: AssetId::from(<[u8; 32]>::from(asset_id)),
amount,
pc,
is
}
);
decoder.decode_type(ty_id, data)?;
}
fuel::Receipt::Panic { id, reason, .. } => {
#check_if_subscribed_to_contract
let ty_id = Panic::type_id();
let data = serialize(
&Panic {
contract_id: ContractId::from(<[u8; 32]>::from(id)),
reason: *reason.reason() as u32
}
);
decoder.decode_type(ty_id, data)?;
}
fuel::Receipt::Revert { id, ra, .. } => {
#check_if_subscribed_to_contract
let ty_id = Revert::type_id();
let data = serialize(
&Revert {
contract_id: ContractId::from(<[u8; 32]>::from(id)),
error_val: u64::from(ra & 0xF)
}
);
decoder.decode_type(ty_id, data)?;
}
fuel::Receipt::Mint { sub_id, contract_id, val, pc, is } => {
let ty_id = Mint::type_id();
let data = serialize(
&Mint {
sub_id: AssetId::from(<[u8; 32]>::from(sub_id)),
contract_id: ContractId::from(<[u8; 32]>::from(contract_id)),
val,
pc,
is
}
);
decoder.decode_type(ty_id, data)?;
}
fuel::Receipt::Burn { sub_id, contract_id, val, pc, is } => {
let ty_id = Burn::type_id();
let data = serialize(
&Burn {
sub_id: AssetId::from(<[u8; 32]>::from(sub_id)),
contract_id: ContractId::from(<[u8; 32]>::from(contract_id)),
val,
pc,
is
}
);
decoder.decode_type(ty_id, data)?;
}
_ => {
info!("This type is not handled yet. (>'.')>");
}
}
}
Ok(())
};
let mut process_block = |block: BlockData| -> anyhow::Result<()> {
#start_block
let mut decoder = Decoders::default();
let ty_id = BlockData::type_id();
let data = serialize(&block);
decoder.decode_type(ty_id, data)?;
for tx in block.transactions {
let tx_id = tx.id;
process_transaction(&mut decoder, tx).with_context(|| format!("Failed processing Transaction {:?}", tx_id))?
}
decoder.dispatch()?;
let metadata = IndexMetadataEntity::new(block.time as u64, block.header.height, block.id);
metadata.save();
Ok(())
};
for block in blocks {
let block_height = block.header.height;
process_block(block).with_context(|| format!("Failed processing Block #{}", block_height))?;
}
},
quote! {
#decoder_struct
#(#handler_fns)*
},
)
}
pub fn prefix_abi_and_schema_paths(
abi: Option<&str>,
schema: &str,
) -> (Option<String>, String) {
if let Some(abi) = abi {
match std::env::var("COMPILE_TEST_PREFIX") {
Ok(prefix) => {
let prefixed = std::path::Path::new(&prefix).join(abi);
let abi_string = prefixed
.into_os_string()
.to_str()
.expect("Could not parse prefixed ABI path.")
.to_string();
let prefixed = std::path::Path::new(&prefix).join(schema);
let schema = prefixed
.into_os_string()
.to_str()
.expect("Could not parse prefixed GraphQL schema path.")
.to_string();
return (Some(abi_string), schema);
}
Err(_) => {
return (Some(abi.into()), schema.to_string());
}
};
}
(None, schema.to_string())
}
pub fn get_abi_tokens(namespace: &str, abi: &str) -> proc_macro2::TokenStream {
match Abigen::generate(
vec![AbigenTarget {
name: namespace.to_string(),
abi: abi.to_owned(),
program_type: ProgramType::Contract,
}],
true,
) {
Ok(tokens) => tokens,
Err(e) => {
proc_macro_error::abort_call_site!(
"Could not generate tokens for abi: {:?}.",
e
)
}
}
}
pub fn process_indexer_module(attrs: TokenStream, item: TokenStream) -> TokenStream {
let config = parse_macro_input!(attrs as IndexerConfig);
let IndexerConfig { manifest } = config;
let path = workspace_manifest_prefix()
.map(|x| Path::new(&x).join(&manifest))
.unwrap_or_else(|| PathBuf::from(&manifest));
let manifest = Manifest::from_file(path).expect("Could not parse manifest.");