Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions contracts/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 18 additions & 5 deletions contracts/continuous_bonding_curve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,16 +100,23 @@ pub mod fp18 {
/// Checked multiply of two 18-decimal FP values.
#[inline]
pub fn mul(a: i128, b: i128) -> Option<i128> {
a.checked_mul(b)?.checked_div(SCALE18)
let rounding = if (a < 0) ^ (b < 0) {
math::Rounding::Up
} else {
math::Rounding::Down
};
math::checked_mul_div_signed(a, b, SCALE18, rounding)
}

/// Checked divide of two 18-decimal FP values.
#[inline]
pub fn div(a: i128, b: i128) -> Option<i128> {
if b == 0 {
return None;
}
a.checked_mul(SCALE18)?.checked_div(b)
let rounding = if (a < 0) ^ (b < 0) {
math::Rounding::Up
} else {
math::Rounding::Down
};
math::checked_mul_div_signed(a, SCALE18, b, rounding)
}
}

Expand Down Expand Up @@ -636,6 +643,12 @@ mod tests {
assert_eq!(pricing::curve_payout(5, 2, 2 * FP, FP), Some(12));
}

#[test]
fn fp18_helpers_accept_full_width_intermediates() {
assert_eq!(fp18::mul(i128::MAX, fp18::SCALE18), Some(i128::MAX));
assert_eq!(fp18::div(i128::MAX, i128::MAX), Some(fp18::SCALE18));
}

