-
Notifications
You must be signed in to change notification settings - Fork 120
/
lib.rs
300 lines (275 loc) · 7.99 KB
/
lib.rs
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
// Copyright 2018-2023 Parity Technologies (UK) Ltd.
// This file is part of cargo-contract.
//
// cargo-contract is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// cargo-contract is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with cargo-contract. If not, see <http://www.gnu.org/licenses/>.
mod balance;
mod call;
mod contract_artifacts;
mod contract_info;
mod contract_storage;
mod env_check;
mod error;
mod events;
mod extrinsic_calls;
mod extrinsic_opts;
mod instantiate;
pub mod pallet_contracts_primitives;
mod prod_chains;
mod remove;
mod rpc;
mod upload;
#[cfg(test)]
mod contract_storage_tests;
#[cfg(test)]
#[cfg(feature = "integration-tests")]
mod integration_tests;
use env_check::compare_node_env_with_contract;
pub use extrinsic_opts::Chain;
pub use prod_chains::ProductionChain;
use anyhow::Result;
use contract_build::{
CrateMetadata,
Verbosity,
DEFAULT_KEY_COL_WIDTH,
};
use scale::{
Decode,
Encode,
};
use subxt::{
backend::legacy::LegacyRpcMethods,
blocks,
config,
tx,
Config,
OnlineClient,
};
pub use balance::{
BalanceVariant,
TokenMetadata,
};
pub use call::{
CallCommandBuilder,
CallExec,
};
pub use contract_artifacts::ContractArtifacts;
pub use contract_info::{
fetch_all_contracts,
fetch_contract_info,
fetch_wasm_code,
ContractInfo,
TrieId,
};
use contract_metadata::ContractMetadata;
pub use contract_storage::{
ContractStorage,
ContractStorageCell,
ContractStorageLayout,
ContractStorageRpc,
};
pub use contract_transcode::ContractMessageTranscoder;
pub use error::{
ErrorVariant,
GenericError,
};
pub use events::DisplayEvents;
pub use extrinsic_opts::ExtrinsicOptsBuilder;
pub use instantiate::{
Code,
InstantiateArgs,
InstantiateCommandBuilder,
InstantiateDryRunResult,
InstantiateExec,
InstantiateExecResult,
};
pub use remove::{
RemoveCommandBuilder,
RemoveExec,
RemoveResult,
};
pub use upload::{
UploadCommandBuilder,
UploadExec,
UploadResult,
};
pub use rpc::{
RawParams,
RpcRequest,
};
/// The Wasm code of a contract.
#[derive(Debug, Clone)]
pub struct WasmCode(Vec<u8>);
impl WasmCode {
/// The hash of the contract code: uniquely identifies the contract code on-chain.
pub fn code_hash(&self) -> [u8; 32] {
contract_build::code_hash(&self.0)
}
}
/// Wait for the transaction to be included successfully into a block.
///
/// # Errors
///
/// If a runtime Module error occurs, this will only display the pallet and error indices.
/// Dynamic lookups of the actual error will be available once the following issue is
/// resolved: <https://github.com/paritytech/subxt/issues/443>.
///
/// # Finality
///
/// Currently this will report success once the transaction is included in a block. In the
/// future there could be a flag to wait for finality before reporting success.
async fn submit_extrinsic<C, Call, Signer>(
client: &OnlineClient<C>,
rpc: &LegacyRpcMethods<C>,
call: &Call,
signer: &Signer,
) -> core::result::Result<blocks::ExtrinsicEvents<C>, subxt::Error>
where
C: Config,
Call: tx::TxPayload,
Signer: tx::Signer<C>,
<C::ExtrinsicParams as config::ExtrinsicParams<C>>::OtherParams: Default,
{
let account_id = Signer::account_id(signer);
let account_nonce = get_account_nonce(client, rpc, &account_id).await?;
let mut tx = client
.tx()
.create_signed_with_nonce(call, signer, account_nonce, Default::default())?
.submit_and_watch()
.await?;
// Below we use the low level API to replicate the `wait_for_in_block` behaviour which
// was removed in subxt 0.33.0. See https://github.com/paritytech/subxt/pull/1237.
//
// We require this because we use `substrate-contracts-node` as our development node,
// which does not currently support finality, so we just want to wait until it is
// included in a block.
use subxt::error::{
RpcError,
TransactionError,
};
use tx::TxStatus;
while let Some(status) = tx.next().await {
match status? {
TxStatus::InBestBlock(tx_in_block)
| TxStatus::InFinalizedBlock(tx_in_block) => {
let events = tx_in_block.wait_for_success().await?;
return Ok(events)
}
TxStatus::Error { message } => {
return Err(TransactionError::Error(message).into())
}
TxStatus::Invalid { message } => {
return Err(TransactionError::Invalid(message).into())
}
TxStatus::Dropped { message } => {
return Err(TransactionError::Dropped(message).into())
}
_ => continue,
}
}
Err(RpcError::SubscriptionDropped.into())
}
/// Return the account nonce at the *best* block for an account ID.
async fn get_account_nonce<C>(
client: &OnlineClient<C>,
rpc: &LegacyRpcMethods<C>,
account_id: &C::AccountId,
) -> core::result::Result<u64, subxt::Error>
where
C: Config,
{
let best_block = rpc
.chain_get_block_hash(None)
.await?
.ok_or(subxt::Error::Other("Best block not found".into()))?;
let account_nonce = client
.blocks()
.at(best_block)
.await?
.account_nonce(account_id)
.await?;
Ok(account_nonce)
}
async fn state_call<C, A: Encode, R: Decode>(
rpc: &LegacyRpcMethods<C>,
func: &str,
args: A,
) -> Result<R>
where
C: Config,
{
let params = args.encode();
let bytes = rpc.state_call(func, Some(¶ms), None).await?;
Ok(R::decode(&mut bytes.as_ref())?)
}
/// Fetch the hash of the *best* block (included but not guaranteed to be finalized).
async fn get_best_block<C>(
rpc: &LegacyRpcMethods<C>,
) -> core::result::Result<C::Hash, subxt::Error>
where
C: Config,
{
rpc.chain_get_block_hash(None)
.await?
.ok_or(subxt::Error::Other("Best block not found".into()))
}
fn check_env_types<C>(
client: &OnlineClient<C>,
transcoder: &ContractMessageTranscoder,
verbosity: &Verbosity,
) -> Result<()>
where
C: Config,
{
compare_node_env_with_contract(
client.metadata().types(),
transcoder.metadata(),
verbosity,
)
}
// Converts a Url into a String representation without excluding the default port.
pub fn url_to_string(url: &url::Url) -> String {
match (url.port(), url.port_or_known_default()) {
(None, Some(port)) => {
format!(
"{}:{port}{}",
&url[..url::Position::AfterHost],
&url[url::Position::BeforePath..]
)
.to_string()
}
_ => url.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn url_to_string_works() {
// with custom port
let url = url::Url::parse("ws://127.0.0.1:9944").unwrap();
assert_eq!(url_to_string(&url), "ws://127.0.0.1:9944/");
// with default port
let url = url::Url::parse("wss://127.0.0.1:443").unwrap();
assert_eq!(url_to_string(&url), "wss://127.0.0.1:443/");
// with default port and path
let url = url::Url::parse("wss://127.0.0.1:443/test/1").unwrap();
assert_eq!(url_to_string(&url), "wss://127.0.0.1:443/test/1");
// with default port and domain
let url = url::Url::parse("wss://test.io:443").unwrap();
assert_eq!(url_to_string(&url), "wss://test.io:443/");
// with default port, domain and path
let url = url::Url::parse("wss://test.io/test/1").unwrap();
assert_eq!(url_to_string(&url), "wss://test.io:443/test/1");
}
}