diff --git a/Cargo.toml b/Cargo.toml index a5ad116..d09dc89 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,6 +38,7 @@ members = [ "contracts/vesting_schedule", "contracts/insurance", "contracts/whitelist", + "contracts/item_durability", "contracts/anti_bot", "contracts/skill_rating", "contracts/governance", diff --git a/contracts/item_durability/Cargo.toml b/contracts/item_durability/Cargo.toml new file mode 100644 index 0000000..ef2a204 --- /dev/null +++ b/contracts/item_durability/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "item_durability" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +soroban-sdk = { workspace = true } + +[dev-dependencies] +soroban-sdk = { workspace = true, features = ["testutils"] } + +[features] +testutils = ["soroban-sdk/testutils"] diff --git a/contracts/item_durability/README.md b/contracts/item_durability/README.md new file mode 100644 index 0000000..c83ca88 --- /dev/null +++ b/contracts/item_durability/README.md @@ -0,0 +1,88 @@ +# Item Durability Module (Soroban Smart Contract) + +A modular game mechanics smart contract built for Soroban on the Stellar network. It implements on-chain item durability tracking where game items experience degradation through gameplay usage. + +--- + +## ๐Ÿš€ Features + +- **Item Registration**: Administrators register game items with defined maximum durability. +- **Usage & Degradation**: `use_item(user, item_id)` decrements the item's current durability by exactly 1 on every puzzle interaction. +- **Fail-Closed Zero Durability**: Rejects item usage when current durability reaches zero with `ZeroDurability`. +- **Owner Verification**: Ensures only the authenticated owner of the item can use it. +- **Durability Events**: Emits Soroban events `(use, item_id) -> (user, current_durability)` on every successful item usage. +- **Admin Governance**: Supports secure administrator role transfer with two-way cryptographic verification. + +--- + +## ๐Ÿ“ฆ Data Structures + +### `Item` + +```rust +#[contracttype] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Item { + pub owner: Address, + pub max_durability: u32, + pub current_durability: u32, +} +``` + +### Storage Keys + +| Key | Storage Tier | Value Type | Description | +|:---|:---|:---|:---| +| `Symbol("ADMIN")` | Instance | `Address` | Current contract administrator | +| `(Symbol("ITEM"), u64)` | Persistent | `Item` | Item record mapped by unique `item_id` | + +--- + +## ๐Ÿ›ก๏ธ Error Codes + +```rust +#[contracterror] +#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)] +#[repr(u32)] +pub enum DurabilityError { + NotAuthorized = 1, // Caller is not authorized or not the item owner + ItemNotFound = 2, // Item ID not found in persistent storage + ZeroDurability = 3, // Item has zero durability remaining and cannot be used + InvalidMaxDurability = 4, // Item max durability must be greater than zero + ItemAlreadyExists = 5, // Item ID already registered + AdminNotFound = 6, // Admin address has not been set + AlreadyInitialized = 7, // Contract has already been initialized +} +``` + +--- + +## ๐Ÿ“ก Events + +| Event Topic | Event Payload | Description | +|:---|:---|:---| +| `(Symbol("use"), u64)` | `(Address, u32)` | Emitted when an item is used: `(user, current_durability)` | + +--- + +## ๐Ÿ’ป Contract Interface + +```rust +pub trait ItemDurabilityInterface { + fn initialize(env: Env, admin: Address) -> Result<(), DurabilityError>; + fn register_item(env: Env, admin: Address, item_id: u64, owner: Address, max_durability: u32) -> Result<(), DurabilityError>; + fn use_item(env: Env, user: Address, item_id: u64) -> Result; + fn get_item(env: Env, item_id: u64) -> Option; + fn get_durability(env: Env, item_id: u64) -> Result; + fn transfer_admin(env: Env, current_admin: Address, new_admin: Address) -> Result<(), DurabilityError>; + fn get_admin(env: Env) -> Option
; +} +``` + +--- + +## ๐Ÿงช Testing + +```bash +cargo check --package item_durability +``` diff --git a/contracts/item_durability/src/lib.rs b/contracts/item_durability/src/lib.rs new file mode 100644 index 0000000..0d72f98 --- /dev/null +++ b/contracts/item_durability/src/lib.rs @@ -0,0 +1,166 @@ +#![no_std] + +use soroban_sdk::{ + contract, contractimpl, contracttype, contracterror, contractmeta, + Address, Env, Symbol, symbol_short, +}; + +mod test; + +// Contract metadata +contractmeta!( + key = "Description", + val = "Item Durability contract for tracking and decrementing game item durability" +); + +#[contracttype] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Item { + pub owner: Address, + pub max_durability: u32, + pub current_durability: u32, +} + +#[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, +} + +// Storage keys +const ADMIN: Symbol = symbol_short!("ADMIN"); +const ITEM: Symbol = symbol_short!("ITEM"); + +#[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(()) + } + + /// 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, + }; + + env.storage().persistent().set(&key, &item); + Ok(()) + } + + /// Use an item in a puzzle/game, decrementing its durability by 1. + /// Rejects if durability is zero. Emits durability change event. + 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.current_durability == 0 { + return Err(DurabilityError::ZeroDurability); + } + + item.current_durability -= 1; + 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) + } + + /// 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), + } + } + + /// 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..674c799 --- /dev/null +++ b/contracts/item_durability/src/test.rs @@ -0,0 +1,163 @@ +#![cfg(test)] + +use super::*; +use soroban_sdk::{ + testutils::{Address as _}, + Address, Env, +}; + +fn create_test_env() -> (Env, Address, Address, Address) { + let env = Env::default(); + let admin = Address::generate(&env); + let player1 = Address::generate(&env); + let player2 = Address::generate(&env); + + env.mock_all_auths(); + + (env, admin, player1, player2) +} + +#[test] +fn test_initialize() { + let (env, admin, _, _) = create_test_env(); + let contract_id = env.register_contract(None, ItemDurabilityContract); + let client = ItemDurabilityContractClient::new(&env, &contract_id); + + client.initialize(&admin); + assert_eq!(client.get_admin(), Some(admin.clone())); + + // Initializing twice should fail + let res = client.try_initialize(&admin); + assert_eq!(res, Err(Ok(DurabilityError::AlreadyInitialized))); +} + +#[test] +fn test_register_and_get_item() { + let (env, admin, player1, _) = create_test_env(); + let contract_id = env.register_contract(None, ItemDurabilityContract); + let client = ItemDurabilityContractClient::new(&env, &contract_id); + + client.initialize(&admin); + + let item_id: u64 = 101; + client.register_item(&admin, &item_id, &player1, &5); + + let item = client.get_item(&item_id).unwrap(); + assert_eq!(item.owner, player1); + assert_eq!(item.max_durability, 5); + assert_eq!(item.current_durability, 5); + + assert_eq!(client.get_durability(&item_id), 5); +} + +#[test] +fn test_use_item_decreases_by_one() { + let (env, admin, player1, _) = create_test_env(); + let contract_id = env.register_contract(None, ItemDurabilityContract); + let client = ItemDurabilityContractClient::new(&env, &contract_id); + + client.initialize(&admin); + + let item_id: u64 = 102; + client.register_item(&admin, &item_id, &player1, &3); + + // First use: 3 -> 2 + let d1 = client.use_item(&player1, &item_id); + assert_eq!(d1, 2); + assert_eq!(client.get_durability(&item_id), 2); + + // Second use: 2 -> 1 + let d2 = client.use_item(&player1, &item_id); + assert_eq!(d2, 1); + assert_eq!(client.get_durability(&item_id), 1); + + // Third use: 1 -> 0 + let d3 = client.use_item(&player1, &item_id); + assert_eq!(d3, 0); + assert_eq!(client.get_durability(&item_id), 0); +} + +#[test] +fn test_zero_durability_cannot_be_used() { + let (env, admin, player1, _) = create_test_env(); + let contract_id = env.register_contract(None, ItemDurabilityContract); + let client = ItemDurabilityContractClient::new(&env, &contract_id); + + client.initialize(&admin); + + let item_id: u64 = 103; + client.register_item(&admin, &item_id, &player1, &1); + + // Use once to reach 0 + let d = client.use_item(&player1, &item_id); + assert_eq!(d, 0); + + // Using again should fail with ZeroDurability + let res = client.try_use_item(&player1, &item_id); + assert_eq!(res, Err(Ok(DurabilityError::ZeroDurability))); +} + +#[test] +fn test_unauthorized_use_rejected() { + let (env, admin, player1, player2) = create_test_env(); + let contract_id = env.register_contract(None, ItemDurabilityContract); + let client = ItemDurabilityContractClient::new(&env, &contract_id); + + client.initialize(&admin); + + let item_id: u64 = 104; + client.register_item(&admin, &item_id, &player1, &5); + + // player2 is not the owner + let res = client.try_use_item(&player2, &item_id); + assert_eq!(res, Err(Ok(DurabilityError::NotAuthorized))); + + // Durability unchanged + assert_eq!(client.get_durability(&item_id), 5); +} + +#[test] +fn test_item_not_found() { + let (env, admin, player1, _) = create_test_env(); + let contract_id = env.register_contract(None, ItemDurabilityContract); + let client = ItemDurabilityContractClient::new(&env, &contract_id); + + client.initialize(&admin); + + let res = client.try_use_item(&player1, &999); + assert_eq!(res, Err(Ok(DurabilityError::ItemNotFound))); + + assert_eq!(client.get_item(&999), None); +} + +#[test] +fn test_invalid_max_durability() { + let (env, admin, player1, _) = create_test_env(); + let contract_id = env.register_contract(None, ItemDurabilityContract); + let client = ItemDurabilityContractClient::new(&env, &contract_id); + + client.initialize(&admin); + + let res = client.try_register_item(&admin, &105, &player1, &0); + assert_eq!(res, Err(Ok(DurabilityError::InvalidMaxDurability))); +} + +#[test] +fn test_transfer_admin() { + let (env, admin, player1, new_admin) = create_test_env(); + let contract_id = env.register_contract(None, ItemDurabilityContract); + let client = ItemDurabilityContractClient::new(&env, &contract_id); + + client.initialize(&admin); + client.transfer_admin(&admin, &new_admin); + + assert_eq!(client.get_admin(), Some(new_admin.clone())); + + // Old admin cannot register + let old_res = client.try_register_item(&admin, &106, &player1, &5); + assert_eq!(old_res, Err(Ok(DurabilityError::NotAuthorized))); + + // New admin can register + let new_res = client.try_register_item(&new_admin, &106, &player1, &5); + assert!(new_res.is_ok()); +}