iota-client 0.5.0-alpha.3

Client to use Iota APIs
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
//! Response types
use crate::error::*;
use iota_bundle_preview::{Address, Hash, Tag, Transaction, TransactionField};
use iota_ternary_preview::TryteBuf;
use serde::ser::{Serialize, SerializeSeq, SerializeStruct, Serializer};

// TODO: remove this struct once iota_bundle_preview::Transaction implements Serialize
/// a Transaction wrapper that can be serialized
#[derive(Serialize)]
pub struct TransactionDef {
    payload: String,
    address: String,
    value: String,
    obsolete_tag: String,
    timestamp: String,
    index: String,
    last_index: String,
    bundle: Vec<i8>,
    trunk: Vec<i8>,
    branch: Vec<i8>,
    tag: String,
    attachment_ts: String,
    attachment_lbts: String,
    attachment_ubts: String,
    nonce: String,
}

impl From<&Transaction> for TransactionDef {
    fn from(transaction: &Transaction) -> Self {
        TransactionDef {
            payload: serde_json::to_string(transaction.payload()).unwrap(),
            address: serde_json::to_string(transaction.address()).unwrap(),
            value: serde_json::to_string(transaction.value()).unwrap(),
            obsolete_tag: serde_json::to_string(transaction.obsolete_tag()).unwrap(),
            timestamp: serde_json::to_string(transaction.timestamp()).unwrap(),
            index: serde_json::to_string(transaction.index()).unwrap(),
            last_index: serde_json::to_string(transaction.last_index()).unwrap(),
            bundle: transaction.bundle().as_bytes().to_vec(),
            trunk: transaction.trunk().as_bytes().to_vec(),
            branch: transaction.branch().as_bytes().to_vec(),
            tag: serde_json::to_string(transaction.tag()).unwrap(),
            attachment_ts: serde_json::to_string(transaction.attachment_ts()).unwrap(),
            attachment_lbts: serde_json::to_string(transaction.attachment_lbts()).unwrap(),
            attachment_ubts: serde_json::to_string(transaction.attachment_ubts()).unwrap(),
            nonce: serde_json::to_string(transaction.nonce()).unwrap(),
        }
    }
}

fn transaction_serializer<S>(x: &Vec<Transaction>, s: S) -> std::result::Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let mut seq = s.serialize_seq(Some(x.len()))?;
    for e in x {
        seq.serialize_element(&TransactionDef::from(e))?;
    }
    seq.end()
}

/// addNeighbors Response Type
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AddNeighborsResponse {
    #[serde(rename = "addedNeighbors")]
    /// Total number of added neighbors
    pub added_neighbors: Option<usize>,
}

/// checkConsistency Response Type
#[derive(Clone, Debug, Serialize)]
pub struct ConsistencyResponse {
    /// State of the given transactions in the `tails` parameter. A `true` value means
    /// that all given transactions are consistent. A `false` value means that one
    /// or more of the given transactions are inconsistent.
    pub state: bool,
    /// If the `state` field is false, this field contains information about why the transaction is inconsistent.
    pub info: Option<String>,
}

#[derive(Clone, Debug, Deserialize)]
pub(crate) struct ConsistencyResponseBuilder {
    state: Option<bool>,
    info: Option<String>,
    exception: Option<String>,
    error: Option<String>,
}

impl ConsistencyResponseBuilder {
    pub(crate) async fn build(self) -> Result<ConsistencyResponse> {
        let mut state = false;
        if let Some(exception) = self.exception {
            return Err(Error::ResponseError(exception));
        } else if let Some(error) = self.error {
            return Err(Error::ResponseError(error));
        } else if let Some(s) = self.state {
            state = s;
        }

        Ok(ConsistencyResponse {
            state: state,
            info: self.info,
        })
    }
}

/// attachToTangle Response Type
#[derive(Serialize)]
pub struct AttachToTangleResponse {
    /// Transaction trytes that include a valid `nonce` field
    #[serde(serialize_with = "transaction_serializer")]
    pub trytes: Vec<Transaction>,
}

#[derive(Clone, Debug, Deserialize)]
pub(crate) struct AttachToTangleResponseBuilder {
    trytes: Option<Vec<String>>,
    error: Option<String>,
    exception: Option<String>,
}

