mudra-cli 0.1.0

A robust, high-performance currency converter with caching and CLI interface
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# ๐Ÿช™ Mudra - Currency Converter

A robust, high-performance currency converter built in Rust with real-time and historical exchange rates, intelligent caching, and a beautiful CLI interface.

[![Build Status](https://img.shields.io/badge/build-passing-brightgreen)](https://github.com/AshishBagdane/mudra)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Rust](https://img.shields.io/badge/rust-1.70+-orange.svg)](https://www.rust-lang.org)

> **Mudra** (เคฎเฅเคฆเฅเคฐเคพ) - Sanskrit/Hindi word meaning "currency" or "money"

## โœจ Features

- ๐ŸŒ **Real-time exchange rates** from multiple currency providers
- ๐Ÿ“Š **Historical data support** with date-specific conversions
- โšก **High-performance caching** with configurable TTL
- ๐ŸŽฏ **Type-safe currency handling** with compile-time validation
- ๐Ÿ–ฅ๏ธ **Beautiful CLI interface** with colored output and progress indicators
- ๐Ÿ“ฑ **Interactive mode** for continuous currency conversions
- ๐Ÿ”„ **Batch processing** for multiple conversions
- ๐Ÿงช **Comprehensive error handling** with detailed messages
- ๐Ÿ“ˆ **Performance monitoring** with cache statistics
- ๐Ÿ›ก๏ธ **Production-ready** with extensive testing

## ๐Ÿš€ Quick Start

### Installation

```bash
# Install from crates.io
cargo install mudra-cli

# Or build from source
git clone https://github.com/AshishBagdane/mudra.git
cd mudra
cargo build --release

# Or download pre-built binaries from GitHub releases
# https://github.com/AshishBagdane/mudra/releases
```

> **Note**: The package name is `mudra-cli` but the binary is called `mudra`

### Get an API Key

1. Sign up for a **free account** at [exchangerate-api.com]https://exchangerate-api.com
2. Get your API key from the dashboard (free tier: 1,500 requests/month)
3. Set your environment variable:

```bash
export EXCHANGE_API_KEY=your_api_key_here
```

### Basic Usage

```bash
# Convert 100 USD to EUR
mudra convert 100 USD EUR
# Output: 100.00 USD = 85.23 EUR

# Get current exchange rates for USD
mudra rates USD

# Historical conversion
mudra convert 100 USD EUR --date 2024-01-01

# Interactive mode
mudra interactive

# Compare across multiple currencies
mudra compare 100 USD EUR,GBP,JPY,CAD
```

## ๐Ÿ“– Documentation

### CLI Commands

#### Convert Currency

```bash
# Basic conversion
mudra convert <amount> <from> <to>

# With custom precision
mudra convert 100 USD EUR --precision 4

# Historical conversion
mudra convert 100 USD EUR --date 2024-01-01

# Verbose output
mudra convert 100 USD EUR --verbose
```

#### List Currencies

```bash
# Compact list
mudra list

# Extended format
mudra list --extended

# Filter currencies
mudra list --filter EUR
```

#### Exchange Rates

```bash
# All rates for USD
mudra rates USD

# Specific currencies only
mudra rates USD --currencies EUR,GBP,JPY

# Historical rates
mudra rates USD --date 2024-01-01

# Limited results
mudra rates USD --limit 10
```

#### Compare Currencies

```bash
# Compare across multiple currencies
mudra compare 100 USD EUR,GBP,JPY,CAD,AUD

# Historical comparison
mudra compare 100 USD EUR,GBP --date 2024-01-01
```

#### Cache Management

```bash
# View cache statistics
mudra cache stats

# Clear all cached data
mudra cache clear

# Clean up expired entries
mudra cache cleanup
```

#### Interactive Mode

```bash
mudra interactive

# Then use commands like:
# > 100 USD EUR
# > convert 50 GBP JPY
# > rates USD
# > list
# > help
# > quit
```

## ๐Ÿ—๏ธ Library Usage

### Basic Example

```rust
use currency_converter::{CurrencyConverter, ConversionRequest};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create converter (requires EXCHANGE_API_KEY environment variable)
    let converter = CurrencyConverter::from_env()?;

    // Convert 100 USD to EUR
    let request = ConversionRequest::from_components(100.0, "USD", "EUR")?;
    let result = converter.convert(request).await?;

    println!("Conversion: {}", result.summary());
    println!("Rate: {:.6}", result.exchange_rate);
    println!("Result: {}", result.result);

    Ok(())
}
```

### Advanced Example with Caching

```rust
use currency_converter::{
    CurrencyConverter, ExchangeRateService, CurrencyClient,
    Config, CacheConfig, ConversionRequest
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Custom configuration
    let config = Config::new()
        .with_api_key("your-api-key")
        .with_timeout(std::time::Duration::from_secs(10));

    // Custom cache configuration
    let cache_config = CacheConfig {
        max_capacity: 500,
        latest_ttl: 600,      // 10 minutes
        historical_ttl: 7200, // 2 hours
        enable_stats: true,
    };

    // Create client and service
    let client = CurrencyClient::with_config(config)?;
    let service = ExchangeRateService::with_cache_config(client, cache_config);
    let converter = CurrencyConverter::new(service);

    // Batch conversion
    let requests = vec![
        ConversionRequest::from_components(100.0, "USD", "EUR")?,
        ConversionRequest::from_components(100.0, "USD", "GBP")?,
        ConversionRequest::from_components(100.0, "USD", "JPY")?,
    ];

    let results = converter.convert_batch(requests).await;

    for (i, result) in results.iter().enumerate() {
        match result {
            Ok(conversion) => println!("Conversion {}: {}", i + 1, conversion.summary()),
            Err(e) => println!("Error {}: {}", i + 1, e),
        }
    }

    // Check cache performance
    let stats = converter.exchange_service.get_cache_stats();
    println!("Cache hit rate: {:.1}%", stats.hit_rate);

    Ok(())
}
```

### Historical Data Example

```rust
use currency_converter::{ExchangeRateService, api::types::HistoricalConversionRequest};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let service = ExchangeRateService::from_env()?;

    // Historical conversion
    let request = HistoricalConversionRequest {
        amount: 100.0,
        from: "USD".to_string(),
        to: "EUR".to_string(),
        date: "2024-01-01".to_string(),
    };

    let result = service.convert_historical(request).await?;
    println!("Historical rate on 2024-01-01: {:.6}", result.conversion_rate);

    // Get historical rates
    let rates = service.get_historical_rates("USD", "2024-01-01").await?;
    println!("USD rates on {}: {:?}", rates.get_date_string(), rates.conversion_rates);

    Ok(())
}
```

## ๐Ÿ—๏ธ Architecture

### Core Components

```
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚       CLI       โ”‚    โ”‚    Library      โ”‚    โ”‚   API Client    โ”‚
โ”‚   (clap-based)  โ”‚โ”€โ”€โ”€โ–ถโ”‚   (type-safe)   โ”‚โ”€โ”€โ”€โ–ถโ”‚  (HTTP client)  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚                        โ”‚
                                โ–ผ                        โ–ผ
                       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                       โ”‚      Cache      โ”‚    โ”‚  External API   โ”‚
                       โ”‚   (in-memory)   โ”‚    โ”‚ (exchangerate-  โ”‚
                       โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ”‚     api.com)    โ”‚
                                              โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
```

### Key Design Principles

1. **Type Safety**: All currency codes and amounts are validated at compile time
2. **Error Handling**: Comprehensive error types with context
3. **Performance**: Intelligent caching with configurable TTL
4. **Modularity**: Clean separation between CLI, library, and API layers
5. **Testability**: Extensive unit and integration tests with mocking

### Conversion Algorithm

1. **Same Currency**: Return input amount (no API call)
2. **Direct Conversion**: Use base currency rates directly
3. **Cross Conversion**: Convert via USD as intermediate currency

```rust
// Example: GBP โ†’ JPY via USD
// Step 1: Get USD rates (contains both GBP and JPY)
// Step 2: Calculate cross rate: JPY_rate / GBP_rate
// Step 3: Apply rate to amount
```

## ๐Ÿงช Testing

### Run All Tests

```bash
# Unit tests
cargo test

# Integration tests (requires wiremock)
cargo test --test integration_tests

# With coverage (requires cargo-tarpaulin)
cargo tarpaulin --out html
```

### Property-Based Testing

The project includes property-based tests using `proptest`:

```bash
# Run property tests
cargo test property_tests
```

### Performance Benchmarks

```bash
# Run benchmarks (requires API key for realistic results)
EXCHANGE_API_KEY=your_key cargo run --bin benchmarks

# Memory usage analysis
cargo run --bin benchmarks 2>&1 | grep "bytes"
```

## ๐Ÿš€ Performance

### Benchmarks

Typical performance on modern hardware:

- **Type creation**: ~10ns per Currency/Money instance
- **Cache hit**: ~1-5ms for cached conversions
- **Cache miss**: ~100-500ms (network dependent)
- **Batch conversion**: ~50-200ms for 10 currencies
- **Memory usage**: ~50KB baseline, ~1KB per cached entry

### Cache Effectiveness

- **Hit rate**: 85-95% in typical usage
- **TTL**: 5 minutes for latest rates, 1 hour for historical
- **Capacity**: 1000 entries (configurable)
- **Eviction**: LRU (Least Recently Used)

## ๐Ÿ› ๏ธ Development

### Prerequisites

- Rust 1.70+
- API key from [exchangerate-api.com]https://exchangerate-api.com

### Build from Source

```bash
git clone https://github.com/AshishBagdane/mudra.git
cd mudra
cargo build
```

### Development Commands

```bash
# Check code
cargo check

# Format code
cargo fmt

# Lint code
cargo clippy

# Run tests
cargo test

# Build release
cargo build --release

# Run mudra
./target/release/mudra --help

# Build documentation
cargo doc --open
```

### Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature-name`
3. Make your changes and add tests
4. Ensure all tests pass: `cargo test`
5. Format code: `cargo fmt`
6. Submit a pull request

## ๐Ÿ“Š Supported Currencies

The converter supports 168+ currencies including:

- **Major**: USD, EUR, GBP, JPY, CHF, CAD, AUD
- **Asian**: CNY, KRW, INR, SGD, HKD, THB, MYR
- **European**: SEK, NOK, DKK, PLN, CZK, HUF
- **Americas**: BRL, MXN, ARS, CLP, COP, PEN
- **Others**: ZAR, RUB, TRY, ILS, SAR, AED

Use `currency_converter list` to see all supported currencies.

## โš™๏ธ Configuration

### Environment Variables

- `EXCHANGE_API_KEY`: Your API key (required)
- `EXCHANGE_BASE_URL`: Custom API base URL (optional)
- `NO_COLOR`: Disable colored output (optional)

### Cache Configuration

```rust
CacheConfig {
    max_capacity: 1000,        // Maximum cached entries
    latest_ttl: 300,           // Latest rates TTL (seconds)
    historical_ttl: 3600,      // Historical rates TTL (seconds)
    enable_stats: true,        // Enable statistics collection
}
```

## ๐Ÿ› Troubleshooting

### Common Issues

**"API key not found"**

```bash
export EXCHANGE_API_KEY=your_actual_api_key
```

**"Invalid currency code"**

- Use 3-letter ISO codes (USD, EUR, GBP)
- Check `currency_converter list` for supported currencies

**"Network timeout"**

- Check internet connection
- Increase timeout with custom configuration

**"Rate limit exceeded"**

- Free tier: 1,500 requests/month
- Upgrade plan or wait for reset

### Debug Mode

```bash
# Enable verbose logging
RUST_LOG=debug mudra convert 100 USD EUR --verbose
```

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™ Acknowledgments

- [ExchangeRate-API]https://exchangerate-api.com for providing free exchange rate data
- [Rust community]https://www.rust-lang.org for excellent libraries and tools
- All contributors who help improve this project

## ๐Ÿ”— Links

- [Documentation]https://docs.rs/mudra-cli
- [Crates.io]https://crates.io/crates/mudra-cli
- [GitHub Issues]https://github.com/AshishBagdane/mudra/issues
- [Changelog]CHANGELOG.md

---

**Made with โค๏ธ and ๐Ÿฆ€ Rust**