subxt_core/custom_values/
address.rs

1// Copyright 2019-2024 Parity Technologies (UK) Ltd.
2// This file is dual-licensed as Apache-2.0 or GPL-3.0.
3// see LICENSE for license details.
4
5//! Construct addresses to access custom values with.
6
7use crate::dynamic::DecodedValueThunk;
8use crate::metadata::DecodeWithMetadata;
9use derive_where::derive_where;
10
11/// Use this with [`Address::IsDecodable`].
12pub use crate::utils::Yes;
13
14/// This represents the address of a custom value in the metadata.
15/// Anything that implements it can be used to fetch custom values from the metadata.
16/// The trait is implemented by [`str`] for dynamic lookup and [`StaticAddress`] for static queries.
17pub trait Address {
18    /// The type of the custom value.
19    type Target: DecodeWithMetadata;
20    /// Should be set to `Yes` for Dynamic values and static values that have a valid type.
21    /// Should be `()` for custom values, that have an invalid type id.
22    type IsDecodable;
23
24    /// the name (key) by which the custom value can be accessed in the metadata.
25    fn name(&self) -> &str;
26
27    /// An optional hash which, if present, can be checked against node metadata.
28    fn validation_hash(&self) -> Option<[u8; 32]> {
29        None
30    }
31}
32
33impl Address for str {
34    type Target = DecodedValueThunk;
35    type IsDecodable = Yes;
36
37    fn name(&self) -> &str {
38        self
39    }
40}
41
42/// A static address to a custom value.
43#[derive_where(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
44pub struct StaticAddress<ReturnTy, IsDecodable> {
45    name: &'static str,
46    hash: Option<[u8; 32]>,
47    phantom: core::marker::PhantomData<(ReturnTy, IsDecodable)>,
48}
49
50impl<ReturnTy, IsDecodable> StaticAddress<ReturnTy, IsDecodable> {
51    #[doc(hidden)]
52    /// Creates a new StaticAddress.
53    pub fn new_static(name: &'static str, hash: [u8; 32]) -> StaticAddress<ReturnTy, IsDecodable> {
54        StaticAddress::<ReturnTy, IsDecodable> {
55            name,
56            hash: Some(hash),
57            phantom: core::marker::PhantomData,
58        }
59    }
60
61    /// Do not validate this custom value prior to accessing it.
62    pub fn unvalidated(self) -> Self {
63        Self {
64            name: self.name,
65            hash: None,
66            phantom: self.phantom,
67        }
68    }
69}
70
71impl<R: DecodeWithMetadata, Y> Address for StaticAddress<R, Y> {
72    type Target = R;
73    type IsDecodable = Y;
74
75    fn name(&self) -> &str {
76        self.name
77    }
78
79    fn validation_hash(&self) -> Option<[u8; 32]> {
80        self.hash
81    }
82}