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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
use super::module_reference::ModuleReference;
use crate::objects::namespace::Namespace;
use crate::{error::AbstractError, AbstractResult};
use cosmwasm_std::{to_binary, Binary, StdError, StdResult};
use cw2::ContractVersion;
use cw_semver::Version;
use cw_storage_plus::{Key, KeyDeserialize, Prefixer, PrimaryKey};
use std::fmt::{self, Display};

/// ID of the module
pub type ModuleId<'a> = &'a str;

/// Module status
#[cosmwasm_schema::cw_serde]
pub enum ModuleStatus {
    /// Modules in use
    REGISTERED,
    /// Pending modules
    PENDING,
    /// Yanked modules
    YANKED,
}

/// Stores the namespace, name, and version of an Abstract module.
#[cosmwasm_schema::cw_serde]
pub struct ModuleInfo {
    /// Namespace of the module
    pub namespace: Namespace,
    /// Name of the contract
    pub name: String,
    /// Version of the module
    pub version: ModuleVersion,
}

const MAX_LENGTH: usize = 64;

/// Validate attributes of a [`ModuleInfo`].
/// We use the same conventions as Rust package names.
/// See https://github.com/rust-lang/api-guidelines/discussions/29
pub fn validate_name(name: &str) -> AbstractResult<()> {
    if name.is_empty() {
        return Err(AbstractError::FormattingError {
            object: "module name".into(),
            expected: "with content".into(),
            actual: "empty".to_string(),
        });
    }
    if name.len() > MAX_LENGTH {
        return Err(AbstractError::FormattingError {
            object: "module name".into(),
            expected: "at most 64 characters".into(),
            actual: name.len().to_string(),
        });
    }
    if name.contains(|c: char| !c.is_ascii_alphanumeric() && c != '-') {
        return Err(AbstractError::FormattingError {
            object: "module name".into(),
            expected: "alphanumeric characters and hyphens".into(),
            actual: name.to_string(),
        });
    }

    if name != name.to_lowercase() {
        return Err(AbstractError::FormattingError {
            object: "module name".into(),
            expected: name.to_ascii_lowercase(),
            actual: name.to_string(),
        });
    }
    Ok(())
}

impl ModuleInfo {
    pub fn from_id(id: &str, version: ModuleVersion) -> AbstractResult<Self> {
        let split: Vec<&str> = id.split(':').collect();
        if split.len() != 2 {
            return Err(AbstractError::FormattingError {
                object: "contract id".into(),
                expected: "namespace:contract_name".to_string(),
                actual: id.to_string(),
            });
        }
        Ok(ModuleInfo {
            namespace: Namespace::try_from(split[0])?,
            name: split[1].to_lowercase(),
            version,
        })
    }
    pub fn from_id_latest(id: &str) -> AbstractResult<Self> {
        Self::from_id(id, ModuleVersion::Latest)
    }

    pub fn validate(&self) -> AbstractResult<()> {
        self.namespace.validate()?;
        validate_name(&self.name)?;
        self.version.validate().map_err(|e| {
            StdError::generic_err(format!("Invalid version for module {}: {}", self.id(), e))
        })?;
        Ok(())
    }

    pub fn id(&self) -> String {
        format!("{}:{}", self.namespace, self.name)
    }

    pub fn id_with_version(&self) -> String {
        format!("{}:{}", self.id(), self.version)
    }

    pub fn assert_version_variant(&self) -> AbstractResult<()> {
        match &self.version {
            ModuleVersion::Latest => Err(AbstractError::Assert(
                "Module version must be set to a specific version".into(),
            )),
            ModuleVersion::Version(ver) => {
                // assert version parses correctly
                semver::Version::parse(ver)?;
                Ok(())
            }
        }
    }
}

impl<'a> PrimaryKey<'a> for &ModuleInfo {
    /// (namespace, name)
    type Prefix = (Namespace, String);

    /// namespace
    type SubPrefix = Namespace;

    /// Possibly change to ModuleVersion in future by implementing PrimaryKey
    /// version
    type Suffix = String;

    // (name, version)
    type SuperSuffix = (String, String);

    fn key(&self) -> Vec<cw_storage_plus::Key> {
        let mut keys = self.namespace.key();
        keys.extend(self.name.key());
        let temp = match &self.version {
            ModuleVersion::Latest => "latest".key(),
            ModuleVersion::Version(ver) => ver.key(),
        };
        keys.extend(temp);
        keys
    }
}

