abstract_std/objects/account/
account_trace.rs

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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use std::fmt::Display;

use super::account_id::deser::split_first_key;
use cosmwasm_std::{ensure, Env, StdError, StdResult};
use cw_storage_plus::{Key, KeyDeserialize, Prefixer, PrimaryKey};

use crate::{constants::CHAIN_DELIMITER, objects::TruncatedChainId, AbstractError};

pub const MAX_TRACE_LENGTH: u16 = 6;
pub(crate) const LOCAL: &str = "local";

/// The identifier of chain that triggered the account creation
///
/// Note that the serialization to string and to Cw-storage-plus keys is different
///
/// For String, `AccountTrace::Remote(vec!["neutron", "osmosis"])` will be serialized as `osmosis>neutron`
///
/// For cw-storage-plus-key, `AccountTrace::Remote(vec!["neutron", "osmosis"])` will be serialized as `remote:["neutron", "osmosis", "", "", "", ""]`

#[cosmwasm_schema::cw_serde]
pub enum AccountTrace {
    Local,
    // path of the chains that triggered the account creation
    Remote(Vec<TruncatedChainId>),
}

pub const ACCOUNT_TRACE_KEY_PLACEHOLDER: &[u8] = &[];

impl KeyDeserialize for &AccountTrace {
    type Output = AccountTrace;
    const KEY_ELEMS: u16 = MAX_TRACE_LENGTH;

    #[inline(always)]
    fn from_vec(value: Vec<u8>) -> StdResult<Self::Output> {
        let mut trace = vec![];
        // We parse the whole data for the MAX_TRACE_LENGTH keys
        let mut value = value.as_ref();
        for i in 0..MAX_TRACE_LENGTH - 1 {
            let (current_chain, remainder) = split_first_key(1, value)?;
            value = remainder;
            if current_chain == ACCOUNT_TRACE_KEY_PLACEHOLDER {
                continue;
            }
            let chain = String::from_utf8(current_chain)?;
            if i == 0 && chain == "local" {
                return Ok(AccountTrace::Local);
            }
            trace.push(TruncatedChainId::from_string(chain).unwrap())
        }

        Ok(AccountTrace::Remote(trace))
    }
}

impl KeyDeserialize for AccountTrace {
    type Output = AccountTrace;
    const KEY_ELEMS: u16 = <&AccountTrace>::KEY_ELEMS;

    #[inline(always)]
    fn from_vec(value: Vec<u8>) -> StdResult<Self::Output> {
        <&AccountTrace>::from_vec(value)
    }
}

impl PrimaryKey<'_> for AccountTrace {
    type Prefix = ();
    type SubPrefix = ();
    type Suffix = Self;
    type SuperSuffix = Self;

    fn key(&self) -> Vec<cw_storage_plus::Key> {
        let mut serialization_result = match self {
            AccountTrace::Local => LOCAL.key(),
            AccountTrace::Remote(chain_name) => chain_name
                .iter()
                .flat_map(|c| c.str_ref().key())
                .collect::<Vec<Key>>(),
        };
        for _ in serialization_result.len()..(MAX_TRACE_LENGTH as usize) {
            serialization_result.extend(ACCOUNT_TRACE_KEY_PLACEHOLDER.key());
        }
        serialization_result
    }
}

impl Prefixer<'_> for AccountTrace {
    fn prefix(&self) -> Vec<Key> {
        self.key()
    }
}

impl AccountTrace {
    /// verify the formatting of the Account trace chain
    pub fn verify(&self) -> Result<(), AbstractError> {
        match self {
            AccountTrace::Local => Ok(()),
            AccountTrace::Remote(chain_trace) => {
                // Ensure the trace length is limited
                ensure!(
                    chain_trace.len() <= MAX_TRACE_LENGTH as usize,
                    AbstractError::FormattingError {
                        object: "chain-seq".into(),
                        expected: format!("between 1 and {MAX_TRACE_LENGTH}"),
                        actual: chain_trace.len().to_string(),
                    }
                );
                for chain in chain_trace {
                    chain.verify()?;
                    if chain.as_str().eq(LOCAL) {
                        return Err(AbstractError::FormattingError {
                            object: "chain-seq".into(),
                            expected: "not 'local'".into(),
                            actual: chain.to_string(),
                        });
                    }
                }
                Ok(())
            }
        }
    }

