Skip to content

Commit

Permalink
⚡️ [API-2293] Swap Directly On Astroport Pools, Deprecate Router Use (#…
Browse files Browse the repository at this point in the history
…84)

* remove use of router contract, swap directly on pools

* update existing tests

* remove router contract from deploy script and configs

* add unit tests for ExecuteMsg::AstroportPoolSwap

* remove router in code comments

* remove router from instantiate message and consolidate InstantiateMsg
  • Loading branch information
NotJeremyLiu authored Jan 5, 2024
1 parent 11a778e commit 83a5033
Show file tree
Hide file tree
Showing 17 changed files with 372 additions and 265 deletions.
24 changes: 4 additions & 20 deletions contracts/adapters/swap/astroport/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Neutron Astroport Swap Adapter Contract

The Neutron Astroport swap adapter contract is responsible for:
1. Taking the standardized entry point swap operations message format and converting it to the Astroport Router `SwapOperation` format.
2. Swapping by calling the Astroport router.
1. Taking the standardized entry point swap operations message format and converting it to Astroport pool swaps message format.
2. Swapping by dispatching swaps to Astroport pool contracts.
3. Providing query methods that can be called by the entry point contract (generally, to any external actor) to simulate multi-hop swaps that either specify an exact amount in (estimating how much would be received from the swap) or an exact amount out (estimating how much is required to get the specified amount out).

Note: Swap adapter contracts expect to be called by an entry point contract that provides basic validation and minimum amount out safety guarantees for the caller. There are no slippage guarantees provided by swap adapter contracts.
Expand All @@ -11,11 +11,11 @@ WARNING: Do not send funds directly to the contract without calling one of its f

## InstantiateMsg

Instantiates a new Neutron Astroport swap adapter contract using the Astroport router provided in the instantiation message.
Instantiates a new Neutron Astroport swap adapter contract using the Entrypoint contract address provided in the instantiation message.

``` json
{
"router_contract_address": "neutron..."
"entry_point_contract_address": "neutron..."
}
```

Expand Down Expand Up @@ -60,22 +60,6 @@ Note: This function can be called by anyone as the contract is assumed to have n

## QueryMsg

### `router_contract_address`

Returns the Astroport router contract address set at instantiation.

Query:
``` json
{
"router_contract_address": {}
}
```

Response:
``` json
"neutron..."
```

### `simulate_swap_exact_coin_out`

Returns the coin in required to receive the `coin_out` specified in the call (swapped through the `swap_operatons` provided)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use cosmwasm_schema::write_api;
use skip::swap::{AstroportInstantiateMsg as InstantiateMsg, ExecuteMsg, QueryMsg};
use skip::swap::{ExecuteMsg, InstantiateMsg, QueryMsg};

