-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathnode.rs
More file actions
300 lines (256 loc) · 9.96 KB
/
node.rs
File metadata and controls
300 lines (256 loc) · 9.96 KB
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
use std::net::SocketAddr;
use std::path::Path;
use std::process::Command;
use std::sync::Arc;
use katana_chain_spec::{dev, ChainSpec};
use katana_core::backend::Backend;
use katana_executor::implementation::blockifier::BlockifierFactory;
use katana_node::config::dev::DevConfig;
use katana_node::config::rpc::{RpcConfig, RpcModulesList, DEFAULT_RPC_ADDR};
use katana_node::config::sequencing::SequencingConfig;
use katana_node::config::Config;
use katana_node::{LaunchedNode, Node};
use katana_primitives::address;
use katana_primitives::chain::ChainId;
use katana_provider::{
DbProviderFactory, ForkProviderFactory, ProviderFactory, ProviderRO, ProviderRW,
};
use katana_rpc_server::HttpClient;
use starknet::accounts::{ExecutionEncoding, SingleOwnerAccount};
use starknet::core::types::BlockTag;
pub use starknet::core::types::StarknetError;
use starknet::providers::jsonrpc::HttpTransport;
use starknet::providers::{JsonRpcClient, Url};
pub use starknet::providers::{Provider, ProviderError};
use starknet::signers::{LocalWallet, SigningKey};
/// Errors that can occur when migrating contracts to a test node.
#[derive(Debug, thiserror::Error)]
pub enum MigrateError {
#[error("Failed to create temp directory: {0}")]
TempDir(#[from] std::io::Error),
#[error("Git clone failed: {0}")]
GitClone(String),
#[error("Scarb build failed: {0}")]
ScarbBuild(String),
#[error("Sozo migrate failed: {0}")]
SozoMigrate(String),
#[error("Missing genesis account private key")]
MissingPrivateKey,
#[error("Spawn blocking task failed: {0}")]
SpawnBlocking(#[from] tokio::task::JoinError),
}
pub type ForkTestNode = TestNode<ForkProviderFactory>;
#[derive(Debug)]
pub struct TestNode<P = DbProviderFactory>
where
P: ProviderFactory,
<P as ProviderFactory>::Provider: ProviderRO,
<P as ProviderFactory>::ProviderMut: ProviderRW,
{
node: LaunchedNode<P>,
}
impl TestNode {
pub async fn new() -> Self {
Self::new_with_config(test_config()).await
}
pub async fn new_with_block_time(block_time: u64) -> Self {
let mut config = test_config();
config.sequencing.block_time = Some(block_time);
Self::new_with_config(config).await
}
pub async fn new_with_config(config: Config) -> Self {
Self {
node: Node::build(config)
.expect("failed to build node")
.launch()
.await
.expect("failed to launch node"),
}
}
}
impl ForkTestNode {
pub async fn new_forked_with_config(config: Config) -> Self {
Self {
node: Node::build_forked(config)
.await
.expect("failed to build node")
.launch()
.await
.expect("failed to launch node"),
}
}
}
impl<P> TestNode<P>
where
P: ProviderFactory,
<P as ProviderFactory>::Provider: ProviderRO,
<P as ProviderFactory>::ProviderMut: ProviderRW,
{
/// Returns the address of the node's RPC server.
pub fn rpc_addr(&self) -> &SocketAddr {
self.node.rpc().addr()
}
pub fn backend(&self) -> &Arc<Backend<BlockifierFactory, P>> {
self.node.node().backend()
}
/// Returns a reference to the launched node handle.
pub fn handle(&self) -> &LaunchedNode<P> {
&self.node
}
pub fn starknet_provider(&self) -> JsonRpcClient<HttpTransport> {
let url = Url::parse(&format!("http://{}", self.rpc_addr())).expect("failed to parse url");
JsonRpcClient::new(HttpTransport::new(url))
}
pub fn account(&self) -> SingleOwnerAccount<JsonRpcClient<HttpTransport>, LocalWallet> {
let (address, account) =
self.backend().chain_spec.genesis().accounts().next().expect("must have at least one");
let private_key = account.private_key().expect("must exist");
let signer = LocalWallet::from_signing_key(SigningKey::from_secret_scalar(private_key));
let mut account = SingleOwnerAccount::new(
self.starknet_provider(),
signer,
(*address).into(),
self.backend().chain_spec.id().into(),
ExecutionEncoding::New,
);
account.set_block_id(starknet::core::types::BlockId::Tag(BlockTag::PreConfirmed));
account
}
/// Returns a HTTP client to the JSON-RPC server.
pub fn rpc_http_client(&self) -> HttpClient {
self.handle().rpc().http_client().expect("failed to get http client for the rpc server")
}
/// Returns a HTTP client to the JSON-RPC server.
pub fn starknet_rpc_client(&self) -> katana_rpc_client::starknet::Client {
let client = self.rpc_http_client();
katana_rpc_client::starknet::Client::new_with_client(client)
}
/// Migrates the `spawn-and-move` example contracts from the dojo repository.
///
/// This method requires `git`, `asdf`, and `sozo` to be available in PATH.
/// The scarb version is managed by asdf using the `.tool-versions` file
/// in the dojo repository.
pub async fn migrate_spawn_and_move(&self) -> Result<(), MigrateError> {
self.migrate_example("spawn-and-move").await
}
/// Migrates the `simple` example contracts from the dojo repository.
///
/// This method requires `git`, `asdf`, and `sozo` to be available in PATH.
/// The scarb version is managed by asdf using the `.tool-versions` file
/// in the dojo repository.
pub async fn migrate_simple(&self) -> Result<(), MigrateError> {
self.migrate_example("simple").await
}
/// Migrates contracts from a dojo example project.
///
/// Clones the dojo repository, builds contracts with `scarb`, and deploys
/// them with `sozo migrate`.
///
/// This method requires `git`, `asdf`, and `sozo` to be available in PATH.
/// The scarb version is managed by asdf using the `.tool-versions` file
/// in the dojo repository.
async fn migrate_example(&self, example: &str) -> Result<(), MigrateError> {
let rpc_url = format!("http://{}", self.rpc_addr());
let (address, account) = self
.backend()
.chain_spec
.genesis()
.accounts()
.next()
.expect("must have at least one genesis account");
let private_key = account.private_key().ok_or(MigrateError::MissingPrivateKey)?;
let address_hex = address.to_string();
let private_key_hex = format!("{private_key:#x}");
let example_path = format!("dojo/examples/{example}");
tokio::task::spawn_blocking(move || {
let temp_dir = tempfile::tempdir()?;
// Clone dojo repository at v1.7.0
run_git_clone(temp_dir.path())?;
let project_dir = temp_dir.path().join(&example_path);
// Build contracts using asdf to ensure correct scarb version
run_scarb_build(&project_dir)?;
// Deploy contracts to the katana node
run_sozo_migrate(&project_dir, &rpc_url, &address_hex, &private_key_hex)?;
Ok(())
})
.await?
}
}
fn run_git_clone(temp_dir: &Path) -> Result<(), MigrateError> {
let output = Command::new("git")
.args(["clone", "--depth", "1", "--branch", "v1.7.0", "https://github.com/dojoengine/dojo"])
.current_dir(temp_dir)
.output()
.map_err(|e| MigrateError::GitClone(e.to_string()))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(MigrateError::GitClone(stderr.to_string()));
}
Ok(())
}
fn run_scarb_build(project_dir: &Path) -> Result<(), MigrateError> {
let output = Command::new("asdf")
.args(["exec", "scarb", "build"])
.current_dir(project_dir)
.output()
.map_err(|e| MigrateError::ScarbBuild(e.to_string()))?;
if !output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let combined = format!("{stdout}\n{stderr}");
let lines: Vec<&str> = combined.lines().collect();
let last_50: String =
lines.iter().rev().take(50).rev().cloned().collect::<Vec<_>>().join("\n");
return Err(MigrateError::ScarbBuild(last_50));
}
Ok(())
}
fn run_sozo_migrate(
project_dir: &Path,
rpc_url: &str,
address: &str,
private_key: &str,
) -> Result<(), MigrateError> {
let output = Command::new("sozo")
.args([
"migrate",
"--rpc-url",
rpc_url,
"--account-address",
address,
"--private-key",
private_key,
])
.current_dir(project_dir)
.output()
.map_err(|e| MigrateError::SozoMigrate(e.to_string()))?;
if !output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let combined = format!("{stdout}\n{stderr}");
let lines: Vec<&str> = combined.lines().collect();
let last_50: String =
lines.iter().rev().take(50).rev().cloned().collect::<Vec<_>>().join("\n");
eprintln!("sozo migrate failed. Last 50 lines of output:\n{last_50}");
return Err(MigrateError::SozoMigrate(last_50));
}
Ok(())
}
pub fn test_config() -> Config {
let sequencing = SequencingConfig::default();
let dev = DevConfig { fee: false, account_validation: true, fixed_gas_prices: None };
let mut chain = dev::ChainSpec { id: ChainId::SEPOLIA, ..Default::default() };
chain.genesis.sequencer_address = address!("0x1");
let rpc = RpcConfig {
port: 0,
#[cfg(feature = "explorer")]
explorer: true,
addr: DEFAULT_RPC_ADDR,
apis: RpcModulesList::all(),
max_proof_keys: Some(100),
max_event_page_size: Some(100),
max_concurrent_estimate_fee_requests: None,
..Default::default()
};
Config { sequencing, rpc, dev, chain: ChainSpec::Dev(chain).into(), ..Default::default() }
}