Skip to main content

sui_types/
lib.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3#![warn(
4    future_incompatible,
5    nonstandard_style,
6    rust_2018_idioms,
7    rust_2021_compatibility
8)]
9
10use base_types::{SequenceNumber, SuiAddress};
11use move_binary_format::CompiledModule;
12use move_binary_format::file_format::{AbilitySet, SignatureToken};
13use move_bytecode_utils::resolve_struct;
14use move_core_types::language_storage::ModuleId;
15use move_core_types::{account_address::AccountAddress, language_storage::StructTag};
16pub use move_core_types::{identifier::Identifier, language_storage::TypeTag};
17use object::OBJECT_START_VERSION;
18
19use base_types::ObjectID;
20
21pub use mysten_network::multiaddr;
22
23use crate::base_types::{RESOLVED_ASCII_STR, RESOLVED_UTF8_STR};
24use crate::{base_types::RESOLVED_STD_OPTION, id::RESOLVED_SUI_ID};
25
26#[macro_use]
27pub mod error;
28pub mod accumulator_event;
29pub mod accumulator_metadata;
30pub mod accumulator_root;
31pub mod address_alias;
32pub mod allowance;
33pub mod authenticator_state;
34pub mod balance;
35pub mod balance_change;
36pub mod base_types;
37pub mod bridge;
38pub mod clock;
39pub mod coin;
40pub mod coin_registry;
41pub mod coin_reservation;
42pub mod collection_types;
43pub mod committee;
44pub mod config;
45pub mod crypto;
46pub mod deny_list_v1;
47pub mod deny_list_v2;
48pub mod derived_object;
49pub mod digests;
50pub mod display;
51pub mod display_registry;
52pub mod dynamic_field;
53pub mod effects;
54pub mod epoch_data;
55pub mod event;
56pub mod executable_transaction;
57pub mod execution;
58pub mod execution_params;
59pub mod execution_status;
60pub mod full_checkpoint_content;
61pub mod funds_accumulator;
62pub mod gas;
63pub mod gas_coin;
64pub mod gas_model;
65pub mod global_state_hash;
66pub mod governance;
67pub mod id;
68pub mod in_memory_storage;
69pub mod inner_temporary_store;
70pub mod layout_resolver;
71pub mod message_envelope;
72pub mod messages_checkpoint;
73pub mod messages_consensus;
74pub mod messages_grpc;
75pub mod messages_safe_client;
76pub mod metrics;
77pub mod move_package;
78pub mod multisig;
79pub mod multisig_legacy;
80pub mod nitro_attestation;
81pub mod node_role;
82pub mod object;
83pub mod passkey_authenticator;
84pub mod programmable_transaction_builder;
85pub mod ptb_trace;
86pub mod randomness_state;
87pub mod rpc_proto_conversions;
88pub mod signature;
89pub mod signature_verification;
90pub mod storage;
91pub mod sui_sdk_types_conversions;
92pub mod sui_serde;
93pub mod sui_system_state;
94pub mod supported_protocol_versions;
95pub mod test_checkpoint_data_builder;
96pub mod traffic_control;
97pub mod transaction;
98pub mod transaction_deny_rules;
99pub mod transaction_driver_types;
100pub mod transaction_executor;
101pub mod transfer;
102pub mod type_input;
103pub mod versioned;
104pub mod zk_login_authenticator;
105pub mod zk_login_util;
106
107#[path = "./unit_tests/utils.rs"]
108pub mod utils;
109
110macro_rules! built_in_ids {
111    ($($addr:ident / $id:ident = $init:expr);* $(;)?) => {
112        $(
113            pub const $addr: AccountAddress = AccountAddress::from_suffix($init);
114            pub const $id: ObjectID = ObjectID::from_address($addr);
115        )*
116    }
117}
118
119macro_rules! built_in_pkgs {
120    ($($addr:ident / $id:ident = $init:expr);* $(;)?) => {
121        built_in_ids! { $($addr / $id = $init;)* }
122        pub const SYSTEM_PACKAGE_ADDRESSES: &[AccountAddress] = &[$($addr),*];
123        pub fn is_system_package(addr: impl Into<AccountAddress>) -> bool {
124            matches!(addr.into(), $($addr)|*)
125        }
126    }
127}
128
129built_in_pkgs! {
130    MOVE_STDLIB_ADDRESS / MOVE_STDLIB_PACKAGE_ID = 0x1;
131    SUI_FRAMEWORK_ADDRESS / SUI_FRAMEWORK_PACKAGE_ID = 0x2;
132    SUI_SYSTEM_ADDRESS / SUI_SYSTEM_PACKAGE_ID = 0x3;
133    BRIDGE_ADDRESS / BRIDGE_PACKAGE_ID = 0xb;
134    DEEPBOOK_ADDRESS / DEEPBOOK_PACKAGE_ID = 0xdee9;
135}
136
137built_in_ids! {
138    SUI_SYSTEM_STATE_ADDRESS / SUI_SYSTEM_STATE_OBJECT_ID = 0x5;
139    SUI_CLOCK_ADDRESS / SUI_CLOCK_OBJECT_ID = 0x6;
140    SUI_AUTHENTICATOR_STATE_ADDRESS / SUI_AUTHENTICATOR_STATE_OBJECT_ID = 0x7;
141    SUI_RANDOMNESS_STATE_ADDRESS / SUI_RANDOMNESS_STATE_OBJECT_ID = 0x8;
142    SUI_BRIDGE_ADDRESS / SUI_BRIDGE_OBJECT_ID = 0x9;
143    SUI_COIN_REGISTRY_ADDRESS / SUI_COIN_REGISTRY_OBJECT_ID = 0xc;
144    SUI_DISPLAY_REGISTRY_ADDRESS / SUI_DISPLAY_REGISTRY_OBJECT_ID = 0xd;
145    SUI_DENY_LIST_ADDRESS / SUI_DENY_LIST_OBJECT_ID = 0x403;
146    SUI_ACCUMULATOR_ROOT_ADDRESS / SUI_ACCUMULATOR_ROOT_OBJECT_ID = 0xacc;
147    SUI_ADDRESS_ALIAS_STATE_ADDRESS / SUI_ADDRESS_ALIAS_STATE_OBJECT_ID = 0xa;
148    SUI_FORWARDING_ADDRESS_REGISTRY_ADDRESS / SUI_FORWARDING_ADDRESS_REGISTRY_OBJECT_ID = 0xfa;
149}
150
151pub const SUI_SYSTEM_STATE_OBJECT_SHARED_VERSION: SequenceNumber = OBJECT_START_VERSION;
152pub const SUI_CLOCK_OBJECT_SHARED_VERSION: SequenceNumber = OBJECT_START_VERSION;
153
154/// System objects that a transaction may read *implicitly* during execution, i.e. without declaring
155/// them as shared inputs. Their read version is recorded in effects (as a read-only consensus
156/// object) and reproduced when executing from effects (checkpoint execution during state sync, and
157/// crash recovery) so the read resolves to the same version on every node. Execution paths that are
158/// not sequenced by consensus (dev-inspect / dry-run) pin these objects at their latest committed
159/// versions instead.
160///
161/// Membership here only says the object *may* be read implicitly, so its read version must be
162/// reproducible. A transaction can still declare such an object as an explicit shared input (e.g.
163/// a settlement transaction mutating the accumulator root, or a user transaction that passes it
164/// in); declared inputs are version-assigned through the normal shared-input path, independent of
165/// this set. Extend this as more implicitly-read system objects arise.
166pub const IMPLICITLY_READ_SYSTEM_OBJECTS: &[ObjectID] = &[SUI_ACCUMULATOR_ROOT_OBJECT_ID];
167
168pub fn sui_framework_address_concat_string(suffix: &str) -> String {
169    format!("{}{suffix}", SUI_FRAMEWORK_ADDRESS.to_hex_literal())
170}
171
172/// Parses `s` as an address. Valid formats for addresses are:
173///
174/// - A 256bit number, encoded in decimal, or hexadecimal with a leading "0x" prefix.
175/// - One of a number of pre-defined named addresses: std, sui, sui_system, deepbook.
176///
177/// Parsing succeeds if and only if `s` matches one of these formats exactly, with no remaining
178/// suffix. This function is intended for use within the authority codebases.
179pub fn parse_sui_address(s: &str) -> anyhow::Result<SuiAddress> {
180    use move_core_types::parsing::address::ParsedAddress;
181    Ok(ParsedAddress::parse(s)?
182        .into_account_address(&resolve_address)?
183        .into())
184}
185
186/// Parse `s` as a Module ID: An address (see `parse_sui_address`), followed by `::`, and then a
187/// module name (an identifier). Parsing succeeds if and only if `s` matches this format exactly,
188/// with no remaining input. This function is intended for use within the authority codebases.
189pub fn parse_sui_module_id(s: &str) -> anyhow::Result<ModuleId> {
190    use move_core_types::parsing::types::ParsedModuleId;
191    ParsedModuleId::parse(s)?.into_module_id(&resolve_address)
192}
193
194/// Parse `s` as a fully-qualified name: A Module ID (see `parse_sui_module_id`), followed by `::`,
195/// and then an identifier (for the module member). Parsing succeeds if and only if `s` matches this
196/// format exactly, with no remaining input. This function is intended for use within the authority
197/// codebases.
198pub fn parse_sui_fq_name(s: &str) -> anyhow::Result<(ModuleId, String)> {
199    use move_core_types::parsing::types::ParsedFqName;
200    ParsedFqName::parse(s)?.into_fq_name(&resolve_address)
201}
202
203/// Parse `s` as a struct type: A fully-qualified name, optionally followed by a list of type
204/// parameters (types -- see `parse_sui_type_tag`, separated by commas, surrounded by angle
205/// brackets). Parsing succeeds if and only if `s` matches this format exactly, with no remaining
206/// input. This function is intended for use within the authority codebase.
207pub fn parse_sui_struct_tag(s: &str) -> anyhow::Result<StructTag> {
208    use move_core_types::parsing::types::ParsedDatatype;
209    ParsedDatatype::parse(s)?.into_struct_tag(&resolve_address)
210}
211
212/// Parse `s` as a type: Either a struct type (see `parse_sui_struct_tag`), a primitive type, or a
213/// vector with a type parameter. Parsing succeeds if and only if `s` matches this format exactly,
214/// with no remaining input. This function is intended for use within the authority codebase.
215pub fn parse_sui_type_tag(s: &str) -> anyhow::Result<TypeTag> {
216    use move_core_types::parsing::types::ParsedType;
217    ParsedType::parse(s)?.into_type_tag(&resolve_address)
218}
219
220/// Resolve well-known named addresses into numeric addresses.
221pub fn resolve_address(addr: &str) -> Option<AccountAddress> {
222    match addr {
223        "deepbook" => Some(DEEPBOOK_ADDRESS),
224        "std" => Some(MOVE_STDLIB_ADDRESS),
225        "sui" => Some(SUI_FRAMEWORK_ADDRESS),
226        "sui_system" => Some(SUI_SYSTEM_ADDRESS),
227        "bridge" => Some(BRIDGE_ADDRESS),
228        _ => None,
229    }
230}
231
232pub trait MoveTypeTagTrait {
233    fn get_type_tag() -> TypeTag;
234
235    fn get_instance_type_tag(&self) -> TypeTag {
236        Self::get_type_tag()
237    }
238}
239
240impl MoveTypeTagTrait for u8 {
241    fn get_type_tag() -> TypeTag {
242        TypeTag::U8
243    }
244}
245
246impl MoveTypeTagTrait for u64 {
247    fn get_type_tag() -> TypeTag {
248        TypeTag::U64
249    }
250}
251
252impl MoveTypeTagTrait for ObjectID {
253    fn get_type_tag() -> TypeTag {
254        TypeTag::Address
255    }
256}
257
258impl MoveTypeTagTrait for SuiAddress {
259    fn get_type_tag() -> TypeTag {
260        TypeTag::Address
261    }
262}
263
264impl<T: MoveTypeTagTrait> MoveTypeTagTrait for Vec<T> {
265    fn get_type_tag() -> TypeTag {
266        TypeTag::Vector(Box::new(T::get_type_tag()))
267    }
268}
269
270pub trait MoveTypeTagTraitGeneric {
271    fn get_type_tag(type_params: &[TypeTag]) -> TypeTag;
272}
273
274pub fn is_primitive(
275    view: &CompiledModule,
276    function_type_args: &[AbilitySet],
277    s: &SignatureToken,
278) -> bool {
279    use SignatureToken as S;
280    match s {
281        S::Bool | S::U8 | S::U16 | S::U32 | S::U64 | S::U128 | S::U256 | S::Address => true,
282        S::Signer => false,
283        // optimistic, but no primitive has key
284        S::TypeParameter(idx) => !function_type_args[*idx as usize].has_key(),
285
286        S::Datatype(idx) => [RESOLVED_SUI_ID, RESOLVED_ASCII_STR, RESOLVED_UTF8_STR]
287            .contains(&resolve_struct(view, *idx)),
288
289        S::DatatypeInstantiation(inst) => {
290            let (idx, targs) = &**inst;
291            let resolved_struct = resolve_struct(view, *idx);
292            // option is a primitive
293            resolved_struct == RESOLVED_STD_OPTION
294                && targs.len() == 1
295                && is_primitive(view, function_type_args, &targs[0])
296        }
297
298        S::Vector(inner) => is_primitive(view, function_type_args, inner),
299        S::Reference(_) | S::MutableReference(_) => false,
300    }
301}
302
303pub fn is_object(
304    view: &CompiledModule,
305    function_type_args: &[AbilitySet],
306    t: &SignatureToken,
307) -> Result<bool, String> {
308    use SignatureToken as S;
309    match t {
310        S::Reference(inner) | S::MutableReference(inner) => {
311            is_object(view, function_type_args, inner)
312        }
313        _ => is_object_struct(view, function_type_args, t),
314    }
315}
316
317pub fn is_object_vector(
318    view: &CompiledModule,
319    function_type_args: &[AbilitySet],
320    t: &SignatureToken,
321) -> Result<bool, String> {
322    use SignatureToken as S;
323    match t {
324        S::Vector(inner) => is_object_struct(view, function_type_args, inner),
325        _ => is_object_struct(view, function_type_args, t),
326    }
327}
328
329fn is_object_struct(
330    view: &CompiledModule,
331    function_type_args: &[AbilitySet],
332    s: &SignatureToken,
333) -> Result<bool, String> {
334    use SignatureToken as S;
335    match s {
336        S::Bool
337        | S::U8
338        | S::U16
339        | S::U32
340        | S::U64
341        | S::U128
342        | S::U256
343        | S::Address
344        | S::Signer
345        | S::Vector(_)
346        | S::Reference(_)
347        | S::MutableReference(_) => Ok(false),
348        S::TypeParameter(idx) => Ok(function_type_args
349            .get(*idx as usize)
350            .map(|abs| abs.has_key())
351            .unwrap_or(false)),
352        S::Datatype(_) | S::DatatypeInstantiation(_) => {
353            let abilities = view
354                .abilities(s, function_type_args)
355                .map_err(|vm_err| vm_err.to_string())?;
356            Ok(abilities.has_key())
357        }
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364    use expect_test::expect;
365
366    #[test]
367    fn test_parse_sui_numeric_address() {
368        let result = parse_sui_address("0x2").expect("should not error");
369
370        let expected =
371            expect!["0x0000000000000000000000000000000000000000000000000000000000000002"];
372        expected.assert_eq(&result.to_string());
373    }
374
375    #[test]
376    fn test_parse_sui_named_address() {
377        let result = parse_sui_address("sui").expect("should not error");
378
379        let expected =
380            expect!["0x0000000000000000000000000000000000000000000000000000000000000002"];
381        expected.assert_eq(&result.to_string());
382    }
383
384    #[test]
385    fn test_parse_sui_module_id() {
386        let result = parse_sui_module_id("0x2::sui").expect("should not error");
387        let expected =
388            expect!["0x0000000000000000000000000000000000000000000000000000000000000002::sui"];
389        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
390    }
391
392    #[test]
393    fn test_parse_sui_fq_name() {
394        let (module, name) = parse_sui_fq_name("0x2::object::new").expect("should not error");
395        let expected = expect![
396            "0x0000000000000000000000000000000000000000000000000000000000000002::object::new"
397        ];
398        expected.assert_eq(&format!(
399            "{}::{name}",
400            module.to_canonical_display(/* with_prefix */ true)
401        ));
402    }
403
404    #[test]
405    fn test_parse_sui_struct_tag_short_account_addr() {
406        let result = parse_sui_struct_tag("0x2::sui::SUI").expect("should not error");
407
408        let expected = expect!["0x2::sui::SUI"];
409        expected.assert_eq(&result.to_string());
410
411        let expected =
412            expect!["0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI"];
413        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
414    }
415
416    #[test]
417    fn test_parse_sui_struct_tag_long_account_addr() {
418        let result = parse_sui_struct_tag(
419            "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",
420        )
421        .expect("should not error");
422
423        let expected = expect!["0x2::sui::SUI"];
424        expected.assert_eq(&result.to_string());
425
426        let expected =
427            expect!["0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI"];
428        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
429    }
430
431    #[test]
432    fn test_parse_sui_struct_with_type_param_short_addr() {
433        let result =
434            parse_sui_struct_tag("0x2::coin::COIN<0x2::sui::SUI>").expect("should not error");
435
436        let expected = expect!["0x2::coin::COIN<0x2::sui::SUI>"];
437        expected.assert_eq(&result.to_string());
438
439        let expected = expect![
440            "0x0000000000000000000000000000000000000000000000000000000000000002::coin::COIN<0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI>"
441        ];
442        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
443    }
444
445    #[test]
446    fn test_parse_sui_struct_with_type_param_long_addr() {
447        let result = parse_sui_struct_tag("0x0000000000000000000000000000000000000000000000000000000000000002::coin::COIN<0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI>")
448            .expect("should not error");
449
450        let expected = expect!["0x2::coin::COIN<0x2::sui::SUI>"];
451        expected.assert_eq(&result.to_string());
452
453        let expected = expect![
454            "0x0000000000000000000000000000000000000000000000000000000000000002::coin::COIN<0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI>"
455        ];
456        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
457    }
458
459    #[test]
460    fn test_complex_struct_tag_with_short_addr() {
461        let result =
462            parse_sui_struct_tag("0xe7::vec_coin::VecCoin<vector<0x2::coin::Coin<0x2::sui::SUI>>>")
463                .expect("should not error");
464
465        let expected = expect!["0xe7::vec_coin::VecCoin<vector<0x2::coin::Coin<0x2::sui::SUI>>>"];
466        expected.assert_eq(&result.to_string());
467
468        let expected = expect![
469            "0x00000000000000000000000000000000000000000000000000000000000000e7::vec_coin::VecCoin<vector<0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI>>>"
470        ];
471        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
472    }
473
474    #[test]
475    fn test_complex_struct_tag_with_long_addr() {
476        let result = parse_sui_struct_tag("0x00000000000000000000000000000000000000000000000000000000000000e7::vec_coin::VecCoin<vector<0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI>>>")
477            .expect("should not error");
478
479        let expected = expect!["0xe7::vec_coin::VecCoin<vector<0x2::coin::Coin<0x2::sui::SUI>>>"];
480        expected.assert_eq(&result.to_string());
481
482        let expected = expect![
483            "0x00000000000000000000000000000000000000000000000000000000000000e7::vec_coin::VecCoin<vector<0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI>>>"
484        ];
485        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
486    }
487
488    #[test]
489    fn test_dynamic_field_short_addr() {
490        let result = parse_sui_struct_tag(
491            "0x2::dynamic_field::Field<address, 0xdee9::custodian_v2::Account<0x234::coin::COIN>>",
492        )
493        .expect("should not error");
494
495        let expected = expect![
496            "0x2::dynamic_field::Field<address, 0xdee9::custodian_v2::Account<0x234::coin::COIN>>"
497        ];
498        expected.assert_eq(&result.to_string());
499
500        let expected = expect![
501            "0x0000000000000000000000000000000000000000000000000000000000000002::dynamic_field::Field<address,0x000000000000000000000000000000000000000000000000000000000000dee9::custodian_v2::Account<0x0000000000000000000000000000000000000000000000000000000000000234::coin::COIN>>"
502        ];
503        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
504    }
505
506    #[test]
507    fn test_dynamic_field_long_addr() {
508        let result = parse_sui_struct_tag(
509            "0x2::dynamic_field::Field<address, 0xdee9::custodian_v2::Account<0x234::coin::COIN>>",
510        )
511        .expect("should not error");
512
513        let expected = expect![
514            "0x2::dynamic_field::Field<address, 0xdee9::custodian_v2::Account<0x234::coin::COIN>>"
515        ];
516        expected.assert_eq(&result.to_string());
517
518        let expected = expect![
519            "0x0000000000000000000000000000000000000000000000000000000000000002::dynamic_field::Field<address,0x000000000000000000000000000000000000000000000000000000000000dee9::custodian_v2::Account<0x0000000000000000000000000000000000000000000000000000000000000234::coin::COIN>>"
520        ];
521        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
522    }
523}