Command: echo '# Cost-Based Debit Routing Implementation Plan for Hyperswitch
This document outlines the implementation plan for cost-based debit routing in Hyperswitch, detailing the necessary changes across card network extensions, configuration additions, core routing module structure, OpenRouter API integration, and payment method handling.
1. Card Network Extensions
1.1 Understanding Existing Card Networks
Hyperswitch already supports various card networks through the CardNetwork enum in /workspace/archit/trace_generation/repos/hyperswitch_pool_0/crates/common_enums/src/enums.rs:
To support cost-based debit routing, we need to extend the existing card network definitions:
Enhance CardNetwork Enum: Add support for specific debit card types:
Debit Visa
Debit Mastercard
Debit Maestro
Debit Switch
Debit Solo
Payment Method Type Extension: Extend the PaymentMethod enum to include debit-specific categories:
rust
pub enum PaymentMethod {
Card,
DebitCard, // New category for debit cards
CardRedirect,
PayLater,
Wallet,
BankRedirect,
// ... other payment methods
}
Connector-Specific Debit Handling: Each connector needs to distinguish between credit and debit card processing costs.
2. Configuration Additions
2.1 Routing Configuration Structure
The routing configuration needs to support cost-based routing rules through updates to the RoutingAlgorithm structure in /workspace/archit/trace_generation/repos/hyperswitch_pool_0/crates/api_models/src/routing.rs.
2.2 Cost-Based Routing Parameters
Add configuration fields for cost-based routing in dynamic routing algorithms:
Add merchant-level configurations to store cost preferences:
rust
// In merchant_account.rs or similar
pub struct MerchantCostConfig {
pub default_cost_model: CostModel,
pub per_network_costs: HashMap<CardNetwork, f64>,
pub surcharge_rules: Vec<SurchargeRule>,
pub cost_optimization_enabled: bool,
}
3. Core Routing Module Structure
3.1 Updated Routing Algorithms
The core routing logic needs enhancements in /workspace/archit/trace_generation/repos/hyperswitch_pool_0/crates/router/src/core/payments/routing.rs:
Cost Calculation Layer: Integrate cost calculation logic into the routing process
Debit-Specific Prioritization: Modify priority algorithms to consider costs
Dynamic Cost Adjustment: Implement real-time cost adjustments based on market conditions
3.2 Routing Algorithm Updates
Extend existing routing algorithm implementations to handle cost-based decisions:
rust
// New cost-aware routing logic
pub async fn perform_cost_based_routing(
state: &SessionState,
payment_data: &PaymentData,
available_connectors: Vec<RoutableConnectorChoice>,
cost_config: &CostBasedRoutingConfig,
) -> Result<Vec<RoutableConnectorChoice>, RoutingError> {
let mut scored_connectors = Vec::new();
for connector in available_connectors {
let cost = calculate_connector_cost(&connector, payment_data, cost_config);
scored_connectors.push((connector, cost));
}
// Sort by cost (ascending for lowest cost first)
scored_connectors.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
Ok(scored_connectors.into_iter().map(|(c, _)| c).collect())
}
3.3 Enhanced Routing Decision Engine
Update the decision engine in the routing core to incorporate cost considerations:
Cost Score Calculation: Each connector gets a cost score based on historical performance and current pricing
Priority Adjustment: Adjust connector priorities based on cost vs. performance trade-offs
Budget Constraints: Implement budget-aware routing for merchants with spending limits
4. OpenRouter API Integration
4.1 Integration Overview
Hyperswitch already integrates with OpenRouter for dynamic routing decisions. The implementation should enhance this integration to support cost-based routing.
4.2 API Endpoints Enhancement
Update OpenRouter API calls to include cost-based parameters:
rust
// In routing/routing.rs
pub async fn perform_cost_based_routing_with_open_router(
state: &SessionState,
routable_connectors: Vec<RoutableConnectorChoice>,
profile: &Profile,
payment_data: PaymentAttempt,
cost_config: &CostBasedRoutingConfig,
) -> Result<Vec<RoutableConnectorChoice>, RoutingError> {
// Construct request with cost parameters
let open_router_req_body = OpenRouterDecideGatewayRequest::construct_sr_request(
&payment_data,
routable_connectors.clone(),
Some(RankingAlgorithm::CostBasedRouting),
cost_config.clone(),
);
// Call OpenRouter with enhanced cost parameters
let response = call_open_router_api(state, open_router_req_body).await?;
// Process response with cost optimization
process_cost_optimized_response(response, cost_config)
}
Modify payment processing to handle cost-based routing decisions:
rust
// In payment_processing.rs
pub async fn process_debit_payment_with_cost_routing(
state: &SessionState,
payment_data: PaymentData,
merchant_config: &MerchantConfig,
) -> Result<PaymentResult, ProcessingError> {
// Determine if debit routing is needed
if is_debit_payment(&payment_data) {
// Apply cost-based routing
let cost_config = merchant_config.cost_config.clone();
let preferred_connectors = perform_cost_based_routing(
state,
&payment_data,
&cost_config,
).await?;
// Process with preferred connectors
process_payment_with_connectors(state, payment_data, preferred_connectors).await
} else {
// Standard routing
process_standard_payment(state, payment_data).await
}
}
5.3 Debit Card Surcharge Handling
Implement surcharge logic specifically for debit card transactions:
rust
// Surcharge calculations for debit cards
pub fn calculate_debit_surcharge(
amount: Amount,
card_network: &CardNetwork,
cost_config: &CostBasedRoutingConfig,
) -> Result<Amount, SurchargeError> {
// Debit cards typically have lower interchange fees but may have fixed processing costs
let base_cost = match card_network {
CardNetwork::Maestro | CardNetwork::Switch => {
cost_config.network_costs.get(card_network).copied().unwrap_or(0.05) // Base cost for debit
},
_ => cost_config.network_costs.get(card_network).copied().unwrap_or(0.10), // Default credit cost
};
let surcharge_amount = amount * base_cost;
Ok(surcharge_amount)
}
5.4 Dynamic Connector Selection for Debit Cards
Implement dynamic selection logic that prioritizes connectors based on:
Processing Cost: Lowest cost for debit transactions
Success Rate: Historical success rates for debit processing
Geographic Proximity: Regional cost advantages
Network Compatibility: Support for specific debit networks
rust
// Enhanced connector selection logic
pub fn select_optimal_debit_connector(
connectors: Vec<RoutableConnectorChoice>,
payment_data: &PaymentData,
cost_config: &CostBasedRoutingConfig,
) -> Result<RoutableConnectorChoice, RoutingError> {
let mut ranked_connectors = Vec::new();
for connector in connectors {
let score = calculate_debit_connector_score(
&connector,
payment_data,
cost_config,
);
ranked_connectors.push((connector, score));
}
// Sort by best score (lowest cost, highest success rate)
ranked_connectors.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
Ok(ranked_connectors.first().unwrap().0.clone())
}
6. Implementation Roadmap
Phase 1: Core Infrastructure (Weeks 1-2)
Extend CardNetwork enum with debit-specific variants
Add DebitCard to PaymentMethod enum
Create cost configuration structures
Update routing algorithm interfaces
Phase 2: Core Routing Logic (Weeks 3-4)
Implement cost calculation logic
Enhance routing decision engine
Add cost-based sorting mechanisms
Update connector selection algorithms
Phase 3: OpenRouter Integration (Weeks 5-6)
Extend OpenRouter API calls with cost parameters
Implement cost tracking mechanisms
Set up feedback loop for cost optimization
Test integration with existing dynamic routing
Phase 4: Payment Method Handling (Weeks 7-8)
Enhance debit card detection
Implement surcharge handling for debit cards
Add dynamic connector selection for debit payments
Comprehensive testing and validation
7. Testing Considerations
7.1 Unit Testing
Test cost calculation functions with various card networks
Validate routing algorithm behavior with different cost configurations
Test connector selection logic with cost parameters
7.2 Integration Testing
Test OpenRouter API integration with cost-based parameters
Verify cost tracking and feedback loop functionality
Validate end-to-end payment processing with debit cards
7.3 Performance Testing
Benchmark cost calculation overhead
Test routing performance with large connector sets
Validate real-time cost adjustment responsiveness
8. Security and Compliance
PCI DSS Compliance: Ensure cost data transmission follows PCI standards
Data Protection: Secure handling of cost-sensitive information
Audit Trail: Maintain logs of cost-based routing decisions for compliance
Privacy Controls: Respect merchant privacy preferences for cost data sharing
This implementation plan provides a comprehensive framework for integrating cost-based debit routing into Hyperswitch while maintaining compatibility with existing systems and extending functionality to support sophisticated payment routing decisions.' > IMPLEMENTATION_PLAN.txt
Output: