1use heika_block::statement::{
8 AddressResolutionStatement, BalanceChange, BalanceTransfer, BlockStatement, Mosaic,
9 MosaicResolutionStatement, Receipt, ReceiptBody, ReceiptSource, ResolutionEntry,
10 TransactionStatement,
11};
12use heika_core::address::Address;
13use heika_transaction::{MosaicId, NamespaceId, UnresolvedAddress, UnresolvedMosaicId};
14use serde::{Deserialize, Serialize};
15
16use crate::{RestError, hex, hex_array, number};
17
18#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
20pub struct TransactionStatementInfo {
21 pub statement: TransactionStatementJson,
22}
23
24#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
26pub struct TransactionStatementJson {
27 pub height: String,
28 pub source: SourceJson,
29 pub receipts: Vec<ReceiptJson>,
30}
31
32#[derive(Clone, Copy, PartialEq, Eq, Debug, Deserialize, Serialize)]
34#[serde(rename_all = "camelCase")]
35pub struct SourceJson {
36 pub primary_id: u32,
37 pub secondary_id: u32,
38}
39
40#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
42#[serde(rename_all = "camelCase")]
43pub struct ReceiptJson {
44 pub version: u16,
45 #[serde(rename = "type")]
46 pub receipt_type: u16,
47 #[serde(skip_serializing_if = "Option::is_none")]
48 pub sender_address: Option<String>,
49 #[serde(skip_serializing_if = "Option::is_none")]
50 pub recipient_address: Option<String>,
51 #[serde(skip_serializing_if = "Option::is_none")]
52 pub target_address: Option<String>,
53 #[serde(skip_serializing_if = "Option::is_none")]
54 pub mosaic_id: Option<String>,
55 #[serde(skip_serializing_if = "Option::is_none")]
56 pub amount: Option<String>,
57 #[serde(skip_serializing_if = "Option::is_none")]
58 pub artifact_id: Option<String>,
59}
60
61#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
63pub struct ResolutionStatementInfo {
64 pub statement: ResolutionStatementJson,
65}
66
67#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
69#[serde(rename_all = "camelCase")]
70pub struct ResolutionStatementJson {
71 pub height: String,
72 pub unresolved: String,
74 pub resolution_entries: Vec<ResolutionEntryJson>,
75}
76
77#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
79pub struct ResolutionEntryJson {
80 pub source: SourceJson,
81 pub resolved: String,
82}
83
84impl From<SourceJson> for ReceiptSource {
85 fn from(source: SourceJson) -> Self {
86 Self {
87 primary_id: source.primary_id,
88 secondary_id: source.secondary_id,
89 }
90 }
91}
92
93impl From<ReceiptSource> for SourceJson {
94 fn from(source: ReceiptSource) -> Self {
95 Self {
96 primary_id: source.primary_id,
97 secondary_id: source.secondary_id,
98 }
99 }
100}
101
102impl TryFrom<&ReceiptJson> for Receipt {
103 type Error = RestError;
104
105 fn try_from(json: &ReceiptJson) -> Result<Self, Self::Error> {
106 let address =
107 |value: &Option<String>, field| hex_array(required(value, field)?, field).map(Address);
108 let mosaic = || -> Result<Mosaic, RestError> {
109 Ok(Mosaic {
110 mosaic_id: MosaicId(id(required(&json.mosaic_id, "mosaicId")?, "mosaicId")?),
111 amount: number(required(&json.amount, "amount")?, "amount")?,
112 })
113 };
114 let transfer = || -> Result<BalanceTransfer, RestError> {
115 Ok(BalanceTransfer {
116 mosaic: mosaic()?,
117 sender_address: address(&json.sender_address, "senderAddress")?,
118 recipient_address: address(&json.recipient_address, "recipientAddress")?,
119 })
120 };
121 let change = || -> Result<BalanceChange, RestError> {
122 Ok(BalanceChange {
123 mosaic: mosaic()?,
124 target_address: address(&json.target_address, "targetAddress")?,
125 })
126 };
127 let artifact = || id(required(&json.artifact_id, "artifactId")?, "artifactId");
128 let body = match json.receipt_type {
129 0x124D => ReceiptBody::MosaicRentalFee(transfer()?),
130 0x134E => ReceiptBody::NamespaceRentalFee(transfer()?),
131 0x2143 => ReceiptBody::HarvestFee(change()?),
132 0x2248 => ReceiptBody::LockHashCompleted(change()?),
133 0x2348 => ReceiptBody::LockHashExpired(change()?),
134 0x2252 => ReceiptBody::LockSecretCompleted(change()?),
135 0x2352 => ReceiptBody::LockSecretExpired(change()?),
136 0x3148 => ReceiptBody::LockHashCreated(change()?),
137 0x3152 => ReceiptBody::LockSecretCreated(change()?),
138 0x414D => ReceiptBody::MosaicExpired(MosaicId(artifact()?)),
139 0x414E => ReceiptBody::NamespaceExpired(NamespaceId(artifact()?)),
140 0x424E => ReceiptBody::NamespaceDeleted(NamespaceId(artifact()?)),
141 0x5143 => ReceiptBody::Inflation(mosaic()?),
142 _ => return Err(RestError::InvalidValue { field: "type" }),
143 };
144 Ok(Self {
145 version: json.version,
146 body,
147 })
148 }
149}
150
151impl From<&Receipt> for ReceiptJson {
152 fn from(receipt: &Receipt) -> Self {
153 let mut json = Self {
154 version: receipt.version,
155 receipt_type: receipt.body.receipt_type(),
156 sender_address: None,
157 recipient_address: None,
158 target_address: None,
159 mosaic_id: None,
160 amount: None,
161 artifact_id: None,
162 };
163 let mosaic = |mosaic: &Mosaic, json: &mut Self| {
164 json.mosaic_id = Some(format!("{:016X}", mosaic.mosaic_id.0));
165 json.amount = Some(mosaic.amount.to_string());
166 };
167 match &receipt.body {
168 ReceiptBody::MosaicRentalFee(transfer) | ReceiptBody::NamespaceRentalFee(transfer) => {
169 mosaic(&transfer.mosaic, &mut json);
170 json.sender_address = Some(transfer.sender_address.to_hex());
171 json.recipient_address = Some(transfer.recipient_address.to_hex());
172 }
173 ReceiptBody::HarvestFee(change)
174 | ReceiptBody::LockHashCompleted(change)
175 | ReceiptBody::LockHashExpired(change)
176 | ReceiptBody::LockSecretCompleted(change)
177 | ReceiptBody::LockSecretExpired(change)
178 | ReceiptBody::LockHashCreated(change)
179 | ReceiptBody::LockSecretCreated(change) => {
180 mosaic(&change.mosaic, &mut json);
181 json.target_address = Some(change.target_address.to_hex());
182 }
183 ReceiptBody::MosaicExpired(id) => json.artifact_id = Some(format!("{:016X}", id.0)),
184 ReceiptBody::NamespaceExpired(id) | ReceiptBody::NamespaceDeleted(id) => {
185 json.artifact_id = Some(format!("{:016X}", id.0))
186 }
187 ReceiptBody::Inflation(inflation) => mosaic(inflation, &mut json),
188 }
189 json
190 }
191}
192
193impl TryFrom<&TransactionStatementJson> for TransactionStatement {
194 type Error = RestError;
195
196 fn try_from(json: &TransactionStatementJson) -> Result<Self, Self::Error> {
197 Ok(Self {
198 source: json.source.into(),
199 receipts: json
200 .receipts
201 .iter()
202 .map(Receipt::try_from)
203 .collect::<Result<_, _>>()?,
204 })
205 }
206}
207
208impl TransactionStatementJson {
209 pub fn new(height: u64, statement: &TransactionStatement) -> Self {
211 Self {
212 height: height.to_string(),
213 source: statement.source.into(),
214 receipts: statement.receipts.iter().map(ReceiptJson::from).collect(),
215 }
216 }
217}
218
219impl TryFrom<&ResolutionStatementJson> for AddressResolutionStatement {
220 type Error = RestError;
221
222 fn try_from(json: &ResolutionStatementJson) -> Result<Self, Self::Error> {
223 Ok(Self {
224 unresolved: UnresolvedAddress(hex_array(&json.unresolved, "unresolved")?),
225 entries: json
226 .resolution_entries
227 .iter()
228 .map(|entry| {
229 Ok(ResolutionEntry {
230 source: entry.source.into(),
231 resolved: Address(hex_array(&entry.resolved, "resolved")?),
232 })
233 })
234 .collect::<Result<_, RestError>>()?,
235 })
236 }
237}
238
239impl TryFrom<&ResolutionStatementJson> for MosaicResolutionStatement {
240 type Error = RestError;
241
242 fn try_from(json: &ResolutionStatementJson) -> Result<Self, Self::Error> {
243 Ok(Self {
244 unresolved: UnresolvedMosaicId(id(&json.unresolved, "unresolved")?),
245 entries: json
246 .resolution_entries
247 .iter()
248 .map(|entry| {
249 Ok(ResolutionEntry {
250 source: entry.source.into(),
251 resolved: MosaicId(id(&entry.resolved, "resolved")?),
252 })
253 })
254 .collect::<Result<_, RestError>>()?,
255 })
256 }
257}
258
259impl ResolutionStatementJson {
260 pub fn from_address(height: u64, statement: &AddressResolutionStatement) -> Self {
262 Self {
263 height: height.to_string(),
264 unresolved: hex(&statement.unresolved.0),
265 resolution_entries: statement
266 .entries
267 .iter()
268 .map(|entry| ResolutionEntryJson {
269 source: entry.source.into(),
270 resolved: entry.resolved.to_hex(),
271 })
272 .collect(),
273 }
274 }
275
276 pub fn from_mosaic(height: u64, statement: &MosaicResolutionStatement) -> Self {
278 Self {
279 height: height.to_string(),
280 unresolved: format!("{:016X}", statement.unresolved.0),
281 resolution_entries: statement
282 .entries
283 .iter()
284 .map(|entry| ResolutionEntryJson {
285 source: entry.source.into(),
286 resolved: format!("{:016X}", entry.resolved.0),
287 })
288 .collect(),
289 }
290 }
291}
292
293pub fn block_statement(
299 transactions: &[TransactionStatementInfo],
300 addresses: &[ResolutionStatementInfo],
301 mosaics: &[ResolutionStatementInfo],
302) -> Result<BlockStatement, RestError> {
303 let mut transaction_statements = transactions
304 .iter()
305 .map(|info| TransactionStatement::try_from(&info.statement))
306 .collect::<Result<Vec<_>, _>>()?;
307 transaction_statements.sort_by_key(|statement| statement.source);
308 let mut address_resolution_statements = addresses
309 .iter()
310 .map(|info| AddressResolutionStatement::try_from(&info.statement))
311 .collect::<Result<Vec<_>, _>>()?;
312 address_resolution_statements.sort_by_key(|statement| statement.unresolved.0);
313 let mut mosaic_resolution_statements = mosaics
314 .iter()
315 .map(|info| MosaicResolutionStatement::try_from(&info.statement))
316 .collect::<Result<Vec<_>, _>>()?;
317 mosaic_resolution_statements.sort_by_key(|statement| statement.unresolved.0);
318 Ok(BlockStatement {
319 transaction_statements,
320 address_resolution_statements,
321 mosaic_resolution_statements,
322 })
323}
324
325fn required<'a, T>(value: &'a Option<T>, field: &'static str) -> Result<&'a T, RestError> {
326 value.as_ref().ok_or(RestError::Missing { field })
327}
328
329fn id(text: &str, field: &'static str) -> Result<u64, RestError> {
331 hex_array(text, field).map(u64::from_be_bytes)
332}