# Rialo Client Development Kit (CDK)

[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

The Rialo CDK is a comprehensive toolkit that provides the fundamental building blocks for interacting with the Rialo blockchain. It serves as the foundation for keyring management, transaction processing, RPC communication, and configuration handling.

## Features

- **Keyring Management**: Create, load, and manage keyrings with secure key handling
- **HD Derivation Support**: BIP39 mnemonic generation and hierarchical deterministic key derivation
- **Transaction Building**: Create, sign, and serialize blockchain transactions
- **RPC Client**: Communicate with Rialo blockchain nodes using JSON-RPC
- **Configuration Management**: Flexible configuration system with multiple storage backends
- **Secure Key Storage**: Encrypted keyring storage with password protection

## Terminology

| Term | Definition |
|------|------------|
| **Keyring** | A local collection of derived keypairs, optionally backed by a mnemonic |
| **DerivedKeypair** | A single Ed25519 keypair with its derivation metadata |
| **On-chain Account** | A data structure on the blockchain that can hold tokens |
| **Address** | The base58 encoding of a public key, used to identify on-chain accounts |

> **Note**: The CDK uses "keyring" terminology because it manages cryptographic keys, not assets. Balances exist on-chain and are queried via RPC.

## Feature Flags

Rialo CDK uses Cargo feature flags to allow customization of the library's functionality:

- **`file-storage`** (default: enabled): Provides file-based keyring and configuration storage. Disable this in environments where filesystem access is unavailable.
- **`encryption`** (default: enabled): Includes encryption/decryption functionality for keyring security. Can be disabled for testing or specific security environments.
- **`hd-wallet`** (default: enabled): Enables hierarchical deterministic key derivation functionality. Disable for a slimmer build without HD support.
- **`mnemonic`** (default: enabled): Provides mnemonic phrase generation and recovery (depends on `hd-wallet`). Can be disabled for simpler applications.
- **`rpc-client`** (default: enabled): Includes the HTTP RPC client implementation. Disable to use custom RPC implementations without HTTP client dependencies.

### Using Feature Flags

To use Rialo CDK with specific features, specify them in your Cargo.toml:

```toml
[dependencies]
rialo-cdk = { version = "0.1.0", default-features = false, features = ["file-storage", "encryption"] }
```

## Getting Started

### Installation

Add Rialo CDK to your project's dependencies:

```toml
[dependencies]
rialo-cdk = "0.1.0"
```

### Basic Usage Examples


#### Creating and Managing Keyrings

```rust
use rialo_cdk::keyring::{FileKeyringProvider, KeyringProvider};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize keyring provider with default path
    let keyring_dir = FileKeyringProvider::default_path()?;
    let provider = FileKeyringProvider::new(keyring_dir);

    // Create a new keyring with mnemonic
    let keyring = provider.create_with_mnemonic("my_keys", "password123").await?;
    println!("Created keyring with address: {}", keyring.pubkey_string());

    // Load keyring
    let loaded_keyring = provider.load("my_keys", "password123").await?;

    // List all keyrings
    let keyrings = provider.list().await?;
    for keyring_name in keyrings {
        println!("Found keyring: {}", keyring_name);
    }

    Ok(())
}
```

#### Building and Sending Transactions

```rust
use rialo_cdk::keyring::Keyring;
use rialo_cdk::transaction::TransactionBuilder;
use rialo_cdk::rpc::HttpRpcClient;

async fn send_transaction(keyring: &Keyring, recipient: &str, amount: u64) -> Result<String> {
    // Connect to a Rialo node
    let rpc_client = HttpRpcClient::new("http://localhost:4104".to_string());

    // Get current time in milliseconds for valid_from
    let valid_from = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("Time went backwards")
        .as_millis() as i64;

    // Build transaction
    let tx_builder = TransactionBuilder::new(keyring.pubkey(), valid_from);
    let signed_tx = tx_builder
        .add_transfer_instruction(&keyring.pubkey(), recipient, amount)
        .sign(keyring)?;

    // Submit transaction
    let signature = rpc_client.send_transaction(&signed_tx).await?;

    Ok(signature)
}
```

#### Managing Configuration

```rust
use rialo_cdk::config::{FileConfigProvider, ConfigProvider, Config};

async fn manage_config() -> Result<()> {
    // Get config from default location
    let config_path = FileConfigProvider::default_path()?;
    let provider = FileConfigProvider::new(config_path);

    // Load existing config or create default
    let mut config = provider.load().await?;

    // Update settings
    config.set_network("devnet");
    config.default_balance_unit = "RLO".to_string();

    // Save changes
    provider.save(&config).await?;

    Ok(())
}
```

## Core Components

### Keyring Module

The keyring module provides a comprehensive set of tools for secure key management:

- **KeyringProvider**: Trait for keyring storage backends
- **FileKeyringProvider**: Implementation that stores keyrings in the filesystem
- **InMemoryKeyringProvider**: Implementation that keeps keyrings in memory (for testing)
- **Mnemonic Functions**: For generating and using BIP39 seed phrases
- **Encryption Utilities**: For secure storage of sensitive keyring data

### Transaction Module

The transaction module handles the creation and signing of blockchain transactions:

- **TransactionBuilder**: Fluent interface for constructing transactions
- **Instruction**: Representation of individual operations within a transaction
- **AccountMeta**: Metadata about accounts referenced in a transaction

### RPC Module

The RPC module provides communication with Rialo blockchain nodes:

- **RpcClient**: Trait defining the RPC interface
- **HttpRpcClient**: Implementation using HTTP for JSON-RPC communication
- **Response Types**: Structured data models for RPC responses

### Configuration Module

The configuration module manages user preferences and network settings:

- **Config**: Structure holding configuration parameters
- **ConfigProvider**: Trait for configuration storage backends
- **FileConfigProvider**: Implementation using JSON files for storage
- **InMemoryConfigProvider**: Implementation keeping configuration in memory

## Security Considerations

- Keyring private keys are encrypted at rest
- Passwords are never stored
- Secure random number generation is used for cryptographic operations
- Network communication supports TLS

## Migration from v0.1.x

If you're migrating from an earlier version that used `Wallet` terminology:

| Old Type | New Type |
|----------|----------|
| `Wallet` | `Keyring` |
| `Account` | `DerivedKeypair` |
| `WalletProvider` | `KeyringProvider` |
| `FileWalletProvider` | `FileKeyringProvider` |
| `InMemoryWalletProvider` | `InMemoryKeyringProvider` |

The old types remain available as deprecated aliases for backward compatibility.

## License

This project is licensed under the Apache License, Version 2.0.
