# Rialo API Types

This crate contains all the request and response types used by the Rialo RPC API. It provides strongly-typed, validated data structures for all supported RPC endpoints, following the JSON-RPC 2.0 specification with Solana compatibility.

## Features

- **Type Safety**: Strongly typed request and response structures for all RPC endpoints
- **Validation**: Built-in input validation using the `validator` crate  
- **JSON-RPC 2.0**: Full compliance with JSON-RPC 2.0 specification
- **Solana Compatibility**: Compatible with Solana RPC client libraries
- **Serde Support**: Full serialization/deserialization support
- **Documentation**: Comprehensive documentation with examples

## Supported RPC Methods

### Account Operations
- [`getAccountInfo`](src/messages/get_account_info.rs) - Get account information
- [`getBalance`](src/messages/get_balance.rs) - Get account balance  
- [`getMultipleAccounts`](src/messages/get_multiple_accounts.rs) - Get multiple account info

### Transaction Operations  
- [`sendTransaction`](src/messages/send_transaction.rs) - Submit a transaction
- [`getTransaction`](src/messages/get_transaction.rs) - Get transaction details
- [`getSignatureStatuses`](src/messages/get_signature_statuses.rs) - Get transaction statuses
- [`getSignaturesForAddress`](src/messages/get_signatures_for_address.rs) - Get signatures for address

### Block Operations
- [`getBlock`](src/messages/get_block.rs) - Get block information

### Health & Status
- [`getHealth`](src/messages/get_health.rs) - Node health check
- [`getValidatorHealth`](src/messages/get_validator_health.rs) - Validator health check
- [`getConnectedFullNodes`](src/messages/get_connected_full_nodes.rs) - Get full nodes connected to validator
- [`getEpochInfo`](src/messages/get_epoch_info.rs) - Get epoch information

### Utility Operations
- [`requestAirdrop`](src/messages/request_airdrop.rs) - Request test tokens
- [`getMinimumBalanceForRentExemption`](src/messages/get_minimum_balance_for_rent_exemption.rs) - Get rent exemption
- [`getFeeForMessage`](src/messages/get_fee_for_message.rs) - Calculate transaction fees
- [`isBlockhashValid`](src/messages/is_blockhash_valid.rs) - Validate blockhash

### Rialo-Specific Operations
- [`getWorkflowLineage`](src/messages/get_workflow_lineage.rs) - Get workflow transaction lineage
- [`getTriggeredTransactions`](src/messages/get_triggered_transactions.rs) - Get triggered transactions
- [`getSubscription`](src/messages/get_subscription.rs) - Get subscription by subscriber and nonce
- [`getTransactionCount`](src/messages/get_transaction_count.rs) - Get transaction count

### Network Operations
- [`getClusterNodes`](src/messages/get_cluster_nodes.rs) - Get information about all nodes in the current cluster (committee)

## Usage

### Basic Request/Response Types

```rust
use rialo_api_types::messages::get_account_info::{
    GetAccountInfoRequest, GetAccountInfoResponse, GetAccountInfoConfig
};

// Create a request
let request = GetAccountInfoRequest {
    address: "7xB9i2AcjLNJ6M8iZ3LZJvLm7xpSmH7T5uZzR3DeVXWi".to_string(),
    config: Some(GetAccountInfoConfig {
        ..Default::default()
    })
};

// Serialize to JSON
let json = serde_json::to_string(&request)?;
println!("Request: {}", json);
```

### Validation

All request types implement validation using the `validator` crate:

```rust
use rialo_api_types::{
    messages::request_airdrop::RequestAirdropRequest,
    validation::validate_request
};

// Create and validate a request
let request = RequestAirdropRequest::new(
    "7xB9i2AcjLNJ6M8iZ3LZJvLm7xpSmH7T5uZzR3DeVXWi".to_string(),
    1_000_000_000 // 1 RLO
);

// This will validate pubkey format and airdrop amount constraints
let validated = validate_request(request)?;
```

### Array Parameter Support

Some endpoints support both object and array parameter formats for Solana compatibility:

```rust
use rialo_api_types::requests::{SendTransactionRequest, FromArrayParams};
use serde_json::Value;

// Parse from array format: ["transaction", {"encoding": "base64"}]
let params = vec![
    Value::String("base64_transaction_data".to_string()),
    serde_json::json!({"encoding": "base64"})
];

let request = SendTransactionRequest::from_array_params(&params)?;
```

