ab_contracts_common/
metadata.rs

1mod compact;
2pub mod decode;
3#[cfg(test)]
4mod tests;
5
6use crate::metadata::compact::compact_metadata;
7use ab_contracts_io_type::metadata::MAX_METADATA_CAPACITY;
8
9/// Metadata for smart contact methods.
10///
11/// Metadata encoding consists of this enum variant treated as `u8` followed by optional metadata
12/// encoding rules specific to metadata type variant (see variant's description).
13///
14/// This metadata is enough to fully reconstruct the hierarchy of the type to generate language
15/// bindings, auto-generate UI forms, etc.
16#[derive(Debug, Copy, Clone, Eq, PartialEq)]
17#[repr(u8)]
18pub enum ContractMetadataKind {
19    /// Main contract metadata.
20    ///
21    /// Contracts are encoded af follows:
22    /// * Encoding of the state type as described in [`IoTypeMetadataKind`]
23    /// * Encoding of the `#[slot]` type as described in [`IoTypeMetadataKind`]
24    /// * Encoding of the `#[tmp]` type as described in [`IoTypeMetadataKind`]
25    /// * Number of methods (u8)
26    /// * Recursive metadata of methods as defined in one of:
27    ///   * [`Self::Init`]
28    ///   * [`Self::UpdateStateless`]
29    ///   * [`Self::UpdateStatefulRo`]
30    ///   * [`Self::UpdateStatefulRw`]
31    ///   * [`Self::ViewStateless`]
32    ///   * [`Self::ViewStateful`]
33    ///
34    /// [`IoTypeMetadataKind`]: ab_contracts_io_type::metadata::IoTypeMetadataKind
35    Contract,
36    /// Trait metadata.
37    ///
38    /// Traits are encoded af follows:
39    /// * Length of trait name in bytes (u8)
40    /// * Trait name as UTF-8 bytes
41    /// * Number of methods (u8)
42    /// * Recursive metadata of methods as defined in one of:
43    ///   * [`Self::UpdateStateless`]
44    ///   * [`Self::ViewStateless`]
45    Trait,
46
47    /// `#[init]` method.
48    ///
49    /// Initializers are encoded af follows:
50    /// * Length of method name in bytes (u8)
51    /// * Method name as UTF-8 bytes
52    /// * Number of named arguments (u8, excluding state argument `&self` or `&mut self`)
53    ///
54    /// Each argument is encoded as follows:
55    /// * Argument type as u8, one of:
56    ///   * [`Self::EnvRo`]
57    ///   * [`Self::EnvRw`]
58    ///   * [`Self::TmpRo`]
59    ///   * [`Self::TmpRw`]
60    ///   * [`Self::SlotRo`]
61    ///   * [`Self::SlotRw`]
62    ///   * [`Self::Input`]
63    ///   * [`Self::Output`]
64    /// * Length of the argument name in bytes (u8, except for [`Self::EnvRo`] and [`Self::EnvRw`])
65    /// * Argument name as UTF-8 bytes (except for [`Self::EnvRo`] and [`Self::EnvRw`])
66    /// * Only for [`Self::Input`] and [`Self::Output`] recursive metadata of argument's type as
67    ///   described in [`IoTypeMetadataKind`] with following exception:
68    ///   * For last [`Self::Output`] this is skipped if method is [`Self::Init`] (since it is
69    ///     statically known to be `Self`) and present otherwise
70    ///
71    /// [`IoTypeMetadataKind`]: ab_contracts_io_type::metadata::IoTypeMetadataKind
72    ///
73    /// NOTE: [`Self::Output`], regardless of whether it is a return type or explicit `#[output]`
74    /// argument is encoded as a separate argument and counts towards number of arguments. At the
75    /// same time, `self` doesn't count towards the number of arguments as it is implicitly defined
76    /// by the variant of this struct.
77    Init,
78    /// Stateless `#[update]` method (doesn't have `self` in its arguments).
79    ///
80    /// Encoding is the same as [`Self::Init`].
81    UpdateStateless,
82    /// Stateful read-only `#[update]` method (has `&self` in its arguments).
83    ///
84    /// Encoding is the same as [`Self::Init`].
85    UpdateStatefulRo,
86    /// Stateful read-write `#[update]` method (has `&mut self` in its arguments).
87    ///
88    /// Encoding is the same as [`Self::Init`].
89    UpdateStatefulRw,
90    /// Stateless `#[view]` method (doesn't have `self` in its arguments).
91    ///
92    /// Encoding is the same as [`Self::Init`].
93    ViewStateless,
94    /// Stateful read-only `#[view]` method (has `&self` in its arguments).
95    ///
96    /// Encoding is the same as [`Self::Init`].
97    ViewStateful,
98
99    // TODO: `#[env] can be made implicit assuming the name is of the struct is always the same
100    /// Read-only `#[env]` argument.
101    ///
102    /// Example: `#[env] env: &Env,`
103    EnvRo,
104    /// Read-write `#[env]` argument.
105    ///
106    /// Example: `#[env] env: &mut Env<'_>,`
107    EnvRw,
108    /// Read-only `#[tmp]` argument.
109    ///
110    /// Example: `#[tmp] tmp: &MaybeData<Tmp>,`
111    TmpRo,
112    /// Read-write `#[tmp]` argument.
113    ///
114    /// Example: `#[tmp] tmp: &mut MaybeData<Tmp>,`
115    TmpRw,
116    // TODO: What if address is mandatory for slots? Then it would be possible to make `#[slot]`
117    //  implicit
118    /// Read-only `#[slot]` argument with an address.
119    ///
120    /// Example: `#[slot] (from_address, from): (&Address, &MaybeData<Slot>),`
121    SlotRo,
122    /// Read-write `#[slot]` argument with an address.
123    ///
124    /// Example: `#[slot] (from_address, from): (&Address, &mut MaybeData<Slot>),`
125    SlotRw,
126    /// `#[input]` argument.
127    ///
128    /// Example: `#[input] balance: &Balance,`
129    Input,
130    /// Explicit `#[output]` argument or `T` of [`Result<T, ContractError>`] return type or simply
131    /// return type if it is not fallible.
132    ///
133    /// NOTE: Skipped if return type's `T` is `()`.
134    ///
135    /// Example: `#[output] out: &mut VariableBytes<1024>,`
136    Output,
137}
138
139impl ContractMetadataKind {
140    // TODO: Implement `TryFrom` once it is available in const environment
141    /// Try to create an instance from its `u8` representation
142    #[inline(always)]
143    pub const fn try_from_u8(byte: u8) -> Option<Self> {
144        Some(match byte {
145            0 => Self::Contract,
146            1 => Self::Trait,
147            2 => Self::Init,
148            3 => Self::UpdateStateless,
149            4 => Self::UpdateStatefulRo,
150            5 => Self::UpdateStatefulRw,
151            6 => Self::ViewStateless,
152            7 => Self::ViewStateful,
153            8 => Self::EnvRo,
154            9 => Self::EnvRw,
155            10 => Self::TmpRo,
156            11 => Self::TmpRw,
157            12 => Self::SlotRo,
158            13 => Self::SlotRw,
159            14 => Self::Input,
160            15 => Self::Output,
161            _ => {
162                return None;
163            }
164        })
165    }
166
167    // TODO: Create wrapper type for metadata bytes and move this method there
168    /// Produce compact metadata.
169    ///
170    /// Compact metadata retains the shape, but throws some details. Specifically following
171    /// transformations are applied to metadata (crucially, method names are retained!):
172    /// * Struct, trait, enum and enum variant names removed (replaced with 0 bytes names)
173    /// * Structs and enum variants turned into tuple variants (removing field names)
174    /// * Method argument names removed (removing argument names)
175    ///
176    /// This means that two methods with different argument names or struct field names, but the
177    /// same shape otherwise are considered identical, allowing for limited future refactoring
178    /// opportunities without changing compact metadata shape, which is important for
179    /// [`MethodFingerprint`].
180    ///
181    /// [`MethodFingerprint`]: crate::method::MethodFingerprint
182    ///
183    /// Returns `None` if input is invalid or too long.
184    pub const fn compact(metadata: &[u8]) -> Option<([u8; MAX_METADATA_CAPACITY], usize)> {
185        compact_metadata(metadata, false)
186    }
187
188    // TODO: Create wrapper type for metadata bytes and move this method there
189    /// Produce compact metadata for `ExternalArgs`.
190    ///
191    /// Similar to [`Self::compact()`] arguments that are not reflected in `ExternalArgs` will be
192    /// skipped since they don't impact `ExternalArgs` API. This is used for `MethodFingerprint`
193    /// derivation.
194    ///
195    /// Returns `None` if input is invalid or too long.
196    pub const fn compact_external_args(
197        metadata: &[u8],
198    ) -> Option<([u8; MAX_METADATA_CAPACITY], usize)> {
199        compact_metadata(metadata, true)
200    }
201}