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
use cosmrs::proto::cosmos::base::abci::v1beta1::TxResponse as CosmosResponse;

use cosmrs::rpc::endpoint::{
    abci_query::AbciQuery, broadcast::tx_async::Response as AsyncTendermintResponse,
    broadcast::tx_sync::Response as SyncTendermintResponse,
};
use cosmrs::tendermint::abci::Code as TendermintCode;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::error::DeserializeError;

#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq, Default)]
pub struct ChainResponse {
    pub code: Code,
    pub data: Option<Vec<u8>>,
    pub log: String,
}

impl ChainResponse {
    pub fn data<'a, T: Deserialize<'a>>(&'a self) -> Result<T, DeserializeError> {
        let r: T = serde_json::from_slice(
            self.data
                .as_ref()
                .ok_or(DeserializeError::EmptyResponse)?
                .as_slice(),
        )?;
        Ok(r)
    }
}

impl From<AbciQuery> for ChainResponse {
    fn from(res: AbciQuery) -> ChainResponse {
        ChainResponse {
            code: res.code.into(),
            data: Some(res.value),
            log: res.log,
        }
    }
}

// impl From<TxResult> for ChainResponse {
//     fn from(res: TxResult) -> ChainResponse {
//         ChainResponse {
//             code: res.code.into(),
//             data: res.data.map(|d| d.into()),
//             log: res.log.to_string(),
//         }
//     }
// }

/// AsyncChainTxResponse is returned from the async `tx_broadcast()` api.
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq, Default)]
pub struct AsyncChainTxResponse {
    pub res: ChainResponse,
    pub tx_hash: String,
}

impl AsRef<ChainResponse> for AsyncChainTxResponse {
    fn as_ref(&self) -> &ChainResponse {
        &self.res
    }
}

impl From<CosmosResponse> for AsyncChainTxResponse {
    fn from(res: CosmosResponse) -> Self {
        Self {
            res: ChainResponse {
                code: res.code.into(),
                data: Some(res.data.into()), // TODO
                log: res.raw_log,
            },
            tx_hash: res.txhash,
        }
    }
}

impl From<AsyncTendermintResponse> for AsyncChainTxResponse {
    fn from(res: AsyncTendermintResponse) -> Self {
        Self {
            res: ChainResponse {
                code: res.code.into(),
                data: Some(res.data.into()),
                log: res.log.to_string(),
            },
            tx_hash: res.hash.to_string(),
        }
    }
}

impl From<SyncTendermintResponse> for AsyncChainTxResponse {
    fn from(res: SyncTendermintResponse) -> Self {
        Self {
            res: ChainResponse {
                code: res.code.into(),
                data: Some(res.data.into()),
                log: res.log.to_string(),
            },
            tx_hash: res.hash.to_string(),
        }
    }
}

// /// ChainTxResponse is returned from the blocking `tx_broadcast_block()` api.
// /// Since we wait for the tx to be commited in the next block, we get the full tx data.
// #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq, Default)]
// pub struct ChainTxResponse {
//     pub res: ChainResponse,
//     pub events: Vec<Event>,
//     pub gas_wanted: u64,
//     pub gas_used: u64,
//     pub tx_hash: String,
//     pub height: u64,
// }

// impl AsRef<ChainResponse> for ChainTxResponse {
//     fn as_ref(&self) -> &ChainResponse {
//         &self.res
//     }
// }

// impl From<BlockingTendermintResponse> for ChainTxResponse {
//     fn from(res: BlockingTendermintResponse) -> Self {
//         ChainTxResponse {
//             res: ChainResponse {
//                 code: res.deliver_tx.code.into(),
//                 data: Some(res.deliver_tx.data.to_vec()),
//                 log: res.deliver_tx.log.to_string(),
//             },
//             events: res.deliver_tx.events.into_iter().map(Into::into).collect(),
//             gas_used: res.deliver_tx.gas_used.into(),
//             gas_wanted: res.deliver_tx.gas_wanted.into(),
//             tx_hash: res.hash.to_string(),
//             height: res.height.into(),
//         }
//     }
// }

// impl TryFrom<CosmosResponse> for ChainTxResponse {
//     type Error = ChainError;

//     fn try_from(res: CosmosResponse) -> Result<Self, Self::Error> {
//         Ok(ChainTxResponse {
//             res: ChainResponse {
//                 code: res.code.into(),
//                 data: Some(res.data.into()), // TODO
//                 log: res.raw_log,
//             },
//             events: res
//                 .events
//                 .into_iter()
//                 .map(TryInto::try_into)
//                 .collect::<Result<Vec<_>, _>>()?,
//             gas_wanted: res.gas_wanted as u64,
//             gas_used: res.gas_used as u64,
//             tx_hash: res.txhash,
//             height: res.height as u64,
//         })
//     }
// }