impl<'a> Prefixer<'a> for &ModuleInfo {
    fn prefix(&self) -> Vec<Key> {
        let mut res = self.namespace.prefix();
        res.extend(self.name.prefix().into_iter());
        res.extend(self.version.prefix().into_iter());
        res
    }
}

impl<'a> Prefixer<'a> for ModuleVersion {
    fn prefix(&self) -> Vec<Key> {
        let self_as_bytes = match &self {
            ModuleVersion::Latest => "latest".as_bytes(),
            ModuleVersion::Version(ver) => ver.as_bytes(),
        };
        vec![Key::Ref(self_as_bytes)]
    }
}

impl KeyDeserialize for &ModuleInfo {
    type Output = ModuleInfo;

    #[inline(always)]
    fn from_vec(mut value: Vec<u8>) -> StdResult<Self::Output> {
        let mut prov_name_ver = value.split_off(2);
        let prov_len = parse_length(&value)?;
        let mut len_name_ver = prov_name_ver.split_off(prov_len);

        let mut name_ver = len_name_ver.split_off(2);
        let ver_len = parse_length(&len_name_ver)?;
        let ver = name_ver.split_off(ver_len);

        Ok(ModuleInfo {
            namespace: Namespace::try_from(String::from_vec(prov_name_ver)?).map_err(|e| {
                StdError::generic_err(format!("Invalid namespace for module: {}", e))
            })?,
            name: String::from_vec(name_ver)?,
            version: ModuleVersion::from_vec(ver)?,
        })
    }
}

impl KeyDeserialize for ModuleVersion {
    type Output = ModuleVersion;

    #[inline(always)]
    fn from_vec(value: Vec<u8>) -> StdResult<Self::Output> {
        let val = String::from_utf8(value).map_err(StdError::invalid_utf8)?;
        if &val == "latest" {
            Ok(Self::Latest)
        } else {
            Ok(Self::Version(val))
        }
    }
}

#[inline(always)]
fn parse_length(value: &[u8]) -> StdResult<usize> {
    Ok(u16::from_be_bytes(
        value
            .try_into()
            .map_err(|_| StdError::generic_err("Could not read 2 byte length"))?,
    )
    .into())
}

#[cosmwasm_schema::cw_serde]
pub enum ModuleVersion {
    Latest,
    Version(String),
}

impl ModuleVersion {
    pub fn validate(&self) -> AbstractResult<()> {
        match &self {
            ModuleVersion::Latest => Ok(()),
            ModuleVersion::Version(ver) => {
                // assert version parses correctly
                Version::parse(ver)?;
                Ok(())
            }
        }
    }
}

// Do not change!!
impl Display for ModuleVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let print_str = match self {
            ModuleVersion::Latest => "latest".to_string(),
            ModuleVersion::Version(ver) => ver.to_owned(),
        };
        f.write_str(&print_str)
    }
}

impl<T> From<T> for ModuleVersion
where
    T: Into<String>,
{
    fn from(ver: T) -> Self {
        Self::Version(ver.into())
    }
}

impl fmt::Display for ModuleInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} provided by {} with version {}",
            self.name, self.namespace, self.version,
        )
    }
}

impl TryInto<Version> for ModuleVersion {
    type Error = AbstractError;

    fn try_into(self) -> AbstractResult<Version> {
        match self {
            ModuleVersion::Latest => Err(AbstractError::MissingVersion("module".to_string())),
            ModuleVersion::Version(ver) => {
                let version = Version::parse(&ver)?;
                Ok(version)
            }
        }
    }
}

impl TryFrom<ContractVersion> for ModuleInfo {
    type Error = AbstractError;

    fn try_from(value: ContractVersion) -> Result<Self, Self::Error> {
        let split: Vec<&str> = value.contract.split(':').collect();
        if split.len() != 2 {
            return Err(AbstractError::FormattingError {
                object: "contract id".to_string(),
                expected: "namespace:contract_name".into(),
                actual: value.contract,
            });
        }
        Ok(ModuleInfo {
            namespace: Namespace::try_from(split[0])?,
            name: split[1].to_lowercase(),
            version: ModuleVersion::Version(value.version),
        })
    }
}

#[cosmwasm_schema::cw_serde]
pub struct Module {
    pub info: ModuleInfo,
    pub reference: ModuleReference,
}

impl fmt::Display for Module {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "info: {}, reference: {:?}", self.info, self.reference)
    }
}

impl From<(ModuleInfo, ModuleReference)> for Module {
    fn from((info, reference): (ModuleInfo, ModuleReference)) -> Self {
        Self { info, reference }
    }
}

