Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
398 changes: 250 additions & 148 deletions contracts/predictify-hybrid/src/admin.rs

Large diffs are not rendered by default.

127 changes: 68 additions & 59 deletions contracts/predictify-hybrid/src/batch_operations.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use soroban_sdk::{
contracttype, vec, Address, Env, Map, String, Symbol, Vec,
};
use alloc::format;
use alloc::string::ToString;
use soroban_sdk::{contracttype, vec, Address, Env, Map, String, Symbol, Vec};

use crate::errors::Error;
use crate::types::*;
Expand All @@ -12,14 +10,14 @@ use crate::types::*;
#[derive(Clone, Debug, PartialEq, Eq)]
#[contracttype]
pub enum BatchOperationType {
Vote, // Batch vote operations
Claim, // Batch claim operations
CreateMarket, // Batch market creation
OracleCall, // Batch oracle calls
Dispute, // Batch dispute operations
Extension, // Batch market extensions
Resolution, // Batch market resolutions
FeeCollection, // Batch fee collection
Vote, // Batch vote operations
Claim, // Batch claim operations
CreateMarket, // Batch market creation
OracleCall, // Batch oracle calls
Dispute, // Batch dispute operations
Extension, // Batch market extensions
Resolution, // Batch market resolutions
FeeCollection, // Batch fee collection
}

#[derive(Clone, Debug)]
Expand Down Expand Up @@ -132,7 +130,7 @@ pub struct BatchProcessor;

impl BatchProcessor {
// ===== STORAGE KEYS =====

const BATCH_QUEUE_KEY: &'static str = "batch_operation_queue";
const BATCH_STATS_KEY: &'static str = "batch_operation_statistics";
const BATCH_CONFIG_KEY: &'static str = "batch_operation_config";
Expand Down Expand Up @@ -160,12 +158,18 @@ impl BatchProcessor {
gas_efficiency_ratio: 1,
};

env.storage().instance().set(&Symbol::new(env, Self::BATCH_CONFIG_KEY), &config);
env.storage().instance().set(&Symbol::new(env, Self::BATCH_STATS_KEY), &stats);

env.storage()
.instance()
.set(&Symbol::new(env, Self::BATCH_CONFIG_KEY), &config);
env.storage()
.instance()
.set(&Symbol::new(env, Self::BATCH_STATS_KEY), &stats);

// Initialize empty batch queue
let queue: Vec<BatchOperation> = Vec::new(env);
env.storage().instance().set(&Symbol::new(env, Self::BATCH_QUEUE_KEY), &queue);
env.storage()
.instance()
.set(&Symbol::new(env, Self::BATCH_QUEUE_KEY), &queue);

Ok(())
}
Expand All @@ -179,29 +183,28 @@ impl BatchProcessor {
}

