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
// Copyright 2019-2022 Parity Technologies (UK) Ltd.
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.

#[cfg(feature = "decoder")]
use super::decoder::DecoderBuilder;
use super::hash_cache::HashCache;
use codec::Error as CodecError;
use frame_metadata::{
    PalletConstantMetadata,
    RuntimeMetadata,
    RuntimeMetadataPrefixed,
    RuntimeMetadataV14,
    StorageEntryMetadata,
    META_RESERVED,
};
use parking_lot::RwLock;
use scale_info::{
    form::PortableForm,
    PortableRegistry,
    Type,
};
use std::{
    collections::HashMap,
    convert::TryFrom,
    sync::Arc,
};

#[cfg(feature = "decoder")]
use crate::{
    u8_map::U8Map,
    Error,
};
#[cfg(feature = "decoder")]
use scale_info::IntoPortable;

/// Path key
#[cfg(feature = "decoder")]
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct PathKey(Vec<String>);

#[cfg(feature = "decoder")]
impl PathKey {
    /// From path key
    pub fn from_type<T>() -> Self
    where
        T: scale_info::TypeInfo,
    {
        let type_info = T::type_info();
        let path = type_info
            .path()
            .clone()
            .into_portable(&mut Default::default());
        PathKey::from(&path)
    }
}

#[cfg(feature = "decoder")]
impl From<&scale_info::Path<PortableForm>> for PathKey {
    fn from(path: &scale_info::Path<PortableForm>) -> Self {
        PathKey(path.segments().to_vec())
    }
}

/// Metadata error originated from inspecting the internal representation of the runtime metadata.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum MetadataError {
    /// Module is not in metadata.
    #[error("Pallet not found")]
    PalletNotFound,
    /// Pallet is not in metadata.
    #[error("Pallet index {0} not found")]
    PalletIndexNotFound(u8),
    /// Call is not in metadata.
    #[error("Call not found")]
    CallNotFound,
    /// Event is not in metadata.
    #[error("Pallet {0}, Event {0} not found")]
    EventNotFound(u8, u8),
    /// Event is not in metadata.
    #[error("Pallet {0}, Error {0} not found")]
    ErrorNotFound(u8, u8),
    /// Storage is not in metadata.
    #[error("Storage not found")]
    StorageNotFound,
    /// Storage type does not match requested type.
    #[error("Storage type error")]
    StorageTypeError,
    /// Default error.
    #[error("Failed to decode default: {0}")]
    DefaultError(CodecError),
    /// Failure to decode constant value.
    #[error("Failed to decode constant value: {0}")]
    ConstantValueError(CodecError),
    /// Constant is not in metadata.
    #[error("Constant not found")]
    ConstantNotFound,
    /// Type is not in metadata.
    #[error("Type {0} missing from type registry")]
    TypeNotFound(u32),
    /// Runtime constant metadata is incompatible with the static one.
    #[error("Pallet {0} Constant {0} has incompatible metadata")]
    IncompatibleConstantMetadata(String, String),
    /// Runtime call metadata is incompatible with the static one.
    #[error("Pallet {0} Call {0} has incompatible metadata")]
    IncompatibleCallMetadata(String, String),
    /// Runtime storage metadata is incompatible with the static one.
    #[error("Pallet {0} Storage {0} has incompatible metadata")]
    IncompatibleStorageMetadata(String, String),
    /// Runtime metadata is not fully compatible with the static one.
    #[error("Node metadata is not fully compatible")]
    IncompatibleMetadata,
}

// We hide the innards behind an Arc so that it's easy to clone and share.
#[derive(Debug)]
struct MetadataInner {
    metadata: RuntimeMetadataV14,
    pallets: HashMap<String, PalletMetadata>,
    events: HashMap<(u8, u8), EventMetadata>,
    // Errors are hashed by pallet index.
    errors: HashMap<(u8, u8), ErrorMetadata>,
    // Type of the DispatchError type, which is what comes back if
    // an extrinsic fails.
    dispatch_error_ty: Option<u32>,
    // The hashes uniquely identify parts of the metadata; different
    // hashes mean some type difference exists between static and runtime
    // versions. We cache them here to avoid recalculating:
    cached_metadata_hash: RwLock<Option<[u8; 32]>>,
    cached_call_hashes: HashCache,
    cached_constant_hashes: HashCache,
    cached_storage_hashes: HashCache,
    #[cfg(feature = "decoder")]
    decoder: super::Decoder,
}

