aelf-client 0.1.0-alpha.1

HTTP client and DTOs for AElf Rust SDK.
Documentation
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use aelf_proto::aelf::{ResourceTokenCharged, TransactionFeeCharged};
use base64::Engine;
use prost::Message;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Map, Value};
use std::collections::{BTreeMap, HashMap};

/// Chain status returned by the blockchain status endpoint.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ChainStatusDto {
    pub chain_id: String,
    #[serde(default, deserialize_with = "block_height_map_as_default")]
    pub branches: HashMap<String, i64>,
    #[serde(default, deserialize_with = "block_height_map_as_default")]
    pub not_linked_blocks: HashMap<String, i64>,
    pub longest_chain_height: i64,
    pub longest_chain_hash: String,
    pub genesis_block_hash: String,
    pub genesis_contract_address: String,
    pub last_irreversible_block_hash: String,
    pub last_irreversible_block_height: i64,
    pub best_chain_hash: String,
    pub best_chain_height: i64,
}

/// Block payload returned by block lookup endpoints.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct BlockDto {
    pub block_hash: String,
    pub header: BlockHeaderDto,
    pub body: BlockBodyDto,
}

/// Block header subset returned by REST block queries.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct BlockHeaderDto {
    pub height: i64,
    #[serde(default)]
    pub previous_block_hash: String,
}

/// Block body subset returned by REST block queries.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct BlockBodyDto {
    #[serde(default)]
    pub transactions: Vec<String>,
}

/// Transaction pool counters returned by pool status queries.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TransactionPoolStatusOutput {
    #[serde(default)]
    pub queued: i64,
    #[serde(default)]
    pub validated: i64,
}

/// Input payload for node-side raw transaction generation.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CreateRawTransactionInput {
    pub from: String,
    pub to: String,
    pub ref_block_number: i64,
    pub ref_block_hash: String,
    pub method_name: String,
    pub params: String,
}

/// Output payload returned by node-side raw transaction generation.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CreateRawTransactionOutput {
    pub raw_transaction: String,
}

/// Signed raw transaction execution request.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ExecuteRawTransactionDto {
    pub raw_transaction: String,
    pub signature: String,
}

/// Input payload for broadcasting a raw transaction plus signature.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SendRawTransactionInput {
    pub transaction: String,
    pub signature: String,
    pub return_transaction: bool,
}

/// Output payload returned by `sendRawTransaction`.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SendRawTransactionOutput {
    #[serde(alias = "TransactionID")]
    pub transaction_id: String,
    #[serde(default)]
    pub transaction: TransactionDto,
}

/// Input payload for broadcasting a fully signed raw transaction.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SendTransactionInput {
    pub raw_transaction: String,
}

/// Output payload returned by `sendTransaction`.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SendTransactionOutput {
    #[serde(alias = "TransactionID")]
    pub transaction_id: String,
}

/// Input payload for batching multiple signed raw transactions.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SendTransactionsInput {
    pub raw_transactions: String,
}

/// REST-serialized transaction representation returned by some node endpoints.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TransactionDto {
    #[serde(default)]
    pub from: String,
    #[serde(default)]
    pub to: String,
    #[serde(default)]
    pub ref_block_number: i64,
    #[serde(default)]
    pub ref_block_prefix: String,
    #[serde(default)]
    pub method_name: String,
    #[serde(default)]
    pub params: String,
    #[serde(default)]
    pub signature: String,
}

/// Log event emitted by a transaction execution result.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct LogEventDto {
    pub address: String,
    pub name: String,
    #[serde(default, deserialize_with = "null_vec_as_default")]
    pub indexed: Vec<String>,
    #[serde(default, deserialize_with = "null_string_as_default")]
    pub non_indexed: String,
}

