Skip to content

Latest commit

 

History

History
400 lines (303 loc) · 10.1 KB

File metadata and controls

400 lines (303 loc) · 10.1 KB

SDK Configuration

Overview

The SDK Configuration module provides a type-safe way to configure AnchorKit SDK client connections with network settings, anchor domains, timeouts, and custom HTTP headers.

Table of Contents

Data Structures

SdkConfig

Main configuration structure for SDK clients.

pub struct SdkConfig {
    pub network: NetworkType,
    pub anchor_domain: String,
    pub timeout_seconds: u64,
    pub custom_headers: Vec<HttpHeader>,
}

NetworkType

Enum for Stellar network selection.

pub enum NetworkType {
    Testnet = 1,
    Mainnet = 2,
}

HttpHeader

Custom HTTP header for API requests.

pub struct HttpHeader {
    pub key: String,
    pub value: String,
}

Feature Flags

mock-only

The mock-only feature flag is defined in Cargo.toml but is currently not implemented in the codebase.

Current Status

⚠️ Important: This feature flag exists as a placeholder but does not currently affect code behavior. No conditional compilation directives (#[cfg(feature = "mock-only")]) are present in the source code.

Intended Purpose

When implemented, the mock-only feature would be designed for:

  • Unit testing: Run tests without external dependencies
  • Development: Develop and debug without live anchor services
  • CI/CD pipelines: Ensure tests run reliably in isolated environments
  • Integration testing: Test application logic with predictable responses

Current Usage

Currently, you can build with the feature flag, but it has no effect:

# This builds successfully but mock-only has no effect
cargo build --no-default-features --features mock-only
cargo test --no-default-features --features mock-only

Implementation Status

To implement this feature, the codebase would need:

  1. Conditional compilation directives in relevant modules:
#[cfg(feature = "mock-only")]
fn fetch_anchor_info() -> MockResponse {
    // Mock implementation
}

#[cfg(not(feature = "mock-only"))]
fn fetch_anchor_info() -> RealResponse {
    // Real implementation  
}
  1. Mock implementations for:
    • Network requests and HTTP calls
    • SEP-10 authentication flows
    • Transaction operations (deposits/withdrawals)
    • Anchor discovery and info fetching
    • Rate limiting and timing

Mock Testing (Current Approach)

Currently, mock testing is achieved through:

  1. Soroban SDK test utilities:
#[cfg(test)]
mod tests {
    use soroban_sdk::Env;
    
    #[test]
    fn test_function() {
        let env = Env::default();
        env.mock_all_auths(); // Mock authentication
        // Test logic here
    }
}
  1. Mock server for HTTP testing:
# Start the mock anchor server
python3 mock-server.py

# Test against mock server
export ANCHOR_URL=http://localhost:8080
cargo test

Future Implementation

To implement the mock-only feature:

  1. Add conditional compilation to network-related functions
  2. Create mock implementations that return predictable responses
  3. Ensure mock responses match real API schemas
  4. Add feature-specific tests to verify mock behavior

CI/CD Integration

The feature flag is tested in CI pipelines to ensure it compiles:

# .github/workflows/feature-flag-matrix.yml
- name: Build (mock-only)
  run: cargo build --no-default-features --features mock-only

However, since the feature isn't implemented, this only verifies compilation compatibility.

Validation Rules

The SdkConfig::validate() method enforces the following constraints:

Anchor Domain

  • Minimum length: 3 characters
  • Maximum length: 253 characters
  • Format: Valid domain name

Timeout

  • Minimum: 1 second
  • Maximum: 300 seconds (5 minutes)
  • Default: 30 seconds (recommended)

Custom Headers

  • Maximum count: 20 headers
  • Header key length: 1-64 characters
  • Header value length: 0-1024 characters

Usage Example

Rust (Contract)

use soroban_sdk::{Env, String, Vec};

let env = Env::default();

// Create headers
let mut headers = Vec::new(&env);
headers.push_back(HttpHeader {
    key: String::from_str(&env, "Authorization"),
    value: String::from_str(&env, "Bearer token123"),
});

// Create config
let config = SdkConfig {
    network: NetworkType::Testnet,
    anchor_domain: String::from_str(&env, "anchor.example.com"),
    timeout_seconds: 30,
    custom_headers: headers,
};

// Validate
if config.validate() {
    // Use config
}

JavaScript (Client SDK)

const config = {
    network: 'Testnet',
    anchor_domain: 'anchor.example.com',
    timeout_seconds: 30,
    custom_headers: [
        {
            key: 'Authorization',
            value: 'Bearer token123'
        },
        {
            key: 'X-Custom-Header',
            value: 'custom-value'
        }
    ]
};

Configuration Form

An HTML form is provided in sdk_config_form.html for easy configuration generation. The form includes:

  • Network selection (Testnet/Mainnet)
  • Anchor domain input with validation
  • Timeout configuration
  • Dynamic custom header management
  • JSON output generation

Using the Form

  1. Open sdk_config_form.html in a web browser
  2. Select your network (Testnet or Mainnet)
  3. Enter the anchor domain
  4. Set the timeout (default: 30 seconds)
  5. Add custom headers as needed
  6. Click "Generate Configuration" to get JSON output

Security Considerations

Header Security

  • Never include sensitive credentials directly in headers
  • Use secure credential management (see SECURE_CREDENTIALS.md)
  • Rotate tokens regularly
  • Use HTTPS for all anchor communications

Domain Validation

  • Validate anchor domains against a whitelist
  • Use DNS verification for production
  • Implement certificate pinning for critical operations

Timeout Configuration

  • Set appropriate timeouts based on network conditions
  • Consider retry logic for transient failures
  • Monitor timeout rates for performance tuning

Best Practices

Network Selection

  • Use Testnet for development and testing
  • Use Mainnet only for production deployments
  • Never mix testnet and mainnet configurations

Timeout Settings

  • Development: 60-120 seconds (for debugging)
  • Production: 30 seconds (recommended)
  • High-latency networks: 60-90 seconds
  • Low-latency networks: 15-30 seconds

Custom Headers

  • Use headers for:
    • Authentication tokens
    • API versioning
    • Request tracing
    • Custom metadata
  • Avoid headers for:
    • Large payloads (use request body)
    • Sensitive data without encryption
    • Unnecessary metadata

Integration with AnchorKit

The SDK configuration integrates with:

  • Session Management: Timeout settings affect session duration
  • Credential Management: Headers can include auth tokens
  • Health Monitoring: Timeout affects health check intervals
  • Rate Comparison: Network selection determines available anchors
  • Mock Testing: Currently achieved through Soroban SDK test utilities and mock server

Mock Testing Integration

Currently, mock testing is handled through existing mechanisms:

// Using Soroban SDK test utilities (current approach)
let env = Env::default();
env.mock_all_auths(); // Mock authentication for tests

let config = SdkConfig {
    network: NetworkType::Testnet,
    anchor_domain: String::from("test.anchor.com"),
    timeout_seconds: 30,
    custom_headers: vec![],
};

// Tests use real implementations but with mocked Soroban environment

Note: The mock-only feature flag is defined but not yet implemented. When implemented, it would provide compile-time mock behavior.

Testing

Run the SDK configuration tests:

# Run all tests with default features
cargo test sdk_config_tests --lib

# Build with mock-only feature (currently no behavioral difference)
cargo build --no-default-features --features mock-only

# Run specific configuration tests
cargo test sdk_config --lib

Test Coverage

Test coverage includes:

  • Valid configuration validation
  • Domain length constraints
  • Timeout boundary conditions
  • Header count limits
  • Header size constraints
  • Network type enum values
  • Feature flag compilation compatibility

Mock Testing (Current Implementation)

Currently, mock testing uses Soroban SDK utilities:

# Standard test approach with Soroban mocking
cargo test

# Tests use env.mock_all_auths() for authentication mocking
# Use mock-server.py for HTTP endpoint testing
python3 mock-server.py &
cargo test -- --test-threads=1

Note: The mock-only feature flag compiles but doesn't change test behavior yet.

Error Handling

Configuration validation returns a boolean. For detailed error handling, check specific constraints:

if !config.validate() {
    // Check individual constraints
    if config.anchor_domain.len() < 3 {
        // Handle domain too short
    }
    if config.timeout_seconds < 1 || config.timeout_seconds > 300 {
        // Handle invalid timeout
    }
    if config.custom_headers.len() > 20 {
        // Handle too many headers
    }
}

Future Enhancements

Potential improvements:

  • Add retry configuration
  • Support for connection pooling settings
  • Circuit breaker configuration
  • Rate limiting settings
  • Custom DNS resolver configuration
  • Proxy support

Related Documentation