    /// assert that the account trace is a remote account and verify the formatting
    pub fn verify_remote(&self) -> Result<(), AbstractError> {
        if &Self::Local == self {
            Err(AbstractError::Std(StdError::generic_err(
                "expected remote account trace",
            )))
        } else {
            self.verify()
        }
    }

    /// assert that the trace is local
    pub fn verify_local(&self) -> Result<(), AbstractError> {
        if let &Self::Remote(..) = self {
            return Err(AbstractError::Std(StdError::generic_err(
                "expected local account trace",
            )));
        }
        Ok(())
    }

    /// push the `env.block.chain_name` to the chain trace
    pub fn push_local_chain(&mut self, env: &Env) {
        match &self {
            AccountTrace::Local => {
                *self = AccountTrace::Remote(vec![TruncatedChainId::new(env)]);
            }
            AccountTrace::Remote(path) => {
                let mut path = path.clone();
                path.push(TruncatedChainId::new(env));
                *self = AccountTrace::Remote(path);
            }
        }
    }

    /// push a chain name to the account's path
    pub fn push_chain(&mut self, chain_name: TruncatedChainId) {
        match &self {
            AccountTrace::Local => {
                *self = AccountTrace::Remote(vec![chain_name]);
            }
            AccountTrace::Remote(path) => {
                let mut path = path.clone();
                path.push(chain_name);
                *self = AccountTrace::Remote(path);
            }
        }
    }

    /// **No verification is done here**
    ///
    /// **only use this for deserialization**
    pub(crate) fn from_string(trace: String) -> Self {
        account_trace_from_str(&trace)
    }

    pub(crate) fn from_str(trace: &str) -> Result<Self, AbstractError> {
        let acc = account_trace_from_str(trace);
        acc.verify()?;
        Ok(acc)
    }
}

impl TryFrom<&str> for AccountTrace {
    type Error = AbstractError;

    fn try_from(trace: &str) -> Result<Self, Self::Error> {
        AccountTrace::from_str(trace)
    }
}

fn account_trace_from_str(trace: &str) -> AccountTrace {
    if trace == LOCAL {
        AccountTrace::Local
    } else {
        let rev_trace: Vec<_> = trace
            // DoubleEndedSearcher implemented for char, but not for "str"
            .split(CHAIN_DELIMITER.chars().next().unwrap())
            .map(TruncatedChainId::_from_str)
            .rev()
            .collect();
        AccountTrace::Remote(rev_trace)
    }
}

impl Display for AccountTrace {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AccountTrace::Local => write!(f, "{}", LOCAL),
            AccountTrace::Remote(chain_name) => write!(
                f,
                "{}",
                // "juno>terra>osmosis"
                chain_name
                    .iter()
                    .rev()
                    .map(|name| name.as_str())
                    .collect::<Vec<&str>>()
                    .join(CHAIN_DELIMITER)
            ),
        }
    }
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

#[cfg(test)]
mod test {
    #![allow(clippy::needless_borrows_for_generic_args)]
    use std::str::FromStr;

    use cosmwasm_std::{testing::mock_dependencies, Addr, Order};
    use cw_storage_plus::Map;

    use super::*;

    mod format {
        use super::*;
        use crate::objects::truncated_chain_id::MAX_CHAIN_NAME_LENGTH;

        #[coverage_helper::test]
        fn local_works() {
            let trace = AccountTrace::from_str(LOCAL).unwrap();
            assert_eq!(trace, AccountTrace::Local);
        }

        #[coverage_helper::test]
        fn remote_works() {
            let trace = AccountTrace::from_str("bitcoin").unwrap();
            assert_eq!(
                trace,
                AccountTrace::Remote(vec![TruncatedChainId::from_str("bitcoin").unwrap()])
            );
        }

        #[coverage_helper::test]
        fn remote_multi_works() {
            // Here the account originates from ethereum and was then bridged to bitcoin
            let trace = AccountTrace::from_str("bitcoin>ethereum").unwrap();
            assert_eq!(
                trace,
                // The trace vector pushes the last chains last
                AccountTrace::Remote(vec![
                    TruncatedChainId::from_str("ethereum").unwrap(),
                    TruncatedChainId::from_str("bitcoin").unwrap(),
                ])
            );
        }

