1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
use std::fmt::{Display, Formatter, Result as FMTResult};

use crate::error::ContractError;
use crate::os::vfs::vfs_resolve_symlink;
use crate::{ado_contract::ADOContract, os::vfs::vfs_resolve_path};
use cosmwasm_std::{Addr, Api, Deps, QuerierWrapper, Storage};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// An address that can be used within the Andromeda ecosystem.
/// Inspired by the cosmwasm-std `Addr` type. https://github.com/CosmWasm/cosmwasm/blob/2a1c698520a1aacedfe3f4803b0d7d653892217a/packages/std/src/addresses.rs#L33
///
/// This address can be one of two things:
/// 1. A valid human readable address e.g. `cosmos1...`
/// 2. A valid Andromeda VFS path e.g. `/home/user/app/component`
///
/// VFS paths can be local in the case of an app and can be done by referencing `./component` they can also contain protocols for cross chain communication. A VFS path is usually structured as so:
///
/// `<protocol>://<chain (required if ibc used)>/<path>` or `ibc://cosmoshub-4/user/app/component`
#[derive(
    Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, JsonSchema,
)]
pub struct AndrAddr(String);

impl AndrAddr {
    #[inline]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }

    #[inline]
    pub fn into_string(self) -> String {
        self.0
    }

    #[inline]
    pub fn from_string(addr: impl Into<String>) -> AndrAddr {
        AndrAddr(addr.into())
    }

    /// Validates an `AndrAddr`, to be valid the given address must either be a human readable address or a valid VFS path.
    ///
    /// **The existence of the provided path is not validated.**
    ///
    /// **If you wish to validate the existence of the path you must use `get_raw_address`.**
    pub fn validate(&self, api: &dyn Api) -> Result<(), ContractError> {
        match self.is_vfs_path() || self.is_addr(api) {
            true => Ok(()),
            false => Err(ContractError::InvalidAddress {}),
        }
    }

    /// Retrieves the raw address represented by the AndrAddr.
    ///
    /// If the address is a valid human readable address then that is returned, otherwise it is assumed to be a Andromeda VFS path and is resolved accordingly.
    ///
    /// If the address is assumed to be a VFS path and no VFS contract address is provided then an appropriate error is returned.
    pub fn get_raw_address(&self, deps: &Deps) -> Result<Addr, ContractError> {
        if !self.is_vfs_path() {
            return Ok(deps.api.addr_validate(&self.0)?);
        }

        let contract = ADOContract::default();
        let vfs_contract = contract.get_vfs_address(deps.storage, &deps.querier)?;
        self.get_raw_address_from_vfs(deps, vfs_contract)
    }

    /// Retrieves the raw address represented by the AndrAddr from the given VFS contract.
    ///     
    /// If the address is a valid human readable address then that is returned, otherwise it is assumed to be a Andromeda VFS path and is resolved accordingly.
    ///
    /// If the address is assumed to be a VFS path and no VFS contract address is provided then an appropriate error is returned.
    pub fn get_raw_address_from_vfs(
        &self,
        deps: &Deps,
        vfs_contract: impl Into<String>,
    ) -> Result<Addr, ContractError> {
        match self.is_vfs_path() {
            false => Ok(deps.api.addr_validate(&self.0)?),
            true => {
                let vfs_contract: String = vfs_contract.into();
                // Convert local path to VFS path before querying
                let valid_vfs_path =
                    self.local_path_to_vfs_path(deps.storage, &deps.querier, vfs_contract.clone())?;
                let vfs_addr = Addr::unchecked(vfs_contract);
                vfs_resolve_path(valid_vfs_path.clone(), vfs_addr, &deps.querier)
                    .ok()
                    .ok_or(ContractError::InvalidPathname {
                        error: Some(format!(
                            "{:?} does not exist in the file system",
                            valid_vfs_path.0
                        )),
                    })
            }
        }
    }