/// Transaction execution result returned by transaction result queries.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TransactionResultDto {
    #[serde(alias = "TransactionID")]
    pub transaction_id: String,
    pub status: String,
    #[serde(default, deserialize_with = "null_vec_as_default")]
    pub logs: Vec<LogEventDto>,
    #[serde(default, deserialize_with = "null_string_as_default")]
    pub bloom: String,
    #[serde(default, deserialize_with = "null_json_as_default")]
    pub transaction: serde_json::Value,
    #[serde(default, deserialize_with = "null_string_as_default")]
    pub return_value: String,
    #[serde(default, deserialize_with = "null_i64_as_default")]
    pub block_number: i64,
    #[serde(default, deserialize_with = "null_string_as_default")]
    pub block_hash: String,
    #[serde(default, deserialize_with = "null_string_as_default")]
    pub error: String,
}

impl TransactionResultDto {
    /// Extracts ELF and resource token fees from protobuf-encoded execution logs.
    pub fn get_transaction_fees(&self) -> HashMap<String, i64> {
        let engine = base64::engine::general_purpose::STANDARD;
        let mut result = HashMap::new();

        for log in &self.logs {
            match log.name.as_str() {
                "TransactionFeeCharged" => {
                    let Ok(bytes) = engine.decode(&log.non_indexed) else {
                        continue;
                    };
                    let Ok(event) = TransactionFeeCharged::decode(bytes.as_slice()) else {
                        continue;
                    };
                    result.insert(event.symbol, event.amount);
                }
                "ResourceTokenCharged" => {
                    let Ok(bytes) = engine.decode(&log.non_indexed) else {
                        continue;
                    };
                    let Ok(event) = ResourceTokenCharged::decode(bytes.as_slice()) else {
                        continue;
                    };
                    result.insert(event.symbol, event.amount);
                }
                _ => {}
            }
        }

        result
    }
}

fn null_string_as_default<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<String>::deserialize(deserializer)?;
    Ok(value.unwrap_or_default())
}

fn null_vec_as_default<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    let value = Option::<Vec<T>>::deserialize(deserializer)?;
    Ok(value.unwrap_or_default())
}

fn null_json_as_default<'de, D>(deserializer: D) -> Result<serde_json::Value, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
    Ok(value.unwrap_or(serde_json::Value::Null))
}

fn null_i64_as_default<'de, D>(deserializer: D) -> Result<i64, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<i64>::deserialize(deserializer)?;
    Ok(value.unwrap_or_default())
}

fn block_height_map_as_default<'de, D>(deserializer: D) -> Result<HashMap<String, i64>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<Map<String, Value>>::deserialize(deserializer)?;
    let mut result = HashMap::new();

    for (key, value) in value.unwrap_or_default() {
        match value {
            Value::Number(number) => {
                let height = number.as_i64().ok_or_else(|| {
                    serde::de::Error::custom(format!(
                        "block height value for '{key}' is not a signed integer"
                    ))
                })?;
                result.insert(key, height);
            }
            Value::String(text) => {
                if let Ok(height) = text.parse::<i64>() {
                    result.insert(key, height);
                    continue;
                }

                let inverted_height = key.parse::<i64>().map_err(|_| {
                    serde::de::Error::custom(format!(
                        "invalid block height map entry '{key}': '{text}'"
                    ))
                })?;
                result.insert(text, inverted_height);
            }
            other => {
                return Err(serde::de::Error::custom(format!(
                    "invalid block height map value for '{key}': {other}"
                )));
            }
        }
    }

    Ok(result)
}

/// Merkle path node returned by transaction proof queries.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct MerklePathNodeDto {
    pub hash: String,
    pub is_left_child_node: bool,
}

/// Merkle path returned by transaction proof queries.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct MerklePathDto {
    #[serde(default)]
    pub merkle_path_nodes: Vec<MerklePathNodeDto>,
}

/// Peer description returned by the network peers endpoint.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PeerDto {
    #[serde(default)]
    pub ip_address: String,
    #[serde(flatten)]
    pub extra: BTreeMap<String, serde_json::Value>,
}

/// Network metadata returned by the network info endpoint.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct NetworkInfoOutput {
    #[serde(default)]
    pub version: String,
    #[serde(flatten)]
    pub extra: BTreeMap<String, serde_json::Value>,
}