impl AttachToTangleResponseBuilder {
    pub(crate) async fn build(self) -> Result<AttachToTangleResponse> {
        let mut trytes = Vec::new();
        if let Some(exception) = self.exception {
            return Err(Error::ResponseError(exception));
        } else if let Some(error) = self.error {
            return Err(Error::ResponseError(error));
        } else if let Some(s) = self.trytes {
            s.iter().for_each(|x| {
                trytes.push(
                    Transaction::from_trits(TryteBuf::try_from_str(&x).unwrap().as_trits())
                        .unwrap(),
                )
            });
        }

        Ok(AttachToTangleResponse { trytes })
    }
}

#[derive(Clone, Debug, Deserialize)]
pub(crate) struct ErrorResponseBuilder {
    error: Option<String>,
    exception: Option<String>,
}

impl ErrorResponseBuilder {
    pub(crate) async fn build(self) -> Result<()> {
        if let Some(exception) = self.exception {
            return Err(Error::ResponseError(exception));
        } else if let Some(error) = self.error {
            return Err(Error::ResponseError(error));
        }

        Ok(())
    }
}

/// findTransactions Response Type
#[derive(Clone, Debug)]
pub struct FindTransactionsResponse {
    /// The transaction hashes which are returned depend on your input.
    /// * bundles: returns an array of transaction hashes that contain the given bundle hash.
    /// * addresses: returns an array of transaction hashes that contain the given address in the address field.
    /// * tags: returns an array of transaction hashes that contain the given value in the tag field.
    /// * approvees: returns an array of transaction hashes that contain the given transactions in their branchTransaction or trunkTransaction fields.
    pub hashes: Vec<Hash>,
}

// TODO: remove this when iota_bundle_preview::Hash implements Serialize
impl Serialize for FindTransactionsResponse {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("FindTransactionsResponse", 1)?;
        let hashes: Vec<&[i8]> = self.hashes.iter().map(|hash| hash.as_bytes()).collect();
        state.serialize_field("hashes", &hashes)?;
        state.end()
    }
}

#[derive(Clone, Debug, Deserialize)]
pub(crate) struct FindTransactionsResponseBuilder {
    hashes: Option<Vec<String>>,
    error: Option<String>,
    exception: Option<String>,
}

impl FindTransactionsResponseBuilder {
    pub(crate) async fn build(self) -> Result<FindTransactionsResponse> {
        let mut hashes: Vec<Hash> = Vec::new();
        if let Some(exception) = self.exception {
            return Err(Error::ResponseError(exception));
        } else if let Some(error) = self.error {
            return Err(Error::ResponseError(error));
        } else if let Some(s) = self.hashes {
            hashes = s
                .iter()
                .map(|s| {
                    Hash::from_inner_unchecked(
                        TryteBuf::try_from_str(&s).unwrap().as_trits().encode(),
                    )
                })
                .collect::<Vec<Hash>>();
        }

        Ok(FindTransactionsResponse { hashes })
    }
}

/// getBalances Response Type
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct GetBalancesResponse {
    /// Array of balances in the same order as the `addresses` parameters were passed to the endpoint
    pub balances: Vec<u64>,
    /// The index of the milestone that confirmed the most recent balance
    pub milestone_index: i64,
    /// The referencing tips. If no `tips` parameter was passed to the endpoint,
    /// this field contains the hash of the latest milestone that confirmed the balance
    pub references: Vec<Hash>,
}

// TODO: remove this when iota_bundle_preview::Hash implements Serialize
impl Serialize for GetBalancesResponse {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("GetBalancesResponse", 3)?;

        state.serialize_field("balances", &self.balances)?;
        state.serialize_field("milestone_index", &self.milestone_index)?;

        let references: Vec<&[i8]> = self.references.iter().map(|hash| hash.as_bytes()).collect();
        state.serialize_field("references", &references)?;

        state.end()
    }
}

#[derive(Clone, Debug, Deserialize)]
pub(crate) struct GetBalancesResponseBuilder {
    balances: Option<Vec<String>>,
    #[serde(rename = "milestoneIndex")]
    milestone_index: Option<i64>,
    references: Option<Vec<String>>,
    error: Option<String>,
    exception: Option<String>,
}