#[derive(
    Copy,
    Clone,
    Debug,
    Default,
    Eq,
    Hash,
    PartialEq,
    PartialOrd,
    Ord,
    Serialize,
    Deserialize,
    JsonSchema,
)]
pub enum Code {
    #[default]
    Ok,
    Err(u32),
}

impl Code {
    pub fn is_ok(self) -> bool {
        match self {
            Code::Ok => true,
            Code::Err(_) => false,
        }
    }

    pub fn is_err(self) -> bool {
        !self.is_ok()
    }

    pub fn value(self) -> u32 {
        u32::from(self)
    }
}

impl From<u32> for Code {
    fn from(value: u32) -> Code {
        match value {
            0 => Code::Ok,
            err => Code::Err(err),
        }
    }
}

impl From<Code> for u32 {
    fn from(code: Code) -> u32 {
        match code {
            Code::Ok => 0,
            Code::Err(err) => err,
        }
    }
}

impl From<u16> for Code {
    fn from(value: u16) -> Code {
        match value {
            0 => Code::Ok,
            err => Code::Err(err.into()),
        }
    }
}

impl From<u8> for Code {
    fn from(value: u8) -> Code {
        match value {
            0 => Code::Ok,
            err => Code::Err(err.into()),
        }
    }
}

impl From<TendermintCode> for Code {
    fn from(value: TendermintCode) -> Code {
        match value {
            TendermintCode::Ok => Code::Ok,
            TendermintCode::Err(err) => Code::Err(err.into()),
        }
    }
}

// #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Hash)]
// pub struct Event {
//     pub kind: String,
//     pub attributes: Vec<EventAttribute>,
// }

// impl From<TendermintEvent> for Event {
//     fn from(e: TendermintEvent) -> Self {
//         Self {
//             kind: e.type_str,
//             attributes: e.attributes.into_iter().map(Into::into).collect(),
//         }
//     }
// }

// impl TryFrom<Event> for TendermintEvent {
//     type Error = ChainError;

//     fn try_from(e: Event) -> Result<Self, Self::Error> {
//         Ok(Self {
//             kind: e.kind,
//             attributes: e
//                 .attributes
//                 .into_iter()
//                 .map(TryInto::try_into)
//                 .collect::<Result<Vec<_>, _>>()?,
//         })
//     }
// }

// impl TryFrom<ProtoEvent> for Event {
//     type Error = ChainError;

//     fn try_from(e: ProtoEvent) -> Result<Self, Self::Error> {
//         Ok(Self {
//             kind: e.r#type,
//             attributes: e
//                 .attributes
//                 .into_iter()
//                 .map(TryInto::try_into)
//                 .collect::<Result<Vec<_>, _>>()?,
//         })
//     }
// }

// impl From<Event> for ProtoEvent {
//     fn from(e: Event) -> Self {
//         Self {
//             r#type: e.kind,
//             attributes: e.attributes.into_iter().map(Into::into).collect(),
//         }
//     }
// }

// #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq, Hash)]
// pub struct Tag {
//     pub key: String,
//     pub value: String,
// }

// impl From<TendermintProtoTag> for Tag {
//     fn from(tag: TendermintProtoTag) -> Self {
//         Self {
//             key: tag.key.to_string(),
//             value: tag.value.to_string(),
//         }
//     }
// }

// impl TryFrom<Tag> for TendermintProtoTag {
//     type Error = ChainError;

//     fn try_from(tag: Tag) -> Result<Self, Self::Error> {
//         Ok(Self {
//             key: Key::from_str(&tag.key)?,
//             value: Value::from_str(&tag.value)?,
//         })
//     }
// }

// impl From<Tag> for EventAttribute {
//     fn from(tag: Tag) -> Self {
//         Self {
//             key: tag.key.into_bytes().into(),
//             value: tag.value.into_bytes().into(),
//             index: true,
//         }
//     }
// }

// impl TryFrom<EventAttribute> for Tag {
//     type Error = ChainError;

//     fn try_from(attr: EventAttribute) -> Result<Self, Self::Error> {
//         Ok(Self {
//             key: String::from_utf8(attr.key.into()).map_err(|e| ChainError::ProtoDecoding {
//                 message: e.to_string(),
//             })?,
//             value: String::from_utf8(attr.value.into()).map_err(|e| ChainError::ProtoDecoding {
//                 message: e.to_string(),
//             })?,
//         })
//     }
// }