/// Metadata pallet calls
#[cfg(feature = "decoder")]
#[derive(Debug)]
pub struct MetadataPalletCalls {
    /// The pallet name.
    pub name: String,
    /// Metadata may not contain call information. If it does,
    /// it'll be here.
    pub calls: Option<MetadataCalls>,
}

#[cfg(feature = "decoder")]
#[derive(Debug)]
pub struct MetadataCalls {
    /// This allows us to find the type information corresponding to
    /// the call in the [`PortableRegistry`]/
    pub calls_type_id: scale_info::interner::UntrackedSymbol<std::any::TypeId>,
    /// This allows us to map a u8 enum index to the correct call variant
    /// from the calls type, above. The variant contains information on the
    /// fields and such that the call has.
    pub call_variant_indexes: U8Map<usize>,
}

/// A representation of the runtime metadata received from a node.
#[derive(Clone, Debug)]
pub struct Metadata {
    inner: Arc<MetadataInner>,
}

impl Metadata {
    /// Returns a reference to [`PalletMetadata`].
    pub fn pallet(&self, name: &str) -> Result<&PalletMetadata, MetadataError> {
        self.inner
            .pallets
            .get(name)
            .ok_or(MetadataError::PalletNotFound)
    }

    /// Returns the metadata for the event at the given pallet and event indices.
    pub fn event(
        &self,
        pallet_index: u8,
        event_index: u8,
    ) -> Result<&EventMetadata, MetadataError> {
        let event = self
            .inner
            .events
            .get(&(pallet_index, event_index))
            .ok_or(MetadataError::EventNotFound(pallet_index, event_index))?;
        Ok(event)
    }

    /// Returns the metadata for the error at the given pallet and error indices.
    pub fn error(
        &self,
        pallet_index: u8,
        error_index: u8,
    ) -> Result<&ErrorMetadata, MetadataError> {
        let error = self
            .inner
            .errors
            .get(&(pallet_index, error_index))
            .ok_or(MetadataError::ErrorNotFound(pallet_index, error_index))?;
        Ok(error)
    }

    /// Return the DispatchError type ID if it exists.
    pub fn dispatch_error_ty(&self) -> Option<u32> {
        self.inner.dispatch_error_ty
    }

    /// Return the type registry embedded within the metadata.
    pub fn types(&self) -> &PortableRegistry {
        &self.inner.metadata.types
    }

    /// Resolve a type definition.
    pub fn resolve_type(&self, id: u32) -> Option<&Type<PortableForm>> {
        self.inner.metadata.types.resolve(id)
    }

    /// Decode extrinsic
    #[cfg(feature = "decoder")]
    pub fn decode_extrinsic(
        &self,
        data: &mut &[u8],
    ) -> Result<super::decoder::Extrinsic, Error> {
        self.inner.decoder.decode_extrinsic(data)
    }

    /// Decode extrinsic
    #[cfg(feature = "decoder")]
    pub fn decode_as_type(
        &self,
        type_id: u32,
        input: &mut &[u8],
    ) -> Result<scale_value::Value<scale_value::scale::TypeId>, Error> {
        self.inner.decoder.decode(type_id, input)
    }

    /// Return the runtime metadata.
    pub fn runtime_metadata(&self) -> &RuntimeMetadataV14 {
        &self.inner.metadata
    }

    /// Obtain the unique hash for a specific storage entry.
    pub fn storage_hash(
        &self,
        pallet: &str,
        storage: &str,
    ) -> Result<[u8; 32], MetadataError> {
        self.inner
            .cached_storage_hashes
            .get_or_insert(pallet, storage, || {
                subxt_metadata::get_storage_hash(&self.inner.metadata, pallet, storage)
                    .map_err(|e| {
                        match e {
                            subxt_metadata::NotFound::Pallet => {
                                MetadataError::PalletNotFound
                            }
                            subxt_metadata::NotFound::Item => {
                                MetadataError::StorageNotFound
                            }
                        }
                    })
            })
    }

