Skip to content

Commit

Permalink
wip: query directly from Astro pool, given pool address only
Browse files Browse the repository at this point in the history
  • Loading branch information
TropicalDog17 committed Nov 30, 2023
1 parent 63bed2b commit 6222220
Show file tree
Hide file tree
Showing 6 changed files with 113 additions and 15 deletions.
101 changes: 94 additions & 7 deletions src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use cw2::set_contract_version;
use crate::error::ContractError;
use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg};
use crate::state::{State, STATE};
use astroport::asset::AssetInfo;
use astroport::pair::{self};
use cosmwasm_std::{Addr, Order, StdError, WasmMsg};

Expand Down Expand Up @@ -48,6 +49,7 @@ pub fn execute(
token_1,
token_2,
} => execute::add_supported_pool(deps, info, pool_address, token_1, token_2),
ExecuteMsg::MySwap { pool_address } => execute::swap(deps, info, pool_address),
}
}

Expand All @@ -58,6 +60,8 @@ pub fn reply(deps: DepsMut, _env: Env, msg: Reply) -> StdResult<Response> {
id => Err(StdError::generic_err(format!("Unknown reply id: {}", id))),
}
}

// Currently this do nothing
fn handle_swap_reply(_deps: DepsMut, _env: Env, msg: Reply) -> StdResult<Response> {
let data = msg.result.into_result().map_err(StdError::generic_err)?;

Expand Down Expand Up @@ -94,11 +98,16 @@ fn handle_swap_reply(_deps: DepsMut, _env: Env, msg: Reply) -> StdResult<Respons
// };
Ok(Response::new())
}

