Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Separate Querier and TxHandler #298

Merged
merged 23 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 9 additions & 12 deletions contracts/counter/src/interface.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use cw_orch::daemon::queriers::Node;
// ANCHOR: custom_interface
use cw_orch::{interface, prelude::*};

Expand Down Expand Up @@ -30,26 +31,22 @@
// ANCHOR_END: custom_interface

use cw_orch::anyhow::Result;
use cw_orch::prelude::queriers::Node;

// ANCHOR: daemon
impl CounterContract<Daemon> {
/// Deploys the counter contract at a specific block height
pub fn await_launch(&self) -> Result<()> {
let daemon = self.get_chain();
let rt = daemon.rt_handle.clone();

rt.block_on(async {
// Get the node query client, there are a lot of other clients available.
let node = daemon.query_client::<Node>();
let mut latest_block = node.latest_block().await.unwrap();
// Get the node query client, there are a lot of other clients available.
let node: Node = daemon.querier();
let mut latest_block = node.latest_block().unwrap();

Check warning on line 43 in contracts/counter/src/interface.rs

View check run for this annotation

Codecov / codecov/patch

contracts/counter/src/interface.rs#L41-L43

Added lines #L41 - L43 were not covered by tests

while latest_block.header.height.value() < 100 {
// wait for the next block
daemon.next_block().unwrap();
latest_block = node.latest_block().await.unwrap();
}
});
while latest_block.height < 100 {
// wait for the next block
daemon.next_block().unwrap();
latest_block = node.latest_block().unwrap();
}

Check warning on line 49 in contracts/counter/src/interface.rs

View check run for this annotation

Codecov / codecov/patch

contracts/counter/src/interface.rs#L45-L49

Added lines #L45 - L49 were not covered by tests

let contract = CounterContract::new(daemon.clone());

Expand Down
4 changes: 4 additions & 0 deletions contracts/counter/tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ fn count() -> anyhow::Result<()> {
assert_eq!(count1.count, count2.count);
// ANCHOR_END: query

// Or get it manually from the chain
let count3: GetCountResponse = mock.query(&QueryMsg::GetCount {}, &contract.address()?)?;
assert_eq!(count1.count, count3.count);

// Check the count
assert_eq!(count1.count, 2);
// ANCHOR: reset
Expand Down
87 changes: 65 additions & 22 deletions cw-orch-daemon/src/core.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,24 @@
use crate::{queriers::CosmWasm, DaemonState};

use super::{
builder::DaemonAsyncBuilder,
cosmos_modules,
error::DaemonError,
queriers::{DaemonQuerier, Node},
sender::Wallet,
tx_resp::CosmTxResponse,
builder::DaemonAsyncBuilder, cosmos_modules, error::DaemonError, queriers::Node,
sender::Wallet, tx_resp::CosmTxResponse,
};

use cosmrs::{
cosmwasm::{MsgExecuteContract, MsgInstantiateContract, MsgMigrateContract},
proto::cosmwasm::wasm::v1::MsgInstantiateContract2,
tendermint::Time,
AccountId, Denom,
AccountId, Any, Denom,
};
use cosmwasm_std::{Addr, Coin};
use cosmwasm_std::{Addr, Binary, Coin};
use cw_orch_core::{
contract::interface_traits::Uploadable,
environment::{ChainState, IndexResponse},
log::transaction_target,
};
use flate2::{write, Compression};
use prost::Message;
use serde::{de::DeserializeOwned, Serialize};
use serde_json::from_str;
use std::{
Expand Down Expand Up @@ -78,12 +76,6 @@
DaemonAsyncBuilder::default()
}

/// Perform a query with a given query client.
/// See [Querier](crate::queriers) for examples.
pub fn query_client<Querier: DaemonQuerier>(&self) -> Querier {
Querier::new(self.sender.channel())
}

/// Get the channel configured for this DaemonAsync.
pub fn channel(&self) -> Channel {
self.state.grpc_channel.clone()
Expand Down Expand Up @@ -162,6 +154,44 @@
Ok(result)
}

/// Instantiate a contract.
pub async fn instantiate2<I: Serialize + Debug>(
&self,
code_id: u64,
init_msg: &I,
label: Option<&str>,
admin: Option<&Addr>,
coins: &[Coin],
salt: Binary,
) -> Result<CosmTxResponse, DaemonError> {
let sender = &self.sender;

let init_msg = MsgInstantiateContract2 {
code_id,
label: label.unwrap_or("instantiate_contract").to_string(),
admin: admin.map(Into::into).unwrap_or_default(),
sender: sender.address()?.to_string(),
msg: serde_json::to_vec(&init_msg)?,
funds: proto_parse_cw_coins(coins)?,
salt: salt.to_vec(),
fix_msg: false,
};

let result = sender
.commit_tx_any(
vec![Any {
type_url: "/cosmwasm.wasm.v1.MsgInstantiateContract2".to_string(),
value: init_msg.encode_to_vec(),
}],
None,
)
.await?;

log::info!(target: &transaction_target(), "Instantiation done: {:?}", result.txhash);

Ok(result)
}

/// Query a contract.
pub async fn query<Q: Serialize + Debug, T: Serialize + DeserializeOwned>(
&self,
Expand Down Expand Up @@ -198,12 +228,11 @@

/// Wait for a given amount of blocks.
pub async fn wait_blocks(&self, amount: u64) -> Result<(), DaemonError> {
let mut last_height = self.query_client::<Node>().block_height().await?;
let mut last_height = Node::new_async(self.channel())._block_height().await?;

Check warning on line 231 in cw-orch-daemon/src/core.rs

View check run for this annotation

Codecov / codecov/patch

cw-orch-daemon/src/core.rs#L231

Added line #L231 was not covered by tests
let end_height = last_height + amount;

let average_block_speed = self
.query_client::<Node>()
.average_block_speed(Some(0.9))
let average_block_speed = Node::new_async(self.channel())
._average_block_speed(Some(0.9))

Check warning on line 235 in cw-orch-daemon/src/core.rs

View check run for this annotation

Codecov / codecov/patch

cw-orch-daemon/src/core.rs#L234-L235

Added lines #L234 - L235 were not covered by tests
.await?;

let wait_time = average_block_speed * amount;
Expand All @@ -217,7 +246,7 @@
tokio::time::sleep(Duration::from_secs(average_block_speed)).await;

// ping latest block
last_height = self.query_client::<Node>().block_height().await?;
last_height = Node::new_async(self.channel())._block_height().await?;

Check warning on line 249 in cw-orch-daemon/src/core.rs

View check run for this annotation

Codecov / codecov/patch

cw-orch-daemon/src/core.rs#L249

Added line #L249 was not covered by tests
}
Ok(())
}
Expand All @@ -236,7 +265,7 @@

/// Get the current block info.
pub async fn block_info(&self) -> Result<cosmwasm_std::BlockInfo, DaemonError> {
let block = self.query_client::<Node>().latest_block().await?;
let block = Node::new_async(self.channel())._latest_block().await?;

Check warning on line 268 in cw-orch-daemon/src/core.rs

View check run for this annotation

Codecov / codecov/patch

cw-orch-daemon/src/core.rs#L268

Added line #L268 was not covered by tests
let since_epoch = block.header.time.duration_since(Time::unix_epoch())?;
let time = cosmwasm_std::Timestamp::from_nanos(since_epoch.as_nanos() as u64);
Ok(cosmwasm_std::BlockInfo {
Expand Down Expand Up @@ -273,8 +302,8 @@
let code_id = result.uploaded_code_id().unwrap();

// wait for the node to return the contract information for this upload
let wasm = CosmWasm::new(self.channel());
while wasm.code(code_id).await.is_err() {
let wasm = CosmWasm::new_async(self.channel());
while wasm._code(code_id).await.is_err() {
self.next_block().await?;
}
Ok(result)
Expand All @@ -299,3 +328,17 @@
})
.collect::<Result<Vec<_>, DaemonError>>()
}

pub(crate) fn proto_parse_cw_coins(
coins: &[cosmwasm_std::Coin],
) -> Result<Vec<cosmrs::proto::cosmos::base::v1beta1::Coin>, DaemonError> {
coins
.iter()
.map(|cosmwasm_std::Coin { amount, denom }| {
Ok(cosmrs::proto::cosmos::base::v1beta1::Coin {
amount: amount.to_string(),
denom: denom.clone(),
})

Check warning on line 341 in cw-orch-daemon/src/core.rs

View check run for this annotation

Codecov / codecov/patch

cw-orch-daemon/src/core.rs#L338-L341

Added lines #L338 - L341 were not covered by tests
})
.collect::<Result<Vec<_>, DaemonError>>()
}
6 changes: 5 additions & 1 deletion cw-orch-daemon/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![allow(missing_docs)]

use cosmwasm_std::Coin;
use cosmwasm_std::{Coin, Instantiate2AddressError};
use cw_orch_core::CwEnvError;
use thiserror::Error;

Expand Down Expand Up @@ -118,6 +118,10 @@ pub enum DaemonError {
NotEnoughBalance { expected: Coin, current: Coin },
#[error("Can't set the daemon state, it's read-only")]
StateReadOnly,
#[error("You need to pass a runtime to the querier object to do synchronous queries. Use daemon.querier instead")]
QuerierNeedRuntime,
#[error(transparent)]
Instantiate2Error(#[from] Instantiate2AddressError),
}

impl DaemonError {
Expand Down
1 change: 0 additions & 1 deletion cw-orch-daemon/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ pub mod keys;
pub mod live_mock;
mod log;
pub mod queriers;
mod traits;
pub mod tx_broadcaster;
pub mod tx_builder;
pub use self::{builder::*, channel::*, core::*, error::*, state::*, sync::*, tx_resp::*};
Expand Down
68 changes: 28 additions & 40 deletions cw-orch-daemon/src/live_mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,29 @@

use crate::queriers::Bank;
use crate::queriers::CosmWasm;
use crate::queriers::DaemonQuerier;
use crate::queriers::Staking;
use cosmwasm_std::Addr;
use cosmwasm_std::AllBalanceResponse;
use cosmwasm_std::BalanceResponse;
use cosmwasm_std::Delegation;
use cosmwasm_std::{AllDelegationsResponse, BondedDenomResponse};

use cosmwasm_std::BankQuery;
use cosmwasm_std::Binary;
use cosmwasm_std::Delegation;
use cosmwasm_std::Empty;
use cosmwasm_std::StakingQuery;
use cosmwasm_std::{AllDelegationsResponse, BondedDenomResponse};
use cw_orch_core::environment::BankQuerier;
use ibc_chain_registry::chain::ChainData;
use tokio::runtime::Runtime;
use tonic::transport::Channel;

use std::marker::PhantomData;
use std::str::FromStr;

use cosmwasm_std::testing::{MockApi, MockStorage};
use cosmwasm_std::{
from_json, to_json_binary, Coin, ContractResult, OwnedDeps, Querier, QuerierResult,
QueryRequest, SystemError, SystemResult, Uint128, WasmQuery,
};
use cw_orch_core::environment::WasmQuerier;
use std::marker::PhantomData;
use std::str::FromStr;

use crate::channel::GrpcChannel;

Expand Down Expand Up @@ -83,28 +82,28 @@
pub fn handle_query(&self, request: &QueryRequest<Empty>) -> QuerierResult {
match &request {
QueryRequest::Wasm(x) => {
let querier = CosmWasm::new(self.channel.clone());
let querier = CosmWasm {
channel: self.channel.clone(),
rt_handle: Some(self.runtime.handle().clone()),
};

Check warning on line 88 in cw-orch-daemon/src/live_mock.rs

View check run for this annotation

Codecov / codecov/patch

cw-orch-daemon/src/live_mock.rs#L85-L88

Added lines #L85 - L88 were not covered by tests
match x {
WasmQuery::Smart { contract_addr, msg } => {
// We forward the request to the cosmwasm querier

let query_result: Result<Binary, _> = self
.runtime
.block_on(
querier.contract_state(contract_addr.to_string(), msg.to_vec()),
querier._contract_state(contract_addr.to_string(), msg.to_vec()),

Check warning on line 96 in cw-orch-daemon/src/live_mock.rs

View check run for this annotation

Codecov / codecov/patch

cw-orch-daemon/src/live_mock.rs#L96

Added line #L96 was not covered by tests
)
.map(|query_result| query_result.into());
SystemResult::Ok(ContractResult::from(query_result))
}
WasmQuery::Raw { contract_addr, key } => {
// We forward the request to the cosmwasm querier
// We forward the request to the cosmwasm querie
let query_result = querier
.raw_query(contract_addr.to_string(), key.to_vec())
.map(|query_result| query_result.into());

Check warning on line 105 in cw-orch-daemon/src/live_mock.rs

View check run for this annotation

Codecov / codecov/patch

cw-orch-daemon/src/live_mock.rs#L102-L105

Added lines #L102 - L105 were not covered by tests

let query_result = self
.runtime
.block_on(
querier.contract_raw_state(contract_addr.to_string(), key.to_vec()),
)
.map(|query_result| query_result.data.into());
SystemResult::Ok(ContractResult::from(query_result))
}
_ => SystemResult::Err(SystemError::InvalidRequest {
Expand All @@ -114,36 +113,25 @@
}
}
QueryRequest::Bank(x) => {
let querier = Bank::new(self.channel.clone());
let querier = Bank {
channel: self.channel.clone(),
rt_handle: Some(self.runtime.handle().clone()),
};
match x {
BankQuery::Balance { address, denom } => {
let query_result = self
.runtime
.block_on(querier.balance(address, Some(denom.clone())))
.map(|result| {
let query_result =
querier.balance(address, Some(denom.clone())).map(|result| {
to_json_binary(&BalanceResponse {
amount: Coin {
amount: Uint128::from_str(&result[0].amount).unwrap(),
denom: result[0].denom.clone(),
},
amount: result[0].clone(),
})
.unwrap()
});
SystemResult::Ok(ContractResult::from(query_result))
}
BankQuery::AllBalances { address } => {
let query_result = self
.runtime
.block_on(querier.balance(address, None))
.map(|result| AllBalanceResponse {
amount: result
.into_iter()
.map(|c| Coin {
amount: Uint128::from_str(&c.amount).unwrap(),
denom: c.denom,
})
.collect(),
})
let query_result = querier
.balance(address, None)
.map(|result| AllBalanceResponse { amount: result })
.map(|query_result| to_json_binary(&query_result))
.unwrap();
SystemResult::Ok(ContractResult::from(query_result))
Expand All @@ -155,12 +143,12 @@
}
}
QueryRequest::Staking(x) => {
let querier = Staking::new(self.channel.clone());
let querier = Staking::new_async(self.channel.clone());

Check warning on line 146 in cw-orch-daemon/src/live_mock.rs

View check run for this annotation

Codecov / codecov/patch

cw-orch-daemon/src/live_mock.rs#L146

Added line #L146 was not covered by tests
match x {
StakingQuery::BondedDenom {} => {
let query_result = self
.runtime
.block_on(querier.params())
.block_on(querier._params())

Check warning on line 151 in cw-orch-daemon/src/live_mock.rs

View check run for this annotation

Codecov / codecov/patch

cw-orch-daemon/src/live_mock.rs#L151

Added line #L151 was not covered by tests
.map(|result| BondedDenomResponse {
denom: result.params.unwrap().bond_denom,
})
Expand All @@ -173,7 +161,7 @@
StakingQuery::AllDelegations { delegator } => {
let query_result = self
.runtime
.block_on(querier.delegator_delegations(delegator, None))
.block_on(querier._delegator_delegations(delegator, None))

Check warning on line 164 in cw-orch-daemon/src/live_mock.rs

View check run for this annotation

Codecov / codecov/patch

cw-orch-daemon/src/live_mock.rs#L164

Added line #L164 was not covered by tests
.map(|result| AllDelegationsResponse {
delegations: result
.delegation_responses
Expand Down
Loading
Loading