sui_sdk_types/
lib.rs

1//! Core type definitions for the [Sui] blockchain.
2//!
3//! [Sui] is a next-generation smart contract platform with high throughput, low latency, and an
4//! asset-oriented programming model powered by the Move programming language. This crate provides
5//! type definitions for working with the data that makes up the [Sui] blockchain.
6//!
7//! [Sui]: https://sui.io
8//!
9//! # Feature flags
10//!
11//! This library uses a set of [feature flags] to reduce the number of dependencies and amount of
12//! compiled code. By default, no features are enabled which allows one to enable a subset
13//! specifically for their use case. Below is a list of the available feature flags.
14//!
15//! - `serde`: Enables support for serializing and deserializing types to/from BCS utilizing [serde]
16//!   library.
17//! - `rand`: Enables support for generating random instances of a number of types via the [rand]
18//!   library.
19//! - `hash`: Enables support for hashing, which is required for deriving addresses and calculating
20//!   digests for various types.
21//! - `proptest`: Enables support for the [proptest] library by providing implementations of
22//!   [proptest::arbitrary::Arbitrary] for many types.
23//!
24//! [feature flags]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section
25//! [serde]: https://docs.rs/serde
26//! [rand]: https://docs.rs/rand
27//! [proptest]: https://docs.rs/proptest
28//! [proptest::arbitrary::Arbitrary]: https://docs.rs/proptest/latest/proptest/arbitrary/trait.Arbitrary.html
29//!
30//! # BCS
31//!
32//! [BCS] is the serialization format used to represent the state of the blockchain and is used
33//! extensively throughout the Sui ecosystem. In particular the BCS format is leveraged because it
34//! _"guarantees canonical serialization, meaning that for any given data type, there is a
35//! one-to-one correspondence between in-memory values and valid byte representations."_ One
36//! benefit of this property of having a canonical serialized representation is to allow different
37//! entities in the ecosystem to all agree on how a particular type should be interpreted and more
38//! importantly define a deterministic representation for hashing and signing.
39//!
40//! This library strives to guarantee that the types defined are fully BCS-compatible with the data
41//! that the network produces. The one caveat to this would be that as the Sui protocol evolves,
42//! new type variants are added and older versions of this library may not support those newly
43//! added variants. The expectation is that the most recent release of this library will support
44//! new variants and types as they are released to Sui's `testnet` network.
45//!
46//! See the documentation for the various types defined by this crate for a specification of their
47//! BCS serialized representation which will be defined using ABNF notation as described by
48//! [RFC-5234]. In addition to the format itself, some types have an extra layer of verification
49//! and may impose additional restrictions on valid byte representations above and beyond those
50//! already provided by BCS. In these instances the documentation for those types will clearly
51//! specify these additional restrictions.
52//!
53//! Here are some common rules:
54//!
55//! ```text
56//! ; --- BCS Value ---
57//! bcs-value           = bcs-struct / bcs-enum / bcs-length-prefixed / bcs-fixed-length
58//! bcs-length-prefixed = bytes / string / vector / option
59//! bcs-fixed-length    = u8 / u16 / u32 / u64 / u128 /
60//!                       i8 / i16 / i32 / i64 / i128 /
61//!                       boolean
62//! bcs-struct          = *bcs-value                ; Sequence of serialized fields
63//! bcs-enum            = uleb128-index bcs-value   ; Enum index and associated value
64//!
65//! ; --- Length-prefixed types ---
66//! bytes           = uleb128 *OCTET          ; Raw bytes of the specified length
67//! string          = uleb128 *OCTET          ; valid utf8 string of the specified length
68//! vector          = uleb128 *bcs-value      ; Length-prefixed list of values
69//! option          = %x00 / (%x01 bcs-value) ; optional value
70//!
71//! ; --- Fixed-length types ---
72//! u8          = OCTET                     ; 1-byte unsigned integer
73//! u16         = 2OCTET                    ; 2-byte unsigned integer, little-endian
74//! u32         = 4OCTET                    ; 4-byte unsigned integer, little-endian
75//! u64         = 8OCTET                    ; 8-byte unsigned integer, little-endian
76//! u128        = 16OCTET                   ; 16-byte unsigned integer, little-endian
77//! i8          = OCTET                     ; 1-byte signed integer
78//! i16         = 2OCTET                    ; 2-byte signed integer, little-endian
79//! i32         = 4OCTET                    ; 4-byte signed integer, little-endian
80//! i64         = 8OCTET                    ; 8-byte signed integer, little-endian
81//! i128        = 16OCTET                   ; 16-byte signed integer, little-endian
82//! boolean     = %x00 / %x01               ; Boolean: 0 = false, 1 = true
83//! array       = *(bcs-value)              ; Fixed-length array
84//!
85//! ; --- ULEB128 definition ---
86//! uleb128         = 1*5uleb128-byte       ; Variable-length ULEB128 encoding
87//! uleb128-byte    = %x00-7F / %x80-FF     ; ULEB128 continuation rules
88//! uleb128-index   = uleb128               ; ULEB128-encoded variant index
89//! ```
90//!
91//! [BCS]: https://docs.rs/bcs
92//! [RFC-5234]: https://datatracker.ietf.org/doc/html/rfc5234
93
94#![cfg_attr(doc_cfg, feature(doc_cfg))]
95// TODO finish documenting all public items
96// #![warn(missing_docs)]
97
98mod address;
99mod checkpoint;
100mod crypto;
101mod digest;
102mod effects;
103mod events;
104mod execution_status;
105pub mod framework;
106mod gas;
107mod object;
108mod object_id;
109mod transaction;
110mod type_tag;
111mod u256;
112
113#[cfg(feature = "hash")]
114#[cfg_attr(doc_cfg, doc(cfg(feature = "hash")))]
115pub mod hash;
116
117pub use address::Address;
118pub use address::AddressParseError;
119pub use checkpoint::CheckpointCommitment;
120pub use checkpoint::CheckpointContents;
121pub use checkpoint::CheckpointData;
122pub use checkpoint::CheckpointSequenceNumber;
123pub use checkpoint::CheckpointSummary;
124pub use checkpoint::CheckpointTimestamp;
125pub use checkpoint::CheckpointTransaction;
126pub use checkpoint::CheckpointTransactionInfo;
127pub use checkpoint::EndOfEpochData;
128pub use checkpoint::EpochId;
129pub use checkpoint::ProtocolVersion;
130pub use checkpoint::SignedCheckpointSummary;
131pub use checkpoint::StakeUnit;
132pub use crypto::Bls12381PublicKey;
133pub use crypto::Bls12381Signature;
134pub use crypto::Bn254FieldElement;
135pub use crypto::CircomG1;
136pub use crypto::CircomG2;
137pub use crypto::Ed25519PublicKey;
138pub use crypto::Ed25519Signature;
139pub use crypto::Intent;
140pub use crypto::IntentAppId;
141pub use crypto::IntentScope;
142pub use crypto::IntentVersion;
143pub use crypto::Jwk;
144pub use crypto::JwkId;
145pub use crypto::MultisigAggregatedSignature;
146pub use crypto::MultisigCommittee;
147pub use crypto::MultisigMember;
148pub use crypto::MultisigMemberPublicKey;
149pub use crypto::MultisigMemberSignature;
150pub use crypto::PasskeyAuthenticator;
151pub use crypto::PasskeyPublicKey;
152pub use crypto::Secp256k1PublicKey;
153pub use crypto::Secp256k1Signature;
154pub use crypto::Secp256r1PublicKey;
155pub use crypto::Secp256r1Signature;
156pub use crypto::SignatureScheme;
157pub use crypto::SimpleSignature;
158pub use crypto::UserSignature;
159pub use crypto::ValidatorAggregatedSignature;
160pub use crypto::ValidatorCommittee;
161pub use crypto::ValidatorCommitteeMember;
162pub use crypto::ValidatorSignature;
163pub use crypto::ZkLoginAuthenticator;
164pub use crypto::ZkLoginClaim;
165pub use crypto::ZkLoginInputs;
166pub use crypto::ZkLoginProof;
167pub use crypto::ZkLoginPublicIdentifier;
168pub use digest::CheckpointContentsDigest;
169pub use digest::CheckpointDigest;
170pub use digest::ConsensusCommitDigest;
171pub use digest::Digest;
172pub use digest::DigestParseError;
173pub use digest::EffectsAuxiliaryDataDigest;
174pub use digest::ObjectDigest;
175pub use digest::SigningDigest;
176pub use digest::TransactionDigest;
177pub use digest::TransactionEffectsDigest;
178pub use digest::TransactionEventsDigest;
179pub use effects::ChangedObject;
180pub use effects::IdOperation;
181pub use effects::ModifiedAtVersion;
182pub use effects::ObjectIn;
183pub use effects::ObjectOut;
184pub use effects::ObjectReferenceWithOwner;
185pub use effects::TransactionEffects;
186pub use effects::TransactionEffectsV1;
187pub use effects::TransactionEffectsV2;
188pub use effects::UnchangedSharedKind;
189pub use effects::UnchangedSharedObject;
190pub use events::BalanceChange;
191pub use events::Event;
192pub use events::TransactionEvents;
193pub use execution_status::CommandArgumentError;
194pub use execution_status::ExecutionError;
195pub use execution_status::ExecutionStatus;
196pub use execution_status::MoveLocation;
197pub use execution_status::PackageUpgradeError;
198pub use execution_status::TypeArgumentError;
199pub use gas::GasCostSummary;
200pub use object::GenesisObject;
201pub use object::MovePackage;
202pub use object::MoveStruct;
203pub use object::Object;
204pub use object::ObjectData;
205pub use object::ObjectReference;
206pub use object::ObjectType;
207pub use object::Owner;
208pub use object::TypeOrigin;
209pub use object::UpgradeInfo;
210pub use object::Version;
211pub use object_id::ObjectId;
212pub use transaction::ActiveJwk;
213pub use transaction::Argument;
214pub use transaction::AuthenticatorStateExpire;
215pub use transaction::AuthenticatorStateUpdate;
216pub use transaction::CanceledTransaction;
217pub use transaction::ChangeEpoch;
218pub use transaction::Command;
219pub use transaction::ConsensusCommitPrologue;
220pub use transaction::ConsensusCommitPrologueV2;
221pub use transaction::ConsensusCommitPrologueV3;
222pub use transaction::ConsensusCommitPrologueV4;
223pub use transaction::ConsensusDeterminedVersionAssignments;
224pub use transaction::EndOfEpochTransactionKind;
225pub use transaction::ExecutionTimeObservationKey;
226pub use transaction::ExecutionTimeObservations;
227pub use transaction::GasPayment;
228pub use transaction::GenesisTransaction;
229pub use transaction::Input;
230pub use transaction::MakeMoveVector;
231pub use transaction::MergeCoins;
232pub use transaction::MoveCall;
233pub use transaction::ProgrammableTransaction;
234pub use transaction::Publish;
235pub use transaction::RandomnessStateUpdate;
236pub use transaction::SignedTransaction;
237pub use transaction::SplitCoins;
238pub use transaction::SystemPackage;
239pub use transaction::Transaction;
240pub use transaction::TransactionExpiration;
241pub use transaction::TransactionKind;
242pub use transaction::TransferObjects;
243pub use transaction::Upgrade;
244pub use transaction::ValidatorExecutionTimeObservation;
245pub use transaction::VersionAssignment;
246pub use type_tag::Identifier;
247pub use type_tag::StructTag;
248pub use type_tag::TypeParseError;
249pub use type_tag::TypeTag;
250
251#[cfg(feature = "serde")]
252#[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))]
253pub(crate) use transaction::SignedTransactionWithIntentMessage;
254
255#[cfg(test)]
256mod serialization_proptests;
257
258#[derive(Clone, Debug, PartialEq, Eq)]
259pub struct PersonalMessage<'a>(pub std::borrow::Cow<'a, [u8]>);
260
261#[cfg(feature = "serde")]
262mod _serde {
263    use base64ct::Base64;
264    use base64ct::Encoding;
265    use serde::Deserialize;
266    use serde::Deserializer;
267    use serde::Serialize;
268    use serde::Serializer;
269    use serde_with::Bytes;
270    use serde_with::DeserializeAs;
271    use serde_with::SerializeAs;
272    use std::borrow::Cow;
273
274    pub(crate) type ReadableDisplay =
275        ::serde_with::As<::serde_with::IfIsHumanReadable<::serde_with::DisplayFromStr>>;
276
277    pub(crate) type OptionReadableDisplay =
278        ::serde_with::As<Option<::serde_with::IfIsHumanReadable<::serde_with::DisplayFromStr>>>;
279
280    pub(crate) type ReadableBase64Encoded =
281        ::serde_with::As<::serde_with::IfIsHumanReadable<Base64Encoded, ::serde_with::Bytes>>;
282
283    pub(crate) struct Base64Encoded;
284
285    impl<T: AsRef<[u8]>> SerializeAs<T> for Base64Encoded {
286        fn serialize_as<S>(source: &T, serializer: S) -> Result<S::Ok, S::Error>
287        where
288            S: Serializer,
289        {
290            let bytes = source.as_ref();
291            let b64 = Base64::encode_string(bytes);
292            b64.serialize(serializer)
293        }
294    }
295
296    impl<'de, T: TryFrom<Vec<u8>>> DeserializeAs<'de, T> for Base64Encoded {
297        fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
298        where
299            D: Deserializer<'de>,
300        {
301            let b64: Cow<'de, str> = Deserialize::deserialize(deserializer)?;
302            let bytes = Base64::decode_vec(&b64).map_err(serde::de::Error::custom)?;
303            let length = bytes.len();
304            T::try_from(bytes).map_err(|_| {
305                serde::de::Error::custom(format_args!(
306                    "Can't convert a Byte Vector of length {length} to the output type."
307                ))
308            })
309        }
310    }
311
312    /// Serializes a bitmap according to the roaring bitmap on-disk standard.
313    /// <https://github.com/RoaringBitmap/RoaringFormatSpec>
314    pub(crate) struct BinaryRoaringBitmap;
315
316    impl SerializeAs<roaring::RoaringBitmap> for BinaryRoaringBitmap {
317        fn serialize_as<S>(
318            source: &roaring::RoaringBitmap,
319            serializer: S,
320        ) -> Result<S::Ok, S::Error>
321        where
322            S: Serializer,
323        {
324            let mut bytes = vec![];
325
326            source
327                .serialize_into(&mut bytes)
328                .map_err(serde::ser::Error::custom)?;
329            Bytes::serialize_as(&bytes, serializer)
330        }
331    }
332
333    impl<'de> DeserializeAs<'de, roaring::RoaringBitmap> for BinaryRoaringBitmap {
334        fn deserialize_as<D>(deserializer: D) -> Result<roaring::RoaringBitmap, D::Error>
335        where
336            D: Deserializer<'de>,
337        {
338            let bytes: Cow<'de, [u8]> = Bytes::deserialize_as(deserializer)?;
339            roaring::RoaringBitmap::deserialize_from(&bytes[..]).map_err(serde::de::Error::custom)
340        }
341    }
342
343    pub(crate) struct Base64RoaringBitmap;
344
345    impl SerializeAs<roaring::RoaringBitmap> for Base64RoaringBitmap {
346        fn serialize_as<S>(
347            source: &roaring::RoaringBitmap,
348            serializer: S,
349        ) -> Result<S::Ok, S::Error>
350        where
351            S: Serializer,
352        {
353            let mut bytes = vec![];
354
355            source
356                .serialize_into(&mut bytes)
357                .map_err(serde::ser::Error::custom)?;
358            let b64 = Base64::encode_string(&bytes);
359            b64.serialize(serializer)
360        }
361    }
362
363    impl<'de> DeserializeAs<'de, roaring::RoaringBitmap> for Base64RoaringBitmap {
364        fn deserialize_as<D>(deserializer: D) -> Result<roaring::RoaringBitmap, D::Error>
365        where
366            D: Deserializer<'de>,
367        {
368            let b64: Cow<'de, str> = Deserialize::deserialize(deserializer)?;
369            let bytes = Base64::decode_vec(&b64).map_err(serde::de::Error::custom)?;
370            roaring::RoaringBitmap::deserialize_from(&bytes[..]).map_err(serde::de::Error::custom)
371        }
372    }
373
374    pub(crate) use super::SignedTransactionWithIntentMessage;
375}