diff --git a/peerx-contracts/counter/portfolio.rs b/peerx-contracts/counter/portfolio.rs index 2f05816..1b5d063 100644 --- a/peerx-contracts/counter/portfolio.rs +++ b/peerx-contracts/counter/portfolio.rs @@ -881,20 +881,15 @@ impl Portfolio { } /// Get the top N traders by PnL (leaderboard) - /// Capped at top 100 for safety /// Returns Vec<(Address, i128)>: list of (user, pnl) pairs sorted by PnL descending - /// Time complexity: O(1) - precomputed top 100 + /// Time complexity: O(limit) — iterates only up to the requested count. pub fn get_top_traders(&self, env: &Env, limit: u32) -> Vec<(Address, i128)> { - let max_limit: u32 = 100; - let actual_limit = if limit > max_limit { max_limit } else { limit }; - let mut result = Vec::new(env); - let len = self.top_traders.len() as usize; - let limit_usize: usize = actual_limit as usize; - let cap = if len < limit_usize { len } else { limit_usize }; + let len = self.top_traders.len(); + let cap = if (len as u32) < limit { len } else { limit as usize }; - for i in 0..cap { - if let Some(trader) = self.top_traders.get(i as u32) { + for i in 0..cap as u32 { + if let Some(trader) = self.top_traders.get(i) { result.push_back(trader); } } diff --git a/peerx-contracts/counter/src/lib.rs b/peerx-contracts/counter/src/lib.rs index da3f5ad..0d63e72 100644 --- a/peerx-contracts/counter/src/lib.rs +++ b/peerx-contracts/counter/src/lib.rs @@ -319,17 +319,12 @@ fn apply_trader_limit( traders: Vec<(Address, i128)>, limit: u32, ) -> Vec<(Address, i128)> { - let max_limit = if limit > 100 { 100 } else { limit }; let mut result = Vec::new(env); - let len = traders.len() as usize; - let cap = if len < max_limit as usize { - len - } else { - max_limit as usize - }; + let len = traders.len() as u32; + let cap = if len < limit { len } else { limit }; for i in 0..cap { - if let Some(entry) = traders.get(i as u32) { + if let Some(entry) = traders.get(i) { result.push_back(entry); } } @@ -775,7 +770,8 @@ impl CounterContract { .get(&()) .unwrap_or_else(|| Portfolio::new(&env)); - let traders = portfolio.get_top_traders(&env, 100); + let candidate_limit = if limit > 100 { limit } else { limit.max(100) }; + let traders = portfolio.get_top_traders(&env, candidate_limit); env.storage().instance().set( &TOP_TRADERS_CACHE_KEY, &CachedTopTraders {