pub mod execute {
use astroport::asset::Asset;
use astroport::{
asset::{Asset, PairInfo},

Check failure on line 104 in src/contract.rs

View workflow job for this annotation

GitHub Actions / Lints

unused imports: `PairInfo`, `factory`

Check warning on line 104 in src/contract.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused imports: `PairInfo`, `factory`

Check warning on line 104 in src/contract.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused imports: `PairInfo`, `factory`
factory,
pair::PoolResponse,
};
use cosmwasm_std::{Decimal, SubMsg};

use crate::state::{PoolInfo, POOL_INFO};
use crate::state::{PoolInfo, FACTORY_CONTRACT_ADDR, POOL_CONTRACT_ADDR, POOL_INFO};

Check failure on line 110 in src/contract.rs

View workflow job for this annotation

GitHub Actions / Lints

unused imports: `FACTORY_CONTRACT_ADDR`, `POOL_CONTRACT_ADDR`

Check warning on line 110 in src/contract.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused imports: `FACTORY_CONTRACT_ADDR`, `POOL_CONTRACT_ADDR`

Check warning on line 110 in src/contract.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused imports: `FACTORY_CONTRACT_ADDR`, `POOL_CONTRACT_ADDR`

use super::*;

Expand Down Expand Up @@ -133,7 +142,13 @@ pub mod execute {
} else {
coin.amount.into()
};
let asked_asset = pair_info.1.clone();

let asked_asset: String;

Check failure on line 146 in src/contract.rs

View workflow job for this annotation

GitHub Actions / Lints

unneeded late initialization
if pair_info.0 == offer_asset {
asked_asset = pair_info.1.clone();

Check failure on line 148 in src/contract.rs

View workflow job for this annotation

GitHub Actions / Lints

redundant clone
} else {
asked_asset = pair_info.0.clone();

Check failure on line 150 in src/contract.rs

View workflow job for this annotation

GitHub Actions / Lints

redundant clone
}

let swap_astro_msg = pair::ExecuteMsg::Swap {
offer_asset: Asset::native(&offer_asset, amount),
Expand All @@ -157,17 +172,89 @@ pub mod execute {
.add_attribute("ask_asset_info", asked_asset);
Ok(res)
}
// Perform swap of two native tokens
pub fn swap(
deps: DepsMut,
info: MessageInfo,
pool_address: Addr,
) -> Result<Response, ContractError> {
// Query the pool address on astroport contract

let querier = deps.querier;
let pool_response: PoolResponse =
querier.query_wasm_smart(pool_address.clone(), &astroport::pair::QueryMsg::Pool {})?;
let asset_infos = pool_response
.assets
.iter()
.map(|asset| asset.info.clone())
.collect::<Vec<_>>();

if !asset_infos[0].is_native_token() || !asset_infos[1].is_native_token() {
return Err(ContractError::Payment(
cw_utils::PaymentError::MissingDenom("native token".to_string()),
));
}

// Based on cw_utils::must_pay implementation
let coin = cw_utils::one_coin(&info)?;
let offer_asset = coin.denom.clone();
let offer = AssetInfo::NativeToken {
denom: offer_asset.clone(),
};
let amount: u128 = if !offer.equal(&asset_infos[0]) && !offer.equal(&asset_infos[1]) {
return Err(ContractError::Payment(
cw_utils::PaymentError::MissingDenom(coin.denom.to_string()),
));
} else {
coin.amount.into()
};

// Precheck if enough balance in pool for user swap request
let available_offer = offer.query_pool(&deps.querier, pool_address.clone())?;
// TODO: Use a better error type
if available_offer < amount.into() {
return Err(ContractError::Unauthorized {});
}

let asked_asset: String;
if offer.equal(&asset_infos[0]) {
asked_asset = asset_infos[1].to_string();
} else {
asked_asset = asset_infos[0].to_string();
}

let swap_astro_msg = pair::ExecuteMsg::Swap {
offer_asset: Asset::native(&offer_asset, amount),
ask_asset_info: None,
belief_price: None,
max_spread: Some(Decimal::percent(50)),
to: Some(info.sender.to_string()),
};
let exec_cw20_mint_msg = WasmMsg::Execute {
contract_addr: pool_address.clone().to_string(),
msg: to_json_binary(&swap_astro_msg)?,
funds: coins(amount, &offer_asset),
};
let submessage = SubMsg::reply_on_success(exec_cw20_mint_msg, SWAP_REPLY_ID);
let res = Response::new()
.add_submessage(submessage)
.add_attribute("action", "swap")
.add_attribute("pair", pool_address)
.add_attribute("offer_asset", offer_asset)
.add_attribute("ask_asset_info", asked_asset);
Ok(res)
}
pub fn add_supported_pool(
deps: DepsMut,
info: MessageInfo,

Check failure on line 249 in src/contract.rs

View workflow job for this annotation

GitHub Actions / Lints

unused variable: `info`

Check warning on line 249 in src/contract.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused variable: `info`

Check warning on line 249 in src/contract.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused variable: `info`
pool_address: String,
token_1: String,
token_2: String,
) -> Result<Response, ContractError> {
// Check authorization
if info.sender != STATE.load(deps.storage)?.owner {
return Err(ContractError::Unauthorized {});
}
// // Check authorization
// if info.sender != STATE.load(deps.storage)?.owner {
// return Err(ContractError::Unauthorized {});
// }
let pool_info = PoolInfo {
address: Addr::unchecked(pool_address),
token_1: token_1.clone(),
Expand Down
2 changes: 2 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,6 @@ pub enum ContractError {
ExceedMaximumMintableAmount {},
#[error("Pool not exists")]
PoolNotExist {},
#[error("Offer and ask token should not be identical")]
DoublingAssets {},
}
4 changes: 2 additions & 2 deletions src/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use astroport::{pair::PoolResponse, querier};

Check failure on line 1 in src/helpers.rs

View workflow job for this annotation

GitHub Actions / Lints

unused imports: `pair::PoolResponse`, `querier`

Check warning on line 1 in src/helpers.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused imports: `pair::PoolResponse`, `querier`

Check warning on line 1 in src/helpers.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused imports: `pair::PoolResponse`, `querier`
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use cosmwasm_std::{to_json_binary, Addr, CosmosMsg, StdResult, WasmMsg};

use crate::msg::ExecuteMsg;
use cosmwasm_std::{to_json_binary, Addr, CosmosMsg, QuerierWrapper, StdResult, WasmMsg};

Check failure on line 6 in src/helpers.rs

View workflow job for this annotation

GitHub Actions / Lints

unused import: `QuerierWrapper`

Check warning on line 6 in src/helpers.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused import: `QuerierWrapper`

Check warning on line 6 in src/helpers.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused import: `QuerierWrapper`

/// CwTemplateContract is a wrapper around Addr that provides a lot of helpers
/// for working with this.
Expand Down
12 changes: 6 additions & 6 deletions src/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -445,8 +445,8 @@ mod tests {
.unwrap();
assert_eq!(res.unwrap(), Uint128::new(1000001000000));

let my_swap_msg = crate::msg::ExecuteMsg::Astro {
pair_address: pair_contract.addr().into_string(),
let my_swap_msg = crate::msg::ExecuteMsg::MySwap {
pool_address: pair_contract.addr(),
};
let send_funds = vec![Coin {
denom: "inj".to_string(),
Expand Down Expand Up @@ -490,8 +490,8 @@ mod tests {
.amount,
Uint128::from(1_000000u128)
);
let my_swap_msg = crate::msg::ExecuteMsg::Astro {
pair_address: pair_contract.addr().into_string(),
let my_swap_msg = crate::msg::ExecuteMsg::MySwap {
pool_address: pair_contract.addr(),
};
let send_funds = vec![Coin {
denom: "inj".to_owned(),
Expand Down Expand Up @@ -532,8 +532,8 @@ mod tests {
);

// if wrong pair, return error
let my_swap_msg = crate::msg::ExecuteMsg::Astro {
pair_address: pair_contract.addr().into_string(),
let my_swap_msg = crate::msg::ExecuteMsg::MySwap {
pool_address: pair_contract.addr(),
};
let send_funds = vec![Coin {
denom: "abc".to_owned(),
Expand Down
5 changes: 5 additions & 0 deletions src/msg.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use astroport::asset::AssetInfo;

Check failure on line 1 in src/msg.rs

View workflow job for this annotation

GitHub Actions / Lints

unused import: `astroport::asset::AssetInfo`

Check warning on line 1 in src/msg.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused import: `astroport::asset::AssetInfo`

Check warning on line 1 in src/msg.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused import: `astroport::asset::AssetInfo`
use cosmwasm_schema::{cw_serde, QueryResponses};
use cosmwasm_std::Addr;

#[cw_serde]
pub struct InstantiateMsg {}
Expand All @@ -13,6 +15,9 @@ pub enum ExecuteMsg {
token_1: String,
token_2: String,
},
MySwap {
pool_address: Addr,
},
}

#[cw_serde]
Expand Down
4 changes: 4 additions & 0 deletions src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,7 @@ pub struct PoolInfo {
}
pub const STATE: Item<State> = Item::new("state");
pub const POOL_INFO: IndexedMap<&str, PoolInfo, InfoIndexes> = infos();
pub const POOL_CONTRACT_ADDR: Item<Addr> = Item::new("pool_contract_addr");
pub const REGISTRY_CONTRACT_ADDR: Item<Addr> = Item::new("registry_contract_addr");
pub const FACTORY_CONTRACT_ADDR: Item<Addr> = Item::new("factory_contract_addr");
pub const PAIR_CONTRACT_ADDR: Item<Addr> = Item::new("pair_contract_addr");

0 comments on commit 6222220

Please sign in to comment.