Skip to main content

iota_types/stardust/output/
alias.rs

1// Copyright (c) 2024 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use iota_sdk_move_types::iota_framework::bag::Bag;
5use iota_sdk_types::{Address, Identifier, StructTag};
6use serde::{Deserialize, Serialize};
7use serde_with::serde_as;
8
9use crate::{balance::Balance, error::IotaError, id::UID, object::Object};
10
11pub const ALIAS_OUTPUT_MODULE_NAME: Identifier = Identifier::from_static("alias_output");
12pub const ALIAS_OUTPUT_STRUCT_NAME: Identifier = Identifier::from_static("AliasOutput");
13pub const ALIAS_DYNAMIC_OBJECT_FIELD_KEY: &[u8] = b"alias";
14pub const ALIAS_DYNAMIC_OBJECT_FIELD_KEY_TYPE: &str = "vector<u8>";
15
16#[serde_as]
17#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
18pub struct AliasOutput {
19    /// This is a "random" UID, not the AliasID from Stardust.
20    pub id: UID,
21
22    /// The amount of coins held by the output.
23    pub balance: Balance,
24    /// The `Bag` holds native tokens, key-ed by the stringified type of the
25    /// asset. Example: key: "0xabcded::soon::SOON", value:
26    /// Balance<0xabcded::soon::SOON>.
27    pub native_tokens: Bag,
28}
29
30impl AliasOutput {
31    /// Create an `AliasOutput` from BCS bytes.
32    pub fn from_bcs_bytes(content: &[u8]) -> Result<Self, IotaError> {
33        bcs::from_bytes(content).map_err(|err| IotaError::ObjectDeserialization {
34            error: format!("Unable to deserialize AliasOutput object: {err:?}"),
35        })
36    }
37
38    pub fn is_alias_output(s: &StructTag) -> bool {
39        s.address() == Address::STARDUST
40            && s.module() == &ALIAS_OUTPUT_MODULE_NAME
41            && s.name() == &ALIAS_OUTPUT_STRUCT_NAME
42    }
43}
44
45impl TryFrom<&Object> for AliasOutput {
46    type Error = IotaError;
47    fn try_from(object: &Object) -> Result<Self, Self::Error> {
48        if let Some(o) = object.data.as_opt_struct() {
49            if AliasOutput::is_alias_output(o.struct_tag()) {
50                return AliasOutput::from_bcs_bytes(o.contents());
51            }
52        }
53
54        Err(IotaError::Type {
55            error: format!("Object type is not an AliasOutput: {object:?}"),
56        })
57    }
58}