    /// Converts a local path to a valid VFS path by replacing `./` with the app contract address
    fn local_path_to_vfs_path(
        &self,
        storage: &dyn Storage,
        querier: &QuerierWrapper,
        vfs_contract: impl Into<String>,
    ) -> Result<AndrAddr, ContractError> {
        match self.is_local_path() {
            true => {
                let app_contract = ADOContract::default().get_app_contract(storage)?;
                match app_contract {
                    None => Err(ContractError::AppContractNotSpecified {}),
                    Some(app_contract) => {
                        let replaced =
                            AndrAddr(self.0.replace("./", &format!("/home/{app_contract}/")));
                        vfs_resolve_symlink(replaced, vfs_contract, querier)
                    }
                }
            }
            false => Ok(self.clone()),
        }
    }

    /// Whether the provided address is local to the app
    pub fn is_local_path(&self) -> bool {
        self.0.starts_with("./")
    }

    /// Whether the provided address is a VFS path
    pub fn is_vfs_path(&self) -> bool {
        self.is_local_path()
            || self.0.starts_with('/')
            || self.0.split("://").count() > 1
            || self.0.split('/').count() > 1
            || self.0.starts_with('~')
    }

    /// Whether the provided address is a valid human readable address
    pub fn is_addr(&self, api: &dyn Api) -> bool {
        api.addr_validate(&self.0).is_ok()
    }

    /// Gets the chain for a given AndrAddr if it exists
    ///
    /// E.g. `ibc://cosmoshub-4/user/app/component` would return `cosmoshub-4`
    ///
    /// A human readable address will always return `None`
    pub fn get_chain(&self) -> Option<&str> {
        match self.get_protocol() {
            None => None,
            Some(..) => {
                let start = self.0.find("://").unwrap() + 3;
                let end = self.0[start..]
                    .find('/')
                    .unwrap_or_else(|| self.0[start..].len());
                Some(&self.0[start..start + end])
            }
        }
    }

    /// Gets the protocol for a given AndrAddr if it exists
    ///
    /// E.g. `ibc://cosmoshub-4/user/app/component` would return `ibc`
    ///
    /// A human readable address will always return `None`
    pub fn get_protocol(&self) -> Option<&str> {
        if !self.is_vfs_path() {
            None
        } else {
            let mut split = self.0.split("://");
            if split.clone().count() == 1 {
                None
            } else {
                Some(split.next().unwrap())
            }
        }
    }

    /// Gets the raw path for a given AndrAddr by stripping away any protocols or chain declarations.
    ///
    /// E.g. `ibc://cosmoshub-4/user/app/component` would return `/user/app/component`
    ///
    /// Returns the human readable address if the address is not a VFS path.
    pub fn get_raw_path(&self) -> &str {
        if !self.is_vfs_path() {
            self.0.as_str()
        } else {
            match self.get_protocol() {
                None => self.0.as_str(),
                Some(..) => {
                    let start = self.0.find("://").unwrap() + 3;
                    let end = self.0[start..]
                        .find('/')
                        .unwrap_or_else(|| self.0[start..].len());
                    &self.0[start + end..]
                }
            }
        }
    }

    /// Gets the root directory for a given AndrAddr
    ///
    /// E.g. `/home/user/app/component` would return `home`
    ///
    /// Returns the human readable address if the address is not a VFS path or the local path if the address is a local reference
    pub fn get_root_dir(&self) -> &str {
        match self.is_vfs_path() {
            false => self.0.as_str(),
            true => match self.is_local_path() {
                true => self.0.as_str(),
                false => {
                    let raw_path = self.get_raw_path();
                    if raw_path.starts_with('~') {
                        return "home";
                    }
                    raw_path.split('/').nth(1).unwrap()
                }
            },
        }
    }
}

impl Display for AndrAddr {
    fn fmt(&self, f: &mut Formatter) -> FMTResult {
        write!(f, "{}", &self.0)
    }
}

impl AsRef<str> for AndrAddr {
    #[inline]
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl PartialEq<&str> for AndrAddr {
    fn eq(&self, rhs: &&str) -> bool {
        self.0 == *rhs
    }
}

impl PartialEq<AndrAddr> for &str {
    fn eq(&self, rhs: &AndrAddr) -> bool {
        *self == rhs.0
    }
}

impl PartialEq<String> for AndrAddr {
    fn eq(&self, rhs: &String) -> bool {
        &self.0 == rhs
    }
}

impl PartialEq<AndrAddr> for String {
    fn eq(&self, rhs: &AndrAddr) -> bool {
        self == &rhs.0
    }
}

impl From<AndrAddr> for String {
    fn from(addr: AndrAddr) -> Self {
        addr.0
    }
}

impl From<&AndrAddr> for String {
    fn from(addr: &AndrAddr) -> Self {
        addr.0.clone()
    }
}

#[cfg(test)]
mod tests {
    use cosmwasm_std::testing::mock_dependencies;