impl GetBalancesResponseBuilder {
    pub(crate) async fn build(self) -> Result<GetBalancesResponse> {
        let mut res = GetBalancesResponse {
            balances: Vec::new(),
            milestone_index: 0,
            references: Vec::new(),
        };

        if let Some(exception) = self.exception {
            return Err(Error::ResponseError(exception));
        } else if let Some(error) = self.error {
            return Err(Error::ResponseError(error));
        }

        if let Some(s) = self.balances {
            res.balances = s.into_iter().map(|s| s.parse().unwrap()).collect();
        }

        if let Some(s) = self.milestone_index {
            res.milestone_index = s;
        }

        if let Some(s) = self.references {
            res.references = s
                .iter()
                .map(|s| {
                    Hash::from_inner_unchecked(
                        TryteBuf::try_from_str(&s).unwrap().as_trits().encode(),
                    )
                })
                .collect::<Vec<Hash>>();
        }

        Ok(res)
    }
}

/// getInclusionStatesResponse Response Type
#[derive(Clone, Debug, Serialize, Hash, Eq, PartialEq)]
pub struct GetInclusionStatesResponse {
    /// List of boolean values in the same order as the `transactions` parameters.
    /// A `true` value means the transaction was confirmed
    pub states: Vec<bool>,
}

#[derive(Clone, Debug, Deserialize)]
pub(crate) struct GetInclusionStatesResponseBuilder {
    states: Option<Vec<bool>>,
    error: Option<String>,
    exception: Option<String>,
}

impl GetInclusionStatesResponseBuilder {
    pub(crate) async fn build(self) -> Result<GetInclusionStatesResponse> {
        let mut states = Vec::new();
        if let Some(exception) = self.exception {
            return Err(Error::ResponseError(exception));
        } else if let Some(error) = self.error {
            return Err(Error::ResponseError(error));
        } else if let Some(s) = self.states {
            states = s;
        }

        Ok(GetInclusionStatesResponse { states })
    }
}

/// getNeighbors Response Type
#[derive(Clone, Debug, Serialize)]
pub struct GetNeighborsResponse {
    /// Vector of `NeighborResponse`
    pub neighbors: Vec<NeighborResponse>,
}

/// getNeighbors Response Type
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct GetNeighborsResponseBuilder {
    neighbors: Option<Vec<NeighborResponse>>,
    error: Option<String>,
    exception: Option<String>,
}

impl GetNeighborsResponseBuilder {
    pub(crate) async fn build(self) -> Result<GetNeighborsResponse> {
        let mut neighbors = Vec::new();
        if let Some(exception) = self.exception {
            return Err(Error::ResponseError(exception));
        } else if let Some(error) = self.error {
            return Err(Error::ResponseError(error));
        } else if let Some(s) = self.neighbors {
            neighbors = s;
        }

        Ok(GetNeighborsResponse { neighbors })
    }
}

/// getNodeAPIConfiguration Response Type
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GetNodeAPIConfigurationResponse {
    /// Maximum number of transactions that may be returned by the findTransactions endpoint
    #[serde(rename = "maxFindTransactions")]
    pub max_find_transactions: Option<usize>,
    /// Maximum number of parameters in an API call
    #[serde(rename = "maxRequestsList")]
    pub max_requests_list: Option<usize>,
    /// Maximum number of trytes that may be returned by the getTrytes endpoint
    #[serde(rename = "maxGetTrytes")]
    pub max_get_trytes: Option<usize>,
    /// Maximum number of characters that the body of an API call may contain
    #[serde(rename = "maxBodyLength")]
    pub max_body_length: Option<usize>,
    /// See if the node runs on a network other than the Mainnet
    #[serde(rename = "testNet")]
    pub testnet: Option<bool>,
    /// Milestone start index on IRI node
    #[serde(rename = "milestoneStartIndex")]
    pub milestone_start_index: i64,
}

