hypixel-sdk 0.2.0

Async client for the Hypixel Public API with typed models and SkyBlock helpers
Documentation
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::models::skyblock::Bazaar;

/// A lookup of unit prices keyed by SkyBlock item id, assembled from market data.
#[derive(Debug, Clone, Default)]
pub struct PriceBook {
    prices: HashMap<String, f64>,
}

impl PriceBook {
    /// Create an empty price book.
    pub fn new() -> Self {
        Self::default()
    }

    /// Seed unit prices from a bazaar snapshot, using each product's instant-sell
    /// (buy-order) price. Bazaar ids are uppercased to match item ids.
    pub fn with_bazaar(mut self, bazaar: &Bazaar) -> Self {
        for (id, product) in &bazaar.products {
            if let Some(status) = &product.quick_status {
                self.prices.insert(id.to_uppercase(), status.buy_price);
            }
        }
        self
    }

    /// Overlay lowest-BIN prices (keyed by item id). BIN prices only fill items
    /// that have no price yet; existing bazaar prices take precedence.
    pub fn with_lowest_bin(mut self, lowest_bin: &HashMap<String, i64>) -> Self {
        for (id, price) in lowest_bin {
            self.prices
                .entry(id.to_uppercase())
                .or_insert(*price as f64);
        }
        self
    }

    /// Insert or override a single price.
    pub fn insert(&mut self, item_id: impl Into<String>, price: f64) {
        self.prices.insert(item_id.into().to_uppercase(), price);
    }

    /// Look up the unit price for an item id.
    pub fn price(&self, item_id: &str) -> Option<f64> {
        self.prices.get(&item_id.to_uppercase()).copied()
    }

    /// The assembled unit prices, keyed by uppercased item id.
    pub fn prices(&self) -> &HashMap<String, f64> {
        &self.prices
    }
}

/// One item stack to be valued.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ItemStack {
    /// SkyBlock item id (e.g. `HYPERION`).
    pub item_id: String,
    /// Number of items in the stack.
    pub count: i64,
}

/// The valuation of a single [`ItemStack`].
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ItemValuation {
    pub item_id: String,
    pub count: i64,
    pub unit_price: f64,
    pub total: f64,
}

/// An itemized networth estimate.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct Networth {
    /// Summed value of every priced stack.
    pub total: f64,
    /// Per-stack valuations that were successfully priced.
    pub items: Vec<ItemValuation>,
    /// Item ids that had no price in the [`PriceBook`].
    pub unpriced: Vec<String>,
}

/// Value-bearing upgrades applied to an item, read from its `ExtraAttributes`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ItemModifiers {
    /// Whether a recombobulator was applied (`rarity_upgrades`).
    #[serde(default)]
    pub recombobulated: bool,
    /// Hot potato books applied; values above 10 are fuming potato books.
    #[serde(default)]
    pub hot_potato_books: i64,
    /// Art of War books applied.
    #[serde(default)]
    pub art_of_war: i64,
    /// Enchantments and their levels (e.g. `sharpness` → 7).
    #[serde(default)]
    pub enchantments: HashMap<String, i64>,
}

/// An [`ItemStack`] together with its value-bearing modifiers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DetailedItemStack {
    pub item_id: String,
    pub count: i64,
    #[serde(default)]
    pub modifiers: ItemModifiers,
}

/// The valuation of a single [`DetailedItemStack`].
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DetailedItemValuation {
    pub item_id: String,
    pub count: i64,
    /// Value of the bare items (unit price × count).
    pub base_value: f64,
    /// Added value of priced modifiers (recomb, potato books, enchantments...).
    pub modifiers_value: f64,
    pub total: f64,
}

/// An itemized networth estimate including modifier value.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct DetailedNetworth {
    pub total: f64,
    pub items: Vec<DetailedItemValuation>,
    /// Item ids that had no base price in the [`PriceBook`].
    pub unpriced: Vec<String>,
}