        #[coverage_helper::test]
        fn remote_multi_multi_works() {
            // Here the account originates from cosmos, and was then bridged to ethereum and was then bridged to bitcoin
            let trace = AccountTrace::from_str("bitcoin>ethereum>cosmos").unwrap();
            assert_eq!(
                trace,
                // The trace vector pushes the last chains last
                AccountTrace::Remote(vec![
                    TruncatedChainId::from_str("cosmos").unwrap(),
                    TruncatedChainId::from_str("ethereum").unwrap(),
                    TruncatedChainId::from_str("bitcoin").unwrap(),
                ])
            );
        }

        // now test failures
        #[coverage_helper::test]
        fn local_empty_fails() {
            AccountTrace::from_str("").unwrap_err();
        }

        #[coverage_helper::test]
        fn local_too_short_fails() {
            AccountTrace::from_str("a").unwrap_err();
        }

        #[coverage_helper::test]
        fn local_too_long_fails() {
            AccountTrace::from_str(&"a".repeat(MAX_CHAIN_NAME_LENGTH + 1)).unwrap_err();
        }

        #[coverage_helper::test]
        fn local_uppercase_fails() {
            AccountTrace::from_str("AAAAA").unwrap_err();
        }

        #[coverage_helper::test]
        fn local_non_alphanumeric_fails() {
            AccountTrace::from_str("a!aoeuoau").unwrap_err();
        }
    }

    mod key {
        use super::*;

        fn mock_key() -> AccountTrace {
            AccountTrace::Remote(vec![TruncatedChainId::from_str("bitcoin").unwrap()])
        }

        fn mock_local_key() -> AccountTrace {
            AccountTrace::Local
        }

        fn mock_multi_hop_key() -> AccountTrace {
            AccountTrace::Remote(vec![
                TruncatedChainId::from_str("bitcoin").unwrap(),
                TruncatedChainId::from_str("atom").unwrap(),
                TruncatedChainId::from_str("foo").unwrap(),
            ])
        }

        #[coverage_helper::test]
        fn storage_key_works() {
            let mut deps = mock_dependencies();
            let local_key = mock_local_key();
            let key = mock_key();
            let multihop_key = mock_multi_hop_key();
            let map: Map<&AccountTrace, u64> = Map::new("map");

            map.save(deps.as_mut().storage, &local_key, &159784)
                .unwrap();
            map.save(deps.as_mut().storage, &key, &42069).unwrap();
            map.save(deps.as_mut().storage, &multihop_key, &69420)
                .unwrap();

            assert_eq!(map.load(deps.as_ref().storage, &local_key).unwrap(), 159784);
            assert_eq!(map.load(deps.as_ref().storage, &key).unwrap(), 42069);
            assert_eq!(
                map.load(deps.as_ref().storage, &multihop_key).unwrap(),
                69420
            );

            let items = map
                .range(deps.as_ref().storage, None, None, Order::Ascending)
                .map(|item| item.unwrap())
                .collect::<Vec<_>>();

            assert_eq!(items.len(), 3);
            assert_eq!(items[0], (local_key, 159784));
            assert_eq!(items[1], (key, 42069));
            assert_eq!(items[2], (multihop_key, 69420));
        }

        #[coverage_helper::test]
        fn composite_key_works() {
            let mut deps = mock_dependencies();
            let key = mock_key();
            let multihop_key = mock_multi_hop_key();
            let map: Map<(&AccountTrace, Addr), u64> = Map::new("map");

            map.save(
                deps.as_mut().storage,
                (&key, Addr::unchecked("larry")),
                &42069,
            )
            .unwrap();
            map.save(
                deps.as_mut().storage,
                (&multihop_key, Addr::unchecked("larry")),
                &42069,
            )
            .unwrap();

            map.save(
                deps.as_mut().storage,
                (&key, Addr::unchecked("jake")),
                &69420,
            )
            .unwrap();

            let items = map
                .prefix(&key)
                .range(deps.as_ref().storage, None, None, Order::Ascending)
                .map(|item| item.unwrap())
                .collect::<Vec<_>>();

            assert_eq!(items.len(), 2);
            assert_eq!(items[0], (Addr::unchecked("jake"), 69420));
            assert_eq!(items[1], (Addr::unchecked("larry"), 42069));
        }
    }
}