/// Update batch processor configuration
pub fn update_config(
env: &Env,
admin: &Address,
config: &BatchConfig,
) -> Result<(), Error> {
pub fn update_config(env: &Env, admin: &Address, config: &BatchConfig) -> Result<(), Error> {
// Validate admin permissions
crate::admin::AdminAccessControl::validate_admin_for_action(env, admin, "update_batch_config")?;
crate::admin::AdminAccessControl::validate_admin_for_action(
env,
admin,
"update_batch_config",
)?;

// Validate configuration
Self::validate_batch_config(config)?;

env.storage().instance().set(&Symbol::new(env, Self::BATCH_CONFIG_KEY), config);
env.storage()
.instance()
.set(&Symbol::new(env, Self::BATCH_CONFIG_KEY), config);

Ok(())
}

// ===== BATCH VOTE OPERATIONS =====

/// Process batch vote operations
pub fn batch_vote(
env: &Env,
votes: &Vec<VoteData>,
) -> Result<BatchResult, Error> {
pub fn batch_vote(env: &Env, votes: &Vec<VoteData>) -> Result<BatchResult, Error> {
let config = Self::get_config(env)?;
let start_time = env.ledger().timestamp();
let mut successful_operations = 0;
Expand Down Expand Up @@ -255,7 +258,7 @@ impl BatchProcessor {

// Check if market exists and is open
let market = crate::markets::MarketStateManager::get_market(env, &vote_data.market_id)?;

if market.end_time <= env.ledger().timestamp() {
return Err(Error::MarketClosed);
}
Expand All @@ -275,10 +278,7 @@ impl BatchProcessor {
// ===== BATCH CLAIM OPERATIONS =====

/// Process batch claim operations
pub fn batch_claim(
env: &Env,
claims: &Vec<ClaimData>,
) -> Result<BatchResult, Error> {
pub fn batch_claim(env: &Env, claims: &Vec<ClaimData>) -> Result<BatchResult, Error> {
let config = Self::get_config(env)?;
let start_time = env.ledger().timestamp();
let mut successful_operations = 0;
Expand Down Expand Up @@ -332,7 +332,7 @@ impl BatchProcessor {

// Check if market exists and is resolved
let market = crate::markets::MarketStateManager::get_market(env, &claim_data.market_id)?;

if !market.is_resolved() {
return Err(Error::MarketNotResolved);
}
Expand All @@ -356,7 +356,11 @@ impl BatchProcessor {
markets: &Vec<MarketData>,
) -> Result<BatchResult, Error> {
// Validate admin permissions
crate::admin::AdminAccessControl::validate_admin_for_action(env, admin, "batch_create_markets")?;
crate::admin::AdminAccessControl::validate_admin_for_action(
env,
admin,
"batch_create_markets",
)?;

let config = Self::get_config(env)?;
let start_time = env.ledger().timestamp();
Expand Down Expand Up @@ -429,10 +433,7 @@ impl BatchProcessor {
// ===== BATCH ORACLE CALLS =====

/// Process batch oracle calls
pub fn batch_oracle_calls(
env: &Env,
feeds: &Vec<OracleFeed>,
) -> Result<BatchResult, Error> {
pub fn batch_oracle_calls(env: &Env, feeds: &Vec<OracleFeed>) -> Result<BatchResult, Error> {
let config = Self::get_config(env)?;
let start_time = env.ledger().timestamp();
let mut successful_operations = 0;
Expand Down Expand Up @@ -486,7 +487,7 @@ impl BatchProcessor {

// Check if market exists
let market = crate::markets::MarketStateManager::get_market(env, &feed_data.market_id)?;

if market.is_resolved() {
return Err(Error::MarketAlreadyResolved);
}
Expand All @@ -507,9 +508,7 @@ impl BatchProcessor {
// ===== BATCH OPERATION VALIDATION =====

/// Validate batch operations
pub fn validate_batch_operations(
operations: &Vec<BatchOperation>,
) -> Result<(), Error> {
pub fn validate_batch_operations(operations: &Vec<BatchOperation>) -> Result<(), Error> {
if operations.is_empty() {
return Err(Error::InvalidInput);
}
Expand Down Expand Up @@ -593,26 +592,28 @@ impl BatchProcessor {
BatchOperationType::FeeCollection => "fee_collection",
};

let current_count = error_counts.get(String::from_str(env, error_type)).unwrap_or(0);
let current_count = error_counts
.get(String::from_str(env, error_type))
.unwrap_or(0);
error_counts.set(String::from_str(env, error_type), current_count + 1);
}

// Create error summary
error_summary.set(
String::from_str(env, "total_errors"),
String::from_str(env, &errors.len().to_string())
String::from_str(env, &errors.len().to_string()),
);

error_summary.set(
String::from_str(env, "error_types"),
String::from_str(env, "See error_counts for breakdown")
String::from_str(env, "See error_counts for breakdown"),
);

// Add error counts
for (error_type, count) in error_counts.iter() {
error_summary.set(
String::from_str(env, &format!("{:?}_errors", error_type)),
String::from_str(env, &count.to_string())
String::from_str(env, &count.to_string()),
);
}

Expand Down Expand Up @@ -640,12 +641,15 @@ impl BatchProcessor {

// Update average batch size
if stats.total_batches_processed > 0 {
stats.average_batch_size = stats.total_operations_processed / stats.total_batches_processed;
stats.average_batch_size =
stats.total_operations_processed / stats.total_batches_processed;
}

// Update average execution time
if stats.total_batches_processed > 0 {
let total_time = stats.average_execution_time * (stats.total_batches_processed - 1) as u64 + result.execution_time;
let total_time = stats.average_execution_time
* (stats.total_batches_processed - 1) as u64
+ result.execution_time;
stats.average_execution_time = total_time / stats.total_batches_processed as u64;
}

Expand All @@ -655,7 +659,9 @@ impl BatchProcessor {
stats.gas_efficiency_ratio = (success_rate * 100.0) as u64;
}

env.storage().instance().set(&Symbol::new(env, Self::BATCH_STATS_KEY), &stats);
env.storage()
.instance()
.set(&Symbol::new(env, Self::BATCH_STATS_KEY), &stats);

Ok(())
}
Expand Down Expand Up @@ -767,7 +773,7 @@ impl BatchUtils {
operation_type: &BatchOperationType,
) -> Result<u32, Error> {
let config = BatchProcessor::get_config(env)?;

match operation_type {
BatchOperationType::Vote => Ok(config.max_batch_size.min(20)),
BatchOperationType::Claim => Ok(config.max_batch_size.min(15)),
Expand All @@ -792,15 +798,12 @@ impl BatchUtils {

let success_rate = successful_operations as f64 / total_operations as f64;
let operations_per_gas = total_operations as f64 / gas_used as f64;

success_rate * operations_per_gas
}

/// Estimate gas cost for batch operation
pub fn estimate_gas_cost(
operation_type: &BatchOperationType,
operation_count: u32,
) -> u64 {
pub fn estimate_gas_cost(operation_type: &BatchOperationType, operation_count: u32) -> u64 {
let base_cost = match operation_type {
BatchOperationType::Vote => 1000,
BatchOperationType::Claim => 1500,
Expand All @@ -826,7 +829,10 @@ impl BatchTesting {
pub fn create_test_vote_data(env: &Env, market_id: &Symbol) -> VoteData {
VoteData {
market_id: market_id.clone(),
voter: Address::from_string(&String::from_str(env, "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF")),
voter: Address::from_string(&String::from_str(
env,
"GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
)),
outcome: String::from_str(env, "Yes"),
stake_amount: 1_000_000_000, // 100 XLM
}
Expand All @@ -836,7 +842,10 @@ impl BatchTesting {
pub fn create_test_claim_data(env: &Env, market_id: &Symbol) -> ClaimData {
ClaimData {
market_id: market_id.clone(),
claimant: Address::from_string(&String::from_str(env, "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF")),
claimant: Address::from_string(&String::from_str(
env,
"GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
)),
expected_amount: 2_000_000_000, // 200 XLM
}
}
Expand All @@ -848,7 +857,7 @@ impl BatchTesting {
outcomes: vec![
&env,
String::from_str(env, "Yes"),
String::from_str(env, "No")
String::from_str(env, "No"),
],
duration_days: 30,
oracle_config: crate::types::OracleConfig {
Expand Down Expand Up @@ -910,4 +919,4 @@ impl BatchTesting {
execution_time,
})
}
}
}
Loading
Loading