ab_contracts_common/
method.rs

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
use crate::metadata::ContractMetadataKind;
use const_sha1::sha1;
use core::fmt;

/// Hash of method's compact metadata, which uniquely represents method signature.
///
/// While nothing can be said about method implementation, matching method fingerprint means method
/// name, inputs and outputs are what they are expected to be (struct and field names are ignored as
/// explained in [`ContractMetadataKind::compact`].
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
#[repr(C)]
pub struct MethodFingerprint([u8; 32]);

impl fmt::Display for MethodFingerprint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.0 {
            write!(f, "{:02x}", byte)?;
        }
        Ok(())
    }
}

impl MethodFingerprint {
    /// Create new method fingerprint from its metadata.
    ///
    /// `None` is returned for invalid metadata (see [`ContractMetadataKind::compact`] for details).
    pub const fn new(method_metadata: &[u8]) -> Option<Self> {
        // `?` is not supported in `const` environment
        let Some((compact_metadata_scratch, compact_metadata_size)) =
            ContractMetadataKind::compact(method_metadata)
        else {
            return None;
        };
        // The same as `&compact_metadata_scratch[..compact_metadata_size]`, but it is not allowed
        // in const environment yet
        let compact_metadata = compact_metadata_scratch.split_at(compact_metadata_size).0;

        let hash = sha1(compact_metadata).as_bytes();

        Some(Self([
            hash[0], hash[1], hash[2], hash[3], hash[4], hash[5], hash[6], hash[7], hash[8],
            hash[9], hash[10], hash[11], hash[12], hash[13], hash[14], hash[15], hash[16],
            hash[17], hash[18], hash[19], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        ]))
    }

    #[inline]
    pub const fn to_bytes(&self) -> &[u8; 32] {
        &self.0
    }
}

/// Marker trait for external arguments when calling methods.
///
/// # Safety
/// Struct that implements this trait must be `#[repr(C)]` and valid `ExternalArgs` for the contract
/// method being called.
///
/// **Do not implement this trait explicitly!** Implementation is automatically generated by the
/// macro which generates smart contract implementation.
pub unsafe trait ExternalArgs {
    /// Fingerprint of the method being called
    const FINGERPRINT: MethodFingerprint;
}