use crate::events::{
get_attr_value_as_coins, get_attr_value_as_str, BOLT_WITHDRAW_QUOTES_EVENT_NAME,
BOLT_WITHDRAW_QUOTES_EVENT_WITHDRAWN_QUOTES,
};
use crate::market::client::MarketAdminClient;
use crate::market::error::MarketError;
use crate::tx_builder::TxBuilder;
use cosmrs::cosmwasm::MsgExecuteContract;
use cosmrs::tendermint::abci::types::ExecTxResult;
use cosmrs::tx::Msg;
use cosmrs::AccountId;
use cosmwasm_std::Addr;
use serde::Serialize;
impl MarketAdminClient {
pub fn append_withdraw_quotes_msg(
&self,
tx_builder: &mut TxBuilder,
market_address: AccountId,
receiver: Option<String>,
) -> Result<(), MarketError> {
let receiver = receiver.map(Addr::unchecked);
let msg = ExecuteMsg {
withdraw_quotes: WithdrawQuotesMsg { receiver },
};
let contract_msg = serde_json::to_vec(&msg).map_err(MarketError::SerdeJsonError)?;
let msg = MsgExecuteContract {
sender: tx_builder.account_id.clone(),
contract: market_address.clone(),
msg: contract_msg,
funds: vec![],
};
let msg = msg.to_any().map_err(MarketError::EyreError)?;
tx_builder.add_msg(msg);
Ok(())
}
}
pub fn parse_withdraw_quotes_tx_for_bolt_event(
tx_result: &ExecTxResult,
) -> Result<Vec<WithdrawQuotesEvent>, MarketError> {
let bolt_events = tx_result
.events
.iter()
.filter(|event| event.kind == BOLT_WITHDRAW_QUOTES_EVENT_NAME)
.map(|event| {
let value = get_attr_value_as_str(event, BOLT_WITHDRAW_QUOTES_EVENT_WITHDRAWN_QUOTES)?;
if value == "none" {
return Ok(WithdrawQuotesEvent {
withdrawn_amounts: vec![],
});
}
let withdrawn_amounts =
get_attr_value_as_coins(event, BOLT_WITHDRAW_QUOTES_EVENT_WITHDRAWN_QUOTES)?;
Ok(WithdrawQuotesEvent { withdrawn_amounts })
})
.collect::<Result<Vec<_>, MarketError>>()?;
Ok(bolt_events)
}
#[derive(Debug, Clone, PartialEq)]
pub struct WithdrawQuotesEvent {
pub withdrawn_amounts: Vec<cosmwasm_std::Coin>,
}
#[derive(Serialize)]
pub struct WithdrawQuotesMsg {
pub receiver: Option<Addr>,
}
#[derive(Serialize)]
struct ExecuteMsg {
pub withdraw_quotes: WithdrawQuotesMsg,
}
#[cfg(test)]
mod tests {
use crate::market::client::MarketAdminClient;
use crate::oracle::client::OracleAdminClient;
use crate::test_utils::helpers::{
assert_event_attribute, TEST_ASSET_ARCH_SYMBOL, TEST_ASSET_ETH_SYMBOL,
TEST_ASSET_USDT_SYMBOL,
};
use crate::test_utils::test_scenario::TestScenario;
use crate::tx_builder::TxBuilder;
use cosmrs::tendermint::abci::{Code, Event, EventAttribute};
use cosmrs::{tendermint, AccountId, Coin};
use cosmwasm_std::{Addr, Decimal256, Uint128};
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_append_withdraw_quotes_msg() {
let mut test_scenario = TestScenario::new_from_config("config.json".to_string()).await;
let price_threshold_ratio = Decimal256::from_str("0.1").unwrap();
let price_expire_millis = Some(1000);
let oracle_contract_address = test_scenario
.instantiate_oracle_contract(price_threshold_ratio, price_expire_millis)
.await;
let client = OracleAdminClient::from_scenario(&test_scenario, &oracle_contract_address)
.expect("Failed to create oracle admin client");
test_scenario.set_default_assets(&client).await;
let price_expiry_time = SystemTime::now().add(Duration::from_secs(7200)); let price_expiry_timestamp = price_expiry_time
.duration_since(UNIX_EPOCH)
.expect("Converting to timestamp failed");
test_scenario
.set_default_prices(&client, price_expiry_timestamp, "50000")
.await;
let new_account = test_scenario.create_new_account().await;
let protocol_fee = Decimal256::percent(10);
let lp_fee = Decimal256::percent(10);
let min_base_out = Uint128::new(10);
let market_contract_addr = test_scenario
.instantiate_settlement_contract(
oracle_contract_address,
new_account.account_id.to_string(),
protocol_fee,
lp_fee,
TEST_ASSET_ARCH_SYMBOL.to_owned(),
vec![
TEST_ASSET_USDT_SYMBOL.to_owned(),
TEST_ASSET_ETH_SYMBOL.to_owned(),
],
min_base_out,
)
.await;
let market_client = MarketAdminClient::from_scenario(&test_scenario).unwrap();
let admin_account = test_scenario.admin_account();
test_scenario
.deposit_base(
&market_client,
AccountId::from_str(&market_contract_addr).unwrap(),
&admin_account,
Coin::new(10000000, TEST_ASSET_ARCH_SYMBOL).unwrap(),
)
.await;
let market_client = MarketAdminClient::from_scenario(&test_scenario)
.expect("Failed to create market admin client");
let transfer_amount = 5000000;
let minimum_base_out = Some(Uint128::new(10));
let receiver = Some(Addr::unchecked(new_account.account_id.clone()));
let market_contract_account_id: AccountId =
market_contract_addr.to_string().parse().unwrap();
for asset in [TEST_ASSET_USDT_SYMBOL, TEST_ASSET_ETH_SYMBOL] {
let coin = Coin::new(transfer_amount, asset).unwrap();
test_scenario
.swap(
&market_client,
market_contract_account_id.clone(),
&new_account,
coin,
minimum_base_out,
receiver.clone(),
)
.await;
}
let account = market_client
.account(new_account.account_id.to_string())
.await
.expect("Failed to get account info");
let mut tx_builder = TxBuilder::new(
new_account.mnemonic,
test_scenario.chain_prefix.clone(),
test_scenario.chain_id.clone(),
test_scenario.derivation_path,
account.sequence,
account.account_number,
)
.unwrap();
market_client
.append_withdraw_quotes_msg(
&mut tx_builder,
market_contract_account_id,
receiver.map(|r| r.to_string()),
)
.unwrap();
tx_builder.set_memo("From test_append_withdraw_quotes_msg".to_string());
let gas = 400_000u64;
let amount = 70_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 = market_client
.broadcast_tx(signed_bytes)
.await
.expect("Failed to broadcast tx");
match response.tx_result.code {
Code::Ok => {
println!("Transaction successful: {:?}", response.hash);
println!("Transaction response: {:?}", response);
let event = response
.tx_result
.events
.iter()
.find(|ev| ev.kind == "wasm-bolt_withdraw_quotes")
.expect("Failed to find withdraw quotes event");
assert_event_attribute(
event,
"withdrawn_quotes",
&format!(
"500000{},500000{}",
TEST_ASSET_USDT_SYMBOL, TEST_ASSET_ETH_SYMBOL
),
)
}
Code::Err(code) => {
panic!(
"Transaction failed with code: {:?} response: {:?}",
code, response
);
}
}
}
#[test]
fn empty_tx_result() {
let tx_result = super::ExecTxResult {
code: Code::Ok,
data: vec![].into(),
log: String::new(),
events: vec![],
gas_wanted: 0,
gas_used: 0,
info: String::new(),
codespace: String::new(),
};
let result = super::parse_withdraw_quotes_tx_for_bolt_event(&tx_result);
assert!(result.is_ok());
assert!(result.unwrap().is_empty());
}
#[test]
fn multiple_withraw_tx_events() {
let tx_result = super::ExecTxResult {
code: Code::Ok,
data: vec![].into(),
log: String::new(),
events: vec![
Event {
kind: super::BOLT_WITHDRAW_QUOTES_EVENT_NAME.to_string(),
attributes: vec![EventAttribute::V037(
tendermint::abci::v0_37::EventAttribute {
key: super::BOLT_WITHDRAW_QUOTES_EVENT_WITHDRAWN_QUOTES.to_string(),
value: "500usdt,400eth".to_string(),
index: false,
},
)],
},
Event {
kind: "foo".to_string(),
attributes: vec![EventAttribute::V037(
tendermint::abci::v0_37::EventAttribute {
key: super::BOLT_WITHDRAW_QUOTES_EVENT_WITHDRAWN_QUOTES.to_string(),
value: "200usdt,100eth".to_string(),
index: false,
},
)],
},
Event {
kind: super::BOLT_WITHDRAW_QUOTES_EVENT_NAME.to_string(),
attributes: vec![EventAttribute::V037(
tendermint::abci::v0_37::EventAttribute {
key: super::BOLT_WITHDRAW_QUOTES_EVENT_WITHDRAWN_QUOTES.to_string(),
value: "800usdt,700eth".to_string(),
index: false,
},
)],
},
],
gas_wanted: 0,
gas_used: 0,
info: String::new(),
codespace: String::new(),
};
let result = super::parse_withdraw_quotes_tx_for_bolt_event(&tx_result).unwrap();
assert_eq!(
result,
[
super::WithdrawQuotesEvent {
withdrawn_amounts: vec![
cosmwasm_std::Coin {
denom: "usdt".to_string(),
amount: Uint128::new(500),
},
cosmwasm_std::Coin {
denom: "eth".to_string(),
amount: Uint128::new(400),
},
],
},
super::WithdrawQuotesEvent {
withdrawn_amounts: vec![
cosmwasm_std::Coin {
denom: "usdt".to_string(),
amount: Uint128::new(800),
},
cosmwasm_std::Coin {
denom: "eth".to_string(),
amount: Uint128::new(700),
},
],
}
]
);
}
}