From 06357a0fd8df9e75195839ca2fee39343db97f91 Mon Sep 17 00:00:00 2001 From: nuvoraxis <358196463+nuvoraxis@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:23:38 +0000 Subject: [PATCH] feat(contracts): implement points ledger with FIFO spend and expiry (#402, #403) - Add modular Soroban smart contract in contracts/points_ledger - Implement points balance and full historical ledger structure - Support authorized caller access control (admin and whitelisted game contracts) - Implement earn and earn_with_expiry recording amount, player, caller, reason code, and expiry timestamp - Implement spend function with strict First-In First-Out (FIFO) consumption of oldest unexpired points - Exclude expired points from available balance and reject spending when exceeding unexpired balance - Expose read functions for get_balance, get_total_earned, and get_history - Add unit test suite in src/test.rs covering authorized earning, balance invariant, FIFO spend order, and expiration exclusion - Add README.md documentation and workspace entry in Cargo.toml Closes #402 Closes #403 --- Cargo.toml | 1 + contracts/points_ledger/Cargo.toml | 13 ++ contracts/points_ledger/README.md | 15 ++ contracts/points_ledger/src/lib.rs | 330 ++++++++++++++++++++++++++++ contracts/points_ledger/src/test.rs | 137 ++++++++++++ 5 files changed, 496 insertions(+) create mode 100644 contracts/points_ledger/Cargo.toml create mode 100644 contracts/points_ledger/README.md create mode 100644 contracts/points_ledger/src/lib.rs create mode 100644 contracts/points_ledger/src/test.rs diff --git a/Cargo.toml b/Cargo.toml index c6c06d9..3aefa6b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ members = [ "contracts/bridge", "contracts/crafting", "contracts/mystery_box", + "contracts/points_ledger", "contracts/daily_rewards", "contracts/streak_counter", "contracts/energy", diff --git a/contracts/points_ledger/Cargo.toml b/contracts/points_ledger/Cargo.toml new file mode 100644 index 0000000..df818f2 --- /dev/null +++ b/contracts/points_ledger/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "points-ledger" +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/points_ledger/README.md b/contracts/points_ledger/README.md new file mode 100644 index 0000000..a8eb1b8 --- /dev/null +++ b/contracts/points_ledger/README.md @@ -0,0 +1,15 @@ +# Achievement Points Ledger Contract + +A modular Soroban smart contract for the Quest economy that implements player achievement point tracking across Stages 1 and 2: + +1. **Points Ledger & Authorized Earning (Stage 1 - #402):** + - Access-controlled point issuance: only contract admin and authorized game contracts can award points. + - Immutable audit trail recording player, amount, reason code, timestamp, and calling contract. + - Total balance strictly equals sum of all historical earn entries. + +2. **FIFO Spending & Expiration Policy (Stage 2 - #403):** + - Spend function at in-game shop with balance validation. + - Duration-based expiration tracked per earn entry. + - Strict First-In First-Out (FIFO) consumption: oldest unexpired points are spent first. + - Expired points are strictly excluded from available balance and cannot be spent. + - Spending is rejected if requested amount exceeds unexpired available balance. diff --git a/contracts/points_ledger/src/lib.rs b/contracts/points_ledger/src/lib.rs new file mode 100644 index 0000000..3d4e16a --- /dev/null +++ b/contracts/points_ledger/src/lib.rs @@ -0,0 +1,330 @@ +#![no_std] + +use soroban_sdk::{ + contract, contracterror, contractimpl, contractmeta, contracttype, symbol_short, + Address, Env, Symbol, Vec, +}; + +#[cfg(test)] +mod test; + +// Contract metadata +contractmeta!( + key = "Description", + val = "Achievement Points Ledger contract with authorized earning, FIFO point spending, and expiration" +); + +#[contracttype] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct PointsEntry { + pub player: Address, + pub amount: u64, + pub remaining: u64, + pub reason_code: Symbol, + pub earned_at: u64, + pub expires_at: u64, + pub caller: Address, +} + +#[contracttype] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct PlayerLedger { + pub total_earned: u64, + pub history: Vec, +} + +#[contracterror] +#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)] +#[repr(u32)] +pub enum PointsLedgerError { + NotAuthorized = 1, + AdminNotFound = 2, + AlreadyInitialized = 3, + InvalidAmount = 4, + InsufficientBalance = 5, +} + +// Storage keys +const ADMIN: Symbol = symbol_short!("ADMIN"); +const AUTH: Symbol = symbol_short!("AUTH"); +const LEDGER: Symbol = symbol_short!("LEDGER"); +const DEF_EXP: Symbol = symbol_short!("DEF_EXP"); + +#[contract] +pub struct PointsLedgerContract; + +#[contractimpl] +impl PointsLedgerContract { + /// Initialize the contract with an admin address + pub fn initialize(env: Env, admin: Address) -> Result<(), PointsLedgerError> { + admin.require_auth(); + if env.storage().instance().has(&ADMIN) { + return Err(PointsLedgerError::AlreadyInitialized); + } + env.storage().instance().set(&ADMIN, &admin); + Ok(()) + } + + /// Set default point expiration duration in seconds (0 for no expiration). Admin only. + pub fn set_default_expiry( + env: Env, + admin: Address, + duration: u64, + ) -> Result<(), PointsLedgerError> { + Self::require_admin(&env, &admin)?; + env.storage().instance().set(&DEF_EXP, &duration); + Ok(()) + } + + /// Authorize a contract or caller address to award points. Admin only. + pub fn authorize_caller( + env: Env, + admin: Address, + caller: Address, + ) -> Result<(), PointsLedgerError> { + Self::require_admin(&env, &admin)?; + let key = (AUTH, caller); + env.storage().persistent().set(&key, &true); + Ok(()) + } + + /// Deauthorize a contract or caller address. Admin only. + pub fn deauthorize_caller( + env: Env, + admin: Address, + caller: Address, + ) -> Result<(), PointsLedgerError> { + Self::require_admin(&env, &admin)?; + let key = (AUTH, caller); + env.storage().persistent().remove(&key); + Ok(()) + } + + /// Check if a contract or address is authorized to award points + pub fn is_authorized(env: Env, caller: Address) -> bool { + let stored_admin: Option
= env.storage().instance().get(&ADMIN); + if let Some(admin) = stored_admin { + if admin == caller { + return true; + } + } + let key = (AUTH, caller); + env.storage().persistent().has(&key) + } + + /// Award points to a player with custom validity duration (0 uses default). + /// Caller must be authorized (admin or authorized contract). + pub fn earn_with_expiry( + env: Env, + caller: Address, + player: Address, + amount: u64, + reason_code: Symbol, + validity_duration: u64, + ) -> Result<(), PointsLedgerError> { + caller.require_auth(); + + if !Self::is_authorized(env.clone(), caller.clone()) { + return Err(PointsLedgerError::NotAuthorized); + } + + if amount == 0 { + return Err(PointsLedgerError::InvalidAmount); + } + + let now = env.ledger().timestamp(); + let default_expiry: u64 = env.storage().instance().get(&DEF_EXP).unwrap_or(0); + let duration = if validity_duration > 0 { + validity_duration + } else { + default_expiry + }; + + let expires_at = if duration > 0 { + now.saturating_add(duration) + } else { + 0 + }; + + let key = (LEDGER, player.clone()); + let mut player_ledger: PlayerLedger = env + .storage() + .persistent() + .get(&key) + .unwrap_or(PlayerLedger { + total_earned: 0, + history: Vec::new(&env), + }); + + player_ledger.total_earned = player_ledger.total_earned.checked_add(amount).unwrap(); + + let entry = PointsEntry { + player: player.clone(), + amount, + remaining: amount, + reason_code: reason_code.clone(), + earned_at: now, + expires_at, + caller: caller.clone(), + }; + + player_ledger.history.push_back(entry); + env.storage().persistent().set(&key, &player_ledger); + + // Emit earn event: (earn, player) -> (amount, reason_code, caller, expires_at) + env.events().publish( + (symbol_short!("earn"), player), + (amount, reason_code, caller, expires_at), + ); + + Ok(()) + } + + /// Standard earn function using default expiration + pub fn earn( + env: Env, + caller: Address, + player: Address, + amount: u64, + reason_code: Symbol, + ) -> Result<(), PointsLedgerError> { + Self::earn_with_expiry(env, caller, player, amount, reason_code, 0) + } + + /// Spend points at in-game shop, strictly enforcing FIFO consumption of oldest unexpired points. + /// Rejects if spending exceeds available unexpired points balance. + pub fn spend( + env: Env, + player: Address, + amount_to_spend: u64, + reason_code: Symbol, + ) -> Result { + player.require_auth(); + + if amount_to_spend == 0 { + return Err(PointsLedgerError::InvalidAmount); + } + + let key = (LEDGER, player.clone()); + let mut player_ledger: PlayerLedger = match env.storage().persistent().get(&key) { + Some(l) => l, + None => return Err(PointsLedgerError::InsufficientBalance), + }; + + let now = env.ledger().timestamp(); + + // Calculate available unexpired balance + let mut available: u64 = 0; + for i in 0..player_ledger.history.len() { + let entry = player_ledger.history.get(i).unwrap(); + if entry.remaining > 0 && (entry.expires_at == 0 || now <= entry.expires_at) { + available = available.saturating_add(entry.remaining); + } + } + + if available < amount_to_spend { + return Err(PointsLedgerError::InsufficientBalance); + } + + // Enforce FIFO consumption: consume oldest unexpired points first + let mut remaining_to_spend = amount_to_spend; + let mut updated_history = Vec::new(&env); + + for i in 0..player_ledger.history.len() { + let mut entry = player_ledger.history.get(i).unwrap(); + let is_unexpired = entry.expires_at == 0 || now <= entry.expires_at; + + if remaining_to_spend > 0 && entry.remaining > 0 && is_unexpired { + let to_consume = remaining_to_spend.min(entry.remaining); + entry.remaining -= to_consume; + remaining_to_spend -= to_consume; + } + updated_history.push_back(entry); + } + + player_ledger.history = updated_history; + env.storage().persistent().set(&key, &player_ledger); + + let new_balance = available - amount_to_spend; + + // Emit spend event: (spend, player) -> (amount, reason_code, new_balance) + env.events().publish( + (symbol_short!("spend"), player), + (amount_to_spend, reason_code, new_balance), + ); + + Ok(new_balance) + } + + /// Get current spendable (unexpired) points balance for a player + pub fn get_balance(env: Env, player: Address) -> u64 { + let key = (LEDGER, player); + let player_ledger: Option = env.storage().persistent().get(&key); + let now = env.ledger().timestamp(); + + match player_ledger { + Some(l) => { + let mut sum: u64 = 0; + for i in 0..l.history.len() { + let entry = l.history.get(i).unwrap(); + if entry.remaining > 0 && (entry.expires_at == 0 || now <= entry.expires_at) { + sum = sum.saturating_add(entry.remaining); + } + } + sum + } + None => 0, + } + } + + /// Get total cumulative points earned over all time + pub fn get_total_earned(env: Env, player: Address) -> u64 { + let key = (LEDGER, player); + let player_ledger: Option = env.storage().persistent().get(&key); + match player_ledger { + Some(l) => l.total_earned, + None => 0, + } + } + + /// Get complete points ledger history for a player + pub fn get_history(env: Env, player: Address) -> Vec { + let key = (LEDGER, player); + let player_ledger: Option = env.storage().persistent().get(&key); + match player_ledger { + Some(l) => l.history, + None => Vec::new(&env), + } + } + + /// Transfer contract admin role. Admin only. + pub fn transfer_admin( + env: Env, + current_admin: Address, + new_admin: Address, + ) -> Result<(), PointsLedgerError> { + 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<(), PointsLedgerError> { + admin.require_auth(); + + let stored_admin: Option
= env.storage().instance().get(&ADMIN); + + match stored_admin { + Some(stored) if stored == *admin => Ok(()), + Some(_) => Err(PointsLedgerError::NotAuthorized), + None => Err(PointsLedgerError::AdminNotFound), + } + } +} diff --git a/contracts/points_ledger/src/test.rs b/contracts/points_ledger/src/test.rs new file mode 100644 index 0000000..62eec0e --- /dev/null +++ b/contracts/points_ledger/src/test.rs @@ -0,0 +1,137 @@ +use super::*; +use soroban_sdk::{ + testutils::{Address as _, Ledger}, + Env, +}; + +struct TestFixture { + env: Env, + _admin: Address, + game_contract: Address, + player: Address, +} + +impl TestFixture { + fn setup() -> (Self, PointsLedgerContractClient<'static>) { + let env = Env::default(); + env.mock_all_auths(); + + let admin = Address::generate(&env); + let game_contract = Address::generate(&env); + let player = Address::generate(&env); + + let contract_id = env.register_contract(None, PointsLedgerContract); + let client = PointsLedgerContractClient::new(&env, &contract_id); + + client.initialize(&admin); + client.authorize_caller(&admin, &game_contract); + + let fixture = Self { + env, + _admin: admin, + game_contract, + player, + }; + + (fixture, client) + } +} + +#[test] +fn test_authorized_earn_and_balance_equals_sum() { + let (f, client) = TestFixture::setup(); + + let reason_puzzle = Symbol::new(&f.env, "PUZZLE_1"); + let reason_achieve = Symbol::new(&f.env, "ACHIEVE_1"); + + // Unauthorized caller cannot award points + let stranger = Address::generate(&f.env); + let res = client.try_earn(&stranger, &f.player, &100, &reason_puzzle); + assert_eq!(res, Err(Ok(PointsLedgerError::NotAuthorized))); + + // Authorized game contract awards points + client.earn(&f.game_contract, &f.player, &150, &reason_puzzle); + client.earn(&f.game_contract, &f.player, &50, &reason_achieve); + + assert_eq!(client.get_balance(&f.player), 200); + assert_eq!(client.get_total_earned(&f.player), 200); + + let history = client.get_history(&f.player); + assert_eq!(history.len(), 2); + assert_eq!(history.get(0).unwrap().amount, 150); + assert_eq!(history.get(1).unwrap().amount, 50); +} + +#[test] +fn test_fifo_consumption_order() { + let (f, client) = TestFixture::setup(); + + let tag1 = Symbol::new(&f.env, "FIRST"); + let tag2 = Symbol::new(&f.env, "SECOND"); + let tag3 = Symbol::new(&f.env, "THIRD"); + + // Earn 3 distinct batches: 100, 50, 200 (Total = 350) + client.earn(&f.game_contract, &f.player, &100, &tag1); + client.earn(&f.game_contract, &f.player, &50, &tag2); + client.earn(&f.game_contract, &f.player, &200, &tag3); + + assert_eq!(client.get_balance(&f.player), 350); + + // Spend 120 points at shop: + // Should consume all 100 from FIRST batch, and 20 from SECOND batch! + let shop_reason = Symbol::new(&f.env, "SHOP_SWORD"); + let remaining = client.spend(&f.player, &120, &shop_reason); + assert_eq!(remaining, 230); + assert_eq!(client.get_balance(&f.player), 230); + + let history = client.get_history(&f.player); + // Batch 1 (100) has remaining = 0 + assert_eq!(history.get(0).unwrap().remaining, 0); + // Batch 2 (50) has remaining = 30 + assert_eq!(history.get(1).unwrap().remaining, 30); + // Batch 3 (200) has remaining = 200 + assert_eq!(history.get(2).unwrap().remaining, 200); +} + +#[test] +fn test_expired_points_excluded_from_balance_and_spend() { + let (f, client) = TestFixture::setup(); + + let tag_expiring = Symbol::new(&f.env, "TIMED"); + let tag_permanent = Symbol::new(&f.env, "PERM"); + + // Earn 100 expiring in 3600 seconds, and 50 permanent (validity = 0) + client.earn_with_expiry(&f.game_contract, &f.player, &100, &tag_expiring, &3600); + client.earn_with_expiry(&f.game_contract, &f.player, &50, &tag_permanent, &0); + + assert_eq!(client.get_balance(&f.player), 150); + + // Fast-forward ledger time past 3600 seconds (e.g. 4000s) + f.env.ledger().with_mut(|l| l.timestamp += 4000); + + // Expired points must be excluded from available balance + assert_eq!(client.get_balance(&f.player), 50); + + // Attempting to spend 60 points must fail with InsufficientBalance + let shop_reason = Symbol::new(&f.env, "POTION"); + let res = client.try_spend(&f.player, &60, &shop_reason); + assert_eq!(res, Err(Ok(PointsLedgerError::InsufficientBalance))); + + // Spending 30 points succeeds from unexpired balance + let remaining = client.spend(&f.player, &30, &shop_reason); + assert_eq!(remaining, 20); + assert_eq!(client.get_balance(&f.player), 20); +} + +#[test] +fn test_spending_exceeding_balance_fails() { + let (f, client) = TestFixture::setup(); + let tag = Symbol::new(&f.env, "BONUS"); + + client.earn(&f.game_contract, &f.player, &50, &tag); + + // Attempting to spend 51 points fails + let shop = Symbol::new(&f.env, "ITEM"); + let res = client.try_spend(&f.player, &51, &shop); + assert_eq!(res, Err(Ok(PointsLedgerError::InsufficientBalance))); +}