#[test]
fn buys_mint_and_sells_burn_curve_tokens() {
let (env, _admin, buyer, id, _reserve_token, curve_token) = setup_with_tokens(0);
Expand Down
202 changes: 201 additions & 1 deletion contracts/continuous_bonding_curve/src/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//!
//! Provides a 128-bit fixed-point representation with 18 decimal places of precision (`WAD = 10^18`).
//! Implements deterministic rounding modes (`Down` vs `Up`), full 256-bit intermediate arithmetic for
//! `mul_div`, `wad_mul`, `wad_div`, `sqrt`, and `pow`, with clean overflow and division-by-zero detection.
//! multiplication/division, and checked Taylor-series `ln`, `exp`, and fractional powers.

pub const WAD: u128 = 1_000_000_000_000_000_000; // 10^18
pub const HALF_WAD: u128 = WAD / 2;
Expand Down Expand Up @@ -154,6 +154,164 @@ pub fn wad_div(a: u128, b: u128, rounding: Rounding) -> u128 {
mul_div(a, WAD, b, rounding)
}

/// Computes `(a * b) / denominator` with full-width intermediates.
/// Returns `None` for division by zero or if the result exceeds `u128`.
pub fn checked_mul_div(a: u128, b: u128, denominator: u128, rounding: Rounding) -> Option<u128> {
if denominator == 0 {
return None;
}

let (quotient, remainder) = div_rem_u256(mul_u128(a, b), denominator);
if quotient.hi > 0 {
return None;
}

let mut result = quotient.lo;
if rounding == Rounding::Up && remainder > 0 {
result = result.checked_add(1)?;
}
Some(result)
}

/// Computes signed `(a * b) / denominator` with full-width intermediates.
/// `Down` rounds toward negative infinity and `Up` toward positive infinity.
pub fn checked_mul_div_signed(
a: i128,
b: i128,
denominator: i128,
rounding: Rounding,
) -> Option<i128> {
if denominator == 0 {
return None;
}

let negative = (a < 0) ^ (b < 0) ^ (denominator < 0);
let (quotient, remainder) = div_rem_u256(
mul_u128(a.unsigned_abs(), b.unsigned_abs()),
denominator.unsigned_abs(),
);
if quotient.hi > 0 {
return None;
}

let round_away_from_zero = remainder > 0
&& ((!negative && rounding == Rounding::Up) || (negative && rounding == Rounding::Down));
let magnitude = if round_away_from_zero {
quotient.lo.checked_add(1)?
} else {
quotient.lo
};

if negative {
let min_magnitude = (i128::MAX as u128).checked_add(1)?;
if magnitude > min_magnitude {
return None;
}
if magnitude == min_magnitude {
Some(i128::MIN)
} else {
Some(-(magnitude as i128))
}
} else {
i128::try_from(magnitude).ok()
}
}

/// Computes the natural logarithm of a positive 18-decimal fixed-point value.
///
/// The atanh series is evaluated after reducing the input to `[0.5, 2]`,
/// where it converges quickly. The result is in 18-decimal fixed-point units.
pub fn ln_wad(value: i128) -> Option<i128> {
const LN_2: i128 = 693_147_180_559_945_309;
const MAX_TERMS: u32 = 64;

if value <= 0 {
return None;
}

let mut normalized = value;
let mut powers_of_two = 0i128;
while normalized > 2 * WAD as i128 {
normalized /= 2;
powers_of_two = powers_of_two.checked_add(1)?;
}
while normalized < WAD as i128 / 2 {
normalized = normalized.checked_mul(2)?;
powers_of_two = powers_of_two.checked_sub(1)?;
}

let wad = WAD as i128;
let z = normalized
.checked_sub(wad)?
.checked_mul(wad)?
.checked_div(normalized.checked_add(wad)?)?;
let z_squared = z.checked_mul(z)?.checked_div(wad)?;
let mut term = z;
let mut sum = z;

for index in 1..=MAX_TERMS {
term = term.checked_mul(z_squared)?.checked_div(wad)?;
let divisor = (index as i128).checked_mul(2)?.checked_add(1)?;
let contribution = term / divisor;
if contribution == 0 {
break;
}
sum = sum.checked_add(contribution)?;
}

sum.checked_mul(2)?
.checked_add(powers_of_two.checked_mul(LN_2)?)
}

/// Computes `e^value` for an 18-decimal fixed-point exponent.
///
/// Range reduction bounds the Taylor series argument to `[-0.5, 0.5]`.
/// Returns `None` if the result cannot be represented.
pub fn exp_wad(value: i128) -> Option<i128> {
const MAX_TERMS: u32 = 64;

let wad = WAD as i128;
let mut reduced = value;
let mut squarings = 0u32;
while reduced > wad / 2 || reduced < -(wad / 2) {
reduced /= 2;
squarings = squarings.checked_add(1)?;
}

let mut term = wad;
let mut sum = wad;
for index in 1..=MAX_TERMS {
term = term
.checked_mul(reduced)?
.checked_div(wad)?
.checked_div(index as i128)?;
if term == 0 {
break;
}
sum = sum.checked_add(term)?;
}

for _ in 0..squarings {
sum = sum.checked_mul(sum)?.checked_div(wad)?;
}
Some(sum)
}

/// Computes a fractional 18-decimal fixed-point power using `exp(ln(base)*exponent)`.
pub fn wad_pow_fractional(base: i128, exponent: i128, rounding: Rounding) -> Option<i128> {
let wad = WAD as i128;
if exponent == 0 {
return Some(wad);
}
if base == 0 {
return if exponent > 0 { Some(0) } else { None };
}

let log_base = ln_wad(base)?;
let power = checked_mul_div_signed(log_base, exponent, wad, rounding)?;
exp_wad(power)
}

/// Computes integer square root `floor(sqrt(x))` using the Babylonian method.
pub fn sqrt(x: u128) -> u128 {
if x == 0 {
Expand Down Expand Up @@ -351,6 +509,48 @@ mod tests {
assert_eq!(one.mul(one, Rounding::Down), one);
}

#[test]
fn checked_mul_div_supports_full_width_intermediates_and_signed_rounding() {
assert_eq!(
checked_mul_div(u128::MAX, WAD, WAD, Rounding::Down),
Some(u128::MAX)
);
assert_eq!(
checked_mul_div_signed(i128::MAX, 2, 2, Rounding::Down),
Some(i128::MAX)
);
assert_eq!(
checked_mul_div_signed(i128::MIN, 1, 1, Rounding::Down),
Some(i128::MIN)
);
assert_eq!(checked_mul_div_signed(-10, 1, 3, Rounding::Down), Some(-4));
assert_eq!(checked_mul_div_signed(-10, 1, 3, Rounding::Up), Some(-3));
assert_eq!(checked_mul_div(1, 1, 0, Rounding::Down), None);
assert_eq!(checked_mul_div_signed(1, 1, 0, Rounding::Down), None);
}

#[test]
fn taylor_log_exp_and_fractional_power_match_reference_values() {
let wad = WAD as i128;
let ln_two_reference = 693_147_180_559_945_309i128;
let e_reference = 2_718_281_828_459_045_235i128;

assert_eq!(ln_wad(wad), Some(0));
assert!(ln_wad(2 * wad).unwrap().abs_diff(ln_two_reference) < 100);
assert_eq!(exp_wad(0), Some(wad));
assert!(exp_wad(wad).unwrap().abs_diff(e_reference) < 1_000);
assert!(exp_wad(ln_two_reference).unwrap().abs_diff(2 * wad) < 100);
assert!(
wad_pow_fractional(4 * wad, wad / 2, Rounding::Down)
.unwrap()
.abs_diff(2 * wad)
< 100
);
assert_eq!(ln_wad(0), None);
assert_eq!(exp_wad(100 * wad), None);
assert_eq!(wad_pow_fractional(0, -wad, Rounding::Down), None);
}

#[test]
fn test_wad_sqrt() {
// sqrt(1) == 1
Expand Down
1 change: 1 addition & 0 deletions contracts/cross_chain_client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ soroban-sdk = "28.0.0"

[dev-dependencies]
soroban-sdk = { version = "28.0.0", features = ["testutils"] }
ed25519-dalek = { version = "2", default-features = false, features = ["std"] }
Loading
Loading