whisky_pallas/converter/tx_builder_body/
value.rs

1use whisky_common::{Asset, WError};
2
3use crate::wrapper::transaction_body::{MultiassetPositiveCoin, Value};
4
5pub fn convert_value(asset_vec: &Vec<Asset>) -> Result<Value, WError> {
6    let mut lovelace: u64 = 0;
7    let mut multiasset: Vec<(String, Vec<(String, u64)>)> = Vec::new();
8    for asset in asset_vec {
9        if asset.unit() == "lovelace".to_string() || asset.unit() == "".to_string() {
10            lovelace = asset.quantity().parse::<u64>().map_err(|_| {
11                WError::new(
12                    "WhiskyPallas - Converting value:",
13                    "Invalid lovelace quantity format",
14                )
15            })?;
16        } else {
17            let policy = asset.policy();
18            let asset_name = asset.name();
19            let quantity = asset.quantity().parse::<u64>().map_err(|_| {
20                WError::new(
21                    "WhiskyPallas - Converting value:",
22                    &format!("Invalid quantity format for asset: {}", asset_name),
23                )
24            })?;
25            multiasset.push((policy, vec![(asset_name, quantity)]));
26        }
27    }
28    if multiasset.is_empty() {
29        Ok(Value::new(lovelace, None))
30    } else {
31        Ok(Value::new(
32            lovelace,
33            Some(MultiassetPositiveCoin::new(multiasset)?),
34        ))
35    }
36}
37
38pub fn value_to_asset_vec(value: &Value) -> Result<Vec<Asset>, WError> {
39    let mut assets: Vec<Asset> = Vec::new();
40    match &value.inner {
41        pallas::ledger::primitives::conway::Value::Coin(coin) => {
42            assets.push(Asset::new_from_str("lovelace", &coin.to_string()));
43        }
44        pallas::ledger::primitives::conway::Value::Multiasset(coin, btree_map) => {
45            assets.push(Asset::new_from_str("lovelace", &coin.to_string()));
46            for (policy_id, asset_map) in btree_map {
47                for (asset_name, quantity) in asset_map {
48                    let concated_name =
49                        format!("{}{}", policy_id.to_string(), asset_name.to_string());
50                    assets.push(Asset::new_from_str(
51                        &concated_name,
52                        &u64::from(quantity).to_string(),
53                    ));
54                }
55            }
56        }
57    }
58    Ok(assets)
59}