sui_sdk_types/
object_id.rs

1use super::Address;
2
3/// An `ObjectId` is a 32-byte identifier used to uniquely identify an object on the Sui
4/// blockchain.
5///
6/// ## Relationship to Address
7///
8/// [`Address`]es and `ObjectId`s share the same 32-byte addressable space but are derived
9/// leveraging different domain-separator values to ensure, cryptographically, that there won't be
10/// any overlap, e.g. there can't be a valid `Object` whose `ObjectId` is equal to that of the
11/// `Address` of a user account.
12///
13/// # BCS
14///
15/// An `ObjectId`'s BCS serialized form is defined by the following:
16///
17/// ```text
18/// object-id = 32*OCTET
19/// ```
20#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
21#[cfg_attr(
22    feature = "serde",
23    derive(serde_derive::Serialize, serde_derive::Deserialize)
24)]
25#[cfg_attr(feature = "proptest", derive(test_strategy::Arbitrary))]
26pub struct ObjectId(Address);
27
28impl ObjectId {
29    pub const LENGTH: usize = Address::LENGTH;
30    pub const ZERO: Self = Self(Address::ZERO);
31
32    /// Generates a new ObjectId from the provided byte array.
33    pub const fn new(bytes: [u8; Self::LENGTH]) -> Self {
34        Self(Address::new(bytes))
35    }
36
37    /// Returns the underlying byte array of an ObjectId.
38    pub const fn into_inner(self) -> [u8; Self::LENGTH] {
39        self.0.into_inner()
40    }
41
42    /// Returns a reference to the underlying byte array of an ObjectId.
43    pub const fn inner(&self) -> &[u8; Self::LENGTH] {
44        self.0.inner()
45    }
46
47    /// Returns a slice of bytes of an ObjectId.
48    pub const fn as_bytes(&self) -> &[u8] {
49        self.0.as_bytes()
50    }
51
52    /// Returns the underlying Address of an ObjectId.
53    pub const fn as_address(&self) -> &Address {
54        &self.0
55    }
56}
57
58impl AsRef<[u8]> for ObjectId {
59    fn as_ref(&self) -> &[u8] {
60        self.0.as_ref()
61    }
62}
63
64impl AsRef<[u8; 32]> for ObjectId {
65    fn as_ref(&self) -> &[u8; 32] {
66        self.0.as_ref()
67    }
68}
69
70impl From<ObjectId> for [u8; 32] {
71    fn from(object_id: ObjectId) -> Self {
72        object_id.into_inner()
73    }
74}
75
76impl From<[u8; 32]> for ObjectId {
77    fn from(object_id: [u8; 32]) -> Self {
78        Self::new(object_id)
79    }
80}
81
82impl From<Address> for ObjectId {
83    fn from(value: Address) -> Self {
84        Self(value)
85    }
86}
87
88impl From<ObjectId> for Vec<u8> {
89    fn from(value: ObjectId) -> Self {
90        value.0.into()
91    }
92}
93
94impl std::str::FromStr for ObjectId {
95    type Err = super::address::AddressParseError;
96
97    fn from_str(s: &str) -> Result<Self, Self::Err> {
98        Address::from_str(s).map(Self)
99    }
100}
101
102impl std::fmt::Display for ObjectId {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        self.0.fmt(f)
105    }
106}