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
use std::fmt;

use cosmrs::proto::cosmos::bank::v1beta1::{
    DenomUnit as ProtoDenomUnit, Metadata, MsgSend, Params as ProtoParams,
    SendEnabled as ProtoSendEnabled,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::chain::coin::Denom;
use crate::chain::msg::Msg;
use crate::{
    chain::{coin::Coin, error::ChainError, request::PaginationResponse},
    modules::auth::model::Address,
};

use super::error::BankError;

#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq)]
pub struct BalanceResponse {
    pub balance: Coin,
}

#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq)]
pub struct BalancesResponse {
    pub balances: Vec<Coin>,

    pub next: Option<PaginationResponse>,
}

#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq)]
pub struct DenomMetadataResponse {
    pub meta: Option<DenomMetadata>,
}

#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq)]
pub struct DenomsMetadataResponse {
    pub metas: Vec<DenomMetadata>,

    pub next: Option<PaginationResponse>,
}

#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq)]
pub struct DenomMetadata {
    pub description: String,

    pub denom_units: Vec<DenomUnit>,

    /// base represents the base denom (should be the DenomUnit with exponent = 0).
    pub base: String,

    /// display indicates the suggested denom string that should be displayed in clients.
    pub display: String,

    /// name defines the name of the token (eg: Cosmos Atom)
    ///
    /// Since: cosmos-sdk 0.43
    pub name: String,

    /// symbol is the token symbol usually shown on exchanges (eg: ATOM).
    /// This can be the same as the display.
    ///
    /// Since: cosmos-sdk 0.43
    pub symbol: String,
    pub uri: String,
    pub uri_hash: String,
}

impl TryFrom<Metadata> for DenomMetadata {
    type Error = ChainError;

    fn try_from(meta: Metadata) -> Result<Self, Self::Error> {
        Ok(Self {
            description: meta.description,
            denom_units: meta
                .denom_units
                .into_iter()
                .map(TryInto::try_into)
                .collect::<Result<Vec<_>, _>>()?,
            base: meta.base,
            display: meta.display,
            name: meta.name,
            symbol: meta.symbol,
            uri: meta.uri,
            uri_hash: meta.uri_hash,
        })
    }
}

impl From<DenomMetadata> for Metadata {
    fn from(meta: DenomMetadata) -> Self {
        Self {
            description: meta.description,
            denom_units: meta.denom_units.into_iter().map(Into::into).collect(),
            base: meta.base,
            display: meta.display,
            name: meta.name,
            symbol: meta.symbol,
            uri: meta.uri,
            uri_hash: meta.uri_hash,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq)]
pub struct DenomUnit {
    /// denom represents the string name of the given denom unit (e.g uatom).
    pub denom: Denom,

    /// exponent represents the power of 10 exponent that one must raise the base_denom to in order to equal the given DenomUnit's denom.
    /// 1 denom = 1^exponent base_denom
    /// (e.g. with a base_denom of uatom, one can create a DenomUnit of 'atom' with exponent = 6, thus: 1 atom = 10^6 uatom).
    pub exponent: u32,

    /// aliases is a list of string aliases for the given denom
    pub aliases: Vec<String>,
}

impl TryFrom<ProtoDenomUnit> for DenomUnit {
    type Error = ChainError;

    fn try_from(du: ProtoDenomUnit) -> Result<Self, Self::Error> {
        Ok(Self {
            denom: du.denom.parse()?,
            exponent: du.exponent,
            aliases: du.aliases,
        })
    }
}

impl From<DenomUnit> for ProtoDenomUnit {
    fn from(du: DenomUnit) -> Self {
        Self {
            denom: du.denom.into(),
            exponent: du.exponent,
            aliases: du.aliases,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq, Hash)]
pub struct ParamsResponse {
    pub params: Option<Params>,
}

#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq, Hash)]
pub struct Params {
    pub send_enabled: Vec<SendEnabled>,
    pub default_send_enabled: bool,
}

impl TryFrom<ProtoParams> for Params {
    type Error = ChainError;

    fn try_from(p: ProtoParams) -> Result<Self, Self::Error> {
        Ok(Self {
            send_enabled: p
                .send_enabled
                .into_iter()
                .map(TryInto::try_into)
                .collect::<Result<Vec<_>, _>>()?,
            default_send_enabled: p.default_send_enabled,
        })
    }
}

impl From<Params> for ProtoParams {
    fn from(p: Params) -> Self {
        Self {
            send_enabled: p.send_enabled.into_iter().map(Into::into).collect(),
            default_send_enabled: p.default_send_enabled,
        }
    }
}

/// SendEnabled maps coin denom to a send_enabled status (whether a denom is sendable).
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq, Hash)]
pub struct SendEnabled {
    pub denom: Denom,
    pub enabled: bool,
}

impl TryFrom<ProtoSendEnabled> for SendEnabled {
    type Error = ChainError;

    fn try_from(se: ProtoSendEnabled) -> Result<Self, Self::Error> {
        Ok(Self {
            denom: se.denom.parse()?,
            enabled: se.enabled,
        })
    }
}

impl From<SendEnabled> for ProtoSendEnabled {
    fn from(se: SendEnabled) -> Self {
        Self {
            denom: se.denom.into(),
            enabled: se.enabled,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct SendRequest {
    pub from: Address,
    pub to: Address,
    pub amounts: Vec<Coin>,
}

pub type SendRequestProto = SendRequest;

impl fmt::Display for SendRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} sends ", self.from)?;

        for a in &self.amounts {
            write!(f, "{a} ")?;
        }

        write!(f, "-> {}", self.to)
    }
}

impl Msg for SendRequestProto {
    type Proto = MsgSend;
    type Err = BankError;
}

impl TryFrom<MsgSend> for SendRequest {
    type Error = BankError;

    fn try_from(msg: MsgSend) -> Result<Self, Self::Error> {
        Ok(Self {
            from: msg.from_address.parse()?,
            to: msg.to_address.parse()?,
            amounts: msg
                .amount
                .into_iter()
                .map(TryFrom::try_from)
                .collect::<Result<Vec<_>, _>>()?,
        })
    }
}

impl TryFrom<SendRequest> for MsgSend {
    type Error = BankError;

    fn try_from(req: SendRequest) -> Result<Self, Self::Error> {
        if req.amounts.is_empty() {
            return Err(BankError::EmptyAmount);
        }

        for amount in &req.amounts {
            if amount.amount == 0 {
                return Err(BankError::EmptyAmount);
            }
        }

        Ok(Self {
            from_address: req.from.into(),
            to_address: req.to.into(),
            amount: req.amounts.into_iter().map(Into::into).collect(),
        })
    }
}

// #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq)]
// pub struct SendResponse {
//     pub res: ChainTxResponse,
// }