diff --git a/Cargo.toml b/Cargo.toml index c6c06d9..2852903 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ members = [ "contracts/bridge", "contracts/crafting", "contracts/mystery_box", + "contracts/item_durability", "contracts/daily_rewards", "contracts/streak_counter", "contracts/energy", diff --git a/contracts/item_durability/Cargo.toml b/contracts/item_durability/Cargo.toml new file mode 100644 index 0000000..dfb7685 --- /dev/null +++ b/contracts/item_durability/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "item-durability" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +soroban-sdk = "21.7.7" + +[dev-dependencies] +soroban-sdk = { version = "21.7.7", features = ["testutils"] } diff --git a/contracts/item_durability/README.md b/contracts/item_durability/README.md new file mode 100644 index 0000000..62af72c --- /dev/null +++ b/contracts/item_durability/README.md @@ -0,0 +1,43 @@ +# Item Durability Contract + +A modular Soroban smart contract for the Quest economy that implements game item durability lifecycle management across Stages 1, 2, and 3: + +1. **Durability Tracking & Usage (Stage 1 - #399):** + - Configurable `max_durability` and `current_durability`. + - `use_item` function: decrements durability by 1 per use. + - Enforces fail-closed rejection when durability reaches zero (`ZeroDurability`). + - Marks item as broken upon reaching zero durability and emits `(broken, item_id)` event. + +2. **Repair with Token Payment Sink (Stage 2 - #400):** + - `repair_item`: owner can pay tokens to restore missing durability. + - Cost is strictly proportional to repaired durability: `cost = units * cost_per_unit`. + - Repair is capped at `max_durability`. + - Payment is routed directly to the designated token `sink_address`. + - Broken items (durability == 0) are blocked from being repaired. + +3. **Break & Salvage Payout (Stage 3 - #401):** + - `salvage_item`: owner can salvage broken items for configured material payout tokens. + - Item record is destroyed upon salvage, preventing double-salvage. + - Non-broken items cannot be salvaged. + +--- + +## Functions + +### Administration +- `initialize(env, admin)`: Sets contract administrator. +- `set_repair_config(env, admin, token, cost_per_unit, sink_address)`: Configures repair token, unit cost, and sink recipient. +- `set_salvage_config(env, admin, material_token, material_payout)`: Configures material token and payout per broken item. +- `register_item(env, admin, item_id, owner, max_durability)`: Registers a new item. +- `transfer_admin(env, current_admin, new_admin)`: Secure admin transfer. + +### Gameplay & Economics +- `use_item(env, user, item_id)`: Decrements durability, marks broken if reaches 0. +- `repair_item(env, user, item_id, amount_to_repair)`: Restores durability via token payment to sink. +- `salvage_item(env, user, item_id)`: Destroys broken item and awards material tokens. + +### Views +- `get_item(env, item_id)`: Returns `Option`. +- `get_durability(env, item_id)`: Returns current durability or error if not found. +- `is_broken(env, item_id)`: Returns boolean indicating broken status. +- `calculate_repair_cost(env, item_id, amount_to_repair)`: Simulates repair cost. diff --git a/contracts/item_durability/src/lib.rs b/contracts/item_durability/src/lib.rs new file mode 100644 index 0000000..c6e7010 --- /dev/null +++ b/contracts/item_durability/src/lib.rs @@ -0,0 +1,406 @@ +#![no_std] + +use soroban_sdk::{ + contract, contracterror, contractimpl, contractmeta, contracttype, symbol_short, token, + Address, Env, Symbol, +}; + +#[cfg(test)] +mod test; + +// Contract metadata +contractmeta!( + key = "Description", + val = "Item Durability contract supporting use decrement, repair with token sink, and salvage of broken items" +); + +#[contracttype] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Item { + pub owner: Address, + pub max_durability: u32, + pub current_durability: u32, + pub is_broken: bool, +} + +#[contracttype] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct RepairConfig { + pub token: Address, + pub cost_per_unit: i128, + pub sink_address: Address, +} + +#[contracttype] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SalvageConfig { + pub material_token: Address, + pub material_payout: i128, +} + +#[contracterror] +#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)] +#[repr(u32)] +pub enum DurabilityError { + NotAuthorized = 1, + ItemNotFound = 2, + ZeroDurability = 3, + InvalidMaxDurability = 4, + ItemAlreadyExists = 5, + AdminNotFound = 6, + AlreadyInitialized = 7, + ItemBroken = 8, + ItemNotBroken = 9, + RepairNotConfigured = 10, + SalvageNotConfigured = 11, + InvalidAmount = 12, +} + +// Storage keys +const ADMIN: Symbol = symbol_short!("ADMIN"); +const ITEM: Symbol = symbol_short!("ITEM"); +const REPAIR_CFG: Symbol = symbol_short!("REP_CFG"); +const SALVAGE_CFG: Symbol = symbol_short!("SAL_CFG"); + +#[contract] +pub struct ItemDurabilityContract; + +#[contractimpl] +impl ItemDurabilityContract { + /// Initialize the contract with an admin address + pub fn initialize(env: Env, admin: Address) -> Result<(), DurabilityError> { + admin.require_auth(); + if env.storage().instance().has(&ADMIN) { + return Err(DurabilityError::AlreadyInitialized); + } + env.storage().instance().set(&ADMIN, &admin); + Ok(()) + } + + /// Configure repair parameters: token accepted, cost per durability unit, and sink address. + pub fn set_repair_config( + env: Env, + admin: Address, + token: Address, + cost_per_unit: i128, + sink_address: Address, + ) -> Result<(), DurabilityError> { + Self::require_admin(&env, &admin)?; + + if cost_per_unit <= 0 { + return Err(DurabilityError::InvalidAmount); + } + + let cfg = RepairConfig { + token, + cost_per_unit, + sink_address, + }; + env.storage().instance().set(&REPAIR_CFG, &cfg); + Ok(()) + } + + /// Configure salvage payout parameters: material token address and payout per salvaged item. + pub fn set_salvage_config( + env: Env, + admin: Address, + material_token: Address, + material_payout: i128, + ) -> Result<(), DurabilityError> { + Self::require_admin(&env, &admin)?; + + if material_payout <= 0 { + return Err(DurabilityError::InvalidAmount); + } + + let cfg = SalvageConfig { + material_token, + material_payout, + }; + env.storage().instance().set(&SALVAGE_CFG, &cfg); + Ok(()) + } + + /// Register a new item with max durability. Admin only. + pub fn register_item( + env: Env, + admin: Address, + item_id: u64, + owner: Address, + max_durability: u32, + ) -> Result<(), DurabilityError> { + Self::require_admin(&env, &admin)?; + + if max_durability == 0 { + return Err(DurabilityError::InvalidMaxDurability); + } + + let key = (ITEM, item_id); + if env.storage().persistent().has(&key) { + return Err(DurabilityError::ItemAlreadyExists); + } + + let item = Item { + owner, + max_durability, + current_durability: max_durability, + is_broken: false, + }; + + env.storage().persistent().set(&key, &item); + Ok(()) + } + + /// Use an item in a puzzle/game, decrementing its durability by 1. + /// When durability drops to zero, marks item as broken and emits a broken event. + /// Rejects if durability is already zero or item is broken. + pub fn use_item( + env: Env, + user: Address, + item_id: u64, + ) -> Result { + user.require_auth(); + + let key = (ITEM, item_id); + let mut item: Item = match env.storage().persistent().get(&key) { + Some(i) => i, + None => return Err(DurabilityError::ItemNotFound), + }; + + if item.owner != user { + return Err(DurabilityError::NotAuthorized); + } + + if item.is_broken || item.current_durability == 0 { + return Err(DurabilityError::ZeroDurability); + } + + item.current_durability -= 1; + if item.current_durability == 0 { + item.is_broken = true; + env.events().publish( + (symbol_short!("broken"), item_id), + (user.clone(), item_id), + ); + } + + env.storage().persistent().set(&key, &item); + + // Emit durability change event: (use, item_id) -> (user, current_durability) + env.events().publish( + (symbol_short!("use"), item_id), + (user, item.current_durability), + ); + + Ok(item.current_durability) + } + + /// Restore item durability by paying tokens to the designated sink address. + /// Repair cost is proportional to missing durability. + /// Durability is capped at max durability. + /// Blocks repair if item is broken (zero durability reached). + pub fn repair_item( + env: Env, + user: Address, + item_id: u64, + amount_to_repair: u32, + ) -> Result { + user.require_auth(); + + if amount_to_repair == 0 { + return Err(DurabilityError::InvalidAmount); + } + + let key = (ITEM, item_id); + let mut item: Item = match env.storage().persistent().get(&key) { + Some(i) => i, + None => return Err(DurabilityError::ItemNotFound), + }; + + if item.owner != user { + return Err(DurabilityError::NotAuthorized); + } + + // Broken items cannot be repaired + if item.is_broken || item.current_durability == 0 { + return Err(DurabilityError::ItemBroken); + } + + let cfg: RepairConfig = match env.storage().instance().get(&REPAIR_CFG) { + Some(c) => c, + None => return Err(DurabilityError::RepairNotConfigured), + }; + + let missing = item.max_durability.saturating_sub(item.current_durability); + if missing == 0 { + return Ok(item.current_durability); + } + + // Cap repair at max durability + let units_to_repair = amount_to_repair.min(missing); + let total_cost = (units_to_repair as i128) + .checked_mul(cfg.cost_per_unit) + .unwrap_or(0); + + if total_cost > 0 { + token::Client::new(&env, &cfg.token).transfer( + &user, + &cfg.sink_address, + &total_cost, + ); + } + + item.current_durability += units_to_repair; + env.storage().persistent().set(&key, &item); + + // Emit repair event: (repair, item_id) -> (user, units_repaired, total_cost) + env.events().publish( + (symbol_short!("repair"), item_id), + (user, units_to_repair, total_cost), + ); + + Ok(item.current_durability) + } + + /// Salvage a broken item for material payout. + /// Once salvaged, item record is destroyed and cannot be salvaged twice. + pub fn salvage_item( + env: Env, + user: Address, + item_id: u64, + ) -> Result { + user.require_auth(); + + let key = (ITEM, item_id); + let item: Item = match env.storage().persistent().get(&key) { + Some(i) => i, + None => return Err(DurabilityError::ItemNotFound), + }; + + if item.owner != user { + return Err(DurabilityError::NotAuthorized); + } + + if !item.is_broken && item.current_durability > 0 { + return Err(DurabilityError::ItemNotBroken); + } + + let cfg: SalvageConfig = match env.storage().instance().get(&SALVAGE_CFG) { + Some(c) => c, + None => return Err(DurabilityError::SalvageNotConfigured), + }; + + // Destroy item record so item cannot be salvaged twice + env.storage().persistent().remove(&key); + + // Transfer configured material payout to owner + if cfg.material_payout > 0 { + token::Client::new(&env, &cfg.material_token).transfer( + &env.current_contract_address(), + &user, + &cfg.material_payout, + ); + } + + // Emit salvage event: (salvage, item_id) -> (user, material_payout) + env.events().publish( + (symbol_short!("salvage"), item_id), + (user, cfg.material_payout), + ); + + Ok(cfg.material_payout) + } + + /// Get item details by item ID + pub fn get_item(env: Env, item_id: u64) -> Option { + let key = (ITEM, item_id); + env.storage().persistent().get(&key) + } + + /// Get current durability for an item + pub fn get_durability(env: Env, item_id: u64) -> Result { + let key = (ITEM, item_id); + let item: Option = env.storage().persistent().get(&key); + match item { + Some(i) => Ok(i.current_durability), + None => Err(DurabilityError::ItemNotFound), + } + } + + /// Check if an item is broken + pub fn is_broken(env: Env, item_id: u64) -> Result { + let key = (ITEM, item_id); + let item: Option = env.storage().persistent().get(&key); + match item { + Some(i) => Ok(i.is_broken), + None => Err(DurabilityError::ItemNotFound), + } + } + + /// Calculate repair cost without executing repair + pub fn calculate_repair_cost( + env: Env, + item_id: u64, + amount_to_repair: u32, + ) -> Result { + let key = (ITEM, item_id); + let item: Item = match env.storage().persistent().get(&key) { + Some(i) => i, + None => return Err(DurabilityError::ItemNotFound), + }; + + if item.is_broken || item.current_durability == 0 { + return Err(DurabilityError::ItemBroken); + } + + let cfg: RepairConfig = match env.storage().instance().get(&REPAIR_CFG) { + Some(c) => c, + None => return Err(DurabilityError::RepairNotConfigured), + }; + + let missing = item.max_durability.saturating_sub(item.current_durability); + let units = amount_to_repair.min(missing); + Ok((units as i128).checked_mul(cfg.cost_per_unit).unwrap_or(0)) + } + + /// Get current repair configuration + pub fn get_repair_config(env: Env) -> Option { + env.storage().instance().get(&REPAIR_CFG) + } + + /// Get current salvage configuration + pub fn get_salvage_config(env: Env) -> Option { + env.storage().instance().get(&SALVAGE_CFG) + } + + /// Transfer contract admin role. Admin only. + pub fn transfer_admin( + env: Env, + current_admin: Address, + new_admin: Address, + ) -> Result<(), DurabilityError> { + Self::require_admin(&env, ¤t_admin)?; + new_admin.require_auth(); + + env.storage().instance().set(&ADMIN, &new_admin); + Ok(()) + } + + /// Get current admin + pub fn get_admin(env: Env) -> Option
{ + env.storage().instance().get(&ADMIN) + } + + // Helper functions + fn require_admin(env: &Env, admin: &Address) -> Result<(), DurabilityError> { + admin.require_auth(); + + let stored_admin: Option
= env.storage().instance().get(&ADMIN); + + match stored_admin { + Some(stored) if stored == *admin => Ok(()), + Some(_) => Err(DurabilityError::NotAuthorized), + None => Err(DurabilityError::AdminNotFound), + } + } +} diff --git a/contracts/item_durability/src/test.rs b/contracts/item_durability/src/test.rs new file mode 100644 index 0000000..278160d --- /dev/null +++ b/contracts/item_durability/src/test.rs @@ -0,0 +1,216 @@ +use super::*; +use soroban_sdk::{ + testutils::Address as _, + token, Env, +}; + +struct TestFixture { + env: Env, + _contract_id: Address, + admin: Address, + user: Address, + sink: Address, + token_addr: Address, + material_addr: Address, +} + +impl TestFixture { + fn setup() -> (Self, ItemDurabilityContractClient<'static>) { + let env = Env::default(); + env.mock_all_auths(); + + let admin = Address::generate(&env); + let user = Address::generate(&env); + let sink = Address::generate(&env); + + let payment_asset = env.register_stellar_asset_contract_v2(admin.clone()); + let token_addr = payment_asset.address(); + + let material_asset = env.register_stellar_asset_contract_v2(admin.clone()); + let material_addr = material_asset.address(); + + let contract_id = env.register_contract(None, ItemDurabilityContract); + let client = ItemDurabilityContractClient::new(&env, &contract_id); + + client.initialize(&admin); + + // Mint payment tokens to user: 10,000 + token::StellarAssetClient::new(&env, &token_addr).mint(&user, &10_000); + + // Mint material tokens to contract for salvage payouts: 50,000 + token::StellarAssetClient::new(&env, &material_addr).mint(&contract_id, &50_000); + + // Configure repair: 10 tokens per durability unit + client.set_repair_config(&admin, &token_addr, &10, &sink); + + // Configure salvage: 50 material tokens per broken item + client.set_salvage_config(&admin, &material_addr, &50); + + let fixture = Self { + env, + _contract_id: contract_id, + admin, + user, + sink, + token_addr, + material_addr, + }; + + (fixture, client) + } +} + +#[test] +fn test_register_and_use_item_decrements_durability() { + let (f, client) = TestFixture::setup(); + + // Register item 1 with max durability 5 + client.register_item(&f.admin, &1, &f.user, &5); + + assert_eq!(client.get_durability(&1), 5); + assert_eq!(client.is_broken(&1), false); + + // Use item: 5 -> 4 + let remaining = client.use_item(&f.user, &1); + assert_eq!(remaining, 4); + assert_eq!(client.get_durability(&1), 4); + assert_eq!(client.is_broken(&1), false); + + // Use item: 4 -> 3 + let remaining = client.use_item(&f.user, &1); + assert_eq!(remaining, 3); + assert_eq!(client.get_durability(&1), 3); +} + +#[test] +fn test_item_breaks_when_durability_reaches_zero() { + let (f, client) = TestFixture::setup(); + + // Register item with durability 2 + client.register_item(&f.admin, &10, &f.user, &2); + + client.use_item(&f.user, &10); // 2 -> 1 + assert_eq!(client.is_broken(&10), false); + + client.use_item(&f.user, &10); // 1 -> 0, now broken! + assert_eq!(client.get_durability(&10), 0); + assert_eq!(client.is_broken(&10), true); + + // Using zero durability item fails with ZeroDurability error + let res = client.try_use_item(&f.user, &10); + assert_eq!(res, Err(Ok(DurabilityError::ZeroDurability))); +} + +#[test] +fn test_repair_item_cost_calculation_and_cap() { + let (f, client) = TestFixture::setup(); + + // Item with max durability 10 + client.register_item(&f.admin, &20, &f.user, &10); + + // Use 3 times: durability becomes 7 (missing 3) + client.use_item(&f.user, &20); + client.use_item(&f.user, &20); + client.use_item(&f.user, &20); + assert_eq!(client.get_durability(&20), 7); + + // Repair cost for 2 units: 2 * 10 = 20 tokens + let calculated_cost = client.calculate_repair_cost(&20, &2); + assert_eq!(calculated_cost, 20); + + let initial_user_balance = token::Client::new(&f.env, &f.token_addr).balance(&f.user); + let initial_sink_balance = token::Client::new(&f.env, &f.token_addr).balance(&f.sink); + + // Repair 2 units + let new_durability = client.repair_item(&f.user, &20, &2); + assert_eq!(new_durability, 9); + assert_eq!(client.get_durability(&20), 9); + + // Verify token payment routed to sink + let final_user_balance = token::Client::new(&f.env, &f.token_addr).balance(&f.user); + let final_sink_balance = token::Client::new(&f.env, &f.token_addr).balance(&f.sink); + assert_eq!(initial_user_balance - final_user_balance, 20); + assert_eq!(final_sink_balance - initial_sink_balance, 20); + + // Requesting more units than missing is capped at max durability + // Durability is 9, max is 10 (missing 1). Requesting 5 repairs only 1 unit! + let capped_durability = client.repair_item(&f.user, &20, &5); + assert_eq!(capped_durability, 10); + assert_eq!(client.get_durability(&20), 10); + + // Cost for 1 capped unit was 10 + let user_balance_after_cap = token::Client::new(&f.env, &f.token_addr).balance(&f.user); + assert_eq!(final_user_balance - user_balance_after_cap, 10); +} + +#[test] +fn test_broken_item_cannot_be_repaired() { + let (f, client) = TestFixture::setup(); + + // Register item with durability 1 + client.register_item(&f.admin, &30, &f.user, &1); + client.use_item(&f.user, &30); // durability 0, item breaks! + + assert_eq!(client.is_broken(&30), true); + + // Attempting to repair a broken item must fail with ItemBroken + let res = client.try_repair_item(&f.user, &30, &1); + assert_eq!(res, Err(Ok(DurabilityError::ItemBroken))); +} + +#[test] +fn test_salvage_broken_item_and_destroy_record() { + let (f, client) = TestFixture::setup(); + + client.register_item(&f.admin, &40, &f.user, &1); + + // Attempting to salvage non-broken item fails with ItemNotBroken + let res = client.try_salvage_item(&f.user, &40); + assert_eq!(res, Err(Ok(DurabilityError::ItemNotBroken))); + + // Break the item + client.use_item(&f.user, &40); + assert_eq!(client.is_broken(&40), true); + + let initial_material_balance = token::Client::new(&f.env, &f.material_addr).balance(&f.user); + + // Salvage broken item + let payout = client.salvage_item(&f.user, &40); + assert_eq!(payout, 50); + + // Verify material token received by user + let final_material_balance = token::Client::new(&f.env, &f.material_addr).balance(&f.user); + assert_eq!(final_material_balance - initial_material_balance, 50); + + // Verify item record destroyed after salvage + assert_eq!(client.get_item(&40), None); + + // Cannot salvage twice: item not found + let res_double = client.try_salvage_item(&f.user, &40); + assert_eq!(res_double, Err(Ok(DurabilityError::ItemNotFound))); +} + +#[test] +fn test_unauthorized_user_cannot_use_repair_or_salvage() { + let (f, client) = TestFixture::setup(); + let stranger = Address::generate(&f.env); + + client.register_item(&f.admin, &50, &f.user, &3); + + // Stranger cannot use item + let res_use = client.try_use_item(&stranger, &50); + assert_eq!(res_use, Err(Ok(DurabilityError::NotAuthorized))); + + // Stranger cannot repair item + let res_repair = client.try_repair_item(&stranger, &50, &1); + assert_eq!(res_repair, Err(Ok(DurabilityError::NotAuthorized))); + + // Break item + client.use_item(&f.user, &50); + client.use_item(&f.user, &50); + client.use_item(&f.user, &50); + + // Stranger cannot salvage item + let res_salvage = client.try_salvage_item(&stranger, &50); + assert_eq!(res_salvage, Err(Ok(DurabilityError::NotAuthorized))); +}