Crate typed_money

Crate typed_money 

Source
Expand description

§Introduction

A type-safe money library for Rust that prevents currency mixing bugs at compile time.

§Features

  • Type-safe - Currency mixing prevented at compile time
  • Zero-cost abstractions - O(1) operations, no runtime overhead
  • 100% Safe Rust - No unsafe code
  • Deterministic - Uses rust_decimal for precise arithmetic
  • Comprehensive - Full arithmetic, conversions, rounding, and formatting
  • Flexible - Optional serde support and conversion tracking
  • Internationalization - 69 currencies with locale-specific formatting
  • Rich metadata - Country, region, volatility, liquidity ratings
  • Precious metals - Gold, Silver, Platinum, Palladium, Diamond
  • Base metals - Copper, Aluminum, Zinc, Nickel
  • Cryptocurrencies - Major cryptos, stablecoins, DeFi tokens

§Quick Start

use typed_money::{Amount, USD, EUR, BTC, ETH, LTC, ADA, USDT, USDC, CAD, CNY, THB, NGN, Rate, RoundingMode};

// Create amounts
let price = Amount::<USD>::from_major(100);  // $100.00
let tax = Amount::<USD>::from_minor(850);     // $8.50

// Arithmetic operations
let total = price + tax;  // $108.50
assert_eq!(total.to_minor(), 10850);

// Currency conversion
let rate = Rate::<USD, EUR>::new(0.85);
let eur_price = price.convert(&rate);  // €85.00

// Cryptocurrency amounts
let bitcoin = Amount::<BTC>::from_minor(100_000_000);  // 1.00000000 BTC
let ethereum = Amount::<ETH>::from_major(1);           // 1.000000000000000000 ETH
let litecoin = Amount::<LTC>::from_major(10);          // 10.00000000 LTC
let cardano = Amount::<ADA>::from_major(1000);         // 1000.000000 ADA

// Stablecoin amounts
let tether = Amount::<USDT>::from_major(100);          // 100.000000 USDT
let usd_coin = Amount::<USDC>::from_major(50);         // 50.000000 USDC

// Multi-currency operations
let cad_amount = Amount::<CAD>::from_major(150);  // C$150.00
let cny_amount = Amount::<CNY>::from_major(700);  // ¥700.00

// Rounding
let divided = Amount::<USD>::from_major(10) / 3;  // $3.333...
let rounded = divided.round(RoundingMode::HalfUp);  // $3.33

§Internationalization & Metadata

use typed_money::{Amount, USD, EUR, BRL, CurrencyMetadata};

// Access rich currency metadata
let usd_amount = Amount::<USD>::from_major(1234);
println!("Currency: {}", usd_amount.currency_name());     // "US Dollar"
println!("Country: {}", usd_amount.currency_country());   // "United States"
println!("Region: {}", usd_amount.currency_region());     // "North America"
println!("Type: {}", usd_amount.currency_type());         // "Fiat"
println!("Volatility: {}", usd_amount.volatility_rating()); // "Low"
println!("Liquidity: {}", usd_amount.liquidity_rating());   // "High"

// Locale-specific formatting
let eur_amount = Amount::<EUR>::from_major(1234);
println!("European format: {}", eur_amount); // "€1.234,00 EUR"

let brl_amount = Amount::<BRL>::from_major(1234);
println!("Brazilian format: {}", brl_amount); // "R$1.234,00 BRL"

§Precious Metals & Commodities

use typed_money::{Amount, XAU, XAG, XPT, XPD, XDI, XCU, XAL, CurrencyMetadata};

// Precious metals with 4 decimal precision
let gold = Amount::<XAU>::from_major(1);        // Au1.0000 XAU
let silver = Amount::<XAG>::from_major(100);    // Ag100.0000 XAG
let platinum = Amount::<XPT>::from_major(1);    // Pt1.0000 XPT
let palladium = Amount::<XPD>::from_major(1);   // Pd1.0000 XPD
let diamond = Amount::<XDI>::from_major(1);     // Di1.0000 XDI

// Base metals
let copper = Amount::<XCU>::from_major(1000);   // Cu1000.0000 XCU
let aluminum = Amount::<XAL>::from_major(1000); // Al1000.0000 XAL

// Access commodity metadata
println!("Gold region: {}", gold.currency_region());     // "Worldwide"
println!("Gold type: {}", gold.currency_type());         // "Commodity"
println!("Gold volatility: {}", gold.volatility_rating()); // "Medium"

§Type Safety

The library prevents currency mixing at compile time:

use typed_money::{Amount, USD, EUR};

let usd = Amount::<USD>::from_major(100);
let eur = Amount::<EUR>::from_major(85);

// This won't compile - type mismatch!
let invalid = usd + eur;

§Supported Currencies

Built-in currencies include:

