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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
use std::{
fmt::Debug,
rc::Rc,
str::{from_utf8, FromStr},
sync::Arc,
time::Duration,
};
use cosmrs::{
cosmwasm::{MsgExecuteContract, MsgInstantiateContract, MsgMigrateContract},
AccountId, Denom,
};
use cosmwasm_std::{Addr, Coin, Empty};
use serde::{de::DeserializeOwned, Serialize};
use serde_json::from_str;
use tokio::runtime::Runtime;
use tonic::transport::Channel;
use crate::{
contract::ContractCodeReference, cosmos_modules, error::BootError, state::ChainState,
tx_handler::TxHandler,
};
use super::{
querier::DaemonQuerier,
sender::{Sender, Wallet},
state::{DaemonOptions, DaemonState, NetworkKind},
tx_resp::CosmTxResponse,
};
pub fn instantiate_daemon_env(
runtime: &Arc<Runtime>,
options: DaemonOptions,
) -> anyhow::Result<(Addr, Daemon)> {
let state = Rc::new(runtime.block_on(DaemonState::new(options))?);
let sender = Rc::new(Sender::new(&state)?);
let chain = Daemon::new(&sender, &state, runtime)?;
Ok((sender.address()?, chain))
}
#[derive(Clone)]
pub struct Daemon {
pub sender: Wallet,
pub state: Rc<DaemonState>,
pub runtime: Arc<Runtime>,
}
impl Daemon {
pub fn new(
sender: &Wallet,
state: &Rc<DaemonState>,
runtime: &Arc<Runtime>,
) -> anyhow::Result<Self> {
let instance = Self {
sender: sender.clone(),
state: state.clone(),
runtime: runtime.clone(),
};
Ok(instance)
}
async fn wait(&self) {
match self.state.kind {
NetworkKind::Local => tokio::time::sleep(Duration::from_secs(6)).await,
NetworkKind::Mainnet => tokio::time::sleep(Duration::from_secs(60)).await,
NetworkKind::Testnet => tokio::time::sleep(Duration::from_secs(30)).await,
}
}
pub fn set_deployment(&mut self, deployment_id: impl Into<String>) -> Result<(), BootError> {
Rc::get_mut(&mut self.state)
.ok_or(BootError::SharedDaemonState)?
.set_deployment(deployment_id);
Ok(())
}
}
impl ChainState for Daemon {
type Out = Rc<DaemonState>;
fn state(&self) -> Self::Out {
self.state.clone()
}
}
impl TxHandler for Daemon {
type Response = CosmTxResponse;
fn sender(&self) -> Addr {
self.sender.address().unwrap()
}
fn execute<E: Serialize>(
&self,
exec_msg: &E,
coins: &[cosmwasm_std::Coin],
contract_address: &Addr,
) -> Result<Self::Response, BootError> {
let exec_msg: MsgExecuteContract = MsgExecuteContract {
sender: self.sender.pub_addr()?,
contract: AccountId::from_str(contract_address.as_str())?,
msg: serde_json::to_vec(&exec_msg)?,
funds: parse_cw_coins(coins)?,
};
let result = self
.runtime
.block_on(self.sender.commit_tx(vec![exec_msg], None))?;
Ok(result)
}
fn instantiate<I: Serialize + Debug>(
&self,
code_id: u64,
init_msg: &I,
label: Option<&str>,
admin: Option<&Addr>,
coins: &[Coin],
) -> Result<Self::Response, BootError> {
let sender = &self.sender;
let init_msg = MsgInstantiateContract {
code_id,
label: Some(label.unwrap_or("instantiate_contract").to_string()),
admin: admin.map(|a| FromStr::from_str(a.as_str()).unwrap()),
sender: sender.pub_addr()?,
msg: serde_json::to_vec(&init_msg)?,
funds: parse_cw_coins(coins)?,
};
let result = self
.runtime
.block_on(sender.commit_tx(vec![init_msg], None))?;
Ok(result)
}
fn query<Q: Serialize + Debug, T: Serialize + DeserializeOwned>(
&self,
query_msg: &Q,
contract_address: &Addr,
) -> Result<T, BootError> {
let sender = &self.sender;
let mut client = cosmos_modules::cosmwasm::query_client::QueryClient::new(sender.channel());
let resp = self.runtime.block_on(client.smart_contract_state(
cosmos_modules::cosmwasm::QuerySmartContractStateRequest {
address: contract_address.to_string(),
query_data: serde_json::to_vec(&query_msg)?,
},
))?;
Ok(from_str(from_utf8(&resp.into_inner().data).unwrap())?)
}
fn migrate<M: Serialize + Debug>(
&self,
migrate_msg: &M,
new_code_id: u64,
contract_address: &Addr,
) -> Result<Self::Response, BootError> {
let exec_msg: MsgMigrateContract = MsgMigrateContract {
sender: self.sender.pub_addr()?,
contract: AccountId::from_str(contract_address.as_str())?,
msg: serde_json::to_vec(&migrate_msg)?,
code_id: new_code_id,
};
let result = self
.runtime
.block_on(self.sender.commit_tx(vec![exec_msg], None))?;
Ok(result)
}
fn upload(
&self,
contract_source: &mut ContractCodeReference<Empty>,
) -> Result<Self::Response, BootError> {
let sender = &self.sender;
let wasm_path = &contract_source.get_wasm_code_path()?;
log::debug!("{}", wasm_path);
let file_contents = std::fs::read(wasm_path)?;
let store_msg = cosmrs::cosmwasm::MsgStoreCode {
sender: sender.pub_addr()?,
wasm_byte_code: file_contents,
instantiate_permission: None,
};
let result = self
.runtime
.block_on(sender.commit_tx(vec![store_msg], None))?;
log::info!("uploaded: {:?}", result.txhash);
self.runtime.block_on(self.wait());
Ok(result)
}
fn wait_blocks(&self, amount: u64) -> Result<(), BootError> {
let channel: Channel = self.sender.channel();
let mut last_height = self
.runtime
.block_on(DaemonQuerier::block_height(channel.clone()))?;
let end_height = last_height + amount;
while last_height < end_height {
self.runtime
.block_on(tokio::time::sleep(Duration::from_secs(4)));
last_height = self
.runtime
.block_on(DaemonQuerier::block_height(channel.clone()))?;
}
Ok(())
}
fn next_block(&self) -> Result<(), BootError> {
let channel: Channel = self.sender.channel();
let mut last_height = self
.runtime
.block_on(DaemonQuerier::block_height(channel.clone()))?;
let end_height = last_height + 1;
while last_height < end_height {
self.runtime
.block_on(tokio::time::sleep(Duration::from_secs(4)));
last_height = self
.runtime
.block_on(DaemonQuerier::block_height(channel.clone()))?;
}
Ok(())
}
}
pub(crate) fn parse_cw_coins(coins: &[cosmwasm_std::Coin]) -> Result<Vec<cosmrs::Coin>, BootError> {
coins
.iter()
.map(|cosmwasm_std::Coin { amount, denom }| {
Ok(cosmrs::Coin {
amount: amount.u128(),
denom: Denom::from_str(denom)?,
})
})
.collect::<Result<Vec<_>, BootError>>()
}