diff --git a/packages/contract-utils/src/math/exp_ln.rs b/packages/contract-utils/src/math/exp_ln.rs new file mode 100644 index 000000000..e53d308e9 --- /dev/null +++ b/packages/contract-utils/src/math/exp_ln.rs @@ -0,0 +1,236 @@ +//! Natural logarithm and exponential for `Wad` (18-decimal fixed-point). +//! +//! "Exponential" here means the **natural exponential function** `e^x`, +//! where `e ≈ 2.71828` is Euler's number. It is *not* a generic power +//! function — `x^y` for arbitrary base `x` is implemented as +//! [`crate::math::wad::Wad::powf`], which composes `exp` and `ln` via +//! `x^y = exp(y * ln(x))`. +//! +//! Ported from Solmate's `SignedWadMath.sol`: +//! +//! +//! Solmate's algorithm uses `int256` throughout because: +//! - Polynomial coefficients are pre-scaled by 2^96 for precision; intermediate +//! products routinely exceed 2^192. +//! - The final scaling factors in `ln` are themselves > 2^192. +//! +//! This module mirrors that algorithm using soroban-sdk `I256`. Inputs and +//! outputs are `i128` in WAD (10^18) scale; everything in between is `I256`. +//! `to_i128()` at the end naturally returns `None` if the result doesn't fit. +//! +//! The "magic" decimal constants are minimax coefficients of `(p, q)` Padé +//! approximants of `ln(m)` on `m ∈ [1, 2)` and `exp(r)` on +//! `r ∈ [-ln(2)/2, ln(2)/2)`, both pre-scaled by 2^96. + +use soroban_sdk::{Env, I256, U256}; + +/// Input threshold at/below which `exp_wad(x)` returns 0. +/// +/// For `x` this small, `e^x * 10^18` evaluates to less than `0.5`, which +/// truncates to `0` in WAD precision. The exact value is +/// `floor(ln(0.5 * 10^-18) * 10^18)` ≈ `-42.139 * 10^18`. +const EXP_INPUT_MIN: i128 = -42_139_678_854_452_767_551; + +/// Input threshold at/above which `exp_wad(x)` overflows. +/// +/// For `x` this large, `e^x` exceeds the range Solmate's algorithm can +/// represent in its internal i256-with-2^96-scale basis. The exact value +/// is `floor(ln((2^255 - 1) / 10^18) * 10^18)` ≈ `135.305 * 10^18`. +const EXP_INPUT_MAX: i128 = 135_305_999_368_893_231_589; + +/// Natural logarithm of a WAD value. +/// +/// Returns `None` if `x <= 0` or the result doesn't fit in `i128`. +/// Output is in WAD scale (i.e. `ln(x) * 10^18`). +pub(super) fn ln_wad(e: &Env, x: i128) -> Option { + if x <= 0 { + return None; + } + + // r = floor(log2(x)). Solmate uses an inline bit-scan; for an `i128` + // input we get the same result from Rust's `ilog2`. + let r = x.ilog2() as i32; // 0 ..= 126 + let k = r - 96; // -96 ..= 30 + + // From here on, all arithmetic is in I256. + let mut x = I256::from_i128(e, x); + + // Solmate normalizes x to (1, 2) * 2^96 via: + // x <<= 159 - k; x = (x as uint256) >> 159; + // Rewriting without relying on i256 wraparound: shift left when k is + // negative, shift right when k is positive. + if k < 0 { + x = x.shl((-k) as u32); + } else if k > 0 { + x = x.shr(k as u32); + } + + // ----- (8, 8)-term rational approximation of ln(x) on [1, 2) ----- + // Coefficients are pre-scaled by 2^96. + + // p = x + 3273285459638523848632254066296 + let mut p = x.add(&I256::from_parts(e, 0, 0, 0x29508e4585, 0x43d8aa4df2abee78)); + // p = ((p * x) >> 96) + 24828157081833163892658089445524 + p = p.mul(&x).shr(96).add(&I256::from_parts(e, 0, 0, 0x139601a2efa, 0xbe717e604cbb4894)); + // p = ((p * x) >> 96) + 43456485725739037958740375743393 + p = p.mul(&x).shr(96).add(&I256::from_parts(e, 0, 0, 0x2247f7a7b65, 0x94320649aa03aba1)); + // p = ((p * x) >> 96) - 11111509109440967052023855526967 + p = p.mul(&x).shr(96).sub(&I256::from_parts(e, 0, 0, 0x8c3f38e95a, 0x6b1ff2ab1c3b3437)); + // p = ((p * x) >> 96) - 45023709667254063763336534515857 + p = p.mul(&x).shr(96).sub(&I256::from_parts(e, 0, 0, 0x2384773bdf1, 0xac5676facced6091)); + // p = ((p * x) >> 96) - 14706773417378608786704636184526 + p = p.mul(&x).shr(96).sub(&I256::from_parts(e, 0, 0, 0xb9a025d814, 0xb29c212b8b1a07ce)); + // p = p * x - (795164235651350426258249787498 << 96) + // (Pre-shifted constant; leaves p in 2^192 basis to skip a final shift.) + p = p.mul(&x).sub(&I256::from_parts(e, 0xa, 0x09507084cc699bb0, 0xe71ea86a00000000, 0)); + + // q polynomial — q has no zeros in the domain (all roots complex). + + // q = x + 5573035233440673466300451813936 + let mut q = x.add(&I256::from_parts(e, 0, 0, 0x465772b2bb, 0xbb5f824b15207a30)); + // q = ((q * x) >> 96) + 71694874799317883764090561454958 + q = q.mul(&x).shr(96).add(&I256::from_parts(e, 0, 0, 0x388eaa27412, 0xd5aca026815d636e)); + // q = ((q * x) >> 96) + 283447036172924575727196451306956 + q = q.mul(&x).shr(96).add(&I256::from_parts(e, 0, 0, 0xdf99ac50203, 0x1bf953eff472fdcc)); + // q = ((q * x) >> 96) + 401686690394027663651624208769553 + q = q.mul(&x).shr(96).add(&I256::from_parts(e, 0, 0, 0x13cdffb29d51, 0xd99322bdff5f2211)); + // q = ((q * x) >> 96) + 204048457590392012362485061816622 + q = q.mul(&x).shr(96).add(&I256::from_parts(e, 0, 0, 0xa0f742023de, 0xf783a307a986912e)); + // q = ((q * x) >> 96) + 31853899698501571402653359427138 + q = q.mul(&x).shr(96).add(&I256::from_parts(e, 0, 0, 0x1920d8043ca, 0x89b5239253284e42)); + // q = ((q * x) >> 96) + 909429971244387300277376558375 + q = q.mul(&x).shr(96).add(&I256::from_parts(e, 0, 0, 0xb7a86d737, 0x5468fac667a0a527)); + + // r = p / q -- result in (0, 0.125) * 2^96 basis (still 2^192 because we + // skipped the final shr in the p polynomial). + let mut r = p.div(&q); + + // Final scaling. Solmate folds three steps into one accumulator: + // * multiply by scale factor s (≈ 5.549) * 5e18 * 2^96 + // * add k * ln(2) * 5e18 * 2^192 + // * add ln(2^96 / 10^18) * 5e18 * 2^192 + // * shr 174 to convert from 5^18 * 2^192 basis back to 10^18 (WAD). + + // r *= 1677202110996718588342820967067443963516166 + r = r.mul(&I256::from_parts(e, 0, 0x1340, 0xdaa0d5f769dba191, 0x5cef59f0815a5506)); + // r += 16597577552685614221487285958193947469193820559219878177908093499208371 + // * k + let k_i256 = I256::from_i32(e, k); + r = r.add( + &I256::from_parts( + e, + 0x267a36c0c95, + 0xb3975ab3ee5b203a, + 0x7614a3f75373f047, + 0xd803ae7b6687f2b3, + ) + .mul(&k_i256), + ); + // r += 600920179829731861736702779321621459595472258049074101567377883020018308 + r = r.add(&I256::from_parts( + e, + 0x57115e47018c, + 0x7177eebf7cd370a3, + 0x356a1b7863008a5a, + 0xe8028c72b8864284, + )); + // r >>= 174 (5^18 * 2^192 → 10^18) + r = r.shr(174); + + r.to_i128() +} + +/// Natural exponential of a WAD value: returns `e^x` where `e ≈ 2.71828` +/// is Euler's number. +/// +/// This is **not** a power function. To raise an arbitrary base to an +/// arbitrary power, use [`crate::math::wad::Wad::powf`]. +/// +/// Returns `Some(0)` for `x <= EXP_INPUT_MIN` (underflow to 0, matching +/// Solmate). Returns `None` for `x >= EXP_INPUT_MAX` (would overflow even +/// in i256-with-2^96-scale). +pub(super) fn exp_wad(e: &Env, x: i128) -> Option { + if x <= EXP_INPUT_MIN { + return Some(0); + } + if x >= EXP_INPUT_MAX { + return None; + } + + // Convert from 10^18 to 2^96 fixed-point. The factor is + // 1e18 / 2^96 = 5^18 / 2^78, so `x = (x << 78) / 5^18`. The shifted + // value can exceed i128, so do this in I256. + let x = I256::from_i128(e, x).shl(78).div(&I256::from_i128(e, 3_814_697_265_625)); // 5^18 + + // Range-reduce: pick integer k so that r = x - k*ln(2)*2^96 has + // |r| ≤ ln(2)/2 * 2^96. Round-to-nearest is `(x + ln2_2pow96 / 2) / ln2_2pow96`, + // rewritten as Solmate does for asm efficiency: + // k = ((x << 96) / ln2_2pow96 + 2^95) >> 96 + let ln2_2pow96 = I256::from_parts(e, 0, 0, 0xb17217f7, 0xd1cf79abc9e3b398); // 54916777467707473351141471128 + let two_pow_95 = I256::from_i32(e, 1).shl(95); + let k = x.shl(96).div(&ln2_2pow96).add(&two_pow_95).shr(96); + let x = x.sub(&k.mul(&ln2_2pow96)); + + // ----- (6, 7)-term rational approximation of exp(r) ----- + + // y = x + 1346386616545796478920950773328 + let y_initial = x.add(&I256::from_parts(e, 0, 0, 0x10fe68e7fd, 0x37d0007b713f7650)); + // y = ((y * x) >> 96) + 57155421227552351082224309758442 + let y = y_initial.mul(&x).shr(96).add(&I256::from_parts( + e, + 0, + 0, + 0x2d16720577b, + 0xd19bf614176fe9ea, + )); + // p = y + x - 94201549194550492254356042504812 + let mut p = y.add(&x).sub(&I256::from_parts(e, 0, 0, 0x4a4fd9f2a8b, 0x96949216d2255a6c)); + // p = ((p * y) >> 96) + 28719021644029726153956944680412240 + p = p.mul(&y).shr(96).add(&I256::from_parts(e, 0, 0, 0x587f503bb6ea2, 0x9d25fcb740196450)); + // p = p * x + (4385272521454847904659076985693276 << 96) + // (pre-shifted constant) + p = p.mul(&x).add(&I256::from_parts(e, 0xd835, 0xebba824c98fb31b8, 0x3b2ca45c00000000, 0)); + + // q = x - 2855989394907223263936484059900 + let mut q = x.sub(&I256::from_parts(e, 0, 0, 0x240c330e9f, 0xb2d9cbaf0fd5aafc)); + // q = ((q * x) >> 96) + 50020603652535783019961831881945 + q = q.mul(&x).shr(96).add(&I256::from_parts(e, 0, 0, 0x277594991cf, 0xc85f6e2461837cd9)); + // q = ((q * x) >> 96) - 533845033583426703283633433725380 + q = q.mul(&x).shr(96).sub(&I256::from_parts(e, 0, 0, 0x1a521255e34f, 0x6a5061b25ef1c9c4)); + // q = ((q * x) >> 96) + 3604857256930695427073651918091429 + q = q.mul(&x).shr(96).add(&I256::from_parts(e, 0, 0, 0xb1bbb201f443, 0xcf962f1a1d3db4a5)); + // q = ((q * x) >> 96) - 14423608567350463180887372962807573 + q = q.mul(&x).shr(96).sub(&I256::from_parts(e, 0, 0, 0x2c72388d9f74f, 0x51a9331fed693f15)); + // q = ((q * x) >> 96) + 26449188498355588339934803723976023 + q = q.mul(&x).shr(96).add(&I256::from_parts(e, 0, 0, 0x5180bb14799ab, 0x47a8a8cb2a527d57)); + + // r = p / q -- result in (0.09, 0.25) * 2^96 (still 2^192 because we + // skipped a final shr in the p polynomial). + let r = p.div(&q); + + // Combined final scaling. Multiply by: + // * scale factor s (≈ 6.031...) * 1e18 * 2^96 + // * 2^k from range reduction + // * 1e18 / 2^96 base conversion + // Done as a single multiplication by `exp_final_mul` followed by a + // shr of `(195 - k)`. + // + // Solmate's source casts `r` to `uint256` here: + // int256((uint256(r) * 3822833...) >> uint256(195 - k)) + // This matters because the product `r * final_mul` can reach ~2^255, + // which overflows signed 256-bit but fits unsigned. We mirror that by + // moving the multiplication and shift into U256 (the final result is + // always positive — `exp` is positive — so the cast back is safe). + let r_bytes = r.to_be_bytes(); + let r_u256 = U256::from_be_bytes(e, &r_bytes); + + // dec: 3822833074963236453042738258902158003155416615667 + let final_mul = U256::from_parts(e, 0, 0x29d9dc385, 0x63c32e5c2f6dc192, 0xee70ef65f9978af3); + + // k is i32-sized after range reduction; narrow via to_i128. + let k_i128 = k.to_i128()?; + let shr_amount = (195_i128 - k_i128) as u32; + + let result_bytes = r_u256.mul(&final_mul).shr(shr_amount).to_be_bytes(); + I256::from_be_bytes(e, &result_bytes).to_i128() +} diff --git a/packages/contract-utils/src/math/mod.rs b/packages/contract-utils/src/math/mod.rs index e7e0616db..2af7e9d46 100644 --- a/packages/contract-utils/src/math/mod.rs +++ b/packages/contract-utils/src/math/mod.rs @@ -44,6 +44,7 @@ //! Based on the Soroban fixed-point mathematics library. //! Original implementation: +mod exp_ln; pub mod i128_fixed_point; pub mod i256_fixed_point; pub mod wad; @@ -63,6 +64,9 @@ pub enum SorobanFixedPointError { Overflow = 1500, /// Division by zero DivisionByZero = 1501, + /// Base is outside the valid domain (e.g. `ln(x)` for `x <= 0`, + /// or `powf(x, y)` with non-positive `x` combined with float exponent). + InvalidBase = 1502, } /// Rounding direction for division operations diff --git a/packages/contract-utils/src/math/test/wad.rs b/packages/contract-utils/src/math/test/wad.rs index 7db8b6717..5e5c6f7b4 100644 --- a/packages/contract-utils/src/math/test/wad.rs +++ b/packages/contract-utils/src/math/test/wad.rs @@ -495,75 +495,75 @@ fn test_abs_with_fractional() { // ################## POW TESTS ################## #[test] -fn test_pow_zero_exponent() { +fn test_powi_zero_exponent() { let e = Env::default(); let base = Wad::from_integer(&e, 42); - let result = base.pow(&e, 0); + let result = base.powi(&e, 0); assert_eq!(result, Wad::from_integer(&e, 1)); // x^0 = 1 } #[test] -fn test_pow_zero_base_zero_exponent() { +fn test_powi_zero_base_zero_exponent() { let e = Env::default(); let zero = Wad::from_raw(0); - let result = zero.pow(&e, 0); + let result = zero.powi(&e, 0); assert_eq!(result, Wad::from_integer(&e, 1)); // 0^0 = 1 (by convention) } #[test] -fn test_pow_one_exponent() { +fn test_powi_one_exponent() { let e = Env::default(); let base = Wad::from_ratio(&e, 355, 113); // π approximation - let result = base.pow(&e, 1); + let result = base.powi(&e, 1); assert_eq!(result, base); // x^1 = x } #[test] -fn test_pow_zero_base() { +fn test_powi_zero_base() { let e = Env::default(); let zero = Wad::from_raw(0); - let result = zero.pow(&e, 5); + let result = zero.powi(&e, 5); assert_eq!(result, Wad::from_raw(0)); // 0^n = 0 for n > 0 } #[test] -fn test_pow_one_base() { +fn test_powi_one_base() { let e = Env::default(); let one = Wad::from_integer(&e, 1); - let result = one.pow(&e, 100); + let result = one.powi(&e, 100); assert_eq!(result, Wad::from_integer(&e, 1)); // 1^n = 1 } #[test] -fn test_pow_integer_base_small_exponent() { +fn test_powi_integer_base_small_exponent() { let e = Env::default(); let two = Wad::from_integer(&e, 2); - let result = two.pow(&e, 10); + let result = two.powi(&e, 10); assert_eq!(result, Wad::from_integer(&e, 1024)); // 2^10 = 1024 } #[test] -fn test_pow_integer_base_quadratic() { +fn test_powi_integer_base_quadratic() { let e = Env::default(); let five = Wad::from_integer(&e, 5); - let result = five.pow(&e, 2); + let result = five.powi(&e, 2); assert_eq!(result, Wad::from_integer(&e, 25)); // 5^2 = 25 } #[test] -fn test_pow_integer_base_cubic() { +fn test_powi_integer_base_cubic() { let e = Env::default(); let three = Wad::from_integer(&e, 3); - let result = three.pow(&e, 3); + let result = three.powi(&e, 3); assert_eq!(result, Wad::from_integer(&e, 27)); // 3^3 = 27 } #[test] -fn test_pow_compound_interest() { +fn test_powi_compound_interest() { let e = Env::default(); // 5% annual rate: 1.05 let rate = Wad::from_ratio(&e, 105, 100); - let result = rate.pow(&e, 10); + let result = rate.powi(&e, 10); // (1.05)^10 ≈ 1.62889462677744140625 // In WAD: 1_628_894_626_777_441_406 (with truncation) @@ -572,10 +572,10 @@ fn test_pow_compound_interest() { } #[test] -fn test_pow_fractional_base_squared() { +fn test_powi_fractional_base_squared() { let e = Env::default(); let half = Wad::from_ratio(&e, 1, 2); // 0.5 - let result = half.pow(&e, 2); + let result = half.powi(&e, 2); // 0.5^2 = 0.25 let expected = Wad::from_ratio(&e, 1, 4); @@ -583,10 +583,10 @@ fn test_pow_fractional_base_squared() { } #[test] -fn test_pow_fractional_base_cubed() { +fn test_powi_fractional_base_cubed() { let e = Env::default(); let half = Wad::from_ratio(&e, 1, 2); // 0.5 - let result = half.pow(&e, 3); + let result = half.powi(&e, 3); // 0.5^3 = 0.125 let expected = Wad::from_ratio(&e, 1, 8); @@ -594,11 +594,11 @@ fn test_pow_fractional_base_cubed() { } #[test] -fn test_pow_fractional_less_than_one() { +fn test_powi_fractional_less_than_one() { let e = Env::default(); // 0.95 let decay = Wad::from_ratio(&e, 95, 100); - let result = decay.pow(&e, 10); + let result = decay.powi(&e, 10); // (0.95)^10 ≈ 0.59873693923837890625 // In WAD: 598_736_939_238_378_906 (with truncation) @@ -607,26 +607,26 @@ fn test_pow_fractional_less_than_one() { } #[test] -fn test_pow_negative_base_even_exponent() { +fn test_powi_negative_base_even_exponent() { let e = Env::default(); let neg_two = Wad::from_integer(&e, -2); - let result = neg_two.pow(&e, 4); + let result = neg_two.powi(&e, 4); assert_eq!(result, Wad::from_integer(&e, 16)); // (-2)^4 = 16 } #[test] -fn test_pow_negative_base_odd_exponent() { +fn test_powi_negative_base_odd_exponent() { let e = Env::default(); let neg_two = Wad::from_integer(&e, -2); - let result = neg_two.pow(&e, 3); + let result = neg_two.powi(&e, 3); assert_eq!(result, Wad::from_integer(&e, -8)); // (-2)^3 = -8 } #[test] -fn test_pow_negative_fractional_even() { +fn test_powi_negative_fractional_even() { let e = Env::default(); let neg_half = Wad::from_ratio(&e, -1, 2); // -0.5 - let result = neg_half.pow(&e, 2); + let result = neg_half.powi(&e, 2); // (-0.5)^2 = 0.25 let expected = Wad::from_ratio(&e, 1, 4); @@ -634,10 +634,10 @@ fn test_pow_negative_fractional_even() { } #[test] -fn test_pow_negative_fractional_odd() { +fn test_powi_negative_fractional_odd() { let e = Env::default(); let neg_half = Wad::from_ratio(&e, -1, 2); // -0.5 - let result = neg_half.pow(&e, 3); + let result = neg_half.powi(&e, 3); // (-0.5)^3 = -0.125 let expected = Wad::from_ratio(&e, -1, 8); @@ -645,11 +645,11 @@ fn test_pow_negative_fractional_odd() { } #[test] -fn test_pow_precision_decay() { +fn test_powi_precision_decay() { let e = Env::default(); // Each power operation involves truncation let base = Wad::from_ratio(&e, 999, 1000); // 0.999 - let result = base.pow(&e, 100); + let result = base.powi(&e, 100); // (0.999)^100 = // actual -> 0.9047921471137089XX @@ -661,19 +661,19 @@ fn test_pow_precision_decay() { } #[test] -fn test_pow_large_integer_base() { +fn test_powi_large_integer_base() { let e = Env::default(); let base = Wad::from_integer(&e, 10); - let result = base.pow(&e, 5); + let result = base.powi(&e, 5); assert_eq!(result, Wad::from_integer(&e, 100_000)); // 10^5 = 100,000 } #[test] -fn test_pow_truncation_behavior() { +fn test_powi_truncation_behavior() { let e = Env::default(); // Use a base that will produce fractional intermediate results let base = Wad::from_raw(1_414_213_562_373_095_048); // √2 ≈ 1.414213562373095048 - let result = base.pow(&e, 2); + let result = base.powi(&e, 2); // (√2)^2 should be very close to 2, but truncation may cause slight deviation let two = Wad::from_integer(&e, 2); @@ -685,75 +685,75 @@ fn test_pow_truncation_behavior() { #[test] #[should_panic(expected = "Error(Contract, #1500)")] -fn test_pow_overflow_large_base() { +fn test_powi_overflow_large_base() { let e = Env::default(); // Base that's too large let large = Wad::from_integer(&e, i128::MAX / WAD_SCALE); - let _ = large.pow(&e, 2); // Will overflow + let _ = large.powi(&e, 2); // Will overflow } #[test] #[should_panic(expected = "Error(Contract, #1500)")] -fn test_pow_overflow_large_exponent() { +fn test_powi_overflow_large_exponent() { let e = Env::default(); let two = Wad::from_integer(&e, 2); - let _ = two.pow(&e, 128); // 2^128 overflows i128 + let _ = two.powi(&e, 128); // 2^128 overflows i128 } // ################## CHECKED_POW TESTS ################## #[test] -fn test_checked_pow_success() { +fn test_checked_powi_success() { let e = Env::default(); let two = Wad::from_integer(&e, 2); - let result = two.checked_pow(&e, 10); + let result = two.checked_powi(&e, 10); assert_eq!(result, Some(Wad::from_integer(&e, 1024))); } #[test] -fn test_checked_pow_overflow_returns_none() { +fn test_checked_powi_overflow_returns_none() { let e = Env::default(); let large = Wad::from_integer(&e, i128::MAX / WAD_SCALE); - let result = large.checked_pow(&e, 2); + let result = large.checked_powi(&e, 2); assert_eq!(result, None); // Overflow returns None instead of panicking } #[test] -fn test_checked_pow_zero_exponent() { +fn test_checked_powi_zero_exponent() { let e = Env::default(); let base = Wad::from_integer(&e, 42); - let result = base.checked_pow(&e, 0); + let result = base.checked_powi(&e, 0); assert_eq!(result, Some(Wad::from_integer(&e, 1))); } #[test] -fn test_checked_pow_one_exponent() { +fn test_checked_powi_one_exponent() { let e = Env::default(); let base = Wad::from_ratio(&e, 355, 113); - let result = base.checked_pow(&e, 1); + let result = base.checked_powi(&e, 1); assert_eq!(result, Some(base)); } #[test] -fn test_checked_pow_zero_base() { +fn test_checked_powi_zero_base() { let e = Env::default(); let zero = Wad::from_raw(0); - let result = zero.checked_pow(&e, 5); + let result = zero.checked_powi(&e, 5); assert_eq!(result, Some(Wad::from_raw(0))); } #[test] -fn test_checked_pow_compound_interest() { +fn test_checked_powi_compound_interest() { let e = Env::default(); let rate = Wad::from_ratio(&e, 105, 100); // 1.05 - let result = rate.checked_pow(&e, 10); + let result = rate.checked_powi(&e, 10); let expected = Wad::from_raw(1_628_894_626_777_441_406); assert_eq!(result, Some(expected)); } #[test] -fn test_checked_pow_large_exponent_overflow() { +fn test_checked_powi_large_exponent_overflow() { /* 2^n × 10^18 ≤ i128::MAX 2^n × 2^59.79 ≤ 2^127 @@ -763,14 +763,445 @@ fn test_checked_pow_large_exponent_overflow() { */ let e = Env::default(); let two = Wad::from_integer(&e, 2); - let result = two.checked_pow(&e, 68); + let result = two.checked_powi(&e, 68); assert_eq!(result, None); } #[test] -fn test_checked_pow_fractional_base() { +fn test_checked_powi_fractional_base() { let e = Env::default(); let half = Wad::from_ratio(&e, 1, 2); - let result = half.checked_pow(&e, 3); + let result = half.checked_powi(&e, 3); assert_eq!(result, Some(Wad::from_ratio(&e, 1, 8))); } + +// ################## LN TESTS ################## + +/// Helper: assert two Wad values are within `tol` (tolerance) raw units of each +/// other. +fn assert_close(actual: Wad, expected: Wad, tol: i128, label: &str) { + let diff = (actual.raw() - expected.raw()).abs(); + assert!( + diff <= tol, + "{label}: actual={} expected={} diff={} tol={}", + actual.raw(), + expected.raw(), + diff, + tol + ); +} + +#[test] +fn test_ln_one() { + let e = Env::default(); + let one = Wad::from_integer(&e, 1); + // ln(1) = 0 exactly + assert_eq!(one.ln(&e), Wad::from_raw(0)); +} + +#[test] +fn test_ln_e() { + let e = Env::default(); + // e ≈ 2.718281828459045235 + let e_wad = Wad::from_raw(2_718_281_828_459_045_235); + let result = e_wad.ln(&e); + // ln(e) = 1 + assert_close(result, Wad::from_integer(&e, 1), 5, "ln(e)"); +} + +#[test] +fn test_ln_two() { + let e = Env::default(); + let two = Wad::from_integer(&e, 2); + let result = two.ln(&e); + // ln(2) ≈ 0.693147180559945309 + let expected = Wad::from_raw(693_147_180_559_945_309); + assert_close(result, expected, 5, "ln(2)"); +} + +#[test] +fn test_ln_ten() { + let e = Env::default(); + let ten = Wad::from_integer(&e, 10); + let result = ten.ln(&e); + // ln(10) ≈ 2.302585092994045684 + let expected = Wad::from_raw(2_302_585_092_994_045_684); + assert_close(result, expected, 5, "ln(10)"); +} + +#[test] +fn test_ln_half() { + let e = Env::default(); + let half = Wad::from_ratio(&e, 1, 2); + let result = half.ln(&e); + // ln(0.5) = -ln(2) ≈ -0.693147180559945309 + let expected = Wad::from_raw(-693_147_180_559_945_309); + assert_close(result, expected, 5, "ln(0.5)"); +} + +#[test] +fn test_ln_large() { + let e = Env::default(); + // ln(1e10) = 10 * ln(10) ≈ 23.025850929940456840 + let large = Wad::from_integer(&e, 10_000_000_000); + let result = large.ln(&e); + let expected = Wad::from_raw(23_025_850_929_940_456_840); + assert_close(result, expected, 50, "ln(1e10)"); +} + +#[test] +fn test_ln_very_large_triggers_shr_branch() { + let e = Env::default(); + // Raw WAD value 10^30 ≈ 2^99.66, so ilog2 = 99 and k = 3 > 0, + // which exercises the right-shift normalization branch in ln_wad. + // ln(1e12) = 12 * ln(10) ≈ 27.631021115928548208 + let large = Wad::from_integer(&e, 1_000_000_000_000); + let result = large.ln(&e); + let expected = Wad::from_raw(27_631_021_115_928_548_208); + assert_close(result, expected, 100, "ln(1e12)"); +} + +#[test] +#[should_panic(expected = "Error(Contract, #1502)")] +fn test_ln_zero_panics() { + let e = Env::default(); + let _ = Wad::from_raw(0).ln(&e); +} + +#[test] +#[should_panic(expected = "Error(Contract, #1502)")] +fn test_ln_negative_panics() { + let e = Env::default(); + let _ = Wad::from_integer(&e, -5).ln(&e); +} + +#[test] +fn test_checked_ln_zero_returns_none() { + let e = Env::default(); + assert_eq!(Wad::from_raw(0).checked_ln(&e), None); +} + +#[test] +fn test_checked_ln_negative_returns_none() { + let e = Env::default(); + assert_eq!(Wad::from_integer(&e, -1).checked_ln(&e), None); +} + +#[test] +fn test_checked_ln_positive() { + let e = Env::default(); + let two = Wad::from_integer(&e, 2); + let result = two.checked_ln(&e).unwrap(); + let expected = Wad::from_raw(693_147_180_559_945_309); + assert_close(result, expected, 5, "checked_ln(2)"); +} + +// ################## EXP TESTS ################## + +#[test] +fn test_exp_zero() { + let e = Env::default(); + let result = Wad::from_raw(0).exp(&e); + assert_eq!(result, Wad::from_integer(&e, 1)); +} + +#[test] +fn test_exp_one() { + let e = Env::default(); + let one = Wad::from_integer(&e, 1); + let result = one.exp(&e); + // e ≈ 2.718281828459045235 + let expected = Wad::from_raw(2_718_281_828_459_045_235); + assert_close(result, expected, 5, "exp(1)"); +} + +#[test] +fn test_exp_negative_one() { + let e = Env::default(); + let neg_one = Wad::from_integer(&e, -1); + let result = neg_one.exp(&e); + // 1/e ≈ 0.367879441171442322 + let expected = Wad::from_raw(367_879_441_171_442_322); + assert_close(result, expected, 5, "exp(-1)"); +} + +#[test] +fn test_exp_ln_two_is_two() { + let e = Env::default(); + // ln(2) ≈ 0.693147180559945309 → exp(ln(2)) = 2 + let ln2 = Wad::from_raw(693_147_180_559_945_309); + let result = ln2.exp(&e); + assert_close(result, Wad::from_integer(&e, 2), 5, "exp(ln(2))"); +} + +#[test] +fn test_exp_underflow_returns_zero() { + let e = Env::default(); + // Below -42.139... — Solmate convention: rounds to 0. + let very_negative = Wad::from_integer(&e, -100); + assert_eq!(very_negative.exp(&e), Wad::from_raw(0)); +} + +#[test] +fn test_exp_at_lower_bound_returns_zero() { + let e = Env::default(); + let bound = Wad::from_raw(-42_139_678_854_452_767_551); + assert_eq!(bound.exp(&e), Wad::from_raw(0)); +} + +#[test] +#[should_panic(expected = "Error(Contract, #1500)")] +fn test_exp_overflow_panics() { + let e = Env::default(); + // Just above the upper bound (135.305...). + let too_large = Wad::from_raw(135_305_999_368_893_231_589); + let _ = too_large.exp(&e); +} + +#[test] +fn test_checked_exp_overflow_returns_none() { + let e = Env::default(); + let too_large = Wad::from_integer(&e, 200); + assert_eq!(too_large.checked_exp(&e), None); +} + +#[test] +fn test_checked_exp_underflow_returns_zero() { + // Underflow is not an error — it's a defined return of 0. + let e = Env::default(); + let very_negative = Wad::from_integer(&e, -100); + assert_eq!(very_negative.checked_exp(&e), Some(Wad::from_raw(0))); +} + +#[test] +fn test_exp_ln_roundtrip() { + let e = Env::default(); + // exp(ln(x)) ≈ x for various positive x. Tolerance is per-magnitude + // (~1e-15 relative): for large x, raw error scales with x. + for raw_x in [ + 500_000_000_000_000_000i128, // 0.5 + 1_000_000_000_000_000_000, // 1 + 2_500_000_000_000_000_000, // 2.5 + 100_000_000_000_000_000_000, // 100 + 1_000_000_000_000_000_000_000, // 1000 + ] { + let x = Wad::from_raw(raw_x); + let recovered = x.ln(&e).exp(&e); + // ~1e-15 relative tolerance: tol = max(10, raw_x / 1e15) + let tol = (raw_x / 1_000_000_000_000_000).max(10); + assert_close(recovered, x, tol, "exp(ln(x)) roundtrip"); + } +} + +// ################## POW_WAD TESTS ################## + +#[test] +fn test_powf_y_zero() { + let e = Env::default(); + let x = Wad::from_integer(&e, 42); + assert_eq!(x.powf(&e, Wad::from_raw(0)), Wad::from_integer(&e, 1)); +} + +#[test] +fn test_powf_zero_zero() { + let e = Env::default(); + let zero = Wad::from_raw(0); + // 0^0 = 1 (matches existing pow convention) + assert_eq!(zero.powf(&e, zero), Wad::from_integer(&e, 1)); +} + +#[test] +fn test_powf_zero_positive_y() { + let e = Env::default(); + let zero = Wad::from_raw(0); + let y = Wad::from_integer(&e, 5); + assert_eq!(zero.powf(&e, y), Wad::from_raw(0)); +} + +#[test] +#[should_panic(expected = "Error(Contract, #1501)")] +fn test_powf_zero_negative_y_panics() { + let e = Env::default(); + let zero = Wad::from_raw(0); + let neg_y = Wad::from_integer(&e, -1); + let _ = zero.powf(&e, neg_y); +} + +#[test] +fn test_powf_one_base() { + let e = Env::default(); + let one = Wad::from_integer(&e, 1); + let weird_y = Wad::from_ratio(&e, 355, 113); // π-ish + assert_eq!(one.powf(&e, weird_y), one); +} + +#[test] +fn test_powf_y_one() { + let e = Env::default(); + let x = Wad::from_ratio(&e, 7, 13); + let one = Wad::from_integer(&e, 1); + assert_eq!(x.powf(&e, one), x); +} + +#[test] +fn test_powf_integer_exponent_matches_powi() { + // Integer-y fast path should produce identical results to pow(u32). + let e = Env::default(); + for &(raw_x, n) in &[ + (2_000_000_000_000_000_000i128, 10u32), // 2^10 + (1_050_000_000_000_000_000, 20), // 1.05^20 + (3_000_000_000_000_000_000, 5), // 3^5 + ] { + let x = Wad::from_raw(raw_x); + let y_wad = Wad::from_integer(&e, n as i128); + assert_eq!(x.powf(&e, y_wad), x.powi(&e, n)); + } +} + +#[test] +fn test_powf_negative_base_integer_exponent() { + let e = Env::default(); + let neg_two = Wad::from_integer(&e, -2); + // (-2)^3 = -8 — handled by integer fast path. + assert_eq!(neg_two.powf(&e, Wad::from_integer(&e, 3)), Wad::from_integer(&e, -8)); + // (-2)^4 = 16 + assert_eq!(neg_two.powf(&e, Wad::from_integer(&e, 4)), Wad::from_integer(&e, 16)); +} + +#[test] +fn test_powf_sqrt_two() { + let e = Env::default(); + // 2^0.5 = √2 ≈ 1.414213562373095048 + let two = Wad::from_integer(&e, 2); + let half = Wad::from_ratio(&e, 1, 2); + let result = two.powf(&e, half); + let expected = Wad::from_raw(1_414_213_562_373_095_048); + assert_close(result, expected, 10, "2^0.5"); +} + +#[test] +fn test_powf_two_to_the_2_5() { + let e = Env::default(); + // 2^2.5 = 4 * √2 ≈ 5.656854249492380195 + let two = Wad::from_integer(&e, 2); + let exp = Wad::from_raw(2_500_000_000_000_000_000); // 2.5 + let result = two.powf(&e, exp); + let expected = Wad::from_raw(5_656_854_249_492_380_195); + assert_close(result, expected, 50, "2^2.5"); +} + +#[test] +fn test_powf_compound_interest_fractional() { + let e = Env::default(); + // (1.05)^2.5 ≈ 1.126162419641586023 + let rate = Wad::from_ratio(&e, 105, 100); + let years = Wad::from_raw(2_500_000_000_000_000_000); // 2.5 + let result = rate.powf(&e, years); + // Truncated 1.129726321947045721750119514527445981979... + let expected = Wad::from_raw(1_129_726_321_947_045_721); + assert_close(result, expected, 10, "1.05^2.5"); +} + +#[test] +fn test_powf_negative_exponent() { + let e = Env::default(); + // 2^(-1) = 0.5 — falls through to general path (negative non-integer-flagged y) + let two = Wad::from_integer(&e, 2); + let neg_one = Wad::from_integer(&e, -1); + let result = two.powf(&e, neg_one); + let expected = Wad::from_ratio(&e, 1, 2); + assert_close(result, expected, 10, "2^-1"); +} + +#[test] +fn test_powf_negative_fractional_exponent() { + let e = Env::default(); + // 2^(-0.5) = 1/√2 ≈ 0.707106781186547524 + let two = Wad::from_integer(&e, 2); + let neg_half = Wad::from_ratio(&e, -1, 2); + let result = two.powf(&e, neg_half); + let expected = Wad::from_raw(707_106_781_186_547_524); + assert_close(result, expected, 10, "2^-0.5"); +} + +#[test] +#[should_panic(expected = "Error(Contract, #1502)")] +fn test_powf_negative_base_non_integer_panics() { + let e = Env::default(); + // (-2)^0.5 — undefined in real numbers. + let neg_two = Wad::from_integer(&e, -2); + let half = Wad::from_ratio(&e, 1, 2); + let _ = neg_two.powf(&e, half); +} + +#[test] +fn test_checked_powf_overflow_returns_none() { + let e = Env::default(); + // 1000^1000 overflows wildly. + let big = Wad::from_integer(&e, 1000); + let result = big.checked_powf(&e, big); + assert_eq!(result, None); +} + +#[test] +fn test_checked_powf_negative_base_returns_none() { + let e = Env::default(); + let neg_two = Wad::from_integer(&e, -2); + let half = Wad::from_ratio(&e, 1, 2); + assert_eq!(neg_two.checked_powf(&e, half), None); +} + +#[test] +fn test_checked_powf_zero_negative_returns_none() { + let e = Env::default(); + let zero = Wad::from_raw(0); + let neg_one = Wad::from_integer(&e, -1); + assert_eq!(zero.checked_powf(&e, neg_one), None); +} + +#[test] +fn test_checked_powf_success() { + let e = Env::default(); + let two = Wad::from_integer(&e, 2); + let half = Wad::from_ratio(&e, 1, 2); + let result = two.checked_powf(&e, half).unwrap(); + let expected = Wad::from_raw(1_414_213_562_373_095_048); + assert_close(result, expected, 10, "checked_powf(2, 0.5)"); +} + +#[test] +fn test_checked_powf_y_zero() { + // x^0 = 1 for any x, via the y==0 fast path. + let e = Env::default(); + let x = Wad::from_integer(&e, 42); + assert_eq!(x.checked_powf(&e, Wad::from_raw(0)), Some(Wad::from_integer(&e, 1))); +} + +#[test] +fn test_checked_powf_one_base() { + // 1^y = 1 for any y, via the x==1 fast path. + let e = Env::default(); + let one = Wad::from_integer(&e, 1); + let weird_y = Wad::from_ratio(&e, 355, 113); // π-ish, definitely non-integer + assert_eq!(one.checked_powf(&e, weird_y), Some(one)); +} + +#[test] +fn test_checked_powf_y_one() { + // x^1 = x for any x, via the y==1 fast path. + let e = Env::default(); + let x = Wad::from_ratio(&e, 7, 13); + let one = Wad::from_integer(&e, 1); + assert_eq!(x.checked_powf(&e, one), Some(x)); +} + +#[test] +fn test_checked_powf_integer_exponent_matches_powi() { + // Integer-y fast path: checked_powf delegates to checked_powi when the + // exponent is an exact non-negative integer in u32 range. + let e = Env::default(); + let two = Wad::from_integer(&e, 2); + let three_wad = Wad::from_integer(&e, 3); + assert_eq!(two.checked_powf(&e, three_wad), two.checked_powi(&e, 3)); + assert_eq!(two.checked_powf(&e, three_wad), Some(Wad::from_integer(&e, 8))); +} diff --git a/packages/contract-utils/src/math/wad.rs b/packages/contract-utils/src/math/wad.rs index bd063c297..a7d2fe0f5 100644 --- a/packages/contract-utils/src/math/wad.rs +++ b/packages/contract-utils/src/math/wad.rs @@ -5,7 +5,11 @@ use core::{ use soroban_sdk::{panic_with_error, Env}; -use crate::math::{i128_fixed_point::checked_mul_div, SorobanFixedPointError}; +use crate::math::{ + exp_ln::{exp_wad, ln_wad}, + i128_fixed_point::checked_mul_div, + SorobanFixedPointError, +}; /// Fixed-point decimal number with 18 decimal places of precision. /// @@ -358,7 +362,6 @@ impl Wad { /// # Examples /// /// ```ignore - /// let e = Env::default(); /// let negative = Wad::from_integer(&e, -5); /// assert_eq!(negative.abs(), Wad::from_integer(&e, 5)); /// ``` @@ -374,6 +377,8 @@ impl Wad { /// maintains fixed-point precision by dividing by WAD_SCALE, with /// truncation toward zero. /// + /// For non-integer exponents, see [`Wad::powf`] (uses `exp(y * ln(x))`). + /// /// # Arguments /// /// * `e` - Access to the Soroban environment for error handling. @@ -389,19 +394,19 @@ impl Wad { /// ```ignore /// // Compound interest: (1.05)^10 /// let rate = Wad::from_ratio(&e, 105, 100); // 1.05 - /// let final_multiplier = rate.pow(&e, 10); + /// let final_multiplier = rate.powi(&e, 10); /// let final_amount = principal * final_multiplier; /// /// // Quadratic bonding curve: price = supply^2 /// let supply = Wad::from_integer(&e, 1000); - /// let price = supply.pow(&e, 2); + /// let price = supply.powi(&e, 2); /// ``` - pub fn pow(self, e: &Env, exponent: u32) -> Self { - self.checked_pow(e, exponent) + pub fn powi(self, e: &Env, exponent: u32) -> Self { + self.checked_powi(e, exponent) .unwrap_or_else(|| panic_with_error!(e, SorobanFixedPointError::Overflow)) } - /// Checked version of [`Wad::pow`]. + /// Checked version of [`Wad::powi`]. /// /// Returns `None` instead of panicking on overflow. Handles phantom /// overflow transparently by scaling to `I256` when intermediate @@ -415,18 +420,17 @@ impl Wad { /// # Examples /// /// ```ignore - /// let e = Env::default(); /// let small = Wad::from_integer(&e, 2); - /// assert_eq!(small.checked_pow(&e, 10), Some(Wad::from_integer(&e, 1024))); + /// assert_eq!(small.checked_powi(&e, 10), Some(Wad::from_integer(&e, 1024))); /// /// let large = Wad::from_integer(&e, i128::MAX / WAD_SCALE); - /// assert_eq!(large.checked_pow(&e, 2), None); // Overflows + /// assert_eq!(large.checked_powi(&e, 2), None); // Overflows /// ``` /// /// # Notes /// /// Phantom overflow is handled internally. - pub fn checked_pow(self, e: &Env, mut exponent: u32) -> Option { + pub fn checked_powi(self, e: &Env, mut exponent: u32) -> Option { // Handle base cases if exponent == 0 { return Some(Wad(WAD_SCALE)); // x^0 = 1 @@ -482,6 +486,204 @@ impl Wad { Some(result) } + + /// Natural logarithm of `self`. + /// + /// # Arguments + /// + /// * `e` - Access to the Soroban environment. + /// + /// # Errors + /// + /// * [`SorobanFixedPointError::InvalidBase`] - When `self <= 0`. `ln` is + /// undefined for non-positive inputs. + /// + /// # Examples + /// + /// ```ignore + /// let one = Wad::from_integer(&e, 1); + /// assert_eq!(one.ln(&e), Wad::from_raw(0)); // ln(1) = 0 + /// ``` + pub fn ln(self, e: &Env) -> Self { + self.checked_ln(e) + .unwrap_or_else(|| panic_with_error!(e, SorobanFixedPointError::InvalidBase)) + } + + /// Checked version of [`Wad::ln`]. + /// + /// Returns `None` if `self <= 0`. + pub fn checked_ln(self, e: &Env) -> Option { + ln_wad(e, self.0).map(Wad) + } + + /// Natural exponential of `self`: returns `e^self`, where `e ≈ 2.71828` + /// is Euler's number. + /// + /// This is **not** a generic power function — for `x^y` with an arbitrary + /// base, use [`Wad::powf`]. `Wad::exp` is the inverse of [`Wad::ln`] + /// + /// Returns `0` for inputs at or below `≈ -42.139` (the result rounds to 0 + /// in WAD precision). Panics for inputs at or above `≈ 135.305` (overflow). + /// + /// # Arguments + /// + /// * `e` - Access to the Soroban environment. + /// + /// # Errors + /// + /// * [`SorobanFixedPointError::Overflow`] - When the input is too large to + /// represent the result in i128. + /// + /// # Examples + /// + /// ```ignore + /// let zero = Wad::from_raw(0); + /// assert_eq!(zero.exp(&e), Wad::from_integer(&e, 1)); // exp(0) = 1 + /// ``` + pub fn exp(self, e: &Env) -> Self { + self.checked_exp(e) + .unwrap_or_else(|| panic_with_error!(e, SorobanFixedPointError::Overflow)) + } + + /// Checked version of [`Wad::exp`]. Computes `e^self` where `e` is + /// Euler's number; not a power function. + /// + /// Returns `None` if the input is at or above the overflow bound. + pub fn checked_exp(self, e: &Env) -> Option { + exp_wad(e, self.0).map(Wad) + } + + /// Raises `self` to a `Wad` power (the floating-point analogue of + /// [`Wad::powi`]). + /// + /// Computes `self^exponent` for arbitrary fractional exponents using + /// `exp(exponent * ln(self))`. Falls back to integer exponentiation + /// (via [`Wad::powi`]) when `exponent` is an exact non-negative integer + /// in the `u32` range — this is faster and more precise. + /// + /// # Special cases + /// + /// - `x^0 = 1` for any `x` (including `0^0 = 1`, matching the convention + /// used by [`Wad::powi`], Python's `pow`, and IEEE 754). + /// - `0^y = 0` for `y > 0`. + /// - `1^y = 1` for any `y`. + /// - `x^1 = x` for any `x`. + /// + /// # Arguments + /// + /// * `e` - Access to the Soroban environment. + /// * `exponent` - The exponent. + /// + /// # Errors + /// + /// * [`SorobanFixedPointError::DivisionByZero`] - When `self == 0` and + /// `exponent < 0`. + /// * [`SorobanFixedPointError::InvalidBase`] - When `self < 0` + /// * [`SorobanFixedPointError::Overflow`] - When the result doesn't fit in + /// i128. + /// + /// # Examples + /// + /// ```ignore + /// // 2^0.5 ≈ √2 + /// let two = Wad::from_integer(&e, 2); + /// let half = Wad::from_ratio(&e, 1, 2); + /// let sqrt_two = two.powf(&e, half); + /// ``` + pub fn powf(self, e: &Env, exponent: Wad) -> Self { + // 0^0 = 1 + if exponent.0 == 0 { + return Wad(WAD_SCALE); + } + // 0^y for y > 0 = 0; + // 0^y for y < 0 → division by zero + if self.0 == 0 { + if exponent.0 > 0 { + return Wad(0); + } + panic_with_error!(e, SorobanFixedPointError::DivisionByZero); + } + // 1^y = 1 + if self.0 == WAD_SCALE { + return self; + } + // x^1 = x + if exponent.0 == WAD_SCALE { + return self; + } + + // Integer-y fast path: when `exponent` is an exact non-negative + // integer that fits in u32, delegate to the integer `powi`. This + // also handles `x < 0` correctly (e.g. `(-2)^3 = -8`), which the + // general path below rejects (`(-2)^1.5` is complex). + // + // `exponent.0 % WAD_SCALE == 0` checks for "no fractional part": + // a WAD value is an exact integer iff its raw representation is a + // clean multiple of `WAD_SCALE` (10^18). For example, `2.0` has + // raw = `2 * 10^18` (mod = 0); `2.5` has raw = `2.5 * 10^18` + // (mod ≠ 0). + if exponent.0 > 0 && exponent.0 % WAD_SCALE == 0 { + let n = exponent.0 / WAD_SCALE; + if n <= u32::MAX as i128 { + return self.powi(e, n as u32); + } + } + + // General path requires a positive base (because we compute ln(x)). + if self.0 < 0 { + panic_with_error!(e, SorobanFixedPointError::InvalidBase); + } + + // x^y = exp(y * ln(x)) + let ln_x = ln_wad(e, self.0) + .unwrap_or_else(|| panic_with_error!(e, SorobanFixedPointError::InvalidBase)); + let y_ln_x = checked_mul_div(e, &exponent.0, &ln_x, &WAD_SCALE) + .unwrap_or_else(|| panic_with_error!(e, SorobanFixedPointError::Overflow)); + exp_wad(e, y_ln_x) + .map(Wad) + .unwrap_or_else(|| panic_with_error!(e, SorobanFixedPointError::Overflow)) + } + + /// Checked version of [`Wad::powf`]. + /// + /// Special cases mirror [`Wad::powf`]: `x^0 = 1` for any `x` (including + /// `0^0 = 1`), `0^y = 0` for `y > 0`, `1^y = 1`, `x^1 = x`. + /// + /// Returns `None` for all error conditions: overflow, `0^negative`, + /// and negative base with non-integer exponent. + pub fn checked_powf(self, e: &Env, exponent: Wad) -> Option { + if exponent.0 == 0 { + return Some(Wad(WAD_SCALE)); + } + if self.0 == 0 { + return if exponent.0 > 0 { Some(Wad(0)) } else { None }; + } + if self.0 == WAD_SCALE { + return Some(self); + } + if exponent.0 == WAD_SCALE { + return Some(self); + } + + // Integer-y fast path. `exponent.0 % WAD_SCALE == 0` means the WAD + // value has no fractional part (raw is an exact multiple of 10^18). + // See `powf` for details. + if exponent.0 > 0 && exponent.0 % WAD_SCALE == 0 { + let n = exponent.0 / WAD_SCALE; + if n <= u32::MAX as i128 { + return self.checked_powi(e, n as u32); + } + } + + if self.0 < 0 { + return None; + } + + // x^y = exp(y * ln(x)) + let ln_x = ln_wad(e, self.0)?; + let y_ln_x = checked_mul_div(e, &exponent.0, &ln_x, &WAD_SCALE)?; + exp_wad(e, y_ln_x).map(Wad) + } } // Wad + Wad