waves_rust/model/asset/
asset_distribution.rs1use crate::error::{Error, Result};
2use crate::model::Address;
3use crate::util::JsonDeserializer;
4use serde_json::Value;
5use std::collections::HashMap;
6
7#[derive(Clone, Eq, PartialEq, Debug)]
8pub struct AssetDistribution {
9 items: HashMap<Address, u64>,
10 last_item: Address,
11 has_next: bool,
12}
13
14impl AssetDistribution {
15 pub fn new(items: HashMap<Address, u64>, last_item: Address, has_next: bool) -> Self {
16 Self {
17 items,
18 last_item,
19 has_next,
20 }
21 }
22
23 pub fn items(&self) -> HashMap<Address, u64> {
24 self.items.clone()
25 }
26
27 pub fn last_item(&self) -> Address {
28 self.last_item.clone()
29 }
30
31 pub fn has_next(&self) -> bool {
32 self.has_next
33 }
34}
35
36impl TryFrom<&Value> for AssetDistribution {
37 type Error = Error;
38
39 fn try_from(value: &Value) -> Result<Self> {
40 let has_next = JsonDeserializer::safe_to_boolean_from_field(value, "hasNext")?;
41 let last_item = JsonDeserializer::safe_to_string_from_field(value, "lastItem")?;
42 let items = JsonDeserializer::safe_to_map_from_field(value, "items")?
43 .into_iter()
44 .map(|entry| {
45 Ok((
46 Address::from_string(&entry.0)?,
47 JsonDeserializer::safe_to_int(&entry.1)? as u64,
48 ))
49 })
50 .collect::<Result<HashMap<Address, u64>>>()?;
51 Ok(AssetDistribution {
52 items,
53 last_item: Address::from_string(&last_item)?,
54 has_next,
55 })
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use crate::error::Result;
62 use crate::model::asset::asset_distribution::AssetDistribution;
63 use crate::model::{Address, ByteString};
64 use serde_json::Value;
65 use std::fs;
66
67 #[test]
68 fn test_json_to_asset_distribution() -> Result<()> {
69 let data = fs::read_to_string("./tests/resources/assets/asset_distribution_rs.json")
70 .expect("Unable to read file");
71 let json: &Value = &serde_json::from_str(&data).expect("failed to convert");
72
73 let asset_distribution: AssetDistribution = json.try_into()?;
74
75 assert_eq!(true, asset_distribution.has_next());
76 assert_eq!(
77 "3PDh2FtgoL8ZMdbu3Zs5tCk6HuqE674SWnn",
78 asset_distribution.last_item().encoded()
79 );
80 let items = asset_distribution.items();
81 assert_eq!(
82 700,
83 items[&Address::from_string("3PR6Z2LHA6CBp4z2qEfALfExYvH8xaX9UhH")?]
84 );
85 assert_eq!(
86 101500,
87 items[&Address::from_string("3PDh2FtgoL8ZMdbu3Zs5tCk6HuqE674SWnn")?]
88 );
89 assert_eq!(
90 10000,
91 items[&Address::from_string("3P4U4DfUQqkfKDz9whSikqpvC9oKtWbsPtu")?]
92 );
93 Ok(())
94 }
95}