    /// Obtain the unique hash for a constant.
    pub fn constant_hash(
        &self,
        pallet: &str,
        constant: &str,
    ) -> Result<[u8; 32], MetadataError> {
        self.inner
            .cached_constant_hashes
            .get_or_insert(pallet, constant, || {
                subxt_metadata::get_constant_hash(&self.inner.metadata, pallet, constant)
                    .map_err(|e| {
                        match e {
                            subxt_metadata::NotFound::Pallet => {
                                MetadataError::PalletNotFound
                            }
                            subxt_metadata::NotFound::Item => {
                                MetadataError::ConstantNotFound
                            }
                        }
                    })
            })
    }

    /// Obtain the unique hash for a call.
    pub fn call_hash(
        &self,
        pallet: &str,
        function: &str,
    ) -> Result<[u8; 32], MetadataError> {
        self.inner
            .cached_call_hashes
            .get_or_insert(pallet, function, || {
                subxt_metadata::get_call_hash(&self.inner.metadata, pallet, function)
                    .map_err(|e| {
                        match e {
                            subxt_metadata::NotFound::Pallet => {
                                MetadataError::PalletNotFound
                            }
                            subxt_metadata::NotFound::Item => MetadataError::CallNotFound,
                        }
                    })
            })
    }

    /// Obtain the unique hash for this metadata.
    pub fn metadata_hash<T: AsRef<str>>(&self, pallets: &[T]) -> [u8; 32] {
        if let Some(hash) = *self.inner.cached_metadata_hash.read() {
            return hash
        }

        let hash = subxt_metadata::get_metadata_per_pallet_hash(
            self.runtime_metadata(),
            pallets,
        );
        *self.inner.cached_metadata_hash.write() = Some(hash);

        hash
    }
}

/// Metadata for a specific pallet.
#[derive(Clone, Debug)]
pub struct PalletMetadata {
    index: u8,
    name: String,
    call_indexes: HashMap<String, u8>,
    call_ty_id: Option<u32>,
    storage: HashMap<String, StorageEntryMetadata<PortableForm>>,
    constants: HashMap<String, PalletConstantMetadata<PortableForm>>,
}

impl PalletMetadata {
    /// Get the name of the pallet.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the index of this pallet.
    pub fn index(&self) -> u8 {
        self.index
    }

    /// If calls exist for this pallet, this returns the type ID of the variant
    /// representing the different possible calls.
    pub fn call_ty_id(&self) -> Option<u32> {
        self.call_ty_id
    }

    /// Attempt to resolve a call into an index in this pallet, failing
    /// if the call is not found in this pallet.
    pub fn call_index(&self, function: &str) -> Result<u8, MetadataError> {
        let fn_index = *self
            .call_indexes
            .get(function)
            .ok_or(MetadataError::CallNotFound)?;
        Ok(fn_index)
    }

    /// Return [`StorageEntryMetadata`] given some storage key.
    pub fn storage(
        &self,
        key: &str,
    ) -> Result<&StorageEntryMetadata<PortableForm>, MetadataError> {
        self.storage.get(key).ok_or(MetadataError::StorageNotFound)
    }

    /// Get a constant's metadata by name.
    pub fn constant(
        &self,
        key: &str,
    ) -> Result<&PalletConstantMetadata<PortableForm>, MetadataError> {
        self.constants
            .get(key)
            .ok_or(MetadataError::ConstantNotFound)
    }
}

/// Metadata for specific field.
#[derive(Clone, Debug)]
pub struct EventFieldMetadata {
    name: Option<String>,
    type_name: Option<String>,
    type_id: u32,
}

impl EventFieldMetadata {
    /// Construct a new [`EventFieldMetadata`]
    pub fn new(name: Option<String>, type_name: Option<String>, type_id: u32) -> Self {
        EventFieldMetadata {
            name,
            type_name,
            type_id,
        }
    }

    /// Get the name of the field.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Get the type name of the field as it appears in the code
    pub fn type_name(&self) -> Option<&str> {
        self.type_name.as_deref()
    }

    /// Get the id of a type
    pub fn type_id(&self) -> u32 {
        self.type_id
    }
}

