Skip to main content

iota_types/
lib.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2026 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5#![warn(
6    future_incompatible,
7    nonstandard_style,
8    rust_2018_idioms,
9    rust_2021_compatibility
10)]
11
12use iota_sdk_types::{Address, ObjectId, StructTag, TypeTag, Version};
13use move_binary_format::{
14    CompiledModule,
15    file_format::{AbilitySet, SignatureToken},
16};
17use move_bytecode_utils::resolve_struct;
18use move_core_types::{account_address::AccountAddress, language_storage::ModuleId};
19use object::OBJECT_START_VERSION;
20
21use crate::{
22    base_types::{RESOLVED_ASCII_STR, RESOLVED_IOTA_ID, RESOLVED_STD_OPTION, RESOLVED_UTF8_STR},
23    iota_sdk_types_conversions::{struct_tag_core_to_sdk, type_tag_core_to_sdk},
24};
25
26#[macro_use]
27pub mod error;
28
29pub mod account_abstraction;
30pub mod attestation;
31pub mod auth_context;
32pub mod balance;
33pub mod base_types;
34pub mod clock;
35pub mod coin;
36pub mod coin_manager;
37pub mod committee;
38pub mod config;
39pub mod crypto;
40pub mod deny_list_v1;
41pub mod deny_rule_governance;
42pub mod digests;
43pub mod dynamic_field;
44pub mod effects;
45pub mod epoch_data;
46pub mod event;
47pub mod executable_transaction;
48pub mod execution;
49pub mod execution_config_utils;
50pub mod full_checkpoint_content;
51pub mod gas;
52pub mod gas_coin;
53pub mod gas_model;
54pub mod global_state_hash;
55pub mod governance;
56pub mod in_memory_storage;
57pub mod inner_temporary_store;
58pub mod iota_sdk_types_conversions;
59pub mod iota_serde;
60pub mod iota_system_state;
61pub mod layout_resolver;
62pub mod message_envelope;
63pub mod messages_checkpoint;
64// Consensus message types (and the gRPC API types that carry them) are
65// node-only and pull in fastcrypto-threshold / tonic, which don't build on wasm32.
66#[cfg(not(target_arch = "wasm32"))]
67pub mod messages_consensus;
68#[cfg(not(target_arch = "wasm32"))]
69pub mod messages_grpc;
70pub mod messages_safe_client;
71pub mod metrics;
72pub mod mock_checkpoint_builder;
73pub mod move_authenticator;
74pub mod move_layout;
75pub mod move_package;
76pub mod multisig;
77pub mod object;
78pub mod passkey_authenticator;
79pub mod programmable_transaction_builder;
80pub mod proto_value;
81pub mod ptb_trace;
82pub mod quorum_driver_types;
83pub mod randomness_state;
84pub mod signature;
85pub mod signature_verification;
86pub mod stardust;
87pub mod storage;
88pub mod supported_protocol_versions;
89pub mod test_checkpoint_data_builder;
90pub mod timelock;
91pub mod traffic_control;
92pub mod transaction;
93pub mod transaction_deny_rules;
94pub mod transaction_driver_types;
95pub mod transaction_executor;
96pub mod transfer;
97
98#[path = "./unit_tests/utils.rs"]
99pub mod utils;
100
101macro_rules! built_in_ids {
102    ($($addr:ident / $id:ident = $init:expr);* $(;)?) => {
103        $(
104            pub const $addr: AccountAddress = builtin_address($init);
105            pub const $id: ObjectId = ObjectId::new($addr.into_bytes());
106        )*
107    }
108}
109
110macro_rules! built_in_pkgs {
111    ($($addr:ident / $id:ident = $init:expr);* $(;)?) => {
112        built_in_ids! { $($addr / $id = $init;)* }
113    }
114}
115
116built_in_pkgs! {
117    MOVE_STDLIB_ADDRESS / MOVE_STDLIB_PACKAGE_ID = 0x1;
118    IOTA_FRAMEWORK_ADDRESS / IOTA_FRAMEWORK_PACKAGE_ID = 0x2;
119    IOTA_SYSTEM_ADDRESS / IOTA_SYSTEM_PACKAGE_ID = 0x3;
120    GENESIS_BRIDGE_ADDRESS / GENESIS_BRIDGE_PACKAGE_ID = 0xb;
121    STARDUST_ADDRESS / STARDUST_PACKAGE_ID = 0x107a;
122}
123
124built_in_ids! {
125    IOTA_SYSTEM_STATE_ADDRESS / IOTA_SYSTEM_STATE_OBJECT_ID = 0x5;
126    IOTA_CLOCK_ADDRESS / IOTA_CLOCK_OBJECT_ID = 0x6;
127    IOTA_AUTHENTICATOR_STATE_ADDRESS / IOTA_AUTHENTICATOR_STATE_OBJECT_ID = 0x7;
128    IOTA_RANDOMNESS_STATE_ADDRESS / IOTA_RANDOMNESS_STATE_OBJECT_ID = 0x8;
129    GENESIS_IOTA_BRIDGE_ADDRESS / GENESIS_IOTA_BRIDGE_OBJECT_ID = 0x9;
130    IOTA_DENY_LIST_ADDRESS / IOTA_DENY_LIST_OBJECT_ID = 0x403;
131    IOTA_TRANSACTION_DENY_RULES_ADDRESS / IOTA_TRANSACTION_DENY_RULES_OBJECT_ID = 0xde9;
132}
133
134pub const SYSTEM_PACKAGE_ADDRESSES: [Address; 5] = [
135    Address::STD,
136    Address::FRAMEWORK,
137    Address::SYSTEM,
138    Address::GENESIS_BRIDGE,
139    Address::STARDUST,
140];
141
142pub const IOTA_SYSTEM_STATE_OBJECT_SHARED_VERSION: Version = OBJECT_START_VERSION;
143pub const IOTA_CLOCK_OBJECT_SHARED_VERSION: Version = OBJECT_START_VERSION;
144
145const fn builtin_address(suffix: u16) -> AccountAddress {
146    let mut addr = [0u8; AccountAddress::LENGTH];
147    let [hi, lo] = suffix.to_be_bytes();
148    addr[AccountAddress::LENGTH - 2] = hi;
149    addr[AccountAddress::LENGTH - 1] = lo;
150    AccountAddress::new(addr)
151}
152
153pub fn iota_framework_address_concat_string(suffix: &str) -> String {
154    format!("{}{suffix}", Address::FRAMEWORK.to_short_hex())
155}
156
157/// Parses `s` as an address. Valid formats for addresses are:
158///
159/// - A 256bit number, encoded in decimal, or hexadecimal with a leading "0x" prefix.
160/// - One of a number of pre-defined named addresses: std, iota, iota_system, stardust.
161///
162/// Parsing succeeds if and only if `s` matches one of these formats exactly,
163/// with no remaining suffix. This function is intended for use within the
164/// authority codebases.
165pub fn parse_iota_address(s: &str) -> anyhow::Result<Address> {
166    use move_core_types::parsing::address::ParsedAddress;
167    Ok(Address::new(
168        ParsedAddress::parse(s)?
169            .into_account_address(&resolve_address)?
170            .into_bytes(),
171    ))
172}
173
174/// Parse `s` as a Module ID: An address (see `parse_iota_address`), followed by
175/// `::`, and then a module name (an identifier). Parsing succeeds if and only
176/// if `s` matches this format exactly, with no remaining input. This function
177/// is intended for use within the authority codebases.
178pub fn parse_iota_module_id(s: &str) -> anyhow::Result<ModuleId> {
179    use move_core_types::parsing::types::ParsedModuleId;
180    ParsedModuleId::parse(s)?.into_module_id(&resolve_address)
181}
182
183/// Parse `s` as a fully-qualified name: A Module ID (see
184/// `parse_iota_module_id`), followed by `::`, and then an identifier (for the
185/// module member). Parsing succeeds if and only if `s` matches this
186/// format exactly, with no remaining input. This function is intended for use
187/// within the authority codebases.
188pub fn parse_iota_fq_name(s: &str) -> anyhow::Result<(ModuleId, String)> {
189    use move_core_types::parsing::types::ParsedFqName;
190    ParsedFqName::parse(s)?.into_fq_name(&resolve_address)
191}
192
193/// Parse `s` as a struct type: A fully-qualified name, optionally followed by a
194/// list of type parameters (types -- see `parse_iota_type_tag`, separated by
195/// commas, surrounded by angle brackets). Parsing succeeds if and only if `s`
196/// matches this format exactly, with no remaining input. This function is
197/// intended for use within the authority codebase.
198pub fn parse_iota_struct_tag(s: &str) -> anyhow::Result<StructTag> {
199    use move_core_types::parsing::types::ParsedStructType;
200    ParsedStructType::parse(s)?
201        .into_struct_tag(&resolve_address)
202        .map(|s| struct_tag_core_to_sdk(&s))
203}
204
205/// Parse `s` as a type: Either a struct type (see `parse_iota_struct_tag`), a
206/// primitive type, or a vector with a type parameter. Parsing succeeds if and
207/// only if `s` matches this format exactly, with no remaining input. This
208/// function is intended for use within the authority codebase.
209pub fn parse_iota_type_tag(s: &str) -> anyhow::Result<TypeTag> {
210    use move_core_types::parsing::types::ParsedType;
211    ParsedType::parse(s)?
212        .into_type_tag(&resolve_address)
213        .map(|s| type_tag_core_to_sdk(&s))
214}
215
216/// Resolve well-known named addresses into numeric addresses.
217pub fn resolve_address(addr: &str) -> Option<AccountAddress> {
218    match addr {
219        "std" => Some(Address::STD),
220        "iota" => Some(Address::FRAMEWORK),
221        "iota_system" => Some(Address::SYSTEM),
222        "stardust" => Some(Address::STARDUST),
223        _ => None,
224    }
225    .map(|addr| AccountAddress::new(addr.into_bytes()))
226}
227
228/// Check if a type is a primitive type in optimistic mode. It invokes the inner
229/// function with is_strict = false.
230pub fn is_primitive(
231    view: &CompiledModule,
232    function_type_args: &[AbilitySet],
233    s: &SignatureToken,
234) -> bool {
235    is_primitive_inner(view, function_type_args, s, false)
236}
237
238/// Check if a type is a primitive type in strict mode. It invokes the inner
239/// function with is_strict = true.
240pub fn is_primitive_strict(
241    view: &CompiledModule,
242    function_type_args: &[AbilitySet],
243    s: &SignatureToken,
244) -> bool {
245    is_primitive_inner(view, function_type_args, s, true)
246}
247
248/// Check if a type is a primitive type.
249/// In optimistic mode (is_strict = false), a type parameter is considered
250/// primitive if it has no key ability. In strict mode (is_strict = true), a
251/// type parameter is considered primitive if it has at least copy or drop
252/// ability.
253pub fn is_primitive_inner(
254    view: &CompiledModule,
255    function_type_args: &[AbilitySet],
256    s: &SignatureToken,
257    is_strict: bool,
258) -> bool {
259    use SignatureToken as S;
260    match s {
261        S::Bool | S::U8 | S::U16 | S::U32 | S::U64 | S::U128 | S::U256 | S::Address => true,
262        S::Signer => false,
263        // optimistic -> no primitive has key
264        // strict -> all primitives have at least copy or drop
265        S::TypeParameter(idx) => {
266            if !is_strict {
267                // optimistic: has no key
268                !function_type_args[*idx as usize].has_key()
269            } else {
270                // strict: has at least one of: copy or drop (or store and one of the others).
271                // copy or drop abilities always imply having no key, but here we double check
272                let abilities = function_type_args[*idx as usize];
273                !abilities.has_key() && (abilities.has_copy() || abilities.has_drop())
274            }
275        }
276
277        S::Datatype(idx) => [RESOLVED_IOTA_ID, RESOLVED_ASCII_STR, RESOLVED_UTF8_STR]
278            .contains(&resolve_struct(view, *idx)),
279
280        S::DatatypeInstantiation(inst) => {
281            let (idx, targs) = &**inst;
282            let resolved_struct = resolve_struct(view, *idx);
283            // option is a primitive
284            resolved_struct == RESOLVED_STD_OPTION
285                && targs.len() == 1
286                && is_primitive_inner(view, function_type_args, &targs[0], is_strict)
287        }
288
289        S::Vector(inner) => is_primitive_inner(view, function_type_args, inner, is_strict),
290        S::Reference(_) | S::MutableReference(_) => false,
291    }
292}
293
294pub fn is_object(
295    view: &CompiledModule,
296    function_type_args: &[AbilitySet],
297    t: &SignatureToken,
298) -> Result<bool, String> {
299    use SignatureToken as S;
300    match t {
301        S::Reference(inner) | S::MutableReference(inner) => {
302            is_object(view, function_type_args, inner)
303        }
304        _ => is_object_struct(view, function_type_args, t),
305    }
306}
307
308pub fn is_object_vector(
309    view: &CompiledModule,
310    function_type_args: &[AbilitySet],
311    t: &SignatureToken,
312) -> Result<bool, String> {
313    use SignatureToken as S;
314    match t {
315        S::Vector(inner) => is_object_struct(view, function_type_args, inner),
316        _ => is_object_struct(view, function_type_args, t),
317    }
318}
319
320pub fn is_object_struct(
321    view: &CompiledModule,
322    function_type_args: &[AbilitySet],
323    s: &SignatureToken,
324) -> Result<bool, String> {
325    use SignatureToken as S;
326    match s {
327        S::Bool
328        | S::U8
329        | S::U16
330        | S::U32
331        | S::U64
332        | S::U128
333        | S::U256
334        | S::Address
335        | S::Signer
336        | S::Vector(_)
337        | S::Reference(_)
338        | S::MutableReference(_) => Ok(false),
339        S::TypeParameter(idx) => Ok(function_type_args
340            .get(*idx as usize)
341            .map(|abs| abs.has_key())
342            .unwrap_or(false)),
343        S::Datatype(_) | S::DatatypeInstantiation(_) => {
344            let abilities = view
345                .abilities(s, function_type_args)
346                .map_err(|vm_err| vm_err.to_string())?;
347            Ok(abilities.has_key())
348        }
349    }
350}
351
352#[cfg(test)]
353mod tests {
354    use expect_test::expect;
355
356    use super::*;
357
358    #[test]
359    fn test_parse_iota_numeric_address() {
360        let result = parse_iota_address("0x2").expect("should not error");
361
362        let expected =
363            expect!["0x0000000000000000000000000000000000000000000000000000000000000002"];
364        expected.assert_eq(&result.to_string());
365    }
366
367    #[test]
368    fn test_parse_iota_named_address() {
369        let result = parse_iota_address("iota").expect("should not error");
370
371        let expected =
372            expect!["0x0000000000000000000000000000000000000000000000000000000000000002"];
373        expected.assert_eq(&result.to_string());
374    }
375
376    #[test]
377    fn test_parse_iota_module_id() {
378        let result = parse_iota_module_id("0x2::iota").expect("should not error");
379        let expected =
380            expect!["0x0000000000000000000000000000000000000000000000000000000000000002::iota"];
381        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
382    }
383
384    #[test]
385    fn test_parse_iota_fq_name() {
386        let (module, name) = parse_iota_fq_name("0x2::object::new").expect("should not error");
387        let expected = expect![
388            "0x0000000000000000000000000000000000000000000000000000000000000002::object::new"
389        ];
390        expected.assert_eq(&format!(
391            "{}::{name}",
392            module.to_canonical_display(/* with_prefix */ true)
393        ));
394    }
395
396    #[test]
397    fn test_parse_iota_struct_tag_short_account_addr() {
398        let result = parse_iota_struct_tag("0x2::iota::IOTA").expect("should not error");
399
400        let expected = expect!["0x2::iota::IOTA"];
401        expected.assert_eq(&result.to_string());
402
403        let expected = expect![
404            "0x0000000000000000000000000000000000000000000000000000000000000002::iota::IOTA"
405        ];
406        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
407    }
408
409    #[test]
410    fn test_parse_iota_struct_tag_long_account_addr() {
411        let result = parse_iota_struct_tag(
412            "0x0000000000000000000000000000000000000000000000000000000000000002::iota::IOTA",
413        )
414        .expect("should not error");
415
416        let expected = expect!["0x2::iota::IOTA"];
417        expected.assert_eq(&result.to_string());
418
419        let expected = expect![
420            "0x0000000000000000000000000000000000000000000000000000000000000002::iota::IOTA"
421        ];
422        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
423    }
424
425    #[test]
426    fn test_parse_iota_struct_with_type_param_short_addr() {
427        let result =
428            parse_iota_struct_tag("0x2::coin::COIN<0x2::iota::IOTA>").expect("should not error");
429
430        let expected = expect!["0x2::coin::COIN<0x2::iota::IOTA>"];
431        expected.assert_eq(&result.to_string());
432
433        let expected = expect![
434            "0x0000000000000000000000000000000000000000000000000000000000000002::coin::COIN<0x0000000000000000000000000000000000000000000000000000000000000002::iota::IOTA>"
435        ];
436        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
437    }
438
439    #[test]
440    fn test_parse_iota_struct_with_type_param_long_addr() {
441        let result = parse_iota_struct_tag("0x0000000000000000000000000000000000000000000000000000000000000002::coin::COIN<0x0000000000000000000000000000000000000000000000000000000000000002::iota::IOTA>")
442            .expect("should not error");
443
444        let expected = expect!["0x2::coin::COIN<0x2::iota::IOTA>"];
445        expected.assert_eq(&result.to_string());
446
447        let expected = expect![
448            "0x0000000000000000000000000000000000000000000000000000000000000002::coin::COIN<0x0000000000000000000000000000000000000000000000000000000000000002::iota::IOTA>"
449        ];
450        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
451    }
452
453    #[test]
454    fn test_complex_struct_tag_with_short_addr() {
455        let result = parse_iota_struct_tag(
456            "0xe7::vec_coin::VecCoin<vector<0x2::coin::Coin<0x2::iota::IOTA>>>",
457        )
458        .expect("should not error");
459
460        let expected = expect!["0xe7::vec_coin::VecCoin<vector<0x2::coin::Coin<0x2::iota::IOTA>>>"];
461        expected.assert_eq(&result.to_string());
462
463        let expected = expect![
464            "0x00000000000000000000000000000000000000000000000000000000000000e7::vec_coin::VecCoin<vector<0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<0x0000000000000000000000000000000000000000000000000000000000000002::iota::IOTA>>>"
465        ];
466        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
467    }
468
469    #[test]
470    fn test_complex_struct_tag_with_long_addr() {
471        let result = parse_iota_struct_tag("0x00000000000000000000000000000000000000000000000000000000000000e7::vec_coin::VecCoin<vector<0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<0x0000000000000000000000000000000000000000000000000000000000000002::iota::IOTA>>>")
472            .expect("should not error");
473
474        let expected = expect!["0xe7::vec_coin::VecCoin<vector<0x2::coin::Coin<0x2::iota::IOTA>>>"];
475        expected.assert_eq(&result.to_string());
476
477        let expected = expect![
478            "0x00000000000000000000000000000000000000000000000000000000000000e7::vec_coin::VecCoin<vector<0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<0x0000000000000000000000000000000000000000000000000000000000000002::iota::IOTA>>>"
479        ];
480        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
481    }
482
483    #[test]
484    fn test_dynamic_field_short_addr() {
485        let result = parse_iota_struct_tag(
486            "0x2::dynamic_field::Field<address, 0x2::balance::Balance<0x234::coin::COIN>>",
487        )
488        .expect("should not error");
489
490        let expected =
491            expect!["0x2::dynamic_field::Field<address, 0x2::balance::Balance<0x234::coin::COIN>>"];
492        expected.assert_eq(&result.to_string());
493
494        let expected = expect![
495            "0x0000000000000000000000000000000000000000000000000000000000000002::dynamic_field::Field<address,0x0000000000000000000000000000000000000000000000000000000000000002::balance::Balance<0x0000000000000000000000000000000000000000000000000000000000000234::coin::COIN>>"
496        ];
497        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
498    }
499
500    #[test]
501    fn test_dynamic_field_long_addr() {
502        let result = parse_iota_struct_tag(
503            "0x2::dynamic_field::Field<address, 0x2::balance::Balance<0x234::coin::COIN>>",
504        )
505        .expect("should not error");
506
507        let expected =
508            expect!["0x2::dynamic_field::Field<address, 0x2::balance::Balance<0x234::coin::COIN>>"];
509        expected.assert_eq(&result.to_string());
510
511        let expected = expect![
512            "0x0000000000000000000000000000000000000000000000000000000000000002::dynamic_field::Field<address,0x0000000000000000000000000000000000000000000000000000000000000002::balance::Balance<0x0000000000000000000000000000000000000000000000000000000000000234::coin::COIN>>"
513        ];
514        expected.assert_eq(&result.to_canonical_string(/* with_prefix */ true));
515    }
516}