Skip to content

Commit

Permalink
fix helper
Browse files Browse the repository at this point in the history
  • Loading branch information
tubackkhoa committed Aug 28, 2024
1 parent ad9dc33 commit 96bb42b
Show file tree
Hide file tree
Showing 7 changed files with 133 additions and 57 deletions.
40 changes: 26 additions & 14 deletions contracts/oraiswap-v3/src/entrypoints/common.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use cosmwasm_std::{Addr, Api, CosmosMsg, Deps, DepsMut, Env, MessageInfo, Storage, Timestamp};
use cosmwasm_std::{
Addr, Api, CosmosMsg, Deps, DepsMut, Env, MessageInfo, Order, Storage, Timestamp,
};

use cw20::Expiration;
use cw_storage_plus::Bound;
use decimal::{CheckedOps, Decimal};

use crate::{
Expand All @@ -9,8 +12,7 @@ use crate::{
sqrt_price::{get_max_tick, get_min_tick, SqrtPrice},
state::{self},
token_amount::TokenAmount,
ContractError, PoolKey, Position, Tick, UpdatePoolTick, MAX_SQRT_PRICE, MAX_TICKMAP_QUERY_SIZE,
MIN_SQRT_PRICE,
ContractError, PoolKey, Position, Tick, UpdatePoolTick, MAX_SQRT_PRICE, MIN_SQRT_PRICE,
};

pub trait TimeStampExt {
Expand Down Expand Up @@ -309,20 +311,30 @@ pub fn route(

pub fn tickmap_slice(
store: &dyn Storage,
range: impl Iterator<Item = u16>,
min_chunk: u16,
max_chunk: u16,
pool_key: &PoolKey,
limit: usize,
) -> Vec<(u16, u64)> {
let mut tickmap_slice: Vec<(u16, u64)> = vec![];

for chunk_index in range {
if let Ok(chunk) = state::get_bitmap_item(store, chunk_index, pool_key) {
tickmap_slice.push((chunk_index, chunk));

if tickmap_slice.len() == MAX_TICKMAP_QUERY_SIZE {
return tickmap_slice;
let pool_key = pool_key.key();
let mut min_key = min_chunk.to_be_bytes().to_vec();
let mut max_key = max_chunk.to_be_bytes().to_vec();
min_key.extend_from_slice(&pool_key);
max_key.extend_from_slice(&pool_key);
let min = Some(Bound::InclusiveRaw(min_key));
let max = Some(Bound::InclusiveRaw(max_key));
let tickmap_slice = state::BITMAP
.range_raw(store, min, max, Order::Ascending)
.filter_map(|item| {
if let Ok((k, v)) = item {
if pool_key.eq(&k[2..]) {
return Some((u16::from_be_bytes([k[0], k[1]]), v));
}
}
}
}
None
})
.take(limit)
.collect();

tickmap_slice
}
Expand Down
20 changes: 11 additions & 9 deletions contracts/oraiswap-v3/src/entrypoints/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::{
tick_to_position,
token_amount::TokenAmount,
ContractError, FeeTier, LiquidityTick, Pool, PoolKey, Position, PositionTick, Tick, CHUNK_SIZE,
LIQUIDITY_TICK_LIMIT, POSITION_TICK_LIMIT,
LIQUIDITY_TICK_LIMIT, MAX_TICKMAP_QUERY_SIZE, POSITION_TICK_LIMIT,
};

use super::{calculate_swap, route, tickmap_slice, TimeStampExt};
Expand Down Expand Up @@ -242,14 +242,16 @@ pub fn get_tickmap(
let min_chunk_index = get_min_chunk(tick_spacing).max(start_chunk);
let max_chunk_index = get_max_chunk(tick_spacing).min(end_chunk);

let tickmaps = if x_to_y {
tickmap_slice(
deps.storage,
(min_chunk_index..=max_chunk_index).rev(),
&pool_key,
)
} else {
tickmap_slice(deps.storage, min_chunk_index..=max_chunk_index, &pool_key)
let mut tickmaps = tickmap_slice(
deps.storage,
min_chunk_index,
max_chunk_index,
&pool_key,
MAX_TICKMAP_QUERY_SIZE,
);

if x_to_y {
tickmaps.reverse();
};

Ok(tickmaps)
Expand Down
53 changes: 48 additions & 5 deletions contracts/oraiswap-v3/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,9 +251,16 @@ pub fn get_all_positions(
let from_idx = offset.unwrap_or(0);
// maximum 100 items
let to_idx = get_position_length(store, account_id).min(from_idx + limit.unwrap_or(MAX_LIMIT));
(from_idx..to_idx)
.map(|index| get_position(store, account_id, index))
.collect()

let min = Some(Bound::InclusiveRaw(position_key(account_id, from_idx)));
let max = Some(Bound::ExclusiveRaw(position_key(account_id, to_idx)));

let positions = POSITIONS
.range_raw(store, min, max, Order::Ascending)
.map(|item| Ok(item?.1))
.collect::<StdResult<Vec<_>>>()?;

Ok(positions)
}

pub fn get_all_position_keys(
Expand All @@ -278,7 +285,7 @@ pub fn get_position_length(store: &dyn Storage, account_id: &Addr) -> u32 {

pub fn bitmap_key(chunk: u16, pool_key: &PoolKey) -> Vec<u8> {
let mut db_key = chunk.to_be_bytes().to_vec();
db_key.append(&mut pool_key.key());
db_key.extend_from_slice(&pool_key.key());
db_key
}

Expand Down Expand Up @@ -465,9 +472,10 @@ pub fn flip_bitmap(
mod tests {

use super::*;
use crate::entrypoints::tickmap_slice;
use crate::math::percentage::Percentage;
use crate::sqrt_price::SqrtPrice;
use crate::{FeeTier, MAX_TICK, TICK_SEARCH_RANGE};
use crate::{state, FeeTier, MAX_TICK, TICK_SEARCH_RANGE};

use cosmwasm_std::testing::mock_dependencies;
use cosmwasm_std::Addr;
Expand Down Expand Up @@ -1083,4 +1091,39 @@ mod tests {
assert_eq!((prev.is_some(), next.is_some()), (false, false));
}
}

#[test]
fn test_tick_map() {
let mut deps = mock_dependencies();
let min_chunk = 0;
let max_chunk = 2;
let fee_tier = FeeTier::new(Percentage(0), 1).unwrap();
let pool_key_1 = PoolKey::new("x".to_string(), "y".to_string(), fee_tier).unwrap();
let pool_key_2 = PoolKey::new("y".to_string(), "z".to_string(), fee_tier).unwrap();

// update pool1
for index in min_chunk..=max_chunk {
state::BITMAP
.save(
deps.as_mut().storage,
&state::bitmap_key(index, &pool_key_1),
&1,
)
.unwrap();
}

// update pool2
for index in min_chunk..=max_chunk {
state::BITMAP
.save(
deps.as_mut().storage,
&state::bitmap_key(index, &pool_key_2),
&2,
)
.unwrap();
}

let ret = tickmap_slice(deps.as_ref().storage, min_chunk, max_chunk, &pool_key_1, 3);
assert_eq!(ret, [(0, 1), (1, 1), (2, 1)]);
}
}
6 changes: 3 additions & 3 deletions contracts/oraiswap-v3/src/tests/get_position_ticks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ fn test_query_all_positions() {
alice
)
.unwrap();
let block_number = app.get_block_height();

let positions = app.query_all_positions(dex.as_str(), None, None).unwrap();
assert_eq!(positions.len(), 2);
assert_eq!(
Expand All @@ -295,7 +295,7 @@ fn test_query_all_positions() {
upper_tick_index: 10,
fee_growth_inside_x: FeeGrowth(0),
fee_growth_inside_y: FeeGrowth(0),
last_block_number: block_number - 1,
last_block_number: positions[0].last_block_number,
tokens_owed_x: TokenAmount(0),
tokens_owed_y: TokenAmount(0),
approvals: vec![],
Expand All @@ -316,7 +316,7 @@ fn test_query_all_positions() {
upper_tick_index: 100,
fee_growth_inside_x: FeeGrowth(0),
fee_growth_inside_y: FeeGrowth(0),
last_block_number: block_number,
last_block_number: positions[1].last_block_number,
tokens_owed_x: TokenAmount(0),
tokens_owed_y: TokenAmount(0),
token_id: 2,
Expand Down
19 changes: 16 additions & 3 deletions contracts/oraiswap-v3/src/tests/get_tickmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ fn test_get_tickmap() {
approve!(app, token_y, dex, initial_amount, alice).unwrap();

let fee_tier = FeeTier::new(Percentage::from_scale(5, 1), 1).unwrap();
let fee_tier_1 = FeeTier::new(Percentage::from_scale(1, 2), 2).unwrap();
let pool_key = PoolKey::new(token_x.to_string(), token_y.to_string(), fee_tier).unwrap();
let init_tick = 0;
let init_sqrt_price = calculate_sqrt_price(init_tick).unwrap();
Expand All @@ -45,6 +46,18 @@ fn test_get_tickmap() {
alice
);
assert!(result.is_ok());
add_fee_tier!(app, dex, fee_tier_1, alice).unwrap();
let result = create_pool!(
app,
dex,
token_x,
token_y,
fee_tier_1,
init_sqrt_price,
init_tick,
alice
)
.unwrap();

let pool = get_pool!(app, dex, token_x, token_y, fee_tier).unwrap();

Expand Down Expand Up @@ -306,7 +319,7 @@ fn test_get_tickmap_edge_ticks_intialized() {

#[test]
fn test_get_tickmap_more_chunks_above() {
let (mut app, accounts) = MockApp::new(&[("alice", &coins(100_000_000_000, FEE_DENOM))]);
let (mut app, accounts) = MockApp::new(&[("alice", &coins(100_000_000_000_000, FEE_DENOM))]);
let alice = &accounts[0];
let dex = create_dex!(app, Percentage::new(0), alice);
let initial_amount = 10u128.pow(10);
Expand Down Expand Up @@ -371,7 +384,7 @@ fn test_get_tickmap_more_chunks_above() {

#[test]
fn test_get_tickmap_more_chunks_below() {
let (mut app, accounts) = MockApp::new(&[("alice", &coins(100_000_000_000, FEE_DENOM))]);
let (mut app, accounts) = MockApp::new(&[("alice", &coins(100_000_000_000_000, FEE_DENOM))]);
let alice = &accounts[0];
let dex = create_dex!(app, Percentage::new(0), alice);
let initial_amount = 10u128.pow(10);
Expand Down Expand Up @@ -441,7 +454,7 @@ fn test_get_tickmap_more_chunks_below() {

#[test]
fn test_get_tickmap_max_chunks_returned() {
let (mut app, accounts) = MockApp::new(&[("alice", &coins(100_000_000_000, FEE_DENOM))]);
let (mut app, accounts) = MockApp::new(&[("alice", &coins(100_000_000_000_000, FEE_DENOM))]);
let alice = &accounts[0];
let dex = create_dex!(app, Percentage::new(0), alice);
let initial_amount = 10u128.pow(10);
Expand Down
52 changes: 29 additions & 23 deletions contracts/oraiswap-v3/src/tests/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1569,52 +1569,52 @@ pub mod macros {

#[cfg(test)]
mod tests {
use cosmwasm_std::{testing::MOCK_CONTRACT_ADDR, Addr, Coin, Uint128};
use cosmwasm_std::{coins, Addr, Coin, Uint128};

use crate::tests::helper::FEE_DENOM;

use super::MockApp;

#[test]
fn token_balance_querier() {
let (mut app, accounts) = MockApp::new(&[("owner", &[])]);
let (mut app, accounts) = MockApp::new(&[
("owner", &coins(100_000_000_000, FEE_DENOM)),
("receiver", &[]),
]);
let owner = &accounts[0];
let receiver = &accounts[1];

app.set_token_balances(
owner,
&[(&"AIRI".to_string(), &[(MOCK_CONTRACT_ADDR, 123u128)])],
)
.unwrap();
app.set_token_balances(owner, &[(&"AIRI".to_string(), &[(receiver, 123u128)])])
.unwrap();

assert_eq!(
Uint128::from(123u128),
app.query_token_balance(
app.get_token_addr("AIRI").unwrap().as_str(),
MOCK_CONTRACT_ADDR,
)
.unwrap()
app.query_token_balance(app.get_token_addr("AIRI").unwrap().as_str(), receiver,)
.unwrap()
);
}

#[test]
fn balance_querier() {
let (app, _) = MockApp::new(&[(
&MOCK_CONTRACT_ADDR.to_string(),
let (app, accounts) = MockApp::new(&[(
"account",
&[Coin {
denom: "uusd".to_string(),
amount: Uint128::from(200u128),
}],
)]);

assert_eq!(
app.query_balance(Addr::unchecked(MOCK_CONTRACT_ADDR), "uusd".to_string())
app.query_balance(Addr::unchecked(&accounts[0]), "uusd".to_string())
.unwrap(),
Uint128::from(200u128)
);
}

#[test]
fn all_balances_querier() {
let (app, _) = MockApp::new(&[(
&MOCK_CONTRACT_ADDR.to_string(),
let (app, accounts) = MockApp::new(&[(
"account",
&[
Coin {
denom: "uusd".to_string(),
Expand All @@ -1628,7 +1628,7 @@ mod tests {
)]);

let mut balance1 = app
.query_all_balances(Addr::unchecked(MOCK_CONTRACT_ADDR))
.query_all_balances(Addr::unchecked(&accounts[0]))
.unwrap();
balance1.sort_by(|a, b| a.denom.cmp(&b.denom));
let mut balance2 = vec![
Expand All @@ -1647,17 +1647,23 @@ mod tests {

#[test]
fn supply_querier() {
let (mut app, accounts) = MockApp::new(&[("owner", &[])]);
let (mut app, accounts) = MockApp::new(&[
("owner", &coins(100_000_000_000, FEE_DENOM)),
("addr00000", &[]),
("addr00001", &[]),
("addr00002", &[]),
("addr00003", &[]),
]);
let owner = &accounts[0];
app.set_token_balances(
owner,
&[(
&"LPA".to_string(),
&[
(MOCK_CONTRACT_ADDR, 123u128),
(&"addr00000".to_string(), 123u128),
(&"addr00001".to_string(), 123u128),
(&"addr00002".to_string(), 123u128),
(&accounts[1], 123u128),
(&accounts[2], 123u128),
(&accounts[3], 123u128),
(&accounts[4], 123u128),
],
)],
)
Expand Down
Binary file modified contracts/oraiswap-v3/src/tests/testdata/oraiswap-v3.wasm
Binary file not shown.

0 comments on commit 96bb42b

Please sign in to comment.