## Validation Features

The crate provides comprehensive input validation:

### Built-in Validators

- **Public Key Validation**: Ensures valid Solana public key format
- **Signature Validation**: Validates base58-encoded signatures (87-88 chars)
- **Encoding Validation**: Ensures supported encoding formats (base64, base58)  
- **Amount Validation**: Range checking for kelvins amounts and limits
- **Base64/Base58 Validation**: Format validation for encoded data

### Custom Validation

```rust
use rialo_api_types::validation::{
    validate_pubkey, validate_signature, validate_airdrop_amount
};

// Validate individual values
validate_pubkey("7xB9i2AcjLNJ6M8iZ3LZJvLm7xpSmH7T5uZzR3DeVXWi")?;
validate_signature("signature_base58")?;
validate_airdrop_amount(1_000_000_000)?; // 1 RLO
```

## Error Handling

All validation errors implement the `ValidationError` type:

```rust
use rialo_api_types::validation::{ValidationError, ValidationResult};

fn handle_validation(result: ValidationResult<T>) {
    match result {
        Ok(validated_data) => {
            // Process validated data
        }
        Err(ValidationError::InvalidPublicKey(msg)) => {
            println!("Invalid public key: {}", msg);
        }
        Err(ValidationError::InvalidSignature(msg)) => {
            println!("Invalid signature: {}", msg);
        }
        Err(ValidationError::Multiple(msg)) => {
            println!("Multiple validation errors: {}", msg);
        }
        Err(err) => {
            println!("Validation error: {}", err);
        }
    }
}
```

## JSON-RPC 2.0 Examples

### Request Format

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getAccountInfo",
  "params": [
    "7xB9i2AcjLNJ6M8iZ3LZJvLm7xpSmH7T5uZzR3DeVXWi"
  ]
}
```

### Response Format

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "context": {
      "slot": 1234567
    },
    "value": {
      "data": ["base64_encoded_data", "base64"],
      "executable": false,
      "kelvins": 1000000000,
      "owner": "11111111111111111111111111111111",
      "rentEpoch": 200
    }
  }
}
```

## Type Organization

```
src/
├── lib.rs              # Main crate interface
├── messages/           # RPC method types
│   ├── get_*.rs        # Get method types
│   ├── send_*.rs       # Send method types
│   └── request_*.rs    # Request method types
├── parameters.rs       # Parameter re-exports
├── requests.rs         # Array parameter parsing
├── validation.rs       # Validation logic
└── validation_test.rs  # Validation tests
```

## Development

### Adding New RPC Methods

1. Create a new file in `src/messages/`
2. Define request, response, and config types
3. Add validation annotations using `#[validate(...)]`
4. Include comprehensive documentation with examples
5. Add the types to `lib.rs` re-exports
6. Write tests for the new types

### Example New Method

```rust
// src/messages/my_new_method.rs
use serde::{Deserialize, Serialize};
use validator::Validate;
use crate::validation::validate_pubkey;

/// Request for myNewMethod RPC call
/// 
/// This method does something specific...
/// 
/// ## Example
/// 
/// ```json
/// {
///   "jsonrpc": "2.0", 
///   "id": 1,
///   "method": "myNewMethod",
///   "params": ["pubkey_here"]
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct MyNewMethodRequest {
    /// The account public key (base58 encoded)
    #[validate(length(min = 1, message = "Public key cannot be empty"))]
    #[validate(custom(function = validate_pubkey))]
    pub pubkey: String,
}

/// Response for myNewMethod RPC call
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MyNewMethodResponse {
    /// The result data
    pub result: String,
}
```

## Testing

Run the test suite:

```bash
cargo test --package rialo-api-types
```

Run validation-specific tests:

```bash 
cargo test --package rialo-api-types validation
```

## Contributing

When contributing new API types:

1. Follow existing naming conventions
2. Add comprehensive documentation with JSON examples  
3. Include proper validation constraints
4. Write unit tests for all new types
5. Update this README if adding new categories

## Dependencies

- `serde` - Serialization/deserialization
- `validator` - Input validation
- `rialo-s-sdk` - Solana types and utilities
- `thiserror` - Error handling
- `rialo-types` - Shared Rialo types

## License

Licensed under the Apache License, Version 2.0.