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

//! Access custom values from metadata.
//!
//! Use [`get`] to retrieve a custom value from some metadata, or [`validate`] to check that a
//! static custom value address lines up with the value seen in the metadata.
//!
//! # Example
//!
//! ```rust
//! use subxt_macro::subxt;
//! use subxt_core::custom_values;
//! use subxt_core::metadata;
//!
//! // If we generate types without `subxt`, we need to point to `::subxt_core`:
//! #[subxt(
//!     crate = "::subxt_core",
//!     runtime_metadata_path = "../artifacts/polkadot_metadata_small.scale",
//! )]
//! pub mod polkadot {}
//!
//! // Some metadata we'd like to access custom values in:
//! let metadata_bytes = include_bytes!("../../../artifacts/polkadot_metadata_small.scale");
//! let metadata = metadata::decode_from(&metadata_bytes[..]).unwrap();
//!
//! // At the moment, we don't expect to see any custom values in the metadata
//! // for Polkadot, so this will return an error:
//! let err = custom_values::get("Foo", &metadata);
//! ```

pub mod address;

use crate::utils::Yes;
use crate::{error::MetadataError, metadata::DecodeWithMetadata, Error, Metadata};
use address::Address;
use alloc::vec::Vec;

/// Run the validation logic against some custom value address you'd like to access. Returns `Ok(())`
/// if the address is valid (or if it's not possible to check since the address has no validation hash).
/// Returns an error if the address was not valid (wrong name, type or raw bytes)
pub fn validate<Addr: Address + ?Sized>(address: &Addr, metadata: &Metadata) -> Result<(), Error> {
    if let Some(actual_hash) = address.validation_hash() {
        let custom = metadata.custom();
        let custom_value = custom
            .get(address.name())
            .ok_or_else(|| MetadataError::CustomValueNameNotFound(address.name().into()))?;
        let expected_hash = custom_value.hash();
        if actual_hash != expected_hash {
            return Err(MetadataError::IncompatibleCodegen.into());
        }
    }
    if metadata.custom().get(address.name()).is_none() {
        return Err(MetadataError::IncompatibleCodegen.into());
    }
    Ok(())
}

/// Access a custom value by the address it is registered under. This can be just a [str] to get back a dynamic value,
/// or a static address from the generated static interface to get a value of a static type returned.
pub fn get<Addr: Address<IsDecodable = Yes> + ?Sized>(
    address: &Addr,
    metadata: &Metadata,
) -> Result<Addr::Target, Error> {
    // 1. Validate custom value shape if hash given:
    validate(address, metadata)?;

    // 2. Attempt to decode custom value:
    let custom_value = metadata.custom_value_by_name_err(address.name())?;
    let value = <Addr::Target as DecodeWithMetadata>::decode_with_metadata(
        &mut custom_value.bytes(),
        custom_value.type_id(),
        metadata,
    )?;
    Ok(value)
}

/// Access the bytes of a custom value by the address it is registered under.
pub fn get_bytes<Addr: Address + ?Sized>(
    address: &Addr,
    metadata: &Metadata,
) -> Result<Vec<u8>, Error> {
    // 1. Validate custom value shape if hash given:
    validate(address, metadata)?;

    // 2. Return the underlying bytes:
    let custom_value = metadata.custom_value_by_name_err(address.name())?;
    Ok(custom_value.bytes().to_vec())
}

#[cfg(test)]
mod tests {
    use super::*;

    use alloc::collections::BTreeMap;
    use codec::Encode;
    use scale_decode::DecodeAsType;
    use scale_info::form::PortableForm;
    use scale_info::TypeInfo;

    use alloc::borrow::ToOwned;
    use alloc::string::String;
    use alloc::vec;

    use crate::custom_values;

    #[derive(Debug, Clone, PartialEq, Eq, Encode, TypeInfo, DecodeAsType)]
    pub struct Person {
        age: u16,
        name: String,
    }

    fn mock_metadata() -> Metadata {
        let person_ty = scale_info::MetaType::new::<Person>();
        let unit = scale_info::MetaType::new::<()>();
        let mut types = scale_info::Registry::new();
        let person_ty_id = types.register_type(&person_ty);
        let unit_id = types.register_type(&unit);
        let types: scale_info::PortableRegistry = types.into();

        let person = Person {
            age: 42,
            name: "Neo".into(),
        };

        let person_value_metadata: frame_metadata::v15::CustomValueMetadata<PortableForm> =
            frame_metadata::v15::CustomValueMetadata {
                ty: person_ty_id,
                value: person.encode(),
            };

        let frame_metadata = frame_metadata::v15::RuntimeMetadataV15 {
            types,
            pallets: vec![],
            extrinsic: frame_metadata::v15::ExtrinsicMetadata {
                version: 0,
                address_ty: unit_id,
                call_ty: unit_id,
                signature_ty: unit_id,
                extra_ty: unit_id,
                signed_extensions: vec![],
            },
            ty: unit_id,
            apis: vec![],
            outer_enums: frame_metadata::v15::OuterEnums {
                call_enum_ty: unit_id,
                event_enum_ty: unit_id,
                error_enum_ty: unit_id,
            },
            custom: frame_metadata::v15::CustomMetadata {
                map: BTreeMap::from_iter([("Mr. Robot".to_owned(), person_value_metadata)]),
            },
        };

        let metadata: subxt_metadata::Metadata = frame_metadata.try_into().unwrap();
        Metadata::from(metadata)
    }

    #[test]
    fn test_decoding() {
        let metadata = mock_metadata();

        assert!(custom_values::get("Invalid Address", &metadata).is_err());
        let person_decoded_value_thunk = custom_values::get("Mr. Robot", &metadata).unwrap();
        let person: Person = person_decoded_value_thunk.as_type().unwrap();
        assert_eq!(
            person,
            Person {
                age: 42,
                name: "Neo".into()
            }
        )
    }
}