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
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::error::ContractError;
use cosmwasm_std::{Coin, Uint128};
use cw20::Cw20Coin;
use std::convert::TryInto;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Amount {
Native(Coin),
Cw20(Cw20Coin),
}
impl Amount {
pub fn from_parts(denom: String, amount: Uint128) -> Self {
if denom.starts_with("cw20:") {
let address = denom.get(5..).unwrap().into();
Amount::Cw20(Cw20Coin { address, amount })
} else {
Amount::Native(Coin { denom, amount })
}
}
pub fn cw20(amount: u128, addr: &str) -> Self {
Amount::Cw20(Cw20Coin {
address: addr.into(),
amount: Uint128(amount),
})
}
pub fn native(amount: u128, denom: &str) -> Self {
Amount::Native(Coin {
denom: denom.to_string(),
amount: Uint128(amount),
})
}
}
impl Amount {
pub fn denom(&self) -> String {
match self {
Amount::Native(c) => c.denom.clone(),
Amount::Cw20(c) => format!("cw20:{}", c.address.as_str()),
}
}
pub fn amount(&self) -> Uint128 {
match self {
Amount::Native(c) => c.amount,
Amount::Cw20(c) => c.amount,
}
}
pub fn u64_amount(&self) -> Result<u64, ContractError> {
Ok(self.amount().u128().try_into()?)
}
pub fn is_empty(&self) -> bool {
match self {
Amount::Native(c) => c.amount.is_zero(),
Amount::Cw20(c) => c.amount.is_zero(),
}
}
}