ab_contracts_common/method.rs
1use crate::metadata::ContractMetadataKind;
2use ab_blake3::const_hash;
3use ab_core_primitives::hashes::Blake3Hash;
4use ab_io_type::trivial_type::TrivialType;
5use derive_more::Display;
6
7/// Hash of method's compact metadata, which uniquely represents method signature.
8///
9/// While nothing can be said about method implementation, matching method fingerprint means method
10/// name, inputs and outputs are what they are expected to be (struct and field names are ignored as
11/// explained in [`ContractMetadataKind::compact`].
12#[derive(Debug, Display, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, TrivialType)]
13#[repr(C)]
14pub struct MethodFingerprint(Blake3Hash);
15
16impl MethodFingerprint {
17 /// Create a new method fingerprint from its metadata.
18 ///
19 /// `None` is returned for invalid metadata (see
20 /// [`ContractMetadataKind::compact_external_args()`] for details).
21 pub const fn new(method_metadata: &[u8]) -> Option<Self> {
22 let (compact_metadata_scratch, compact_metadata_size) =
23 ContractMetadataKind::compact_external_args(method_metadata)?;
24 let compact_metadata = compact_metadata_scratch.get(..compact_metadata_size)?;
25
26 Some(Self(Blake3Hash::new(const_hash(compact_metadata))))
27 }
28
29 #[inline(always)]
30 pub const fn to_bytes(&self) -> &[u8; Blake3Hash::SIZE] {
31 self.0.as_bytes()
32 }
33}
34
35/// Marker trait for external arguments when calling methods.
36///
37/// # Safety
38/// Struct that implements this trait must be `#[repr(C)]` and valid `ExternalArgs` for the contract
39/// method being called.
40///
41/// **Do not implement this trait explicitly!** Implementation is automatically generated by the
42/// macro which generates contract implementation.
43pub unsafe trait ExternalArgs {
44 /// Fingerprint of the method being called
45 const FINGERPRINT: MethodFingerprint;
46 /// Metadata that corresponds to a method being called
47 const METADATA: &[u8];
48}