#[cosmwasm_schema::cw_serde]

pub struct ModuleInitMsg {
    pub fixed_init: Option<Binary>,
    pub owner_init: Option<Binary>,
}

impl ModuleInitMsg {
    pub fn format(self) -> AbstractResult<Binary> {
        match self {
            // If both set, receiving contract must handle it using the ModuleInitMsg
            ModuleInitMsg {
                fixed_init: Some(_),
                owner_init: Some(_),
            } => to_binary(&self),
            // If not, we can simplify by only sending the custom or fixed message.
            ModuleInitMsg {
                fixed_init: None,
                owner_init: Some(r),
            } => Ok(r),
            ModuleInitMsg {
                fixed_init: Some(f),
                owner_init: None,
            } => Ok(f),
            ModuleInitMsg {
                fixed_init: None,
                owner_init: None,
            } => Err(StdError::generic_err("No init msg set for this module")),
        }
        .map_err(Into::into)
    }
}

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

#[cfg(test)]
mod test {
    use super::*;
    use cosmwasm_std::{testing::mock_dependencies, Addr, Order};
    use cw_storage_plus::Map;
    use speculoos::prelude::*;

    mod storage_plus {
        use super::*;

        fn mock_key() -> ModuleInfo {
            ModuleInfo {
                namespace: Namespace::new("abstract").unwrap(),
                name: "rocket-ship".to_string(),
                version: ModuleVersion::Version("1.9.9".into()),
            }
        }

        fn mock_keys() -> (ModuleInfo, ModuleInfo, ModuleInfo, ModuleInfo) {
            (
                ModuleInfo {
                    namespace: Namespace::new("abstract").unwrap(),
                    name: "boat".to_string(),
                    version: ModuleVersion::Version("1.9.9".into()),
                },
                ModuleInfo {
                    namespace: Namespace::new("abstract").unwrap(),
                    name: "rocket-ship".to_string(),
                    version: ModuleVersion::Version("1.0.0".into()),
                },
                ModuleInfo {
                    namespace: Namespace::new("abstract").unwrap(),
                    name: "rocket-ship".to_string(),
                    version: ModuleVersion::Version("2.0.0".into()),
                },
                ModuleInfo {
                    namespace: Namespace::new("astroport").unwrap(),
                    name: "liquidity-pool".to_string(),
                    version: ModuleVersion::Version("10.5.7".into()),
                },
            )
        }

        #[test]
        fn storage_key_works() {
            let mut deps = mock_dependencies();
            let key = mock_key();
            let map: Map<&ModuleInfo, u64> = Map::new("map");

            map.save(deps.as_mut().storage, &key, &42069).unwrap();

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

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

            assert_eq!(items.len(), 1);
            assert_eq!(items[0], (key, 42069));
        }

        #[test]
        fn storage_key_with_overlapping_name_namespace() {
            let mut deps = mock_dependencies();
            let info1 = ModuleInfo {
                namespace: Namespace::new("abstract").unwrap(),
                name: "ans".to_string(),
                version: ModuleVersion::Version("1.9.9".into()),
            };

            let _key1 = (&info1).joined_key();

            let info2 = ModuleInfo {
                namespace: Namespace::new("abs").unwrap(),
                name: "tractans".to_string(),
                version: ModuleVersion::Version("1.9.9".into()),
            };

            let _key2 = (&info2).joined_key();

            let map: Map<&ModuleInfo, u64> = Map::new("map");

            map.save(deps.as_mut().storage, &info1, &42069).unwrap();
            map.save(deps.as_mut().storage, &info2, &69420).unwrap();

            assert_that!(map
                .keys_raw(&deps.storage, None, None, Order::Ascending)
                .collect::<Vec<_>>())
            .has_length(2);
        }

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

            map.save(
                deps.as_mut().storage,
                (&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));
        }

        #[test]
        fn partial_key_works() {
            let mut deps = mock_dependencies();
            let (key1, key2, key3, key4) = mock_keys();
            let map: Map<&ModuleInfo, u64> = Map::new("map");

            map.save(deps.as_mut().storage, &key1, &42069).unwrap();

            map.save(deps.as_mut().storage, &key2, &69420).unwrap();

            map.save(deps.as_mut().storage, &key3, &999).unwrap();

            map.save(deps.as_mut().storage, &key4, &13).unwrap();

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

            assert_eq!(items.len(), 3);
            assert_eq!(items[0], (("boat".to_string(), "1.9.9".to_string()), 42069));
            assert_eq!(
                items[1],
                (("rocket-ship".to_string(), "1.0.0".to_string()), 69420)
            );

            assert_eq!(
                items[2],
                (("rocket-ship".to_string(), "2.0.0".to_string()), 999)
            );

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

            assert_eq!(items.len(), 1);
            assert_eq!(
                items[0],
                (("liquidity-pool".to_string(), "10.5.7".to_string()), 13)
            );
        }

