Skip to content

Commit

Permalink
Impl and test encode_sqrt_ratio_x96
Browse files Browse the repository at this point in the history
  • Loading branch information
shuhuiluo committed Dec 29, 2023
1 parent dbd2c41 commit 778ff35
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 2 deletions.
7 changes: 7 additions & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ jobs:
restore-keys: |
${{ runner.os }}-cargo-registry-
- name: Install Rust toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true

- name: Build
run: cargo build --verbose

Expand Down
45 changes: 45 additions & 0 deletions src/utils/encode_sqrt_ratio_x96.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use num_bigint::BigInt;
use uniswap_sdk_core_rust::utils::sqrt::sqrt;

/// Returns the sqrt ratio as a Q64.96 corresponding to a given ratio of amount1 and amount0
///
/// # Arguments
///
/// * `amount1`: The numerator amount i.e., the amount of token1
/// * `amount0`: The denominator amount i.e., the amount of token0
///
/// returns: BigInt The sqrt ratio
///
pub fn encode_sqrt_ratio_x96(amount1: impl Into<BigInt>, amount0: impl Into<BigInt>) -> BigInt {
let numerator: BigInt = amount1.into() << 192;
let denominator = amount0.into();
sqrt(&(numerator / denominator))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_encode_sqrt_ratio_x96() {
let q96 = BigInt::from(1) << 96;

assert_eq!(encode_sqrt_ratio_x96(1, 1), q96);
assert_eq!(
encode_sqrt_ratio_x96(100, 1),
792281625142643375935439503360u128.into()
);
assert_eq!(
encode_sqrt_ratio_x96(1, 100),
7922816251426433759354395033u128.into()
);
assert_eq!(
encode_sqrt_ratio_x96(111, 333),
45742400955009932534161870629u128.into()
);
assert_eq!(
encode_sqrt_ratio_x96(333, 111),
137227202865029797602485611888u128.into()
);
}
}
7 changes: 5 additions & 2 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
mod compute_pool_address;
pub use compute_pool_address::compute_pool_address;

mod encode_sqrt_ratio_x96;
pub use encode_sqrt_ratio_x96::encode_sqrt_ratio_x96;

mod nearest_usable_tick;
pub use nearest_usable_tick::nearest_usable_tick;

mod tick_math;
pub use tick_math::*;

pub use nearest_usable_tick::nearest_usable_tick;

0 comments on commit 778ff35

Please sign in to comment.