    use super::*;

    #[test]
    fn test_validate() {
        let deps = mock_dependencies();
        let addr = AndrAddr("cosmos1...".to_string());
        assert!(addr.validate(&deps.api).is_ok());

        let addr = AndrAddr("ibc://cosmoshub-4/home/user/app/component".to_string());
        assert!(addr.validate(&deps.api).is_ok());

        let addr = AndrAddr("/home/user/app/component".to_string());
        assert!(addr.validate(&deps.api).is_ok());

        let addr = AndrAddr("./user/app/component".to_string());
        assert!(addr.validate(&deps.api).is_ok());

        let addr = AndrAddr("1".to_string());
        assert!(addr.validate(&deps.api).is_err());
    }

    #[test]
    fn test_is_vfs() {
        let addr = AndrAddr("/home/user/app/component".to_string());
        assert!(addr.is_vfs_path());

        let addr = AndrAddr("./user/app/component".to_string());
        assert!(addr.is_vfs_path());

        let addr = AndrAddr("ibc://chain/home/user/app/component".to_string());
        assert!(addr.is_vfs_path());

        let addr = AndrAddr("cosmos1...".to_string());
        assert!(!addr.is_vfs_path());
    }

    #[test]
    fn test_is_addr() {
        let deps = mock_dependencies();
        let addr = AndrAddr("cosmos1...".to_string());
        assert!(addr.is_addr(&deps.api));
        assert!(!addr.is_vfs_path());
    }

    #[test]
    fn test_is_local_path() {
        let addr = AndrAddr("./component".to_string());
        assert!(addr.is_local_path());
        assert!(addr.is_vfs_path());
    }

    #[test]
    fn test_get_protocol() {
        let addr = AndrAddr("cosmos1...".to_string());
        assert!(addr.get_protocol().is_none());

        let addr = AndrAddr("ibc://chain/home/user/app/component".to_string());
        assert_eq!(addr.get_protocol().unwrap(), "ibc");
    }

    #[test]
    fn test_get_chain() {
        let addr = AndrAddr("cosmos1...".to_string());
        assert!(addr.get_chain().is_none());

        let addr = AndrAddr("ibc://chain/home/user/app/component".to_string());
        assert_eq!(addr.get_chain().unwrap(), "chain");

        let addr = AndrAddr("/home/user/app/component".to_string());
        assert!(addr.get_chain().is_none());
    }

    #[test]
    fn test_get_raw_path() {
        let addr = AndrAddr("cosmos1...".to_string());
        assert_eq!(addr.get_raw_path(), "cosmos1...");

        let addr = AndrAddr("ibc://chain/user/app/component".to_string());
        assert_eq!(addr.get_raw_path(), "/user/app/component");

        let addr = AndrAddr("/chain/user/app/component".to_string());
        assert_eq!(addr.get_raw_path(), "/chain/user/app/component");
    }

    #[test]
    fn test_get_root_dir() {
        let addr = AndrAddr("/home/user1".to_string());
        assert_eq!(addr.get_root_dir(), "home");

        let addr = AndrAddr("~user1".to_string());
        assert_eq!(addr.get_root_dir(), "home");

        let addr = AndrAddr("~/user1".to_string());
        assert_eq!(addr.get_root_dir(), "home");

        let addr = AndrAddr("ibc://chain/home/user1".to_string());
        assert_eq!(addr.get_root_dir(), "home");

        let addr = AndrAddr("cosmos1...".to_string());
        assert_eq!(addr.get_root_dir(), "cosmos1...");

        let addr = AndrAddr("./home/user1".to_string());
        assert_eq!(addr.get_root_dir(), "./home/user1");
    }
}