/// Task queue snapshot returned by the task queue endpoint.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TaskQueueInfoDto {
    #[serde(flatten)]
    pub extra: BTreeMap<String, serde_json::Value>,
}

/// Input payload for the transaction fee estimation endpoint.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CalculateTransactionFeeInput {
    pub raw_transaction: String,
}

/// Output payload returned by the transaction fee estimation endpoint.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CalculateTransactionFeeOutput {
    pub success: bool,
    #[serde(default)]
    pub transaction_fee: HashMap<String, f64>,
}

/// Standard WebApp error envelope returned by AElf node REST APIs.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct WebAppErrorResponse {
    pub error: WebAppError,
}

/// Error payload nested inside the WebApp error envelope.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct WebAppError {
    pub code: String,
    pub message: String,
    #[serde(default)]
    pub details: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::{ChainStatusDto, LogEventDto, TransactionResultDto};
    use aelf_proto::aelf::{Address, ResourceTokenCharged, TransactionFeeCharged};
    use base64::Engine;
    use prost::Message;
    use serde_json::json;

    #[test]
    fn parses_transaction_fee_logs() {
        let engine = base64::engine::general_purpose::STANDARD;
        let tx_fee = TransactionFeeCharged {
            symbol: "ELF".to_owned(),
            amount: 12_345,
        };
        let resource_fee = ResourceTokenCharged {
            symbol: "CPU".to_owned(),
            amount: 999,
            contract_address: Some(Address {
                value: vec![1_u8; 32],
            }),
        };
        let result = TransactionResultDto {
            transaction_id: "0x01".to_owned(),
            status: "MINED".to_owned(),
            logs: vec![
                LogEventDto {
                    address: "addr".to_owned(),
                    name: "TransactionFeeCharged".to_owned(),
                    indexed: Vec::new(),
                    non_indexed: engine.encode(tx_fee.encode_to_vec()),
                },
                LogEventDto {
                    address: "addr".to_owned(),
                    name: "ResourceTokenCharged".to_owned(),
                    indexed: Vec::new(),
                    non_indexed: engine.encode(resource_fee.encode_to_vec()),
                },
            ],
            bloom: String::new(),
            transaction: serde_json::Value::Null,
            return_value: String::new(),
            block_number: 1,
            block_hash: "0x02".to_owned(),
            error: String::new(),
        };

        let fees = result.get_transaction_fees();
        assert_eq!(fees.get("ELF"), Some(&12_345));
        assert_eq!(fees.get("CPU"), Some(&999));
    }

    #[test]
    fn parses_chain_status_hash_to_height_maps() {
        let status: ChainStatusDto = serde_json::from_value(json!({
            "ChainId": "AELF",
            "Branches": {
                "abc": 42
            },
            "NotLinkedBlocks": null,
            "LongestChainHeight": 42,
            "LongestChainHash": "abc",
            "GenesisBlockHash": "genesis",
            "GenesisContractAddress": "contract",
            "LastIrreversibleBlockHash": "lib",
            "LastIrreversibleBlockHeight": 40,
            "BestChainHash": "abc",
            "BestChainHeight": 42
        }))
        .expect("chain status");

        assert_eq!(status.branches.get("abc"), Some(&42));
        assert!(status.not_linked_blocks.is_empty());
    }

    #[test]
    fn parses_chain_status_height_to_hash_maps() {
        let status: ChainStatusDto = serde_json::from_value(json!({
            "ChainId": "AELF",
            "Branches": {
                "42": "abc"
            },
            "NotLinkedBlocks": {
                "7": "def"
            },
            "LongestChainHeight": 42,
            "LongestChainHash": "abc",
            "GenesisBlockHash": "genesis",
            "GenesisContractAddress": "contract",
            "LastIrreversibleBlockHash": "lib",
            "LastIrreversibleBlockHeight": 40,
            "BestChainHash": "abc",
            "BestChainHeight": 42
        }))
        .expect("chain status");

        assert_eq!(status.branches.get("abc"), Some(&42));
        assert_eq!(status.not_linked_blocks.get("def"), Some(&7));
    }
}