1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use std::str::FromStr;

use colored_json::to_colored_json_auto;
use cosm_utils::{modules::auth::model::Address, prelude::*};
use cw20::Cw20QueryMsg;
use inquire::Text;
use interactive_parse::InteractiveParseObj;
use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value;
use tendermint_rpc::HttpClient;

use crate::{
    contract::Deploy,
    file::{Config, CONFIG},
    utils::replace_strings_any,
};

pub async fn query_contract(contract: &impl Deploy) -> anyhow::Result<Value> {
    println!("Querying");
    let config = CONFIG.read().await;
    let msg = contract.query()?;
    let addr = config.get_contract_addr(&contract.to_string())?.clone();
    let value = query(&config, addr, msg).await?;
    let color = to_colored_json_auto(&value)?;
    println!("{color}");
    Ok(value)
}

pub async fn query(
    config: &Config,
    mut addr: impl AsRef<str> + Serialize + DeserializeOwned + Clone,
    msg: impl Serialize + Sync,
) -> anyhow::Result<Value> {
    replace_strings_any(&mut addr, &config.get_active_env()?.contracts)?;
    let chain_info = config.get_active_chain_info()?.clone();
    let client = HttpClient::get_persistent_compat(chain_info.rpc_endpoint.as_str()).await?;
    let response = client
        .wasm_query(Address::from_str(addr.as_ref())?, &msg)
        .await?;
    let string = String::from_utf8(response.data)?;
    Ok(serde_json::from_str::<Value>(string.as_str())?)
}

pub async fn cw20_query() -> anyhow::Result<Value> {
    println!("Querying cw20");
    let config = CONFIG.read().await;
    let addr = Text::new("Cw20 Contract Address?")
        .with_help_message("string")
        .prompt()?;
    let msg = Cw20QueryMsg::parse_to_obj()?;
    let value = query(&config, addr, msg).await?;
    let color = to_colored_json_auto(&value)?;
    println!("{color}");
    Ok(value)
}