§Major Fiat Currencies

  • USD - United States Dollar (2 decimals)
  • EUR - Euro (2 decimals)
  • GBP - British Pound Sterling (2 decimals)
  • JPY - Japanese Yen (0 decimals)
  • CAD - Canadian Dollar (2 decimals)
  • CHF - Swiss Franc (2 decimals)
  • AUD - Australian Dollar (2 decimals)
  • NZD - New Zealand Dollar (2 decimals)

§Asian Currencies

  • CNY - Chinese Yuan (2 decimals)
  • KRW - South Korean Won (0 decimals)
  • SGD - Singapore Dollar (2 decimals)
  • HKD - Hong Kong Dollar (2 decimals)
  • TWD - New Taiwan Dollar (2 decimals)
  • INR - Indian Rupee (2 decimals)

§European Currencies

  • SEK - Swedish Krona (2 decimals)
  • NOK - Norwegian Krone (2 decimals)
  • DKK - Danish Krone (2 decimals)
  • PLN - Polish Złoty (2 decimals)
  • CZK - Czech Koruna (2 decimals)
  • HUF - Hungarian Forint (0 decimals)

§American Currencies

  • BRL - Brazilian Real (2 decimals)
  • MXN - Mexican Peso (2 decimals)
  • ARS - Argentine Peso (2 decimals)
  • CLP - Chilean Peso (0 decimals)

§African/Middle Eastern Currencies

  • ZAR - South African Rand (2 decimals)
  • EGP - Egyptian Pound (2 decimals)
  • AED - United Arab Emirates Dirham (2 decimals)
  • SAR - Saudi Riyal (2 decimals)
  • ILS - Israeli Shekel (2 decimals)
  • TRY - Turkish Lira (2 decimals)

§Regional Currencies

§European Regional

  • RON - Romanian Leu (2 decimals)
  • BGN - Bulgarian Lev (2 decimals)
  • HRK - Croatian Kuna (2 decimals)
  • RSD - Serbian Dinar (2 decimals)
  • UAH - Ukrainian Hryvnia (2 decimals)

§Asian Regional

  • THB - Thai Baht (2 decimals)
  • MYR - Malaysian Ringgit (2 decimals)
  • IDR - Indonesian Rupiah (0 decimals)
  • PHP - Philippine Peso (2 decimals)
  • VND - Vietnamese Dong (0 decimals)

§American Regional

  • COP - Colombian Peso (2 decimals)
  • PEN - Peruvian Sol (2 decimals)
  • UYU - Uruguayan Peso (2 decimals)
  • BOB - Bolivian Boliviano (2 decimals)
  • PYG - Paraguayan Guarani (0 decimals)

§African Regional

  • NGN - Nigerian Naira (2 decimals)
  • KES - Kenyan Shilling (2 decimals)
  • GHS - Ghanaian Cedi (2 decimals)
  • MAD - Moroccan Dirham (2 decimals)
  • TND - Tunisian Dinar (3 decimals)

§Middle Eastern Regional

  • QAR - Qatari Riyal (2 decimals)
  • KWD - Kuwaiti Dinar (3 decimals)
  • BHD - Bahraini Dinar (3 decimals)
  • OMR - Omani Rial (3 decimals)
  • JOD - Jordanian Dinar (3 decimals)

§Cryptocurrencies

  • BTC - Bitcoin (8 decimals)
  • ETH - Ethereum (18 decimals)

§Precious Metals

  • XAU - Gold (4 decimals - troy ounces)
  • XAG - Silver (4 decimals - troy ounces)
  • XPT - Platinum (4 decimals - troy ounces)
  • XPD - Palladium (4 decimals - troy ounces)
  • XDI - Diamond (4 decimals - carats)

§Base Metals

  • XCU - Copper (4 decimals - metric tons)
  • XAL - Aluminum (4 decimals - metric tons)
  • XZN - Zinc (4 decimals - metric tons)
  • XNI - Nickel (4 decimals - metric tons)

§Feature Flags

  • use_rust_decimal (default) - Use rust_decimal backend
  • use_bigdecimal - Use bigdecimal backend (alternative)
  • serde_support - Enable serde serialization
  • conversion_tracking - Enable conversion tracking/logging

§Examples

The library includes comprehensive examples demonstrating various use cases. Run any example with cargo run --example <name>:

§basic_usage

Fundamental operations including:

  • Creating amounts from major/minor units
  • Arithmetic operations (add, subtract, multiply, divide)
  • Comparisons between amounts
  • Working with different currencies
  • Real-world shopping cart example
cargo run --example basic_usage

§conversions

Currency conversion examples:

  • Basic conversion with exchange rates
  • Inverse rates
  • Chained conversions (USD → EUR → GBP)
  • Rate metadata for auditability
  • International payment processing
cargo run --example conversions

§rounding

Demonstrates all 7 rounding modes:

  • HalfUp, HalfDown, HalfEven (Banker’s)
  • Up, Down, Floor, Ceiling
  • Edge cases with negative numbers
  • Tax and interest calculations
  • When to use each mode
cargo run --example rounding

§custom_currency

