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
use core::marker::PhantomData;

use radix_engine_common::prelude::*;

pub trait TypeInfoMarker {
    const PACKAGE_ADDRESS: Option<PackageAddress>;
    const BLUEPRINT_NAME: &'static str;
    const OWNED_TYPE_NAME: &'static str;
    const GLOBAL_TYPE_NAME: &'static str;
}

pub struct Global<T>(pub ComponentAddress, PhantomData<T>)
where
    T: TypeInfoMarker;

pub struct Owned<T>(pub InternalAddress, PhantomData<T>)
where
    T: TypeInfoMarker;

impl<T> Global<T>
where
    T: TypeInfoMarker,
{
    pub fn new(address: ComponentAddress) -> Self {
        Self(address, PhantomData)
    }
}

impl<T> Owned<T>
where
    T: TypeInfoMarker,
{
    pub fn new(address: InternalAddress) -> Self {
        Self(address, PhantomData)
    }
}

impl<O: TypeInfoMarker> Categorize<ScryptoCustomValueKind> for Global<O> {
    #[inline]
    fn value_kind() -> ValueKind<ScryptoCustomValueKind> {
        ValueKind::Custom(ScryptoCustomValueKind::Reference)
    }
}

impl<O: TypeInfoMarker, E: Encoder<ScryptoCustomValueKind>> Encode<ScryptoCustomValueKind, E>
    for Global<O>
{
    #[inline]
    fn encode_value_kind(&self, encoder: &mut E) -> Result<(), EncodeError> {
        encoder.write_value_kind(Self::value_kind())
    }

    #[inline]
    fn encode_body(&self, encoder: &mut E) -> Result<(), EncodeError> {
        self.0.encode_body(encoder)
    }
}

impl<O: TypeInfoMarker, D: Decoder<ScryptoCustomValueKind>> Decode<ScryptoCustomValueKind, D>
    for Global<O>
{
    fn decode_body_with_value_kind(
        decoder: &mut D,
        value_kind: ValueKind<ScryptoCustomValueKind>,
    ) -> Result<Self, DecodeError> {
        ComponentAddress::decode_body_with_value_kind(decoder, value_kind)
            .map(|address| Self(address, Default::default()))
    }
}

impl<T: TypeInfoMarker> Describe<ScryptoCustomTypeKind> for Global<T> {
    const TYPE_ID: RustTypeId =
        RustTypeId::Novel(const_sha1::sha1(T::GLOBAL_TYPE_NAME.as_bytes()).as_bytes());

    fn type_data() -> TypeData<ScryptoCustomTypeKind, RustTypeId> {
        TypeData {
            kind: TypeKind::Custom(ScryptoCustomTypeKind::Reference),
            metadata: TypeMetadata::no_child_names(T::GLOBAL_TYPE_NAME),
            validation: TypeValidation::Custom(ScryptoCustomTypeValidation::Reference(
                ReferenceValidation::IsGlobalTyped(
                    T::PACKAGE_ADDRESS,
                    T::BLUEPRINT_NAME.to_string(),
                ),
            )),
        }
    }

    fn add_all_dependencies(_aggregator: &mut TypeAggregator<ScryptoCustomTypeKind>) {}
}

impl<O: TypeInfoMarker> Categorize<ScryptoCustomValueKind> for Owned<O> {
    #[inline]
    fn value_kind() -> ValueKind<ScryptoCustomValueKind> {
        ValueKind::Custom(ScryptoCustomValueKind::Own)
    }
}

impl<O: TypeInfoMarker, E: Encoder<ScryptoCustomValueKind>> Encode<ScryptoCustomValueKind, E>
    for Owned<O>
{
    #[inline]
    fn encode_value_kind(&self, encoder: &mut E) -> Result<(), EncodeError> {
        encoder.write_value_kind(Self::value_kind())
    }

    #[inline]
    fn encode_body(&self, encoder: &mut E) -> Result<(), EncodeError> {
        self.0.encode_body(encoder)
    }
}

impl<O: TypeInfoMarker, D: Decoder<ScryptoCustomValueKind>> Decode<ScryptoCustomValueKind, D>
    for Owned<O>
{
    fn decode_body_with_value_kind(
        decoder: &mut D,
        value_kind: ValueKind<ScryptoCustomValueKind>,
    ) -> Result<Self, DecodeError> {
        InternalAddress::decode_body_with_value_kind(decoder, value_kind)
            .map(|address| Self(address, Default::default()))
    }
}

