1use crate::error::ContractError;
2use cosmwasm_schema::cw_serde;
3use cosmwasm_std::{Coin, Uint128};
4use cw20::Cw20Coin;
5use std::convert::TryInto;
6
7#[cw_serde]
8pub enum Amount {
9 Native(Coin),
10 Cw20(Cw20Coin),
12}
13
14impl Amount {
15 pub fn from_parts(denom: String, amount: Uint128) -> Self {
17 if denom.starts_with("cw20:") {
18 let address = denom.get(5..).unwrap().into();
19 Amount::Cw20(Cw20Coin { address, amount })
20 } else {
21 Amount::Native(Coin { denom, amount })
22 }
23 }
24
25 pub fn cw20(amount: u128, addr: &str) -> Self {
26 Amount::Cw20(Cw20Coin {
27 address: addr.into(),
28 amount: Uint128::new(amount),
29 })
30 }
31
32 pub fn native(amount: u128, denom: &str) -> Self {
33 Amount::Native(Coin {
34 denom: denom.to_string(),
35 amount: Uint128::new(amount),
36 })
37 }
38}
39
40impl Amount {
41 pub fn denom(&self) -> String {
42 match self {
43 Amount::Native(c) => c.denom.clone(),
44 Amount::Cw20(c) => format!("cw20:{}", c.address.as_str()),
45 }
46 }
47
48 pub fn amount(&self) -> Uint128 {
49 match self {
50 Amount::Native(c) => c.amount,
51 Amount::Cw20(c) => c.amount,
52 }
53 }
54
55 pub fn u64_amount(&self) -> Result<u64, ContractError> {
57 Ok(self.amount().u128().try_into()?)
58 }
59
60 pub fn is_empty(&self) -> bool {
61 match self {
62 Amount::Native(c) => c.amount.is_zero(),
63 Amount::Cw20(c) => c.amount.is_zero(),
64 }
65 }
66}