1use async_graphql::*;
6use iota_sdk_types::{MoveObjectType, StructTag, TypeTag};
7use move_binary_format::file_format::AbilitySet;
8use move_core_types::annotated_value as A;
9use serde::{Deserialize, Serialize};
10
11use crate::{
12 data::package_resolver::PackageResolver, error::Error, types::open_move_type::MoveAbility,
13};
14
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub(crate) struct MoveType {
17 pub native: TypeTag,
18}
19
20scalar!(
21 MoveTypeSignature,
22 "MoveTypeSignature",
23 "The signature of a concrete Move Type (a type with all its type parameters instantiated with \
24 concrete types, that contains no references), corresponding to the following recursive type:
25
26type MoveTypeSignature =
27 \"address\"
28 | \"bool\"
29 | \"u8\" | \"u16\" | ... | \"u256\"
30 | { vector: MoveTypeSignature }
31 | {
32 datatype: {
33 package: string,
34 module: string,
35 type: string,
36 typeParameters: [MoveTypeSignature],
37 }
38 }"
39);
40
41scalar!(
42 MoveTypeLayout,
43 "MoveTypeLayout",
44 "The shape of a concrete Move Type (a type with all its type parameters instantiated with \
45 concrete types), corresponding to the following recursive type:
46
47type MoveTypeLayout =
48 \"address\"
49 | \"bool\"
50 | \"u8\" | \"u16\" | ... | \"u256\"
51 | { vector: MoveTypeLayout }
52 | {
53 struct: {
54 type: string,
55 fields: [{ name: string, layout: MoveTypeLayout }],
56 }
57 }
58 | { enum: [{
59 type: string,
60 variants: [{
61 name: string,
62 fields: [{ name: string, layout: MoveTypeLayout }],
63 }]
64 }]
65 }"
66);
67
68#[derive(Serialize, Deserialize, Debug)]
69#[serde(rename_all = "camelCase")]
70pub(crate) enum MoveTypeSignature {
71 Address,
72 Bool,
73 U8,
74 U16,
75 U32,
76 U64,
77 U128,
78 U256,
79 Vector(Box<MoveTypeSignature>),
80 Datatype {
81 package: String,
82 module: String,
83 #[serde(rename = "type")]
84 type_: String,
85 #[serde(rename = "typeParameters")]
86 type_parameters: Vec<MoveTypeSignature>,
87 },
88}
89
90#[derive(Serialize, Deserialize)]
91#[serde(rename_all = "camelCase")]
92pub(crate) enum MoveTypeLayout {
93 Address,
94 Bool,
95 U8,
96 U16,
97 U32,
98 U64,
99 U128,
100 U256,
101 Vector(Box<MoveTypeLayout>),
102 Struct(MoveStructLayout),
103 Enum(MoveEnumLayout),
104 InvalidType,
105}
106
107#[derive(Serialize, Deserialize)]
108pub(crate) struct MoveStructLayout {
109 #[serde(rename = "type")]
110 type_: String,
111 fields: Vec<MoveFieldLayout>,
112}
113
114#[derive(Serialize, Deserialize)]
115pub(crate) struct MoveEnumLayout {
116 variants: Vec<MoveVariantLayout>,
117}
118
119#[derive(Serialize, Deserialize)]
120pub(crate) struct MoveVariantLayout {
121 name: String,
122 layout: Vec<MoveFieldLayout>,
123}
124
125#[derive(Serialize, Deserialize)]
126pub(crate) struct MoveFieldLayout {
127 name: String,
128 layout: MoveTypeLayout,
129}
130
131#[Object]
133impl MoveType {
134 async fn repr(&self) -> String {
136 self.native.to_canonical_string(true)
137 }
138
139 async fn signature(&self) -> Result<MoveTypeSignature> {
141 self.signature_impl().extend()
144 }
145
146 async fn layout(&self, ctx: &Context<'_>) -> Result<MoveTypeLayout> {
148 let resolver: &PackageResolver = ctx
149 .data()
150 .map_err(|_| Error::Internal("Unable to fetch Package Cache.".to_string()))
151 .extend()?;
152
153 let layout = self.layout_impl(resolver).await.extend()?;
154
155 MoveTypeLayout::try_from(layout).extend()
156 }
157
158 async fn abilities(&self, ctx: &Context<'_>) -> Result<Vec<MoveAbility>> {
160 let resolver: &PackageResolver = ctx
161 .data()
162 .map_err(|_| Error::Internal("Unable to fetch Package Cache.".to_string()))
163 .extend()?;
164
165 let abilities = self.abilities_impl(resolver).await.extend()?;
166
167 Ok(abilities.into_iter().map(MoveAbility::from).collect())
168 }
169}
170
171impl MoveType {
172 fn signature_impl(&self) -> Result<MoveTypeSignature, Error> {
173 MoveTypeSignature::try_from(self.native.clone())
174 }
175
176 pub(crate) async fn layout_impl(
177 &self,
178 resolver: &PackageResolver,
179 ) -> Result<A::MoveTypeLayout, Error> {
180 resolver
181 .type_layout(self.native.clone())
182 .await
183 .map_err(|e| {
184 Error::Internal(format!(
185 "Error calculating layout for {}: {e}",
186 self.native.to_canonical_string(true),
187 ))
188 })
189 }
190
191 pub(crate) async fn abilities_impl(
192 &self,
193 resolver: &PackageResolver,
194 ) -> Result<AbilitySet, Error> {
195 resolver.abilities(self.native.clone()).await.map_err(|e| {
196 Error::Internal(format!(
197 "Error calculating abilities for {}: {e}",
198 self.native.to_canonical_string(true),
199 ))
200 })
201 }
202}
203
204impl From<MoveObjectType> for MoveType {
205 fn from(obj: MoveObjectType) -> Self {
206 obj.into_struct_tag().into()
207 }
208}
209
210impl From<StructTag> for MoveType {
211 fn from(tag: StructTag) -> Self {
212 let tag: TypeTag = tag.into();
213 Self { native: tag }
214 }
215}
216
217impl From<TypeTag> for MoveType {
218 fn from(native: TypeTag) -> Self {
219 Self { native }
220 }
221}
222
223impl TryFrom<TypeTag> for MoveTypeSignature {
224 type Error = Error;
225
226 fn try_from(tag: TypeTag) -> Result<Self, Error> {
227 use TypeTag as T;
228
229 Ok(match tag {
230 T::Signer => return Err(unexpected_signer_error()),
231
232 T::U8 => Self::U8,
233 T::U16 => Self::U16,
234 T::U32 => Self::U32,
235 T::U64 => Self::U64,
236 T::U128 => Self::U128,
237 T::U256 => Self::U256,
238
239 T::Bool => Self::Bool,
240 T::Address => Self::Address,
241
242 T::Vector(v) => Self::Vector(Box::new(Self::try_from(*v)?)),
243
244 T::Struct(s) => Self::Datatype {
245 package: s.address().to_canonical_string(true),
246 module: s.module().as_str().to_owned(),
247 type_: s.name().as_str().to_owned(),
248 type_parameters: s
249 .type_params()
250 .iter()
251 .cloned()
252 .map(Self::try_from)
253 .collect::<Result<Vec<_>, _>>()?,
254 },
255 })
256 }
257}
258
259impl TryFrom<A::MoveTypeLayout> for MoveTypeLayout {
260 type Error = Error;
261
262 fn try_from(layout: A::MoveTypeLayout) -> Result<Self, Error> {
263 use A::MoveTypeLayout as TL;
264
265 Ok(match layout {
266 TL::Signer => return Err(unexpected_signer_error()),
267
268 TL::U8 => Self::U8,
269 TL::U16 => Self::U16,
270 TL::U32 => Self::U32,
271 TL::U64 => Self::U64,
272 TL::U128 => Self::U128,
273 TL::U256 => Self::U256,
274
275 TL::Bool => Self::Bool,
276 TL::Address => Self::Address,
277
278 TL::Vector(v) => Self::Vector(Box::new(Self::try_from(*v)?)),
279 TL::Struct(s) => Self::Struct((*s).try_into()?),
280 TL::Enum(e) => Self::Enum((*e).try_into()?),
281 })
282 }
283}
284
285impl TryFrom<A::MoveEnumLayout> for MoveEnumLayout {
286 type Error = Error;
287
288 fn try_from(layout: A::MoveEnumLayout) -> Result<Self, Error> {
289 let A::MoveEnumLayout { variants, .. } = layout;
290 let mut variant_layouts = Vec::new();
291 for ((name, _), variant_fields) in variants {
292 let mut field_layouts = Vec::new();
293 for field in variant_fields {
294 field_layouts.push(MoveFieldLayout::try_from(field)?);
295 }
296 variant_layouts.push(MoveVariantLayout {
297 name: name.to_string(),
298 layout: field_layouts,
299 });
300 }
301
302 Ok(MoveEnumLayout {
303 variants: variant_layouts,
304 })
305 }
306}
307
308impl TryFrom<A::MoveStructLayout> for MoveStructLayout {
309 type Error = Error;
310
311 fn try_from(layout: A::MoveStructLayout) -> Result<Self, Error> {
312 Ok(Self {
313 type_: layout.type_.to_canonical_string(true),
314 fields: layout
315 .fields
316 .into_iter()
317 .map(MoveFieldLayout::try_from)
318 .collect::<Result<_, _>>()?,
319 })
320 }
321}
322
323impl TryFrom<A::MoveFieldLayout> for MoveFieldLayout {
324 type Error = Error;
325
326 fn try_from(layout: A::MoveFieldLayout) -> Result<Self, Error> {
327 Ok(Self {
328 name: layout.name.to_string(),
329 layout: layout.layout.try_into()?,
330 })
331 }
332}
333
334pub(crate) fn unexpected_signer_error() -> Error {
337 Error::Internal("Unexpected value of type: signer.".to_string())
338}
339
340#[cfg(test)]
341mod tests {
342 use std::str::FromStr;
343
344 use expect_test::expect;
345
346 use super::*;
347
348 fn signature(repr: impl Into<String>) -> Result<MoveTypeSignature, Error> {
349 let tag = TypeTag::from_str(repr.into().as_str()).unwrap();
350 MoveType::from(tag).signature_impl()
351 }
352
353 #[test]
354 fn complex_type() {
355 let sig = signature("vector<0x42::foo::Bar<address, u32, bool, u256>>").unwrap();
356 let expect = expect![[r#"
357 Vector(
358 Datatype {
359 package: "0x0000000000000000000000000000000000000000000000000000000000000042",
360 module: "foo",
361 type_: "Bar",
362 type_parameters: [
363 Address,
364 U32,
365 Bool,
366 U256,
367 ],
368 },
369 )"#]];
370 expect.assert_eq(&format!("{sig:#?}"));
371 }
372
373 #[test]
374 fn signer_type() {
375 let err = signature("signer").unwrap_err();
376 let expect = expect![[r#"Internal("Unexpected value of type: signer.")"#]];
377 expect.assert_eq(&format!("{err:?}"));
378 }
379
380 #[test]
381 fn nested_signer_type() {
382 let err = signature("0x42::baz::Qux<u32, vector<signer>>").unwrap_err();
383 let expect = expect![[r#"Internal("Unexpected value of type: signer.")"#]];
384 expect.assert_eq(&format!("{err:?}"));
385 }
386}