levana_perpswap_cosmos/
addr.rs

1use anyhow::{Context, Result};
2use cosmwasm_schema::cw_serde;
3use cosmwasm_std::{Addr, Api};
4
5/// A raw address passed in via JSON.
6///
7/// The purpose of this newtype wrapper is to make it clear at the type level if
8/// a parameter is an address, and ensure that we go through a proper validation
9/// step when using it.
10#[cw_serde]
11#[derive(Eq, Ord, PartialOrd)]
12#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
13pub struct RawAddr(String);
14
15impl RawAddr {
16    /// Validate the address into an [Addr].
17    pub fn validate(&self, api: &dyn Api) -> Result<Addr> {
18        api.addr_validate(&self.0)
19            .with_context(|| format!("Could not parse address: {self}"))
20    }
21
22    /// View the raw underlying `str`.
23    pub fn as_str(&self) -> &str {
24        &self.0
25    }
26
27    /// Convert into the raw underlying [String]
28    pub fn into_string(self) -> String {
29        self.0
30    }
31}
32
33impl std::fmt::Display for RawAddr {
34    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
35        self.0.fmt(f)
36    }
37}
38
39impl From<String> for RawAddr {
40    fn from(s: String) -> Self {
41        RawAddr(s)
42    }
43}
44
45impl From<&str> for RawAddr {
46    fn from(s: &str) -> Self {
47        s.to_owned().into()
48    }
49}
50
51impl From<Addr> for RawAddr {
52    fn from(addr: Addr) -> Self {
53        addr.into_string().into()
54    }
55}
56
57impl From<&Addr> for RawAddr {
58    fn from(addr: &Addr) -> Self {
59        addr.to_string().into()
60    }
61}
62
63impl From<RawAddr> for String {
64    fn from(RawAddr(s): RawAddr) -> String {
65        s
66    }
67}