/// Estimate networth including modifier value against a [`PriceBook`].
///
/// On top of the base item price, this values recombobulators
/// (`RECOMBOBULATOR_3000`), hot/fuming potato books (`HOT_POTATO_BOOK`,
/// `FUMING_POTATO_BOOK`), Art of War books (`THE_ART_OF_WAR`), and
/// enchantments (bazaar `ENCHANTMENT_<NAME>_<LEVEL>` products). Modifiers
/// whose components have no price contribute nothing rather than failing.
/// Dungeon stars and gemstones are not valued.
pub fn value_items_detailed(stacks: &[DetailedItemStack], prices: &PriceBook) -> DetailedNetworth {
    let mut networth = DetailedNetworth::default();
    for stack in stacks {
        let Some(unit_price) = prices.price(&stack.item_id) else {
            networth.unpriced.push(stack.item_id.clone());
            continue;
        };
        let m = &stack.modifiers;
        let mut modifiers_value = 0.0;
        if m.recombobulated {
            modifiers_value += prices.price("RECOMBOBULATOR_3000").unwrap_or(0.0);
        }
        if m.hot_potato_books > 0 {
            let plain = m.hot_potato_books.min(10);
            let fuming = (m.hot_potato_books - 10).max(0);
            modifiers_value += plain as f64 * prices.price("HOT_POTATO_BOOK").unwrap_or(0.0);
            modifiers_value += fuming as f64 * prices.price("FUMING_POTATO_BOOK").unwrap_or(0.0);
        }
        if m.art_of_war > 0 {
            modifiers_value += m.art_of_war as f64 * prices.price("THE_ART_OF_WAR").unwrap_or(0.0);
        }
        for (enchant, level) in &m.enchantments {
            let id = format!("ENCHANTMENT_{}_{}", enchant.to_uppercase(), level);
            modifiers_value += prices.price(&id).unwrap_or(0.0);
        }

        let base_value = unit_price * stack.count as f64;
        let total = base_value + modifiers_value;
        networth.total += total;
        networth.items.push(DetailedItemValuation {
            item_id: stack.item_id.clone(),
            count: stack.count,
            base_value,
            modifiers_value,
            total,
        });
    }
    networth
}

/// Estimate the networth of a set of item stacks against a [`PriceBook`].
pub fn value_items(stacks: &[ItemStack], prices: &PriceBook) -> Networth {
    let mut networth = Networth::default();
    for stack in stacks {
        match prices.price(&stack.item_id) {
            Some(unit_price) => {
                let total = unit_price * stack.count as f64;
                networth.total += total;
                networth.items.push(ItemValuation {
                    item_id: stack.item_id.clone(),
                    count: stack.count,
                    unit_price,
                    total,
                });
            }
            None => networth.unpriced.push(stack.item_id.clone()),
        }
    }
    networth
}

/// Extract item stacks (SkyBlock id + count) from a decoded inventory NBT value.
///
/// Reads the standard `{ "i": [ { "Count", "tag": { "ExtraAttributes": { "id" } } } ] }`
/// layout; empty slots and items without a SkyBlock id are skipped.
#[cfg(feature = "nbt")]
pub fn extract_item_stacks(nbt: &fastnbt::Value) -> Vec<ItemStack> {
    extract_item_stacks_detailed(nbt)
        .into_iter()
        .map(|stack| ItemStack {
            item_id: stack.item_id,
            count: stack.count,
        })
        .collect()
}