/// getNodeInfo Response Type
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GetNodeInfoResponse {
    /// Name of IRI node
    #[serde(rename = "appName")]
    pub app_name: String,
    /// IRI version
    #[serde(rename = "appVersion")]
    pub app_version: String,
    /// Number of threads IRI is using
    #[serde(rename = "jreAvailableProcessors")]
    pub jre_available_processors: Option<u16>,
    /// Amount of free memory on IRI node
    #[serde(rename = "jreFreeMemory")]
    pub jre_free_memory: Option<u64>,
    /// Max amount of memory on IRI node
    #[serde(rename = "jreMaxMemory")]
    pub jre_max_memory: Option<u64>,
    /// Total amount of memory on IRI node
    #[serde(rename = "jreTotalMemory")]
    pub jre_total_memory: Option<u64>,
    /// JRE version of IRI node
    #[serde(rename = "jreVersion")]
    pub jre_version: Option<String>,
    /// Latest milestone on IRI node
    #[serde(rename = "latestMilestone")]
    pub latest_milestone: String,
    /// Latest milestone index on IRI node
    #[serde(rename = "latestMilestoneIndex")]
    pub latest_milestone_index: u32,
    /// Latest solid subtangle milestone on IRI node
    #[serde(rename = "latestSolidSubtangleMilestone")]
    pub latest_solid_subtangle_milestone: String,
    /// Latest solid subtangle milestone index on IRI node
    #[serde(rename = "latestSolidSubtangleMilestoneIndex")]
    pub latest_solid_subtangle_milestone_index: u32,
    /// Milestone start index on IRI node
    #[serde(rename = "milestoneStartIndex")]
    pub milestone_start_index: i64,
    /// Amount of neighbors connected to IRI node
    pub neighbors: u16,
    /// Packet queue size on IRI node
    #[serde(rename = "packetsQueueSize")]
    pub packets_queue_size: Option<u16>,
    /// Current time on IRI node (UNIX Seconds),
    pub time: u64,
    /// Amount of tips on IRI node
    pub tips: u32,
    /// Transactions to request on IRI node
    #[serde(rename = "transactionsToRequest")]
    pub transactions_to_request: u32,
}

/// getTips Response Type
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GetTipsResponse {
    /// Vector of tip transaction hashes
    pub hashes: Vec<String>,
}

/// getTransactionsToApprove Response Type
#[derive(Clone, Debug)]
pub struct GTTAResponse {
    /// Valid trunk transaction hash
    pub trunk_transaction: Hash,
    /// Valid branch transaction hash
    pub branch_transaction: Hash,
}

// TODO: remove this when iota_bundle_preview::Hash implements Serialize
impl Serialize for GTTAResponse {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("GTTAResponse", 2)?;

        state.serialize_field("trunk_transaction", &self.trunk_transaction.as_bytes())?;

        state.serialize_field("branch_transaction", &self.branch_transaction.as_bytes())?;

        state.end()
    }
}

#[derive(Clone, Debug, Deserialize)]
pub(crate) struct GTTAResponseBuilder {
    #[serde(rename = "trunkTransaction")]
    trunk_transaction: Option<String>,
    #[serde(rename = "branchTransaction")]
    branch_transaction: Option<String>,
    error: Option<String>,
    exception: Option<String>,
}

impl GTTAResponseBuilder {
    pub(crate) async fn build(self) -> Result<GTTAResponse> {
        let mut res = GTTAResponse {
            trunk_transaction: Hash::zeros(),
            branch_transaction: Hash::zeros(),
        };

        if let Some(exception) = self.exception {
            return Err(Error::ResponseError(exception));
        } else if let Some(error) = self.error {
            return Err(Error::ResponseError(error));
        }

        if let Some(s) = self.trunk_transaction {
            res.trunk_transaction =
                Hash::from_inner_unchecked(TryteBuf::try_from_str(&s).unwrap().as_trits().encode());
        }

        if let Some(b) = self.branch_transaction {
            res.branch_transaction =
                Hash::from_inner_unchecked(TryteBuf::try_from_str(&b).unwrap().as_trits().encode());
        }

        Ok(res)
    }
}

