cosmwasm-common-library 3.0.0

Cosmwasm common library
Documentation
use core::fmt::Display;
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Addr, Api, StdResult};

/// `cw20::Denom` 과 동일한 표현.
///
/// cw20 크레이트를 의존하지 않는 이유: cw-plus 는 아직 cosmwasm-std 3.x 대응
/// 릴리스가 없다(cw20 최신이 2.0.0, `cosmwasm-std ^2.0.0` 요구). 이 타입 하나
/// 때문에 라이브러리 전체가 2.x 에 묶이므로 여기에 옮겨 둔다. 직렬화 형태가
/// 같아서 온체인 데이터는 호환된다.
#[cw_serde]
pub enum Denom {
    Native(String),
    Cw20(Addr),
}

#[cw_serde]
#[derive(Eq, Ord, PartialOrd)]
pub enum SerializableDenom {
    Native(String),
    Cw20(String),
}

impl Display for SerializableDenom {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let str = match self {
            SerializableDenom::Native(denom) => format!("native_{}", denom).to_string(),
            SerializableDenom::Cw20(contract_address) => {
                format!("cw20_{}", contract_address).to_string()
            }
        };
        write!(f, "{}", str)
    }
}

impl From<Denom> for SerializableDenom {
    fn from(value: Denom) -> Self {
        match value {
            Denom::Native(denom) => SerializableDenom::Native(denom),
            Denom::Cw20(contract_address) => SerializableDenom::Cw20(contract_address.to_string()),
        }
    }
}

impl SerializableDenom {
    pub fn to_denom(&self, api: &dyn Api) -> StdResult<Denom> {
        Ok(match self {
            SerializableDenom::Native(denom) => Denom::Native(denom.clone()),
            SerializableDenom::Cw20(contract_address) => {
                Denom::Cw20(api.addr_validate(contract_address)?)
            }
        })
    }
}