Crate currencies

Crate currencies 

Source
Expand description

§💰 currencies

Crates.io docs.rs Build Status MIT License

This crate allows for generic manipulation of currencies (both real-world and cryptocurrencies) via the Amount struct and the Currency trait.

The Amount struct is able to represent arbitrary amounts of any supported Currency with the ability to restrict the underlying currencies at compile-time to only allow checked arithmetic operations and requires consuming an Option in all fallible circumstances.

§Currency math

use currencies::{*, currency::*};

let apple_cost = amt!(USD, "$3.24");
let orange_cost = Amount::<USD>::from_raw(7_97);
assert!(apple_cost < orange_cost);
assert!(apple_cost + orange_cost > orange_cost);
assert_eq!(format!("{}", apple_cost * orange_cost), "$25.82");
assert_eq!(format!("{}", apple_cost * 3), "$9.72");

let mut total = amt!(DOT, "57622449841.0000000004 DOT");
total -= amt!(DOT, "1000.0 DOT");
total *= Amount::from_raw(2_0000000000u64.into());
assert_eq!(format!("{}", total), "115244897682.0000000008 DOT");

§Checked Math

use currencies::{*, currency::*, safety::*};

// When using currency amounts with `Safety = Checked`, the Amount struct has been specially set
// up so that only checked math will be allowed, and you can still use the normal
// operator-based syntax. Thus currency amounts like this should never panic and are
// suitable for use in critical/infallible environments.

let drink_cost = amt_checked!(USD, "$6.29");
let movie_cost = Amount::<USD, Checked>::from_raw(24_99);
let Some(outing_cost) = drink_cost + movie_cost else {
	unimplemented!("compiler forces you to handle this!")
};
assert_eq!(format!("{}", outing_cost), "$31.28");

Modules§

amount
Home of the Amount struct and supporting types and impls.
currency
Home of the Currency trait, all built-in currencies such as USD, AAVE, ETH, etc., the define_currency! macro, and related/supporting types.
safety
Home of the Safety sealed type and its two variants Checked and Unchecked.
serde_integration
Contains impls for serde integration
u256
Home of the U256 type, which is a heavily modified, wrapped version of primitive_types::U256 with several custom impls and additional traits from num_traits that are necessary for currency manipulation but not included by default.

Macros§

amt
amt_checked
define_currency
Shorthand for defining a new Currency. All ISO-4217 currencies already have an entry.

Structs§

Amount
Generically represents an amount of a specified Currency.
ParsedAmount
Represents an Amount that has been parsed from a string representation. Includes Span information.
U256
Wraps primitive_types::U256 enhancing it with some extra trait impls needed for currency manipulation.

Traits§

Backing
Automatically implemented on types capable of being used as the “base” / backing type for an Amount of Currency.
Currency
Uniquely defines a particular currency, such as USD, BTC, or ETH.