Skip to main content

fp

Function fp 

Source
pub fn fp(decimal: &str) -> Result<u128, SolMathError>
Expand description

Parse a decimal string into SolMath fixed-point (SCALE = 1e12).

This helper is intended for tests, examples, fixtures, and off-chain configuration. On-chain programs should pass already-validated integer values across the instruction boundary.

The parser accepts plain decimal notation with up to 12 fractional digits. Extra fractional digits are accepted only when they are zero, so precision is never silently truncated.

use solmath::{fp, SCALE};

assert_eq!(fp("100")?, 100 * SCALE);
assert_eq!(fp("0.05")?, 50_000_000_000);
assert_eq!(fp(".20")?, 200_000_000_000);
Examples found in repository?
examples/weighted_pool_swap.rs (line 10)
7fn main() -> Result<(), SolMathError> {
8    // Run with:
9    // cargo run --example weighted_pool_swap --features pool
10    let balance_in = fp("1000")?;
11    let balance_out = fp("1000")?;
12    let amount_in = fp("10")?;
13    let weight_in = fp("0.5")?;
14    let weight_out = fp("0.5")?;
15    let fee_rate = fp("0.003")?;
16
17    let (net_out, fee) = weighted_pool_swap(
18        balance_in,
19        balance_out,
20        weight_in,
21        weight_out,
22        amount_in,
23        fee_rate,
24    )?;
25
26    println!("net_out: {:.12}", as_decimal(net_out));
27    println!("fee:     {:.12}", as_decimal(fee));
28
29    Ok(())
30}
More examples
Hide additional examples
examples/options_pricing.rs (line 10)
7fn main() -> Result<(), SolMathError> {
8    // Parse once in tests, clients, scripts, or off-chain config. On-chain
9    // programs should pass already-validated integers across instruction data.
10    let spot = fp("100")?;
11    let strike = fp("105")?;
12    let risk_free_rate = fp("0.05")?;
13    let volatility = fp("0.20")?;
14    let years_to_expiry = fp("1")?;
15
16    let greeks = bs_full_hp(spot, strike, risk_free_rate, volatility, years_to_expiry)?;
17
18    println!("call:  {:.12}", as_decimal(greeks.call));
19    println!("put:   {:.12}", as_decimal(greeks.put));
20    println!("gamma: {:.12}", greeks.gamma as f64 / SCALE as f64);
21    println!("vega:  {:.12}", greeks.vega as f64 / SCALE as f64);
22
23    Ok(())
24}