/// Extract item stacks with their value-bearing modifiers from a decoded
/// inventory NBT value.
///
/// Like [`extract_item_stacks`], but also reads recombobulators, potato
/// books, Art of War books, and enchantments out of each item's
/// `ExtraAttributes` for use with [`value_items_detailed`].
#[cfg(feature = "nbt")]
pub fn extract_item_stacks_detailed(nbt: &fastnbt::Value) -> Vec<DetailedItemStack> {
    use fastnbt::Value;

    fn as_compound(v: &Value) -> Option<&std::collections::HashMap<String, Value>> {
        match v {
            Value::Compound(map) => Some(map),
            _ => None,
        }
    }

    fn as_int(v: &Value) -> Option<i64> {
        match v {
            Value::Byte(n) => Some(*n as i64),
            Value::Short(n) => Some(*n as i64),
            Value::Int(n) => Some(*n as i64),
            Value::Long(n) => Some(*n),
            _ => None,
        }
    }

    let items = match nbt {
        Value::Compound(root) => match root.get("i") {
            Some(Value::List(list)) => list,
            _ => return Vec::new(),
        },
        Value::List(list) => list,
        _ => return Vec::new(),
    };

    let mut stacks = Vec::new();
    for entry in items {
        let Some(item) = as_compound(entry) else {
            continue;
        };
        let count = item.get("Count").and_then(as_int).unwrap_or(1);
        let Some(attrs) = as_compound(item.get("tag").unwrap_or(&Value::Byte(0)))
            .and_then(|tag| as_compound(tag.get("ExtraAttributes").unwrap_or(&Value::Byte(0))))
        else {
            continue;
        };
        let Some(Value::String(item_id)) = attrs.get("id") else {
            continue;
        };

        let mut modifiers = ItemModifiers {
            recombobulated: attrs.get("rarity_upgrades").and_then(as_int).unwrap_or(0) > 0,
            hot_potato_books: attrs.get("hot_potato_count").and_then(as_int).unwrap_or(0),
            art_of_war: attrs.get("art_of_war_count").and_then(as_int).unwrap_or(0),
            ..ItemModifiers::default()
        };
        if let Some(enchants) = attrs.get("enchantments").and_then(as_compound) {
            for (name, level) in enchants {
                if let Some(level) = as_int(level) {
                    modifiers.enchantments.insert(name.clone(), level);
                }
            }
        }

        stacks.push(DetailedItemStack {
            item_id: item_id.clone(),
            count,
            modifiers,
        });
    }
    stacks
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn detailed_valuation_prices_modifiers() {
        let mut book = PriceBook::new();
        book.insert("ASPECT_OF_THE_END", 100_000.0);
        book.insert("RECOMBOBULATOR_3000", 8_000_000.0);
        book.insert("HOT_POTATO_BOOK", 80_000.0);
        book.insert("FUMING_POTATO_BOOK", 1_200_000.0);
        book.insert("ENCHANTMENT_SHARPNESS_6", 500_000.0);

        let stack = DetailedItemStack {
            item_id: "ASPECT_OF_THE_END".into(),
            count: 1,
            modifiers: ItemModifiers {
                recombobulated: true,
                hot_potato_books: 12,
                art_of_war: 0,
                enchantments: [("sharpness".to_string(), 6i64)].into_iter().collect(),
            },
        };
        let nw = value_items_detailed(&[stack], &book);
        assert_eq!(nw.items.len(), 1);
        let expected_modifiers = 8_000_000.0 + 10.0 * 80_000.0 + 2.0 * 1_200_000.0 + 500_000.0;
        assert!((nw.items[0].modifiers_value - expected_modifiers).abs() < 1e-6);
        assert!((nw.total - (100_000.0 + expected_modifiers)).abs() < 1e-6);
    }

    #[test]
    fn values_known_items_and_tracks_unpriced() {
        let mut book = PriceBook::new();
        book.insert("HYPERION", 1_000_000.0);
        let stacks = vec![
            ItemStack {
                item_id: "hyperion".into(),
                count: 2,
            },
            ItemStack {
                item_id: "MYSTERY".into(),
                count: 1,
            },
        ];
        let nw = value_items(&stacks, &book);
        assert_eq!(nw.total, 2_000_000.0);
        assert_eq!(nw.items.len(), 1);
        assert_eq!(nw.unpriced, vec!["MYSTERY".to_string()]);
    }
}