/// Metadata for specific events.
#[derive(Clone, Debug)]
pub struct EventMetadata {
    // The pallet name is shared across every event, so put it
    // behind an Arc to avoid lots of needless clones of it existing.
    pallet: Arc<str>,
    event: String,
    fields: Vec<EventFieldMetadata>,
    docs: Vec<String>,
}

impl EventMetadata {
    /// Get the name of the pallet from which the event was emitted.
    pub fn pallet(&self) -> &str {
        &self.pallet
    }

    /// Get the name of the pallet event which was emitted.
    pub fn event(&self) -> &str {
        &self.event
    }

    /// The names, type names & types of each field in the event.
    pub fn fields(&self) -> &[EventFieldMetadata] {
        &self.fields
    }

    /// Documentation for this event.
    pub fn docs(&self) -> &[String] {
        &self.docs
    }
}

/// Details about a specific runtime error.
#[derive(Clone, Debug)]
pub struct ErrorMetadata {
    // The pallet name is shared across every event, so put it
    // behind an Arc to avoid lots of needless clones of it existing.
    pallet: Arc<str>,
    error: String,
    docs: Vec<String>,
}

impl ErrorMetadata {
    /// Get the name of the pallet from which the error originates.
    pub fn pallet(&self) -> &str {
        &self.pallet
    }

    /// The name of the error.
    pub fn error(&self) -> &str {
        &self.error
    }

    /// Documentation for the error.
    pub fn docs(&self) -> &[String] {
        &self.docs
    }
}

/// Error originated from converting a runtime metadata [RuntimeMetadataPrefixed] to
/// the internal [Metadata] representation.
#[derive(Debug, thiserror::Error)]
pub enum InvalidMetadataError {
    /// Invalid prefix
    #[error("Invalid prefix")]
    InvalidPrefix,
    /// Invalid version
    #[error("Invalid version")]
    InvalidVersion,
    /// Type missing from type registry
    #[error("Type {0} missing from type registry")]
    MissingType(u32),
    /// Type was not a variant/enum type
    #[error("Type {0} was not a variant/enum type")]
    TypeDefNotVariant(u32),
    /// Something went wrong
    #[error("{0}")]
    Other(String),
    /// Unable to create decoder
    #[cfg(feature = "decoder")]
    #[error("Unable to initialize decoder")]
    InvalidDecoderBuilder,
}

impl TryFrom<RuntimeMetadataPrefixed> for Metadata {
    type Error = InvalidMetadataError;