fn main() {
write_api! {
Expand Down
130 changes: 63 additions & 67 deletions contracts/adapters/swap/astroport/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,23 @@
use crate::{
error::{ContractError, ContractResult},
state::{ENTRY_POINT_CONTRACT_ADDRESS, ROUTER_CONTRACT_ADDRESS},
state::ENTRY_POINT_CONTRACT_ADDRESS,
};
use astroport::{
pair::{
QueryMsg as PairQueryMsg, ReverseSimulationResponse, SimulationResponse,
MAX_ALLOWED_SLIPPAGE,
},
router::ExecuteMsg as RouterExecuteMsg,
use astroport::pair::{
ExecuteMsg as PairExecuteMsg, QueryMsg as PairQueryMsg, ReverseSimulationResponse,
SimulationResponse, MAX_ALLOWED_SLIPPAGE,
};
use cosmwasm_std::{
entry_point, from_json, to_json_binary, Addr, Api, Binary, Decimal, Deps, DepsMut, Env,
MessageInfo, Response, Uint128, WasmMsg,
entry_point, from_json, to_json_binary, Binary, Decimal, Deps, DepsMut, Env, MessageInfo,
Response, Uint128, WasmMsg,
};
use cw2::set_contract_version;
use cw20::{Cw20Coin, Cw20ReceiveMsg};
use cw_utils::one_coin;
use skip::{
asset::Asset,
asset::{get_current_asset_available, Asset},
swap::{
execute_transfer_funds_back, AstroportInstantiateMsg as InstantiateMsg, Cw20HookMsg,
ExecuteMsg, MigrateMsg, QueryMsg, SimulateSwapExactAssetInResponse,
SimulateSwapExactAssetOutResponse, SwapOperation,
execute_transfer_funds_back, Cw20HookMsg, ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg,
SimulateSwapExactAssetInResponse, SimulateSwapExactAssetOutResponse, SwapOperation,
},
};

Expand Down Expand Up @@ -59,21 +55,11 @@ pub fn instantiate(
// Store the entry point contract address
ENTRY_POINT_CONTRACT_ADDRESS.save(deps.storage, &checked_entry_point_contract_address)?;

// Validate router contract address
let checked_router_contract_address = deps.api.addr_validate(&msg.router_contract_address)?;

// Store the router contract address
ROUTER_CONTRACT_ADDRESS.save(deps.storage, &checked_router_contract_address)?;

Ok(Response::new()
.add_attribute("action", "instantiate")
.add_attribute(
"entry_point_contract_address",
checked_entry_point_contract_address.to_string(),
)
.add_attribute(
"router_contract_address",
checked_router_contract_address.to_string(),
))
}

Expand All @@ -100,7 +86,7 @@ pub fn receive_cw20(
info.sender = deps.api.addr_validate(&cw20_msg.sender)?;

match from_json(&cw20_msg.msg)? {
Cw20HookMsg::Swap { operations } => execute_swap(deps, env, info, sent_asset, operations),
Cw20HookMsg::Swap { operations } => execute_swap(deps, env, info, operations),
}
}

Expand All @@ -118,8 +104,8 @@ pub fn execute(
match msg {
ExecuteMsg::Receive(cw20_msg) => receive_cw20(deps, env, info, cw20_msg),
ExecuteMsg::Swap { operations } => {
let sent_asset: Asset = one_coin(&info)?.into();
execute_swap(deps, env, info, sent_asset, operations)
one_coin(&info)?;
execute_swap(deps, env, info, operations)
}
ExecuteMsg::TransferFundsBack {
swapper,
Expand All @@ -131,14 +117,16 @@ pub fn execute(
swapper,
return_denom,
)?),
ExecuteMsg::AstroportPoolSwap { operation } => {
execute_astroport_pool_swap(deps, env, info, operation)
}
}
}

fn execute_swap(
deps: DepsMut,
env: Env,
info: MessageInfo,
sent_asset: Asset,
operations: Vec<SwapOperation>,
) -> ContractResult<Response> {
// Get entry point contract address from storage
Expand All @@ -149,13 +137,20 @@ fn execute_swap(
return Err(ContractError::Unauthorized);
}

// Create the astroport swap message
let swap_msg = create_astroport_swap_msg(
deps.api,
ROUTER_CONTRACT_ADDRESS.load(deps.storage)?,
sent_asset,
&operations,
)?;
// Create a response object to return
let mut response: Response = Response::new().add_attribute("action", "execute_swap");

// Add an astroport pool swap message to the response for each swap operation
for operation in &operations {
let swap_msg = WasmMsg::Execute {
contract_addr: env.contract.address.to_string(),
msg: to_json_binary(&ExecuteMsg::AstroportPoolSwap {
operation: operation.clone(),
})?,
funds: vec![],
};
response = response.add_message(swap_msg);
}

let return_denom = match operations.last() {
Some(last_op) => last_op.denom_out.clone(),
Expand All @@ -172,44 +167,48 @@ fn execute_swap(
funds: vec![],
};

Ok(Response::new()
.add_message(swap_msg)
Ok(response
.add_message(transfer_funds_back_msg)
.add_attribute("action", "dispatch_swap_and_transfer_back"))
.add_attribute("action", "dispatch_swaps_and_transfer_back"))
}

////////////////////////
/// HELPER FUNCTIONS ///
////////////////////////
fn execute_astroport_pool_swap(
deps: DepsMut,
env: Env,
info: MessageInfo,
operation: SwapOperation,
) -> ContractResult<Response> {
// Ensure the caller is the contract itself
if info.sender != env.contract.address {
return Err(ContractError::Unauthorized);
}

// Get the current asset available on contract to swap in
let offer_asset = get_current_asset_available(&deps, &env, &operation.denom_in)?;

// Converts the swap operations to astroport AstroSwap operations
fn create_astroport_swap_msg(
api: &dyn Api,
router_contract_address: Addr,
asset_in: Asset,
swap_operations: &[SwapOperation],
) -> ContractResult<WasmMsg> {
// Convert the swap operations to astroport swap operations
let astroport_swap_operations = swap_operations
.iter()
.map(|swap_operation| swap_operation.into_astroport_swap_operation(api))
.collect();
// Error if the offer asset amount is zero
if offer_asset.amount().is_zero() {
return Err(ContractError::NoOfferAssetAmount);
}

// Create the astroport router execute message arguments
let astroport_router_msg_args = RouterExecuteMsg::ExecuteSwapOperations {
operations: astroport_swap_operations,
minimum_receive: None,
to: None,
// Create the astroport pool swap message args
let astroport_pool_swap_msg_args = PairExecuteMsg::Swap {
offer_asset: offer_asset.into_astroport_asset(deps.api)?,
ask_asset_info: None,
belief_price: None,
max_spread: Some(MAX_ALLOWED_SLIPPAGE.parse::<Decimal>()?),
to: None,
};

// Create the astroport router swap message
let swap_msg = asset_in.into_wasm_msg(
router_contract_address.to_string(),
to_json_binary(&astroport_router_msg_args)?,
// Create the wasm astroport pool swap message
let swap_msg = offer_asset.into_wasm_msg(
operation.pool,
to_json_binary(&astroport_pool_swap_msg_args)?,
)?;

Ok(swap_msg)
Ok(Response::new()
.add_message(swap_msg)
.add_attribute("action", "dispatch_astroport_pool_swap"))
}

/////////////
Expand All @@ -219,9 +218,6 @@ fn create_astroport_swap_msg(
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> ContractResult<Binary> {
match msg {
QueryMsg::RouterContractAddress {} => {
to_json_binary(&ROUTER_CONTRACT_ADDRESS.load(deps.storage)?)
}
QueryMsg::SimulateSwapExactAssetIn {
asset_in,
swap_operations,
Expand Down Expand Up @@ -262,7 +258,7 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> ContractResult<Binary> {
.map_err(From::from)
}

// Queries the astroport router contract to simulate a swap exact amount in
// Queries the astroport pool contracts to simulate a swap exact amount in
fn query_simulate_swap_exact_asset_in(
deps: Deps,
asset_in: Asset,
Expand Down Expand Up @@ -306,7 +302,7 @@ fn query_simulate_swap_exact_asset_out(
Ok(asset_in)
}

// Queries the astroport router contract to simulate a swap exact amount in with metadata
// Queries the astroport pool contracts to simulate a swap exact amount in with metadata
fn query_simulate_swap_exact_asset_in_with_metadata(
deps: Deps,
asset_in: Asset,
Expand Down
3 changes: 3 additions & 0 deletions contracts/adapters/swap/astroport/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,7 @@ pub enum ContractError {

#[error("Operation exceeds max spread limit")]
MaxSpreadAssertion,

#[error("Contract has no balance of offer asset")]
NoOfferAssetAmount,
}
1 change: 0 additions & 1 deletion contracts/adapters/swap/astroport/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,3 @@ use cosmwasm_std::Addr;
use cw_storage_plus::Item;

pub const ENTRY_POINT_CONTRACT_ADDRESS: Item<Addr> = Item::new("entry_point_contract_address");
pub const ROUTER_CONTRACT_ADDRESS: Item<Addr> = Item::new("router_contract_address");
Loading

0 comments on commit 83a5033

Please sign in to comment.