/// Representation of neighbor node
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
pub struct NeighborResponse {
    /// IP address of neighbors
    pub address: String,
    /// Domain of neighbors
    pub domain: String,
    /// Number of all transactions
    #[serde(rename = "numberOfAllTransactions")]
    pub number_of_all_transactions: usize,
    /// Number of invalid transactions
    #[serde(rename = "numberOfInvalidTransactions")]
    pub number_of_invalid_transactions: usize,
    /// Number of new transactions
    #[serde(rename = "numberOfNewTransactions")]
    pub number_of_new_transactions: usize,
    /// Number of random transaction requests
    #[serde(rename = "numberOfRandomTransactionRequests")]
    pub number_of_random_transactions: usize,
    /// Number of sent transactions
    #[serde(rename = "numberOfSentTransactions")]
    pub number_of_sent_transactions: usize,
    /// Number of sent transactions
    #[serde(rename = "numberOfStaleTransactions")]
    pub number_of_stale_transactions: usize,
    /// Number of sent transactions
    #[serde(rename = "numberOfDroppedSentPackets")]
    pub number_of_dropped_sent_packets: usize,
    /// Type of connection, either tcp or udp
    #[serde(rename = "connectionType")]
    pub connection_type: String,
    /// Status of Neighbor connection
    pub connected: bool,
}

/// getTrytes Response Type
#[derive(Serialize)]
pub struct GetTrytesResponse {
    /// Vector of transaction trytes for the given transaction hashes (in the same order as the parameters)
    #[serde(serialize_with = "transaction_serializer")]
    pub trytes: Vec<Transaction>,
}

#[derive(Clone, Deserialize, Debug)]
pub(crate) struct GetTrytesResponseBuilder {
    trytes: Option<Vec<String>>,
    exception: Option<String>,
    error: Option<String>,
}

impl GetTrytesResponseBuilder {
    pub(crate) async fn build(self) -> Result<GetTrytesResponse> {
        let mut trytes = Vec::new();
        if let Some(exception) = self.exception {
            return Err(Error::ResponseError(exception));
        } else if let Some(error) = self.error {
            return Err(Error::ResponseError(error));
        } else if let Some(s) = self.trytes {
            s.iter().for_each(|x| {
                trytes.push(
                    Transaction::from_trits(TryteBuf::try_from_str(&x).unwrap().as_trits())
                        .unwrap(),
                )
            });
        }

        Ok(GetTrytesResponse { trytes })
    }
}

/// removeNeighbors Response Type
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RemoveNeighborsResponse {
    /// Total number of removed neighbors
    #[serde(rename = "removedNeighbors")]
    pub removed_neighbors: Option<usize>,
}

/// wereAddressesSpentFrom Response Type
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct WereAddressesSpentFromResponse {
    /// States of the specified addresses in the same order as the values in the `addresses` parameter.
    /// A `true` value means that the address has been spent from.
    pub states: Vec<bool>,
}

#[derive(Clone, Debug, Deserialize)]
pub(crate) struct WereAddressesSpentFromResponseBuilder {
    states: Option<Vec<bool>>,
    exception: Option<String>,
    error: Option<String>,
}

impl WereAddressesSpentFromResponseBuilder {
    pub(crate) async fn build(self) -> Result<WereAddressesSpentFromResponse> {
        let mut states = Vec::new();
        if let Some(exception) = self.exception {
            return Err(Error::ResponseError(exception));
        } else if let Some(error) = self.error {
            return Err(Error::ResponseError(error));
        } else if let Some(s) = self.states {
            states = s;
        }

        Ok(WereAddressesSpentFromResponse { states })
    }
}

#[derive(Clone, Debug, Serialize)]
/// Address can be used as input to spend balance
pub struct Input {
    pub(crate) address: Address,
    pub(crate) balance: u64,
    pub(crate) index: u64,
}

/// A transfer could be an input or an output for building a bundle.
/// input/output transfer depends on value, a negative value for an output transfer, a positive value for an input transfer
#[derive(Clone, Debug)]
pub struct Transfer {
    /// Transfer address
    pub address: Address,
    /// Transfer value
    pub value: u64,
    /// Optional message
    pub message: Option<String>,
    /// Optional message
    pub tag: Option<Tag>,
}
OSZAR »