abstract_std/objects/entry/
ans_entry_convertor.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
use crate::{
    constants::{ASSET_DELIMITER, TYPE_DELIMITER},
    objects::{
        ans_host::{AnsHostError, AnsHostResult},
        AssetEntry, DexAssetPairing, LpToken, PoolMetadata,
    },
};

/// A helper struct for Abstract Name Service entry conversions.
pub struct AnsEntryConvertor<T> {
    entry: T,
}

impl<T> AnsEntryConvertor<T> {
    pub fn new(entry: T) -> Self {
        Self { entry }
    }
}

// An LP token can convert to:
impl AnsEntryConvertor<LpToken> {
    pub fn asset_entry(self) -> AssetEntry {
        AssetEntry::from(self.entry.to_string())
    }

    pub fn dex_asset_pairing(self) -> AnsHostResult<DexAssetPairing> {
        let mut assets = self.entry.assets;
        // assets should already be sorted, but just in case
        assets.sort();
        assets.reverse();

        Ok(DexAssetPairing::new(
            assets.pop().unwrap(),
            assets.pop().unwrap(),
            self.entry.dex.as_str(),
        ))
    }
}

impl AnsEntryConvertor<PoolMetadata> {
    pub fn lp_token(self) -> LpToken {
        LpToken {
            dex: self.entry.dex,
            assets: self.entry.assets,
        }
    }

    pub fn lp_token_asset(self) -> AssetEntry {
        AnsEntryConvertor::new(self.lp_token()).asset_entry()
    }
}

impl AnsEntryConvertor<AssetEntry> {
    /// Try from an asset entry that should be formatted as "dex_name/asset1,asset2"
    pub fn lp_token(self) -> AnsHostResult<LpToken> {
        let segments = self
            .entry
            .as_str()
            .split(TYPE_DELIMITER)
            .collect::<Vec<_>>();

        if segments.len() != 2 {
            return Err(AnsHostError::FormattingError {
                object: "lp token".to_string(),
                expected: "type/asset1,asset2".to_string(),
                actual: self.entry.to_string(),
            });
        }

        // get the dex name, like "junoswap"
        let dex_name = segments[0].to_string();

        // get the assets, like "crab,junox" and split them
        let mut assets: Vec<AssetEntry> = segments[1]
            .split(ASSET_DELIMITER)
            .map(AssetEntry::from)
            .collect();

        // sort the assets on name
        assets.sort_unstable();

        if assets.len() < 2 {
            return Err(AnsHostError::FormattingError {
                object: "lp token".into(),
                expected: "at least 2 assets in LP token".into(),
                actual: self.entry.to_string(),
            });
        }

        Ok(LpToken {
            dex: dex_name,
            assets,
        })
    }
}