fix: resolve all remaining clippy warnings in examples and benchmarks including unused imports, variables, empty println statements, and enum naming conventions

This commit is contained in:
floor-licker
2025-12-04 07:37:40 -05:00
parent 3742a5b864
commit 88f116511c
20 changed files with 63 additions and 63 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ use polyfill_rs::{
book::OrderBook,
types::{OrderDelta, Side},
};
use rust_decimal::{Decimal, Decimal as RustDecimal};
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use std::time::Instant;
+1 -1
View File
@@ -1,5 +1,5 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use polyfill_rs::{ClobClient, OrderArgs, Side, OrderBookImpl};
use polyfill_rs::{OrderArgs, Side, OrderBookImpl};
use rust_decimal::Decimal;
use std::str::FromStr;
+1 -1
View File
@@ -9,7 +9,7 @@ use polyfill_rs::{
fill::{FillEngine, FillProcessor},
types::{FillEvent, MarketOrderRequest, OrderDelta, Side},
};
use rust_decimal::{Decimal, Decimal as RustDecimal};
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use std::time::Instant;
+1 -1
View File
@@ -55,7 +55,7 @@ fn benchmark_real_order_creation(c: &mut Criterion) {
let client = ClobClient::new("https://clob.polymarket.com");
// Set up credentials
if let Ok(key) = std::env::var("POLYMARKET_PRIVATE_KEY") {
if let Ok(_key) = std::env::var("POLYMARKET_PRIVATE_KEY") {
// This would require implementing credential setup
// let creds = ApiCredentials::from_private_key(&key)?;
// client.set_credentials(creds);
+1 -1
View File
@@ -185,7 +185,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Collect some samples
for i in 0..5 {
let start = Instant::now();
if let Ok(_) = client.get_server_time().await {
if (client.get_server_time().await).is_ok() {
let duration = start.elapsed();
adaptive_timeout.add_sample(duration);
if i < 3 {
+1 -1
View File
@@ -33,7 +33,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
for i in 0..3 {
let start = Instant::now();
match client.create_or_derive_api_key(None).await {
Ok(creds) => {
Ok(_creds) => {
let duration = start.elapsed();
setup_times.push(duration);
println!(" Run {}: ✅ API key setup in {:?}", i+1, duration);
+1 -1
View File
@@ -151,7 +151,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("• Fixed-point arithmetic in hot paths");
println!("• Zero-allocation order book operations");
println!("• Cache-friendly memory layouts");
println!("");
println!();
println!("🔬 Run `cargo bench` for detailed criterion benchmarks");
println!("📊 Run `./scripts/benchmark_comparison.sh` for comprehensive analysis");
+2 -1
View File
@@ -42,6 +42,7 @@ use tokio::time::sleep;
use tracing::{error, info, debug};
/// Comprehensive demo showcasing all polyfill-rs functionality
#[allow(dead_code)]
pub struct PolyfillDemo {
/// Basic HTTP client
client: ClobClient,
@@ -513,7 +514,7 @@ impl PolyfillDemo {
if rand::random::<bool>() {
Ok("Success!")
} else {
Err(PolyfillError::network("Simulated network error", std::io::Error::new(std::io::ErrorKind::Other, "Simulated error")))
Err(PolyfillError::network("Simulated network error", std::io::Error::other("Simulated error")))
}
};
+1 -1
View File
@@ -53,7 +53,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("==============================================");
println!("Comparing with polymarket-rs-client baseline:");
println!(" 88,053 allocs, 81,823 frees, 15,945,966 bytes allocated");
println!("");
println!();
// Load environment variables
dotenv::dotenv().ok();
+1 -1
View File
@@ -110,7 +110,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("• Processing cached/local data");
println!("• Running in co-located environments");
println!("• Performing high-frequency operations");
println!("");
println!();
println!("For fair comparison with polymarket-rs-client:");
println!("• Run from same geographic location");
println!("• Use same network conditions");
+4 -6
View File
@@ -1,6 +1,4 @@
use polyfill_rs::{ClobClient, OrderArgs, Side};
use rust_decimal::Decimal;
use std::str::FromStr;
use polyfill_rs::ClobClient;
use std::time::Instant;
#[tokio::main]
@@ -19,7 +17,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!(" 1. Private key for EIP-712 signing");
println!(" 2. Proper client initialization with credentials");
println!(" 3. Valid market context for orders");
println!("");
println!();
// What we CAN measure: Network performance
let client = ClobClient::new_internet("https://clob.polymarket.com");
@@ -86,7 +84,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Based on our network measurements:");
println!(" • Network baseline: {:?}", baseline_avg);
println!(" • Market data: {:?} (3.8x faster than original)", market_avg);
println!("");
println!();
println!("For order creation (266.5ms original):");
println!(" • Network component: ~{:?} (measured)", baseline_avg);
@@ -103,7 +101,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!(" ✅ Network baseline: {:?}", baseline_avg);
println!(" ✅ Market data: {:?} (3.8x faster)", market_avg);
println!(" ✅ Computational: microsecond-scale operations");
println!("");
println!();
println!("What we estimate:");
println!(" 📊 Order creation: ~{:?} (vs 266.5ms = 2.2x faster)",
baseline_avg + std::time::Duration::from_millis(15));
+2 -7
View File
@@ -5,7 +5,6 @@
use polyfill_rs::{ClobClient, Side, Result, PolyfillError};
use rust_decimal::Decimal;
use std::str::FromStr;
use tokio::time::{sleep, Duration};
use tracing::{info, error, warn};
@@ -67,7 +66,7 @@ async fn test_connectivity(client: &ClobClient) -> Result<()> {
// Test /ok endpoint
let is_ok = client.get_ok().await;
if !is_ok {
return Err(PolyfillError::network("API not responding", std::io::Error::new(std::io::ErrorKind::Other, "API not responding")));
return Err(PolyfillError::network("API not responding", std::io::Error::other("API not responding")));
}
info!(" /ok endpoint responding");
@@ -81,11 +80,7 @@ async fn test_connectivity(client: &ClobClient) -> Result<()> {
.unwrap()
.as_secs();
let time_diff = if server_time > current_time {
server_time - current_time
} else {
current_time - server_time
};
let time_diff = server_time.abs_diff(current_time);
if time_diff > 86400 { // 24 hours
warn!(" Server time seems off (diff: {} seconds)", time_diff);
+2 -2
View File
@@ -112,7 +112,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// First, try to create or derive API key
match client.create_or_derive_api_key(None).await {
Ok(creds) => {
Ok(_creds) => {
println!(" 🔑 API credentials set up successfully");
// Now test order creation
@@ -127,7 +127,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let start = Instant::now();
match client.create_order(&order_args, None, None, None).await {
Ok(order) => {
Ok(_order) => {
let duration = start.elapsed();
times.push(duration);
if i < 2 {
+1 -1
View File
@@ -322,7 +322,7 @@ impl MockMarketData {
// Generate random price movement
let random_factor = Decimal::from(rand::random::<i64>() % 100 - 50) / Decimal::from(100);
let volatility_f64 = self.volatility.to_f64().unwrap_or(0.01);
let _volatility_f64 = self.volatility.to_f64().unwrap_or(0.01);
let price_change = random_factor * Decimal::from(2) * self.volatility;
let new_price = self.base_price * (Decimal::from(1) + price_change);
+18 -18
View File
@@ -202,7 +202,7 @@ impl ClobClient {
/// Get order book for a token
pub async fn get_order_book(&self, token_id: &str) -> Result<OrderBookSummary> {
let response = self.http_client
.get(&format!("{}/book", self.base_url))
.get(format!("{}/book", self.base_url))
.query(&[("token_id", token_id)])
.send()
.await?;
@@ -218,7 +218,7 @@ impl ClobClient {
/// Get midpoint for a token
pub async fn get_midpoint(&self, token_id: &str) -> Result<MidpointResponse> {
let response = self.http_client
.get(&format!("{}/midpoint", self.base_url))
.get(format!("{}/midpoint", self.base_url))
.query(&[("token_id", token_id)])
.send()
.await?;
@@ -234,7 +234,7 @@ impl ClobClient {
/// Get spread for a token
pub async fn get_spread(&self, token_id: &str) -> Result<SpreadResponse> {
let response = self.http_client
.get(&format!("{}/spread", self.base_url))
.get(format!("{}/spread", self.base_url))
.query(&[("token_id", token_id)])
.send()
.await?;
@@ -259,7 +259,7 @@ impl ClobClient {
.collect();
let response = self.http_client
.post(&format!("{}/spreads", self.base_url))
.post(format!("{}/spreads", self.base_url))
.json(&request_data)
.send()
.await?;
@@ -275,7 +275,7 @@ impl ClobClient {
/// Get price for a token and side
pub async fn get_price(&self, token_id: &str, side: Side) -> Result<PriceResponse> {
let response = self.http_client
.get(&format!("{}/price", self.base_url))
.get(format!("{}/price", self.base_url))
.query(&[
("token_id", token_id),
("side", side.as_str()),
@@ -294,7 +294,7 @@ impl ClobClient {
/// Get tick size for a token
pub async fn get_tick_size(&self, token_id: &str) -> Result<Decimal> {
let response = self.http_client
.get(&format!("{}/tick-size", self.base_url))
.get(format!("{}/tick-size", self.base_url))
.query(&[("token_id", token_id)])
.send()
.await?;
@@ -413,7 +413,7 @@ impl ClobClient {
/// Get neg risk for a token
pub async fn get_neg_risk(&self, token_id: &str) -> Result<bool> {
let response = self.http_client
.get(&format!("{}/neg-risk", self.base_url))
.get(format!("{}/neg-risk", self.base_url))
.query(&[("token_id", token_id)])
.send()
.await?;
@@ -877,7 +877,7 @@ impl ClobClient {
.collect();
let response = self.http_client
.post(&format!("{}/midpoints", self.base_url))
.post(format!("{}/midpoints", self.base_url))
.json(&request_data)
.send()
.await?;
@@ -909,7 +909,7 @@ impl ClobClient {
.collect();
let response = self.http_client
.post(&format!("{}/prices", self.base_url))
.post(format!("{}/prices", self.base_url))
.json(&request_data)
.send()
.await?;
@@ -934,7 +934,7 @@ impl ClobClient {
.collect();
let response = self.http_client
.post(&format!("{}/books", self.base_url))
.post(format!("{}/books", self.base_url))
.json(&request_data)
.send()
.await
@@ -969,7 +969,7 @@ impl ClobClient {
/// Get last trade price for a token
pub async fn get_last_trade_price(&self, token_id: &str) -> Result<Value> {
let response = self.http_client
.get(&format!("{}/last-trade-price", self.base_url))
.get(format!("{}/last-trade-price", self.base_url))
.query(&[("token_id", token_id)])
.send()
.await
@@ -991,7 +991,7 @@ impl ClobClient {
.collect();
let response = self.http_client
.post(&format!("{}/last-trades-prices", self.base_url))
.post(format!("{}/last-trades-prices", self.base_url))
.json(&request_data)
.send()
.await
@@ -1140,7 +1140,7 @@ impl ClobClient {
let next_cursor = next_cursor.unwrap_or("MA=="); // INITIAL_CURSOR
let response = self.http_client
.get(&format!("{}/sampling-markets", self.base_url))
.get(format!("{}/sampling-markets", self.base_url))
.query(&[("next_cursor", next_cursor)])
.send()
.await
@@ -1155,7 +1155,7 @@ impl ClobClient {
let next_cursor = next_cursor.unwrap_or("MA=="); // INITIAL_CURSOR
let response = self.http_client
.get(&format!("{}/sampling-simplified-markets", self.base_url))
.get(format!("{}/sampling-simplified-markets", self.base_url))
.query(&[("next_cursor", next_cursor)])
.send()
.await
@@ -1170,7 +1170,7 @@ impl ClobClient {
let next_cursor = next_cursor.unwrap_or("MA=="); // INITIAL_CURSOR
let response = self.http_client
.get(&format!("{}/markets", self.base_url))
.get(format!("{}/markets", self.base_url))
.query(&[("next_cursor", next_cursor)])
.send()
.await
@@ -1185,7 +1185,7 @@ impl ClobClient {
let next_cursor = next_cursor.unwrap_or("MA=="); // INITIAL_CURSOR
let response = self.http_client
.get(&format!("{}/simplified-markets", self.base_url))
.get(format!("{}/simplified-markets", self.base_url))
.query(&[("next_cursor", next_cursor)])
.send()
.await
@@ -1198,7 +1198,7 @@ impl ClobClient {
/// Get single market by condition ID
pub async fn get_market(&self, condition_id: &str) -> Result<crate::types::Market> {
let response = self.http_client
.get(&format!("{}/markets/{}", self.base_url, condition_id))
.get(format!("{}/markets/{}", self.base_url, condition_id))
.send()
.await
.map_err(|e| PolyfillError::network(format!("Request failed: {}", e), e))?;
@@ -1210,7 +1210,7 @@ impl ClobClient {
/// Get market trades events
pub async fn get_market_trades_events(&self, condition_id: &str) -> Result<Value> {
let response = self.http_client
.get(&format!("{}/live-activity/events/{}", self.base_url, condition_id))
.get(format!("{}/live-activity/events/{}", self.base_url, condition_id))
.send()
.await
.map_err(|e| PolyfillError::network(format!("Request failed: {}", e), e))?;
+1 -1
View File
@@ -409,7 +409,7 @@ impl FillProcessor {
// Add to pending fills
self.pending_fills
.entry(fill.order_id.clone())
.or_insert_with(Vec::new)
.or_default()
.push(fill.clone());
// Move to processed if complete
+1 -1
View File
@@ -13,7 +13,7 @@ pub async fn prewarm_connections(client: &Client, base_url: &str) -> Result<(),
for endpoint in endpoints {
let _ = client
.get(&format!("{}{}", base_url, endpoint))
.get(format!("{}{}", base_url, endpoint))
.timeout(Duration::from_millis(1000))
.send()
.await;
+13
View File
@@ -432,6 +432,12 @@ pub struct MockStream {
connected: bool,
}
impl Default for MockStream {
fn default() -> Self {
Self::new()
}
}
impl MockStream {
pub fn new() -> Self {
Self {
@@ -494,12 +500,19 @@ impl MarketStream for MockStream {
}
/// Stream manager for handling multiple streams
#[allow(dead_code)]
pub struct StreamManager {
streams: Vec<Box<dyn MarketStream>>,
message_tx: mpsc::UnboundedSender<StreamMessage>,
message_rx: mpsc::UnboundedReceiver<StreamMessage>,
}
impl Default for StreamManager {
fn default() -> Self {
Self::new()
}
}
impl StreamManager {
pub fn new() -> Self {
let (message_tx, message_rx) = mpsc::unbounded_channel();
+8 -15
View File
@@ -185,6 +185,7 @@ pub fn is_price_tick_aligned(decimal: Decimal, tick_size_decimal: Decimal) -> bo
/// Trading side for orders
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[allow(clippy::upper_case_acronyms)]
pub enum Side {
BUY = 0,
SELL = 1,
@@ -208,6 +209,7 @@ impl Side {
/// Order type specifications
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[allow(clippy::upper_case_acronyms)]
pub enum OrderType {
GTC,
FOK,
@@ -480,7 +482,7 @@ pub struct Order {
}
/// API credentials for authentication
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ApiCredentials {
#[serde(rename = "apiKey")]
pub api_key: String,
@@ -488,16 +490,6 @@ pub struct ApiCredentials {
pub passphrase: String,
}
impl Default for ApiCredentials {
fn default() -> Self {
Self {
api_key: String::new(),
secret: String::new(),
passphrase: String::new(),
}
}
}
/// Configuration for order creation
#[derive(Debug, Clone)]
pub struct OrderOptions {
@@ -905,16 +897,17 @@ impl BalanceAllowanceParams {
}
/// Asset type enum for balance allowance queries
#[allow(clippy::upper_case_acronyms)]
pub enum AssetType {
COLLATERAL,
CONDITIONAL,
}
impl ToString for AssetType {
fn to_string(&self) -> String {
impl std::fmt::Display for AssetType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AssetType::COLLATERAL => "COLLATERAL".to_string(),
AssetType::CONDITIONAL => "CONDITIONAL".to_string(),
AssetType::COLLATERAL => write!(f, "COLLATERAL"),
AssetType::CONDITIONAL => write!(f, "CONDITIONAL"),
}
}
}
+2 -2
View File
@@ -67,7 +67,7 @@ pub mod time {
#[inline]
pub fn secs_to_datetime(timestamp: u64) -> DateTime<Utc> {
DateTime::from_timestamp(timestamp as i64, 0)
.unwrap_or_else(|| Utc::now())
.unwrap_or_else(Utc::now)
}
}
@@ -392,7 +392,7 @@ pub mod retry {
}
}
Err(last_error.unwrap_or_else(|| PolyfillError::internal("Retry loop failed", std::io::Error::new(std::io::ErrorKind::Other, "No error captured"))))
Err(last_error.unwrap_or_else(|| PolyfillError::internal("Retry loop failed", std::io::Error::other("No error captured"))))
}
}