Defining custom currencies:

  • Custom fiat currencies (CAD, CHF, AUD)
  • Cryptocurrencies (DOGE)
  • Game currencies (GOLD, GEMS)
  • Loyalty points systems
  • Multi-currency wallets
cargo run --example custom_currency

§error_handling

Comprehensive error handling:

  • Parse errors with recovery
  • Precision errors and normalization
  • Invalid rate validation
  • Error propagation with ?
  • User input validation
cargo run --example error_handling

§serialization

Serde integration (requires serde_support feature):

  • JSON serialization/deserialization
  • Struct serialization with amounts
  • Collections and multi-currency data
  • API response handling
  • Persistence examples
cargo run --example serialization --features serde_support

Modules§

amount 🔒
Amount type for type-safe monetary values.
conversion_tracking
Conversion tracking for auditing currency conversions.
currency 🔒
Currency trait and built-in currency types.
error 🔒
Error types for monetary operations.
rate 🔒
Exchange rate types for currency conversion.
rounding 🔒
Rounding modes for monetary calculations.

Structs§

AAVE
Aave (AAVE)
ADA
Cardano (ADA)
AED
United Arab Emirates Dirham (AED)
ARS
Argentine Peso (ARS)
AUD
Australian Dollar (AUD)
Amount
A monetary amount in a specific currency.
BCH
Bitcoin Cash (BCH)
BGN
Bulgarian Lev (BGN)
BHD
Bahraini Dinar (BHD)
BOB
Bolivian Boliviano (BOB)
BRL
Brazilian Real (BRL)
BTC
Bitcoin
BUSD
Binance USD (BUSD)
CAD
Canadian Dollar (CAD)
CHF
Swiss Franc (CHF)
CLP
Chilean Peso (CLP)
CNY
Chinese Yuan (CNY)
COMP
Compound (COMP)
COP
Colombian Peso (COP)
CZK
Czech Koruna (CZK)
DAI
Dai (DAI)
DKK
Danish Krone (DKK)
DOT
Polkadot (DOT)
EGP
Egyptian Pound (EGP)
ETH
Ethereum
EUR
Euro
GBP
British Pound Sterling
GHS
Ghanaian Cedi (GHS)
HKD
Hong Kong Dollar (HKD)
HRK
Croatian Kuna (HRK)
HUF
Hungarian Forint (HUF)
IDR
Indonesian Rupiah (IDR)
ILS
Israeli Shekel (ILS)
INR
Indian Rupee (INR)
JOD
Jordanian Dinar (JOD)
JPY
Japanese Yen
KES
Kenyan Shilling (KES)
KRW
South Korean Won (KRW)
KWD
Kuwaiti Dinar (KWD)
LINK
Chainlink (LINK)
LTC
Litecoin (LTC)
MAD
Moroccan Dirham (MAD)
MKR
Maker (MKR)
MXN
Mexican Peso (MXN)
MYR
Malaysian Ringgit (MYR)
NGN
Nigerian Naira (NGN)
NOK
Norwegian Krone (NOK)
NZD
New Zealand Dollar (NZD)
OMR
Omani Rial (OMR)
PEN
Peruvian Sol (PEN)
PHP
Philippine Peso (PHP)
PLN
Polish Złoty (PLN)
PYG
Paraguayan Guarani (PYG)
QAR
Qatari Riyal (QAR)
RON
Romanian Leu (RON)
RSD
Serbian Dinar (RSD)
Rate
An exchange rate from one currency to another.
SAR
Saudi Riyal (SAR)
SEK
Swedish Krona (SEK)
SGD
Singapore Dollar (SGD)
SUSHI
SushiSwap (SUSHI)
THB
Thai Baht (THB)
TND
Tunisian Dinar (TND)
TRY
Turkish Lira (TRY)
TWD
New Taiwan Dollar (TWD)
UAH
Ukrainian Hryvnia (UAH)
UNI
Uniswap (UNI)
USD
United States Dollar
USDC
USD Coin (USDC)
USDT
Tether (USDT)
UYU
Uruguayan Peso (UYU)
VND
Vietnamese Dong (VND)
XAG
Silver (XAG)
XAL
Aluminum (XAL)
XAU
Gold (XAU)
XCU
Copper (XCU)
XDI
Diamond (XDI)
XNI
Nickel (XNI)
XPD
Palladium (XPD)
XPT
Platinum (XPT)
XRP
XRP (XRP)
XZN
Zinc (XZN)
YFI
Yearn Finance (YFI)
ZAR
South African Rand (ZAR)

Enums§

CurrencyType
Type of currency (Fiat, Cryptocurrency, or Commodity).
LiquidityRating
Liquidity rating for a currency.
MoneyError
Errors that can occur during monetary operations.
RoundingMode
Rounding modes for decimal operations.
SymbolPosition
Position of currency symbol relative to the amount.
VolatilityRating
Volatility rating for a currency.

Traits§

Currency
Trait representing a currency type.
CurrencyMetadata
Extension trait for accessing currency metadata from Amount instances.

Type Aliases§

MoneyResult
Result type alias for money operations.