Skip to main content

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//! - `unstable`: Alpha/experimental APIs. Items behind this feature are not covered by the
22//!   crate's semver guarantees and may change or be removed at any time. Currently this gates
23//!   the proof verification primitives needed to authenticate state against a trusted checkpoint
24//!   summary, including the Blake2b256 Merkle tree implementation in the [`merkle`] module and
25//!   the OCS (Object Checkpoint State) proof verifier types in the [`proof`] module. Implies
26//!   the `hash` and `serde` features.
27//! - `proptest`: Enables support for the [proptest] library by providing implementations of
28//!   [proptest::arbitrary::Arbitrary] for many types.
29//!
30//! [feature flags]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section
31//! [serde]: https://docs.rs/serde
32//! [rand]: https://docs.rs/rand
33//! [proptest]: https://docs.rs/proptest
34//! [proptest::arbitrary::Arbitrary]: https://docs.rs/proptest/latest/proptest/arbitrary/trait.Arbitrary.html
35//!
36//! # BCS
37//!
38//! [BCS] is the serialization format used to represent the state of the blockchain and is used
39//! extensively throughout the Sui ecosystem. In particular the BCS format is leveraged because it
40//! _"guarantees canonical serialization, meaning that for any given data type, there is a
41//! one-to-one correspondence between in-memory values and valid byte representations."_ One
42//! benefit of this property of having a canonical serialized representation is to allow different
43//! entities in the ecosystem to all agree on how a particular type should be interpreted and more
44//! importantly define a deterministic representation for hashing and signing.
45//!
46//! This library strives to guarantee that the types defined are fully BCS-compatible with the data
47//! that the network produces. The one caveat to this would be that as the Sui protocol evolves,
48//! new type variants are added and older versions of this library may not support those newly
49//! added variants. The expectation is that the most recent release of this library will support
50//! new variants and types as they are released to Sui's `testnet` network.
51//!
52//! See the documentation for the various types defined by this crate for a specification of their
53//! BCS serialized representation which will be defined using ABNF notation as described by
54//! [RFC-5234]. In addition to the format itself, some types have an extra layer of verification
55//! and may impose additional restrictions on valid byte representations above and beyond those
56//! already provided by BCS. In these instances the documentation for those types will clearly
57//! specify these additional restrictions.
58//!
59//! Here are some common rules:
60//!
61//! ```text
62//! ; --- BCS Value ---
63//! bcs-value           = bcs-struct / bcs-enum / bcs-length-prefixed / bcs-fixed-length
64//! bcs-length-prefixed = bytes / string / vector / option
65//! bcs-fixed-length    = u8 / u16 / u32 / u64 / u128 /
66//!                       i8 / i16 / i32 / i64 / i128 /
67//!                       boolean
68//! bcs-struct          = *bcs-value                ; Sequence of serialized fields
69//! bcs-enum            = uleb128-index bcs-value   ; Enum index and associated value
70//!
71//! ; --- Length-prefixed types ---
72//! bytes           = uleb128 *OCTET          ; Raw bytes of the specified length
73//! string          = uleb128 *OCTET          ; valid utf8 string of the specified length
74//! vector          = uleb128 *bcs-value      ; Length-prefixed list of values
75//! option          = %x00 / (%x01 bcs-value) ; optional value
76//!
77//! ; --- Fixed-length types ---
78//! u8          = OCTET                     ; 1-byte unsigned integer
79//! u16         = 2OCTET                    ; 2-byte unsigned integer, little-endian
80//! u32         = 4OCTET                    ; 4-byte unsigned integer, little-endian
81//! u64         = 8OCTET                    ; 8-byte unsigned integer, little-endian
82//! u128        = 16OCTET                   ; 16-byte unsigned integer, little-endian
83//! i8          = OCTET                     ; 1-byte signed integer
84//! i16         = 2OCTET                    ; 2-byte signed integer, little-endian
85//! i32         = 4OCTET                    ; 4-byte signed integer, little-endian
86//! i64         = 8OCTET                    ; 8-byte signed integer, little-endian
87//! i128        = 16OCTET                   ; 16-byte signed integer, little-endian
88//! boolean     = %x00 / %x01               ; Boolean: 0 = false, 1 = true
89//! array       = *(bcs-value)              ; Fixed-length array
90//!
91//! ; --- ULEB128 definition ---
92//! uleb128         = 1*5uleb128-byte       ; Variable-length ULEB128 encoding
93//! uleb128-byte    = %x00-7F / %x80-FF     ; ULEB128 continuation rules
94//! uleb128-index   = uleb128               ; ULEB128-encoded variant index
95//! ```
96//!
97//! [BCS]: https://docs.rs/bcs
98//! [RFC-5234]: https://datatracker.ietf.org/doc/html/rfc5234
99
100#![cfg_attr(doc_cfg, feature(doc_cfg))]
101// TODO finish documenting all public items
102// #![warn(missing_docs)]
103
104mod address;
105#[cfg(feature = "serde")]
106#[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))]
107pub mod bcs;
108mod bitmap;
109mod checkpoint;
110mod crypto;
111mod digest;
112mod effects;
113mod events;
114mod execution_status;
115pub mod framework;
116mod gas;
117#[cfg(feature = "hash")]
118#[cfg_attr(doc_cfg, doc(cfg(feature = "hash")))]
119pub mod hash;
120#[cfg(feature = "unstable")]
121#[cfg_attr(doc_cfg, doc(cfg(feature = "unstable")))]
122pub mod merkle;
123mod object;
124#[cfg(feature = "unstable")]
125#[cfg_attr(doc_cfg, doc(cfg(feature = "unstable")))]
126pub mod proof;
127mod transaction;
128mod type_tag;
129mod u256;
130
131pub use address::Address;
132pub use address::AddressParseError;
133pub use bitmap::Bitmap;
134pub use checkpoint::CheckpointCommitment;
135pub use checkpoint::CheckpointContents;
136pub use checkpoint::CheckpointData;
137pub use checkpoint::CheckpointSequenceNumber;
138pub use checkpoint::CheckpointSummary;
139pub use checkpoint::CheckpointTimestamp;
140pub use checkpoint::CheckpointTransaction;
141pub use checkpoint::CheckpointTransactionInfo;
142pub use checkpoint::EndOfEpochData;
143pub use checkpoint::EpochId;
144pub use checkpoint::ProtocolVersion;
145pub use checkpoint::SignedCheckpointSummary;
146pub use checkpoint::StakeUnit;
147pub use crypto::Bls12381PublicKey;
148pub use crypto::Bls12381Signature;
149pub use crypto::Bn254FieldElement;
150pub use crypto::CircomG1;
151pub use crypto::CircomG2;
152pub use crypto::Ed25519PublicKey;
153pub use crypto::Ed25519Signature;
154pub use crypto::Intent;
155pub use crypto::IntentAppId;
156pub use crypto::IntentScope;
157pub use crypto::IntentVersion;
158pub use crypto::InvalidLegacyBitmapError;
159pub use crypto::InvalidZkLoginAuthenticatorError;
160pub use crypto::Jwk;
161pub use crypto::JwkId;
162pub use crypto::MlDsa65PublicKey;
163pub use crypto::MlDsa65Signature;
164pub use crypto::MultisigAggregatedSignature;
165pub use crypto::MultisigCommittee;
166pub use crypto::MultisigMember;
167pub use crypto::MultisigMemberPublicKey;
168pub use crypto::MultisigMemberSignature;
169pub use crypto::PasskeyAuthenticator;
170pub use crypto::PasskeyPublicKey;
171pub use crypto::Secp256k1PublicKey;
172pub use crypto::Secp256k1Signature;
173pub use crypto::Secp256r1PublicKey;
174pub use crypto::Secp256r1Signature;
175pub use crypto::SignatureScheme;
176pub use crypto::SimpleSignature;
177pub use crypto::UserSignature;
178pub use crypto::ValidatorAggregatedSignature;
179pub use crypto::ValidatorCommittee;
180pub use crypto::ValidatorCommitteeMember;
181pub use crypto::ValidatorSignature;
182pub use crypto::ZkLoginAuthenticator;
183pub use crypto::ZkLoginClaim;
184pub use crypto::ZkLoginInputs;
185pub use crypto::ZkLoginProof;
186pub use crypto::ZkLoginPublicIdentifier;
187pub use digest::Digest;
188pub use digest::DigestParseError;
189pub use digest::SigningDigest;
190pub use effects::AccumulatorOperation;
191pub use effects::AccumulatorValue;
192pub use effects::AccumulatorWrite;
193pub use effects::ChangedObject;
194pub use effects::IdOperation;
195pub use effects::ModifiedAtVersion;
196pub use effects::ObjectChange;
197pub use effects::ObjectIn;
198pub use effects::ObjectOut;
199pub use effects::ObjectReferenceWithOwner;
200pub use effects::TransactionEffects;
201pub use effects::TransactionEffectsV1;
202pub use effects::TransactionEffectsV2;
203pub use effects::UnchangedConsensusKind;
204pub use effects::UnchangedConsensusObject;
205pub use events::BalanceChange;
206pub use events::Event;
207pub use events::TransactionEvents;
208pub use execution_status::CommandArgumentError;
209pub use execution_status::ExecutionError;
210pub use execution_status::ExecutionStatus;
211pub use execution_status::MoveLocation;
212pub use execution_status::PackageUpgradeError;
213pub use execution_status::TypeArgumentError;
214pub use gas::GasCostSummary;
215pub use object::GenesisObject;
216pub use object::MovePackage;
217pub use object::MoveStruct;
218pub use object::Object;
219pub use object::ObjectData;
220pub use object::ObjectReference;
221pub use object::ObjectType;
222pub use object::Owner;
223pub use object::TypeOrigin;
224pub use object::UpgradeInfo;
225pub use object::Version;
226pub use transaction::ActiveJwk;
227pub use transaction::AllowedProposers;
228pub use transaction::Argument;
229pub use transaction::AuthenticatorStateExpire;
230pub use transaction::AuthenticatorStateUpdate;
231pub use transaction::CanceledTransaction;
232pub use transaction::CanceledTransactionV2;
233pub use transaction::ChangeEpoch;
234pub use transaction::Command;
235pub use transaction::ConsensusCommitPrologue;
236pub use transaction::ConsensusCommitPrologueV2;
237pub use transaction::ConsensusCommitPrologueV3;
238pub use transaction::ConsensusCommitPrologueV4;
239pub use transaction::ConsensusDeterminedVersionAssignments;
240pub use transaction::EndOfEpochTransactionKind;
241pub use transaction::ExecutionTimeObservationKey;
242pub use transaction::ExecutionTimeObservations;
243pub use transaction::FundsWithdrawal;
244pub use transaction::GasPayment;
245pub use transaction::GenesisTransaction;
246pub use transaction::Input;
247pub use transaction::MakeMoveVector;
248pub use transaction::MergeCoins;
249pub use transaction::MoveCall;
250pub use transaction::Mutability;
251pub use transaction::ProgrammableTransaction;
252pub use transaction::Publish;
253pub use transaction::RandomnessStateUpdate;
254pub use transaction::SharedInput;
255pub use transaction::SignedTransaction;
256pub use transaction::SplitCoins;
257pub use transaction::SystemPackage;
258pub use transaction::Transaction;
259pub use transaction::TransactionExpiration;
260pub use transaction::TransactionKind;
261pub use transaction::TransferObjects;
262pub use transaction::Upgrade;
263pub use transaction::ValidatorExecutionTimeObservation;
264pub use transaction::VersionAssignment;
265pub use transaction::VersionAssignmentV2;
266pub use transaction::WithdrawFrom;
267pub use type_tag::Identifier;
268pub use type_tag::StructTag;
269pub use type_tag::TypeParseError;
270pub use type_tag::TypeTag;
271pub use u256::U256;
272pub use u256::U256ParseError;
273
274#[cfg(feature = "serde")]
275#[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))]
276pub(crate) use transaction::SignedTransactionWithIntentMessage;
277
278#[cfg(test)]
279mod serialization_proptests;
280
281#[derive(Clone, Debug, PartialEq, Eq)]
282pub struct PersonalMessage<'a>(pub std::borrow::Cow<'a, [u8]>);
283
284#[cfg(feature = "serde")]
285mod _serde {
286    use base64ct::Base64;
287    use base64ct::Encoding;
288    use serde::Deserialize;
289    use serde::Deserializer;
290    use serde::Serialize;
291    use serde::Serializer;
292    use serde_with::DeserializeAs;
293    use serde_with::SerializeAs;
294    use std::borrow::Cow;
295
296    pub(crate) type ReadableBase64Encoded =
297        ::serde_with::As<::serde_with::IfIsHumanReadable<Base64Encoded, ::serde_with::Bytes>>;
298
299    pub(crate) struct Base64Encoded;
300
301    impl<T: AsRef<[u8]>> SerializeAs<T> for Base64Encoded {
302        fn serialize_as<S>(source: &T, serializer: S) -> Result<S::Ok, S::Error>
303        where
304            S: Serializer,
305        {
306            let bytes = source.as_ref();
307            let b64 = Base64::encode_string(bytes);
308            b64.serialize(serializer)
309        }
310    }
311
312    impl<'de, T: TryFrom<Vec<u8>>> DeserializeAs<'de, T> for Base64Encoded {
313        fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
314        where
315            D: Deserializer<'de>,
316        {
317            let b64: Cow<'de, str> = Deserialize::deserialize(deserializer)?;
318            let bytes = Base64::decode_vec(&b64).map_err(serde::de::Error::custom)?;
319            let length = bytes.len();
320            T::try_from(bytes).map_err(|_| {
321                serde::de::Error::custom(format_args!(
322                    "Can't convert a Byte Vector of length {length} to the output type."
323                ))
324            })
325        }
326    }
327
328    pub(crate) use super::SignedTransactionWithIntentMessage;
329}