seedelf_cli/assets.rs
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
use pallas_crypto::hash::Hash;
use serde::{Deserialize, Serialize};
/// Represents an asset in the Cardano blockchain.
///
/// An `Asset` is identified by a `policy_id` and a `token_name`, and it tracks
/// the amount of tokens associated with the asset.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Hash, Clone)]
pub struct Asset {
pub policy_id: Hash<28>,
pub token_name: Vec<u8>,
pub amount: u64,
}
impl Asset {
/// Creates a new `Asset` instance.
///
/// # Arguments
///
/// * `policy_id` - A hex-encoded string representing the policy ID.
/// * `token_name` - A hex-encoded string representing the token name.
/// * `amount` - The amount of tokens for the asset.
pub fn new(policy_id: String, token_name: String, amount: u64) -> Self {
Self {
policy_id: Hash::new(
hex::decode(policy_id)
.unwrap()
.try_into()
.expect("Incorrect Length"),
),
token_name: hex::decode(token_name).unwrap(),
amount,
}
}
/// Adds two assets together if they have the same `policy_id` and `token_name`.
///
/// # Arguments
///
/// * `other` - The other asset to add.
///
/// # Returns
///
/// * `Ok(Self)` - The resulting `Asset` with the combined amounts.
/// * `Err(String)` - If the `policy_id` or `token_name` do not match.
pub fn add(&self, other: &Asset) -> Result<Self, String> {
if self.policy_id != other.policy_id || self.token_name != other.token_name {
return Err(
"Assets must have the same policy_id and token_name to be subtracted".to_string(),
);
}
Ok(Self {
policy_id: self.policy_id,
token_name: self.token_name.clone(),
amount: self.amount + other.amount,
})
}
/// Subtracts the amount of another asset if they have the same `policy_id` and `token_name`.
///
/// # Arguments
///
/// * `other` - The other asset to subtract.
///
/// # Returns
///
/// * `Ok(Self)` - The resulting `Asset` after subtraction.
/// * `Err(String)` - If the `policy_id` or `token_name` do not match.
pub fn sub(&self, other: &Asset) -> Result<Self, String> {
if self.policy_id != other.policy_id || self.token_name != other.token_name {
return Err(
"Assets must have the same policy_id and token_name to be subtracted".to_string(),
);
}
Ok(Self {
policy_id: self.policy_id,
token_name: self.token_name.clone(),
amount: self.amount - other.amount,
})
}
/// Compares two assets for equivalence in `policy_id` and `token_name`,
/// and checks if the amount is greater or equal.
///
/// # Arguments
///
/// * `other` - The other asset to compare against.
///
/// # Returns
///
/// * `true` if the `policy_id` and `token_name` match and the amount is greater or equal.
/// * `false` otherwise.
pub fn compare(&self, other: Asset) -> bool {
if self.policy_id != other.policy_id || self.token_name != other.token_name {
false
} else {
self.amount >= other.amount
}
}
}
/// Represents a collection of `Asset` instances.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Hash, Clone)]
pub struct Assets {
pub items: Vec<Asset>,
}
impl Default for Assets {
fn default() -> Self {
Self::new()
}
}
impl Assets {
/// Creates a new, empty `Assets` instance.
pub fn new() -> Self {
Self { items: Vec::new() }
}
/// Adds an asset to the collection, combining amounts if the asset already exists.
///
/// # Arguments
///
/// * `other` - The asset to add.
///
/// # Returns
///
/// * A new `Assets` instance with the updated list of assets.
pub fn add(&self, other: Asset) -> Self {
let mut new_items: Vec<Asset> = self.items.clone();
if let Some(existing) = new_items.iter_mut().find(|existing| {
existing.policy_id == other.policy_id && existing.token_name == other.token_name
}) {
*existing = existing.add(&other).unwrap();
} else {
new_items.push(other);
}
Self { items: new_items }
}
/// Subtracts an asset from the collection, removing it if the amount becomes zero.
///
/// # Arguments
///
/// * `other` - The asset to subtract.
///
/// # Returns
///
/// * A new `Assets` instance with updated asset amounts.
pub fn sub(&self, other: Asset) -> Self {
let mut new_items: Vec<Asset> = self.items.clone();
if let Some(existing) = new_items.iter_mut().find(|existing| {
existing.policy_id == other.policy_id && existing.token_name == other.token_name
}) {
*existing = existing.sub(&other).unwrap();
} else {
new_items.push(other);
}
Self { items: new_items }.remove_zero_amounts()
}
/// Removes assets with zero amounts from the collection.
pub fn remove_zero_amounts(&self) -> Self {
let filtered_items: Vec<Asset> = self
.items
.iter()
.filter(|asset| asset.amount > 0)
.cloned()
.collect();
Self {
items: filtered_items,
}
}
/// Checks if all assets in `other` are contained in this collection.
pub fn contains(&self, other: Assets) -> bool {
// search all other tokens and make sure they exist in these assets
for other_token in other.items {
// we assume we cant find it
let mut found = false;
// lets check all the assets in these assets
for token in self.items.clone() {
if token.compare(other_token.clone()) {
found = true;
break;
}
}
// if we didnt find it then false
if !found {
return false;
}
}
// we found all the other tokens
true
}
/// Checks if any asset in `other` exists in this collection.
pub fn any(&self, other: Assets) -> bool {
if other.items.is_empty() {
return true;
}
// search all other tokens and make sure they exist in these assets
for other_token in other.items {
// lets check all the assets in these assets
for token in self.items.clone() {
// if its greater than or equal then break
if token.policy_id == other_token.policy_id
&& token.token_name == other_token.token_name
{
return true;
}
}
}
// we found nothing
false
}
/// Merges two collections of assets, combining amounts of matching assets.
pub fn merge(&self, other: Assets) -> Self {
let mut merged: Assets = self.clone(); // Clone the current `Assets` as a starting point
for other_asset in other.items {
merged = merged.add(other_asset); // Use `add` to handle merging logic
}
merged
}
/// Separates two collections of assets, subtracting amounts of matching assets.
pub fn separate(&self, other: Assets) -> Self {
let mut separated: Assets = self.clone(); // Clone the current `Assets` as a starting point
for other_asset in other.items {
separated = separated.sub(other_asset); // Use `add` to handle merging logic
}
separated
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
pub fn len(&self) -> u64 {
self.items.len() as u64
}
pub fn split(&self, k: usize) -> Vec<Self> {
self.items
.chunks(k) // Divide the `items` into slices of at most `k` elements
.map(|chunk| Assets {
items: chunk.to_vec(),
}) // Convert each slice into an `Assets` struct
.collect()
}
}
/// Converts a string into a `u64` value.
///
/// # Arguments
///
/// * `input` - The string to parse into a `u64`.
///
/// # Returns
///
/// * `Ok(u64)` - If the conversion is successful.
/// * `Err(String)` - If the conversion fails.
pub fn string_to_u64(input: String) -> Result<u64, String> {
match input.parse::<u64>() {
Ok(value) => Ok(value),
Err(e) => Err(format!("Failed to convert: {}", e)),
}
}