1
use crate::types::{Config, CurrentSwapOperation, CurrentSwapStep, SwapResults, SwapRoute};
2

            
3
use cosmwasm_std::{Order, StdError, StdResult, Storage};
4
use cw_storage_plus::{Bound, Item, Map};
5

            
6
pub const SWAP_ROUTES: Map<(String, String), SwapRoute> = Map::new("swap_routes");
7
pub const SWAP_OPERATION_STATE: Item<CurrentSwapOperation> = Item::new("current_swap_cache");
8
pub const STEP_STATE: Item<CurrentSwapStep> = Item::new("current_step_cache");
9
pub const SWAP_RESULTS: Item<Vec<SwapResults>> = Item::new("swap_results");
10
pub const CONFIG: Item<Config> = Item::new("config");
11

            
12
pub const DEFAULT_LIMIT: u32 = 100u32;
13

            
14
impl Config {
15
16
    pub fn validate(self) -> StdResult<()> {
16
16
        Ok(())
17
16
    }
18
}
19

            
20
42
pub fn store_swap_route(storage: &mut dyn Storage, route: &SwapRoute) -> StdResult<()> {
21
42
    let key = route_key(&route.source_denom, &route.target_denom);
22
42
    SWAP_ROUTES.save(storage, key, route)
23
42
}
24

            
25
56
pub fn read_swap_route(storage: &dyn Storage, source_denom: &str, target_denom: &str) -> StdResult<SwapRoute> {
26
56
    let key = route_key(source_denom, target_denom);
27
56
    SWAP_ROUTES
28
56
        .load(storage, key)
29
65
        .map_err(|_| StdError::msg(format!("No swap route not found from {source_denom} to {target_denom}",)))
30
56
}
31

            
32
4
pub fn get_config(storage: &dyn Storage) -> StdResult<Config> {
33
4
    let config = CONFIG.load(storage)?;
34
4
    Ok(config)
35
4
}
36

            
37
6
pub fn get_all_swap_routes(storage: &dyn Storage, start_after: Option<(String, String)>, limit: Option<u32>) -> StdResult<Vec<SwapRoute>> {
38
6
    let limit = limit.unwrap_or(DEFAULT_LIMIT) as usize;
39
6

            
40
6
    let start_bound = start_after.as_ref().map(|(s, t)| Bound::inclusive((s.clone(), t.clone())));
41

            
42
6
    let routes = SWAP_ROUTES
43
6
        .range(storage, start_bound, None, Order::Ascending)
44
6
        .take(limit)
45
11
        .map(|item| item.map(|(_, route)| route)) // Extract the `SwapRoute` from each item
46
6
        .collect::<StdResult<Vec<SwapRoute>>>()?;
47

            
48
6
    Ok(routes)
49
6
}
50

            
51
4
pub fn remove_swap_route(storage: &mut dyn Storage, source_denom: &str, target_denom: &str) {
52
4
    let key = route_key(source_denom, target_denom);
53
4
    SWAP_ROUTES.remove(storage, key)
54
4
}
55

            
56
102
fn route_key<'a>(source_denom: &'a str, target_denom: &'a str) -> (String, String) {
57
102
    if source_denom < target_denom {
58
86
        (source_denom.to_string(), target_denom.to_string())
59
    } else {
60
16
        (target_denom.to_string(), source_denom.to_string())
61
    }
62
102
}