    fn try_from(metadata: RuntimeMetadataPrefixed) -> Result<Self, Self::Error> {
        if metadata.0 != META_RESERVED {
            return Err(InvalidMetadataError::InvalidPrefix)
        }
        let metadata = match metadata.1 {
            RuntimeMetadata::V14(meta) => meta,
            _ => return Err(InvalidMetadataError::InvalidVersion),
        };

        let get_type_def_variant = |type_id: u32| {
            let ty = metadata
                .types
                .resolve(type_id)
                .ok_or(InvalidMetadataError::MissingType(type_id))?;
            if let scale_info::TypeDef::Variant(var) = ty.type_def() {
                Ok(var)
            } else {
                Err(InvalidMetadataError::TypeDefNotVariant(type_id))
            }
        };
        let pallets = metadata
            .pallets
            .iter()
            .map(|pallet| {
                let call_ty_id = pallet.calls.as_ref().map(|c| c.ty.id());

                let call_indexes =
                    pallet.calls.as_ref().map_or(Ok(HashMap::new()), |call| {
                        let type_def_variant = get_type_def_variant(call.ty.id())?;
                        let call_indexes = type_def_variant
                            .variants()
                            .iter()
                            .map(|v| (v.name().clone(), v.index()))
                            .collect();
                        Ok(call_indexes)
                    })?;

                let storage = pallet.storage.as_ref().map_or(HashMap::new(), |storage| {
                    storage
                        .entries
                        .iter()
                        .map(|entry| (entry.name.clone(), entry.clone()))
                        .collect()
                });

                let constants = pallet
                    .constants
                    .iter()
                    .map(|constant| (constant.name.clone(), constant.clone()))
                    .collect();

                let pallet_metadata = PalletMetadata {
                    index: pallet.index,
                    name: pallet.name.to_string(),
                    call_indexes,
                    call_ty_id,
                    storage,
                    constants,
                };

                Ok((pallet.name.to_string(), pallet_metadata))
            })
            .collect::<Result<_, _>>()?;

        let mut events = HashMap::<(u8, u8), EventMetadata>::new();
        for pallet in &metadata.pallets {
            if let Some(event) = &pallet.event {
                let pallet_name: Arc<str> = pallet.name.to_string().into();
                let event_type_id = event.ty.id();
                let event_variant = get_type_def_variant(event_type_id)?;
                for variant in event_variant.variants() {
                    events.insert(
                        (pallet.index, variant.index()),
                        EventMetadata {
                            pallet: pallet_name.clone(),
                            event: variant.name().to_owned(),
                            fields: variant
                                .fields()
                                .iter()
                                .map(|f| {
                                    EventFieldMetadata::new(
                                        f.name().map(|n| n.to_owned()),
                                        f.type_name().map(|n| n.to_owned()),
                                        f.ty().id(),
                                    )
                                })
                                .collect(),
                            docs: variant.docs().to_vec(),
                        },
                    );
                }
            }
        }

        let mut errors = HashMap::<(u8, u8), ErrorMetadata>::new();
        for pallet in &metadata.pallets {
            if let Some(error) = &pallet.error {
                let pallet_name: Arc<str> = pallet.name.to_string().into();
                let error_variant = get_type_def_variant(error.ty.id())?;
                for variant in error_variant.variants() {
                    errors.insert(
                        (pallet.index, variant.index()),
                        ErrorMetadata {
                            pallet: pallet_name.clone(),
                            error: variant.name().clone(),
                            docs: variant.docs().to_vec(),
                        },
                    );
                }
            }
        }

        let dispatch_error_ty = metadata
            .types
            .types()
            .iter()
            .find(|ty| ty.ty().path().segments() == ["sp_runtime", "DispatchError"])
            .map(|ty| ty.id());

        #[cfg(feature = "decoder")]
        let mut pallet_calls_by_index = U8Map::new();
        // Gather information about the calls/storage in use:
        #[cfg(feature = "decoder")]
        for pallet in &metadata.pallets {
            // capture the call information in this pallet:
            let calls = pallet
                .calls
                .as_ref()
                .map(|call_md| {
                    // Get the type representing the variant of available calls:
                    let calls_type_id = call_md.ty;
                    let calls_type =
                        metadata.types.resolve(calls_type_id.id()).ok_or_else(|| {
                            InvalidMetadataError::Other(format!(
                                "Error not found {}",
                                calls_type_id.id()
                            ))
                        })?;

                    // Expect that type to be a variant:
                    let calls_type_def = calls_type.type_def();
                    let calls_variant = match calls_type_def {
                        scale_info::TypeDef::Variant(variant) => variant,
                        _ => {
                            return Err(InvalidMetadataError::Other(format!(
                                "Invalid call {:?}",
                                calls_type_def
                            )))
                        }
                    };

                    // Store the mapping from u8 index to variant slice index for quicker decode lookup:
                    let call_variant_indexes = calls_variant
                        .variants()
                        .iter()
                        .enumerate()
                        .map(|(idx, v)| (v.index(), idx))
                        .collect();

                    Ok(MetadataCalls {
                        calls_type_id,
                        call_variant_indexes,
                    })
                })
                .transpose()
                .map_err(|err| {
                    InvalidMetadataError::Other(format!("Something wrong {}", err))
                })?;

            pallet_calls_by_index.insert(
                pallet.index,
                MetadataPalletCalls {
                    name: pallet.name.to_owned(),
                    calls,
                },
            );
        }

        #[cfg(feature = "decoder")]
        let decoder = DecoderBuilder::new(
            metadata.types.clone(),
            pallet_calls_by_index,
            metadata.extrinsic.signed_extensions.clone(),
        )
        .with_default_custom_type_decodes()
        .build()
        .map_err(|_| InvalidMetadataError::InvalidDecoderBuilder)?;

        Ok(Metadata {
            inner: Arc::new(MetadataInner {
                metadata,
                pallets,
                events,
                errors,
                dispatch_error_ty,
                cached_metadata_hash: Default::default(),
                cached_call_hashes: Default::default(),
                cached_constant_hashes: Default::default(),
                cached_storage_hashes: Default::default(),
                #[cfg(feature = "decoder")]
                decoder,
            }),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use frame_metadata::{
        ExtrinsicMetadata,
        PalletStorageMetadata,
        StorageEntryModifier,
        StorageEntryType,
    };
    use scale_info::{
        meta_type,
        TypeInfo,
    };

    fn load_metadata() -> Metadata {
        #[allow(dead_code)]
        #[allow(non_camel_case_types)]
        #[derive(TypeInfo)]
        enum Call {
            fill_block { param: u128 },
        }
        let storage = PalletStorageMetadata {
            prefix: "System",
            entries: vec![StorageEntryMetadata {
                name: "Account",
                modifier: StorageEntryModifier::Optional,
                ty: StorageEntryType::Plain(meta_type::<u32>()),
                default: vec![0],
                docs: vec![],
            }],
        };
        let constant = PalletConstantMetadata {
            name: "BlockWeights",
            ty: meta_type::<u32>(),
            value: vec![1, 2, 3],
            docs: vec![],
        };
        let pallet = frame_metadata::PalletMetadata {
            index: 0,
            name: "System",
            calls: Some(frame_metadata::PalletCallMetadata {
                ty: meta_type::<Call>(),
            }),
            storage: Some(storage),
            constants: vec![constant],
            event: None,
            error: None,
        };

        let metadata = RuntimeMetadataV14::new(
            vec![pallet],
            ExtrinsicMetadata {
                ty: meta_type::<()>(),
                version: 0,
                signed_extensions: vec![],
            },
            meta_type::<()>(),
        );
        let prefixed = RuntimeMetadataPrefixed::from(metadata);

        Metadata::try_from(prefixed)
            .expect("Cannot translate runtime metadata to internal Metadata")
    }

    #[test]
    fn metadata_inner_cache() {
        // Note: Dependency on test_runtime can be removed if complex metadata
        // is manually constructed.
        let metadata = load_metadata();

        let hash = metadata.metadata_hash(&["System"]);
        // Check inner caching.
        assert_eq!(metadata.inner.cached_metadata_hash.read().unwrap(), hash);

        // The cache `metadata.inner.cached_metadata_hash` is already populated from
        // the previous call. Therefore, changing the pallets argument must not
        // change the methods behavior.
        let hash_old = metadata.metadata_hash(&["no-pallet"]);
        assert_eq!(hash_old, hash);
    }

    #[test]
    fn metadata_call_inner_cache() {
        let metadata = load_metadata();

        let hash = metadata.call_hash("System", "fill_block");

        let mut call_number = 0;
        let hash_cached = metadata.inner.cached_call_hashes.get_or_insert(
            "System",
            "fill_block",
            || -> Result<[u8; 32], MetadataError> {
                call_number += 1;
                Ok([0; 32])
            },
        );

        // Check function is never called (e.i, value fetched from cache).
        assert_eq!(call_number, 0);
        assert_eq!(hash.unwrap(), hash_cached.unwrap());
    }

    #[test]
    fn metadata_constant_inner_cache() {
        let metadata = load_metadata();

        let hash = metadata.constant_hash("System", "BlockWeights");

        let mut call_number = 0;
        let hash_cached = metadata.inner.cached_constant_hashes.get_or_insert(
            "System",
            "BlockWeights",
            || -> Result<[u8; 32], MetadataError> {
                call_number += 1;
                Ok([0; 32])
            },
        );

        // Check function is never called (e.i, value fetched from cache).
        assert_eq!(call_number, 0);
        assert_eq!(hash.unwrap(), hash_cached.unwrap());
    }

    #[test]
    fn metadata_storage_inner_cache() {
        let metadata = load_metadata();
        let hash = metadata.storage_hash("System", "Account");

        let mut call_number = 0;
        let hash_cached = metadata.inner.cached_storage_hashes.get_or_insert(
            "System",
            "Account",
            || -> Result<[u8; 32], MetadataError> {
                call_number += 1;
                Ok([0; 32])
            },
        );

        // Check function is never called (e.i, value fetched from cache).
        assert_eq!(call_number, 0);
        assert_eq!(hash.unwrap(), hash_cached.unwrap());
    }
}