Skip to content

Commit

Permalink
Merge pull request #287 from invariant-labs/add-utiles-invariant-types
Browse files Browse the repository at this point in the history
Utils Invariant-types module
  • Loading branch information
wojciech-cichocki authored Jul 22, 2023
2 parents a36e2fc + 0f783ac commit 38d98b0
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 3 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

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

54 changes: 53 additions & 1 deletion programs/invariant/invariant-types/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
use std::cmp::Ordering;

use anchor_lang::prelude::Pubkey;

use crate::ID;

pub type TrackableResult<T> = Result<T, TrackableError>;

#[derive(Debug)]
Expand Down Expand Up @@ -47,6 +53,31 @@ impl TrackableError {
}
}

pub fn get_pool_address(
first_token: Pubkey,
second_token: Pubkey,
fee: u128,
tick_spacing: u16,
) -> Pubkey {
let inverse = first_token.to_string().cmp(&second_token.to_string()) == Ordering::Less;
let (token_x, token_y) = match inverse {
true => (first_token, second_token),
false => (second_token, first_token),
};

let (pool_address, _) = Pubkey::find_program_address(
&[
b"poolv1",
token_x.as_ref(),
token_y.as_ref(),
&fee.to_le_bytes(),
&tick_spacing.to_le_bytes(),
],
&ID,
);
pool_address
}

#[macro_use]
pub mod trackable_result {
#[macro_export]
Expand Down Expand Up @@ -105,7 +136,7 @@ pub mod trackable_result {
}

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

fn value() -> TrackableResult<u64> {
Expand Down Expand Up @@ -172,3 +203,24 @@ mod tests {
}
}
}

#[cfg(test)]
mod tests {
use std::str::FromStr;

#[test]
fn test_get_pool_address() {
use super::*;
let token_x = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap();
let token_y = Pubkey::from_str("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB").unwrap();
let fee = 10000000;
let tick_spacing = 1;

let pool_address_1 = get_pool_address(token_x, token_y, fee, tick_spacing);
let pool_address_2 = get_pool_address(token_y, token_x, fee, tick_spacing);
let expected = Pubkey::from_str("BRt1iVYDNoohkL1upEb8UfHE8yji6gEDAmuN9Y4yekyc").unwrap();

assert_eq!(pool_address_1, expected);
assert_eq!(pool_address_2, expected);
}
}

1 comment on commit 38d98b0

@vercel
Copy link

@vercel vercel bot commented on 38d98b0 Jul 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.