bolt-cw-sdk 1.0.0

SDK for the BOLT protocol, providing utilities for interacting with the BOLT contracts.
Documentation
use crate::market::Allowance;
use crate::router::client::RouterAdminClient;
use crate::router::error::RouterError;
use crate::tx_builder::TxBuilder;
use cosmrs::cosmwasm::MsgExecuteContract;
use cosmrs::tx::Msg;
use cosmwasm_std::{Addr, Decimal256, Uint128};
use serde::Serialize;

impl RouterAdminClient {
    #[allow(clippy::too_many_arguments)]
    pub fn append_create_market_msg(
        &self,
        tx_builder: &mut TxBuilder,
        price_oracle_contract: Option<Addr>,
        protocol_fee_recipient: Option<Addr>,
        protocol_fee: Option<Decimal256>,
        lp_fee: Option<Decimal256>,
        base_asset_symbol: String,
        quote_assets_symbols: Vec<String>,
        allowance: Allowance,
        min_base_out: Uint128,
    ) -> Result<(), RouterError> {
        let msg = ExecuteMsg {
            create_market: CreateMarket {
                price_oracle_contract,
                protocol_fee_recipient,
                protocol_fee,
                lp_fee,
                base_asset_symbol,
                quote_assets_symbols,
                allowance,
                min_base_out,
            },
        };
        let contract_msg = serde_json::to_vec(&msg).map_err(RouterError::SerdeJsonError)?;
        let msg = MsgExecuteContract {
            sender: tx_builder.account_id.clone(),
            contract: self.public_router_client.router_contract_address.clone(),
            msg: contract_msg,
            funds: vec![],
        };
        let msg = msg.to_any().map_err(RouterError::EyreError)?;
        tx_builder.add_msg(msg);
        Ok(())
    }
}

#[derive(Serialize)]
pub struct CreateMarket {
    // an already configured oracle contract
    pub price_oracle_contract: Option<Addr>,
    // the address who will receive the protocol fees
    pub protocol_fee_recipient: Option<Addr>,
    // the percentage of value taken as protocol fees. e.g 0.1
    pub protocol_fee: Option<Decimal256>,
    // the percentage of value taken to be given to liquidity providers e.g 0.1
    pub lp_fee: Option<Decimal256>,
    pub base_asset_symbol: String,
    pub quote_assets_symbols: Vec<String>,
    /// Specifies addresses to be allowed/banned from depositing tokens
    pub allowance: Allowance,
    /// The minimum amount of base asset that can be swapped from the pool e.g 1aconst
    pub min_base_out: Uint128,
}

#[derive(Serialize)]
struct ExecuteMsg {
    pub create_market: CreateMarket,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::oracle::client::OracleAdminClient;
    use crate::test_utils::helpers::{
        assert_event_attribute, TEST_ASSET_ARCH_SYMBOL, TEST_ASSET_USDT_SYMBOL,
    };
    use crate::test_utils::test_scenario::TestScenario;
    use cosmrs::tendermint::abci::Code;
    use serial_test::serial;
    use std::ops::Add;
    use std::str::FromStr;
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    #[tokio::test]
    #[serial]
    async fn test_create_market() {
        let mut test_scenario = TestScenario::new_from_config("config.json".to_string()).await;

        // Initialize oracle contract
        let price_threshold_ratio = Decimal256::from_str("0.5").unwrap();
        let price_expire_millis = Some(1000);
        let oracle_contract_address = test_scenario
            .instantiate_oracle_contract(price_threshold_ratio, price_expire_millis)
            .await;

        // Initialize router contract
        let default_protocol_fee = Decimal256::from_str("0.1").unwrap();
        let default_lp_fee = Decimal256::from_str("0.1").unwrap();
        let router_contract_address = test_scenario
            .instantiate_router_contract(
                oracle_contract_address.clone(),
                oracle_contract_address.clone(),
                default_protocol_fee,
                default_lp_fee,
            )
            .await;

        // Set default assets and prices
        let oracle_client =
            OracleAdminClient::from_scenario(&test_scenario, &oracle_contract_address)
                .expect("Failed to create oracle admin client");
        let price_expiry_time = SystemTime::now().add(Duration::from_secs(7200)); // 2h from now
        let price_expiry_timestamp = price_expiry_time
            .duration_since(UNIX_EPOCH)
            .expect("Converting to timestamp failed");
        test_scenario.set_default_assets(&oracle_client).await;
        test_scenario
            .set_default_prices(&oracle_client, price_expiry_timestamp, "50000")
            .await;

        // Post prices
        let router_client = RouterAdminClient::from_scenario(
            &test_scenario,
            router_contract_address.parse().unwrap(),
        )
        .expect("Failed to create router admin client");
        let account = router_client
            .public_router_client
            .account(test_scenario.admin_address.clone())
            .await
            .expect("Failed to get account from public router client");
        let mut tx_builder = TxBuilder::new(
            test_scenario.admin_mnemonic,
            test_scenario.chain_prefix,
            test_scenario.chain_id,
            test_scenario.derivation_path,
            account.sequence,
            account.account_number,
        )
        .expect("Failed to create tx builder");

        router_client
            .append_create_market_msg(
                &mut tx_builder,
                None,
                None,
                None,
                None,
                TEST_ASSET_ARCH_SYMBOL.to_string(),
                vec![TEST_ASSET_USDT_SYMBOL.to_string()],
                Allowance::AllowedLps(vec![test_scenario.admin_address.clone()]),
                Uint128::new(10),
            )
            .expect("Failed to append post prices msg");

        tx_builder.set_memo("From test_create_market".to_string());
        let gas = 650_000u64;
        let amount = 77_000_000_000_000_000u128;
        tx_builder.set_fee(amount, &test_scenario.chain_denom, gas);
        let signed_bytes = tx_builder
            .get_signed_bytes()
            .expect("Failed to get signed bytes");
        let response = router_client
            .broadcast_tx(signed_bytes)
            .await
            .expect("Failed to broadcast tx");

        match response.tx_result.code {
            Code::Ok => {
                println!("Transaction successful: {:?}", response.hash);
                let wasm_event = response
                    .tx_result
                    .events
                    .iter()
                    .find(|ev| ev.kind == "wasm")
                    .expect("Should to find wasm event");
                assert_event_attribute(wasm_event, "action", "create_market_init");
                assert_event_attribute(wasm_event, "base_asset_symbol", TEST_ASSET_ARCH_SYMBOL);
                assert_event_attribute(
                    wasm_event,
                    "settlement_contract_label",
                    &format!("bolt-market-{}", TEST_ASSET_ARCH_SYMBOL),
                );
            }
            Code::Err(code) => {
                panic!(
                    "Transaction failed with code: {:?} response: {:?}",
                    code, response
                );
            }
        }
    }
}