        #[test]
        fn partial_key_versions_works() {
            let mut deps = mock_dependencies();
            let (key1, key2, key3, key4) = mock_keys();
            let map: Map<&ModuleInfo, u64> = Map::new("map");

            map.save(deps.as_mut().storage, &key1, &42069).unwrap();

            map.save(deps.as_mut().storage, &key2, &69420).unwrap();

            map.save(deps.as_mut().storage, &key3, &999).unwrap();

            map.save(deps.as_mut().storage, &key4, &13).unwrap();

            let items = map
                .prefix((
                    Namespace::new("abstract").unwrap(),
                    "rocket-ship".to_string(),
                ))
                .range(deps.as_ref().storage, None, None, Order::Ascending)
                .map(|item| item.unwrap())
                .collect::<Vec<_>>();

            assert_eq!(items.len(), 2);
            assert_eq!(items[0], ("1.0.0".to_string(), 69420));

            assert_eq!(items[1], ("2.0.0".to_string(), 999));
        }
    }

    mod module_info {
        use super::*;

        #[test]
        fn validate_with_empty_name() {
            let info = ModuleInfo {
                namespace: Namespace::try_from("abstract").unwrap(),
                name: "".to_string(),
                version: ModuleVersion::Version("1.9.9".into()),
            };

            assert_that!(info.validate())
                .is_err()
                .matches(|e| e.to_string().contains("empty"));
        }

        #[test]
        fn validate_with_empty_namespace() {
            let info = ModuleInfo {
                namespace: Namespace::unchecked(""),
                name: "ans".to_string(),
                version: ModuleVersion::Version("1.9.9".into()),
            };

            assert_that!(info.validate())
                .is_err()
                .matches(|e| e.to_string().contains("empty"));
        }

        use rstest::rstest;

        #[rstest]
        #[case("ans_host")]
        #[case("ans:host")]
        #[case("ans-host&")]
        fn validate_fails_with_non_alphanumeric(#[case] name: &str) {
            let info = ModuleInfo {
                namespace: Namespace::try_from("abstract").unwrap(),
                name: name.to_string(),
                version: ModuleVersion::Version("1.9.9".into()),
            };

            assert_that!(info.validate())
                .is_err()
                .matches(|e| e.to_string().contains("alphanumeric"));
        }

        #[rstest]
        #[case("lmao")]
        #[case("bad-")]
        fn validate_with_bad_versions(#[case] version: &str) {
            let info = ModuleInfo {
                namespace: Namespace::try_from("abstract").unwrap(),
                name: "ans".to_string(),
                version: ModuleVersion::Version(version.into()),
            };

            assert_that!(info.validate())
                .is_err()
                .matches(|e| e.to_string().contains("Invalid version"));
        }

        #[test]
        fn id() {
            let info = ModuleInfo {
                name: "name".to_string(),
                namespace: Namespace::try_from("namespace").unwrap(),
                version: ModuleVersion::Version("1.0.0".into()),
            };

            let expected = "namespace:name".to_string();

            assert_that!(info.id()).is_equal_to(expected);
        }

        #[test]
        fn id_with_version() {
            let info = ModuleInfo {
                name: "name".to_string(),
                namespace: Namespace::try_from("namespace").unwrap(),
                version: ModuleVersion::Version("1.0.0".into()),
            };

            let expected = "namespace:name:1.0.0".to_string();

            assert_that!(info.id_with_version()).is_equal_to(expected);
        }
    }

    mod module_version {
        use super::*;

        #[test]
        fn try_into_version_happy_path() {
            let version = ModuleVersion::Version("1.0.0".into());

            let expected: Version = "1.0.0".to_string().parse().unwrap();

            let actual: Version = version.try_into().unwrap();

            assert_that!(actual).is_equal_to(expected);
        }

        #[test]
        fn try_into_version_with_latest() {
            let version = ModuleVersion::Latest;

            let actual: Result<Version, _> = version.try_into();

            assert_that!(actual).is_err();
        }
    }
}