impl<T: TypeInfoMarker> Describe<ScryptoCustomTypeKind> for Owned<T> {
    const TYPE_ID: RustTypeId =
        RustTypeId::Novel(const_sha1::sha1(T::OWNED_TYPE_NAME.as_bytes()).as_bytes());

    fn type_data() -> TypeData<ScryptoCustomTypeKind, RustTypeId> {
        TypeData {
            kind: TypeKind::Custom(ScryptoCustomTypeKind::Own),
            metadata: TypeMetadata::no_child_names(T::OWNED_TYPE_NAME),
            validation: TypeValidation::Custom(ScryptoCustomTypeValidation::Own(
                OwnValidation::IsTypedObject(T::PACKAGE_ADDRESS, T::BLUEPRINT_NAME.to_string()),
            )),
        }
    }

    fn add_all_dependencies(_aggregator: &mut TypeAggregator<ScryptoCustomTypeKind>) {}
}

macro_rules! define_type_info_marker {
    ($package_address: expr, $blueprint_name: ident) => {
        paste::paste! {
            pub struct [< $blueprint_name ObjectTypeInfo >];

            impl crate::blueprints::component::TypeInfoMarker
                for [< $blueprint_name ObjectTypeInfo >]
            {
                const PACKAGE_ADDRESS: Option<PackageAddress> = $package_address;
                const BLUEPRINT_NAME: &'static str = stringify!($blueprint_name);
                const OWNED_TYPE_NAME: &'static str = stringify!([< Owned $blueprint_name >]);
                const GLOBAL_TYPE_NAME: &'static str = stringify!([< Global $blueprint_name >]);
            }
        }
    };
}
pub(crate) use define_type_info_marker;

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "alloc")]
    use sbor::prelude::Vec;

    pub const SOME_ADDRESS: PackageAddress =
        PackageAddress::new_or_panic([EntityType::GlobalPackage as u8; NodeId::LENGTH]);

    define_type_info_marker!(Some(SOME_ADDRESS), SomeType);

    #[test]
    fn global_encode_decode() {
        let addr = ComponentAddress::new_or_panic(
            [EntityType::GlobalGenericComponent as u8; NodeId::LENGTH],
        );

        let object = Global::<SomeTypeObjectTypeInfo>::new(addr);
        let mut buf = Vec::new();
        let mut encoder = VecEncoder::<ScryptoCustomValueKind>::new(&mut buf, 1);
        assert!(object.encode_value_kind(&mut encoder).is_ok());
        assert!(object.encode_body(&mut encoder).is_ok());

        let buf_decode = buf.into_iter().skip(1).collect::<Vec<u8>>(); // skip Global value kind, not used in decode_body_with_value_kind() decoding function

        let mut decoder = VecDecoder::<ScryptoCustomValueKind>::new(&buf_decode, 1);
        let output = Global::<SomeTypeObjectTypeInfo>::decode_body_with_value_kind(
            &mut decoder,
            ComponentAddress::value_kind(),
        );
        assert!(output.is_ok());

        let describe = Global::<SomeTypeObjectTypeInfo>::type_data();
        assert_eq!(
            describe.kind,
            TypeKind::Custom(ScryptoCustomTypeKind::Reference)
        );
        assert_eq!(
            describe.metadata.type_name.unwrap().to_string(),
            "GlobalSomeType"
        );
    }

    #[test]
    fn owned_encode_decode() {
        let addr = InternalAddress::new_or_panic(
            [EntityType::InternalGenericComponent as u8; NodeId::LENGTH],
        );

        let object = Owned::<SomeTypeObjectTypeInfo>::new(addr);
        let mut buf = Vec::new();
        let mut encoder = VecEncoder::<ScryptoCustomValueKind>::new(&mut buf, 1);
        assert!(object.encode_value_kind(&mut encoder).is_ok());
        assert!(object.encode_body(&mut encoder).is_ok());

        let buf_decode = buf.into_iter().skip(1).collect::<Vec<u8>>(); // skip Owned value kind, not used in decode_body_with_value_kind() decoding function

        let mut decoder = VecDecoder::<ScryptoCustomValueKind>::new(&buf_decode, 1);
        let output = Owned::<SomeTypeObjectTypeInfo>::decode_body_with_value_kind(
            &mut decoder,
            InternalAddress::value_kind(),
        );
        assert_eq!(output.err(), None);

        let describe = Owned::<SomeTypeObjectTypeInfo>::type_data();
        assert_eq!(describe.kind, TypeKind::Custom(ScryptoCustomTypeKind::Own));
        assert_eq!(
            describe.metadata.type_name.unwrap().to_string(),
            "OwnedSomeType"
        );
    }
}