Skip to main content

iota_types/
id.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::fmt;
6
7use iota_sdk_types::{ObjectId, StructTag, TypeTag};
8use move_core_types::{
9    account_address::AccountAddress,
10    annotated_value::{MoveFieldLayout, MoveStructLayout, MoveTypeLayout},
11    ident_str,
12    identifier::IdentStr,
13};
14use serde::{Deserialize, Serialize};
15
16use crate::{
17    IOTA_FRAMEWORK_ADDRESS, MoveTypeTagTrait, iota_sdk_types_conversions::struct_tag_sdk_to_core,
18};
19
20pub const RESOLVED_IOTA_ID: (&AccountAddress, &IdentStr, &IdentStr) = (
21    &IOTA_FRAMEWORK_ADDRESS,
22    ident_str!("object"),
23    ident_str!("ID"),
24);
25
26/// Rust version of the Move iota::object::Info type
27#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
28pub struct UID {
29    pub id: ID,
30}
31
32/// Rust version of the Move iota::object::ID type
33#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
34#[serde(transparent)]
35pub struct ID {
36    pub bytes: ObjectId,
37}
38
39impl UID {
40    pub fn new(bytes: ObjectId) -> Self {
41        Self {
42            id: { ID::new(bytes) },
43        }
44    }
45
46    pub fn object_id(&self) -> &ObjectId {
47        &self.id.bytes
48    }
49
50    pub fn to_bcs_bytes(&self) -> Vec<u8> {
51        bcs::to_bytes(&self).unwrap()
52    }
53
54    pub fn layout() -> MoveStructLayout {
55        MoveStructLayout {
56            type_: struct_tag_sdk_to_core(&StructTag::new_uid()),
57            fields: vec![MoveFieldLayout::new(
58                ident_str!("id").to_owned(),
59                MoveTypeLayout::Struct(Box::new(ID::layout())),
60            )],
61        }
62    }
63}
64
65impl fmt::Display for UID {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
67        self.id.fmt(f)
68    }
69}
70
71impl ID {
72    pub fn new(object_id: ObjectId) -> Self {
73        Self { bytes: object_id }
74    }
75
76    pub fn layout() -> MoveStructLayout {
77        MoveStructLayout {
78            type_: struct_tag_sdk_to_core(&StructTag::new_id()),
79            fields: vec![MoveFieldLayout::new(
80                ident_str!("bytes").to_owned(),
81                MoveTypeLayout::Address,
82            )],
83        }
84    }
85}
86
87impl fmt::Display for ID {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
89        self.bytes.fmt(f)
90    }
91}
92
93impl MoveTypeTagTrait for ID {
94    fn get_type_tag() -> TypeTag {
95        TypeTag::Struct(Box::new(StructTag::new_id()))
96    }
97}