diem_types/account_config/constants/
coins.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copyright 2021 Conflux Foundation. All rights reserved.
5// Conflux is free software and distributed under GNU General Public License.
6// See http://www.gnu.org/licenses/
7
8use crate::account_config::constants::{
9    from_currency_code_string, CORE_CODE_ADDRESS,
10};
11use move_core_types::{
12    identifier::Identifier,
13    language_storage::{ModuleId, StructTag, TypeTag},
14};
15use once_cell::sync::Lazy;
16
17pub const XDX_NAME: &str = "XDX";
18pub const XUS_NAME: &str = "XUS";
19
20pub fn xus_tag() -> TypeTag {
21    TypeTag::Struct(StructTag {
22        address: CORE_CODE_ADDRESS,
23        module: from_currency_code_string(XUS_NAME).unwrap(),
24        name: from_currency_code_string(XUS_NAME).unwrap(),
25        type_params: vec![],
26    })
27}
28
29pub static XDX_MODULE: Lazy<ModuleId> = Lazy::new(|| {
30    ModuleId::new(CORE_CODE_ADDRESS, Identifier::new(XDX_NAME).unwrap())
31});
32pub static XDX_STRUCT_NAME: Lazy<Identifier> =
33    Lazy::new(|| Identifier::new(XDX_NAME).unwrap());
34
35pub fn xdx_type_tag() -> TypeTag {
36    TypeTag::Struct(StructTag {
37        address: CORE_CODE_ADDRESS,
38        module: from_currency_code_string(XDX_NAME).unwrap(),
39        name: from_currency_code_string(XDX_NAME).unwrap(),
40        type_params: vec![],
41    })
42}
43
44/// Return `Some(struct_name)` if `t` is a `StructTag` representing one of the
45/// current Diem coin types (XDX, XUS), `None` otherwise.
46pub fn coin_name(t: &TypeTag) -> Option<String> {
47    match t {
48        TypeTag::Struct(StructTag {
49            address,
50            module,
51            name,
52            ..
53        }) if *address == CORE_CODE_ADDRESS && module == name => {
54            let name_str = name.to_string();
55            if name_str == XDX_NAME || name_str == XUS_NAME {
56                Some(name_str)
57            } else {
58                None
59            }
60        }
61        _ => None,
62    }
63}
64
65#[test]
66fn coin_names() {
67    assert!(coin_name(&xus_tag()).unwrap() == XUS_NAME);
68    assert!(coin_name(&xdx_type_tag()).unwrap() == XDX_NAME);
69
70    assert!(coin_name(&TypeTag::U64) == None);
71    let bad_name = Identifier::new("NotACoin").unwrap();
72    let bad_coin = TypeTag::Struct(StructTag {
73        address: CORE_CODE_ADDRESS,
74        module: bad_name.clone(),
75        name: bad_name,
76        type_params: vec![],
77    });
78    assert!(coin_name(&bad_coin) == None);
79}