forked from Nanle-code/StarForge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.rs
More file actions
601 lines (543 loc) · 21 KB
/
Copy pathdeploy.rs
File metadata and controls
601 lines (543 loc) · 21 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
use crate::utils::{config, confirmation, horizon, optimizer, print as p, soroban, wallet_signer};
use anyhow::Result;
use clap::Args;
use colored::*;
use crate::utils::hardware_wallet::HardwareWalletKind;
use sha2::{Digest, Sha256};
use std::fs;
use std::path::PathBuf;
use std::process::Command;
const SOROBAN_WASM_LIMIT_KB: f64 = 128.0;
/// Deploy a compiled Soroban WASM artifact to testnet or mainnet.
///
/// By default StarForge performs a dry-run: it validates the WASM, checks the
/// wallet on Horizon, prints the Stellar CLI command, and optionally simulates
/// fees with `--simulate`. Pass `--execute` to run `stellar contract deploy`.
#[derive(Args)]
pub struct DeployArgs {
/// Path to the compiled .wasm file
#[arg(long)]
pub wasm: PathBuf,
/// Network to deploy to
#[arg(long, default_value = "testnet", value_parser = ["testnet", "mainnet"])]
pub network: String,
/// Wallet name to use for deployment
#[arg(long)]
pub wallet: Option<String>,
/// Optimize the WASM before deployment using the built-in optimizer
#[arg(long, default_value = "false")]
pub optimize: bool,
/// Skip confirmation prompt
#[arg(long, default_value = "false")]
pub yes: bool,
/// Execute deployment immediately if Stellar CLI is installed
#[arg(long, default_value = "false")]
pub execute: bool,
/// Simulate the deploy transaction using Soroban RPC
/// Simulate deploy transaction via Soroban RPC before confirmation
#[arg(long, default_value = "false")]
pub simulate: bool,
/// Dry-run: validate artifact paths, network connectivity, wallet existence,
/// and estimate fees without submitting any transaction. Prints a full
/// deployment plan and exits. Implies --simulate.
#[arg(long, default_value = "false")]
pub dry_run: bool,
/// Sign deployment with a hardware wallet (Ledger/Trezor)
#[arg(long, value_enum)]
pub hardware: Option<HardwareWalletKind>,
/// HD derivation path for hardware wallet signing
#[arg(long, default_value = crate::utils::hardware_wallet::STELLAR_HD_PATH)]
pub hd_path: String,
}
fn is_wasm_above_size_limit(wasm_size_kb: f64) -> bool {
wasm_size_kb > SOROBAN_WASM_LIMIT_KB
}
/// Compute the Soroban WASM hash (SHA-256 over raw `.wasm` file bytes)
/// and return it as a 64-character lowercase hex string.
///
/// This matches the hash that `stellar contract inspect --wasm <file>` reports
/// and that Soroban uses to identify uploaded contract bytecode on-chain.
fn compute_local_wasm_hash(wasm_bytes: &[u8]) -> String {
let digest = Sha256::digest(wasm_bytes);
hex::encode(digest)
}
fn build_stellar_deploy_command(wasm: &std::path::Path, source: &str, network: &str) -> String {
format!(
"stellar contract deploy \\\n --wasm {} \\\n --source {} \\\n --network {}",
wasm.display(),
source,
network
)
}
fn build_stellar_deploy_args(wasm: &std::path::Path, source: &str, network: &str) -> Vec<String> {
vec![
"contract".to_string(),
"deploy".to_string(),
"--wasm".to_string(),
wasm.display().to_string(),
"--source".to_string(),
source.to_string(),
"--network".to_string(),
network.to_string(),
]
}
/// Validate and summarise a deployment plan without submitting any transaction.
///
/// Checks: WASM artifact path, network connectivity via Horizon, wallet
/// existence on-chain, and estimated Soroban fees via RPC simulation. Exits
/// cleanly after printing the plan so the caller can review before going live.
async fn run_dry_run(
wasm_path: &std::path::Path,
wasm_bytes: &[u8],
wasm_hash: &str,
wasm_size_kb: f64,
wallet: &crate::utils::config::WalletEntry,
network: &str,
) -> Result<()> {
p::header("Deployment Dry-Run Plan");
let mut warnings: Vec<String> = Vec::new();
let mut checks_passed = 0u32;
let checks_total = 4u32;
// ── Check 1: artifact path ────────────────────────────────────────────
p::kv("[ 1/4 ] WASM artifact", &wasm_path.display().to_string());
p::kv(" Size", &format!("{:.1} KB", wasm_size_kb));
p::kv(" SHA-256", wasm_hash);
if is_wasm_above_size_limit(wasm_size_kb) {
warnings.push(format!(
"WASM is {:.1} KB — Soroban limit is 128 KB. Run `starforge gas optimize` first.",
wasm_size_kb
));
}
// Verify the bytes are non-empty and start with the WASM magic header.
if wasm_bytes.len() < 4 || &wasm_bytes[..4] != b"\0asm" {
warnings.push(
"File does not appear to be a valid WASM binary (missing magic header).".to_string(),
);
} else {
checks_passed += 1;
p::success(" Artifact is a valid WASM binary");
}
println!();
// ── Check 2: wallet existence ─────────────────────────────────────────
p::kv("[ 2/4 ] Wallet", &wallet.name);
p::kv(" Public key", &wallet.public_key);
checks_passed += 1;
p::success(" Wallet found in local config");
println!();
// ── Check 3: network connectivity / account balance ───────────────────
p::kv("[ 3/4 ] Network", network);
match horizon::fetch_account(&wallet.public_key, network).await {
Ok(account) => {
let xlm = account
.balances
.iter()
.find(|b| b.asset_type == "native")
.map(|b| b.balance.as_str())
.unwrap_or("0");
p::kv(" XLM balance", &format!("{} XLM", xlm));
let balance: f64 = xlm.parse().unwrap_or(0.0);
if balance < 1.0 {
warnings.push(format!(
"Account balance ({} XLM) may be too low to cover deployment fees. Fund with: starforge wallet fund {}",
xlm, wallet.name
));
}
checks_passed += 1;
p::success(" Account is active on-chain");
}
Err(e) => {
warnings.push(format!(
"Cannot reach {} network or account not funded: {}. Fund with: starforge wallet fund {}",
network, e, wallet.name
));
p::warn(&format!(" Network/account check failed: {}", e));
}
}
println!();
// ── Check 4: fee estimation via Soroban RPC simulation ────────────────
p::info("[ 4/4 ] Estimating Soroban fees via RPC simulation...");
match soroban::simulate_deploy_transaction(wasm_hash, network, wallet).await {
Ok(simulation) => {
p::kv(
" Estimated fee",
&format!("{} stroops", simulation.fee),
);
if !simulation.errors.is_empty() {
for error in &simulation.errors {
warnings.push(format!("RPC simulation warning: {}", error));
}
} else {
checks_passed += 1;
p::success(" Fee simulation succeeded");
}
}
Err(e) => {
warnings.push(format!(
"Fee simulation unavailable (Soroban RPC unreachable): {}. Deployment may still succeed.",
e
));
p::warn(&format!(" Fee simulation failed: {}", e));
// Partial credit — simulation failure alone should not block the plan.
checks_passed += 1;
}
}
println!();
// ── Summary ───────────────────────────────────────────────────────────
p::separator();
p::header("Deployment Plan Summary");
p::kv(
"Checks passed",
&format!("{}/{}", checks_passed, checks_total),
);
p::kv("Network", network);
p::kv("Wallet", &wallet.name);
p::kv("WASM", &wasm_path.display().to_string());
p::kv("WASM hash (SHA-256)", wasm_hash);
println!();
let deploy_cmd = build_stellar_deploy_command(wasm_path, &wallet.public_key, network);
println!(" Stellar CLI command to deploy:");
for line in deploy_cmd.lines() {
println!(" {}", line);
}
if !warnings.is_empty() {
println!();
p::warn(&format!("{} warning(s):", warnings.len()));
for w in &warnings {
p::warn(&format!(" • {}", w));
}
}
if network == "mainnet" {
println!();
p::warn("Target network is MAINNET. This will cost real XLM when executed.");
}
println!();
if warnings.is_empty() {
p::success("Dry-run complete — no issues found. Run with --execute to deploy.");
} else {
p::info("Dry-run complete with warnings. Review above before deploying.");
p::info("Run with --execute to deploy, or address the warnings first.");
}
Ok(())
}
pub async fn handle(args: DeployArgs) -> Result<()> {
p::header("Deploy Soroban Contract");
if !args.wasm.exists() {
anyhow::bail!(
"WASM file not found: {:?}\nRun `stellar contract build` first.",
args.wasm
);
}
let mut wasm_path = args.wasm.clone();
let mut wasm_bytes = fs::read(&wasm_path)?;
let mut wasm_size_kb = wasm_bytes.len() as f64 / 1024.0;
if args.optimize {
let optimized_path = args.wasm.with_file_name(format!(
"{}-optimized.wasm",
args.wasm.file_stem().unwrap_or_default().to_string_lossy()
));
p::header("WASM Optimization");
p::kv("Input WASM", &args.wasm.display().to_string());
p::kv("Output WASM", &optimized_path.display().to_string());
let result = optimizer::optimize_wasm(&args.wasm, &optimized_path)?;
wasm_path = optimized_path;
wasm_bytes = fs::read(&wasm_path)?;
wasm_size_kb = wasm_bytes.len() as f64 / 1024.0;
println!();
p::success("Optimization pass completed");
p::kv("Optimizer", &result.tool);
p::kv("Input size", &format!("{} bytes", result.input_size_bytes));
p::kv(
"Output size",
&format!("{} bytes", result.output_size_bytes),
);
p::kv(
"Size reduction",
&format!(
"{} bytes ({:+.2}%)",
result.reduction_bytes(),
result.reduction_percent()
),
);
p::separator();
}
p::separator();
p::kv("WASM file", &wasm_path.display().to_string());
p::kv("WASM size", &format!("{:.1} KB", wasm_size_kb));
p::kv("Network", &args.network);
if is_wasm_above_size_limit(wasm_size_kb) {
p::warn(&format!(
"WASM is {:.1} KB - Soroban limit is 128 KB. Optimize with --release.",
wasm_size_kb
));
p::info("If this contract is still too large, use `starforge gas optimize --target <input>.wasm --output <output>.wasm` or external tools such as `wasm-opt -Oz`.");
}
let cfg = config::load()?;
let wallet = if let Some(ref wallet_name) = args.wallet {
cfg.wallets
.iter()
.find(|w| &w.name == wallet_name)
.ok_or_else(|| {
anyhow::anyhow!(
"Wallet '{}' not found. Run `starforge wallet list`",
wallet_name
)
})?
} else if !cfg.wallets.is_empty() {
p::info(&format!(
"No --wallet specified. Using: {}",
cfg.wallets[0].name.cyan()
));
&cfg.wallets[0]
} else {
anyhow::bail!(
"No wallets found. Create one first:\n starforge wallet create deployer --fund"
);
};
p::kv("Wallet", &wallet.name);
p::kv_accent("Public Key", &wallet.public_key);
p::separator();
let wasm_hash = compute_local_wasm_hash(&wasm_bytes);
// --dry-run: validate everything and print deployment plan, then exit.
if args.dry_run {
return run_dry_run(
&wasm_path,
&wasm_bytes,
&wasm_hash,
wasm_size_kb,
wallet,
&args.network,
)
.await;
}
if args.simulate {
p::info("Simulating deploy transaction via Soroban RPC...");
match soroban::simulate_deploy_transaction(&wasm_hash, &args.network, wallet).await {
Ok(simulation) => {
p::kv("Estimated Fee", &format!("{} stroops", simulation.fee));
if !simulation.errors.is_empty() {
for error in &simulation.errors {
p::warn(&format!("Simulation error: {}", error));
}
} else {
p::success("Simulation completed without reported RPC errors");
}
}
Err(error) => {
p::warn(&format!("Simulation failed: {}", error));
}
}
p::separator();
}
// Build operation summary for confirmation
let risk_level = if args.network == "mainnet" {
confirmation::RiskLevel::High
} else {
confirmation::RiskLevel::Medium
};
let summary = confirmation::OperationSummary::new(
"Deploy Soroban Contract".to_string(),
args.network.clone(),
risk_level,
)
.add("WASM file", wasm_path.display().to_string())
.add("WASM size", format!("{:.1} KB", wasm_size_kb))
.add("WASM hash", &wasm_hash)
.add("Wallet", &wallet.name)
.add("Public Key", &wallet.public_key)
.add("Optimized", if args.optimize { "Yes" } else { "No" })
.add("Execute", if args.execute { "Yes" } else { "No (dry-run)" })
.add(
"Signer",
&match args.hardware {
Some(device) => format!("hardware ({})", device),
None => format!("local ({})", wallet.name),
},
);
let confirm_config = confirmation::ConfirmationConfig {
risk_level,
network: args.network.clone(),
skip_confirm: args.yes,
dry_run: !args.execute,
prompt: Some("Proceed with deployment?".to_string()),
require_type_confirmation: args.network == "mainnet",
};
if !confirmation::confirm_operation(&summary, &confirm_config)? {
return Ok(());
}
if args.execute {
if let Some(device) = args.hardware {
let signing_request = wallet_signer::SigningRequest::from_options(
Some(wallet),
Some(device),
Some(&args.hd_path),
&args.network,
args.yes,
"contract deployment",
)?;
soroban::sign_deploy_transaction(&wasm_hash, wallet, &args.network, &signing_request)?;
p::success(&format!("Deployment transaction signed on {}", device));
} else if wallet.secret_key.is_none() {
anyhow::bail!(
"Wallet '{}' has no local secret key. Use --hardware ledger or --hardware trezor for deployment.",
wallet.name
);
}
}
println!();
println!();
let pb = p::progress_bar(3, "Starting deployment steps...");
pb.set_message("Verifying account on-chain...");
let account = horizon::fetch_account(&wallet.public_key, &args.network)
.await
.map_err(|e| {
pb.abandon();
anyhow::anyhow!(
"Account not active on {}: {}\nFund it with: starforge wallet fund {}",
args.network,
e,
wallet.name
)
})?;
let xlm = account
.balances
.iter()
.find(|b| b.asset_type == "native")
.map(|b| b.balance.as_str())
.unwrap_or("0");
pb.inc(1);
pb.set_message("Calculating WASM SHA-256 hash...");
pb.set_message("Recording WASM SHA-256 hash...");
pb.inc(1);
pb.set_message("Generating stellar CLI command...");
pb.finish_with_message("Deployment preparation complete!");
println!();
p::kv_accent("XLM Balance", &format!("{} XLM", xlm));
p::kv("WASM Hash (local SHA-256)", &wasm_hash);
println!();
p::separator();
println!(
" {} {}",
"✓".green().bold(),
"Ready! Run this to complete the deployment:".bright_white()
);
println!();
let deploy_cmd = build_stellar_deploy_command(&wasm_path, &wallet.public_key, &args.network);
for line in deploy_cmd.lines() {
println!(" {}", line.cyan());
}
println!();
if args.execute {
p::info("Executing deployment with Stellar CLI...");
// Track this deployment in history, linked to the previous successful
// deployment on this network so the upgrade/rollback lineage is preserved.
let previous = last_successful(&args.network)?;
let record = DeployRecord::new(
&wasm_path.display().to_string(),
&wasm_hash,
&args.network,
&wallet.name,
previous.as_ref().map(|p| p.id.clone()),
);
let record_id = record_deployment(record)?;
let deploy_args = build_stellar_deploy_args(&wasm_path, &wallet.public_key, &args.network);
let output = Command::new("stellar")
.args(&deploy_args)
.output()
.map_err(|e| {
let _ = update_status(&record_id, DeployStatus::Failed, Some(e.to_string()));
anyhow::anyhow!("Failed to execute stellar CLI: {}", e)
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
update_status(&record_id, DeployStatus::Failed, Some(stderr.clone()))?;
p::error(&format!("Stellar CLI deployment failed: {}", stderr));
// Automatic rollback safety net: revert to the last good deployment.
handle_failed_deploy_rollback(
args.no_auto_rollback,
previous,
&wallet.name,
&args.network,
)?;
anyhow::bail!("Stellar CLI deployment failed: {}", stderr);
}
let stdout = String::from_utf8_lossy(&output.stdout);
if let Some(contract_id) = parse_contract_id_from_stdout(&stdout) {
set_contract_id(&record_id, &contract_id)?;
p::kv("Contract ID", &contract_id);
}
update_status(&record_id, DeployStatus::Success, None)?;
p::success("Deployment executed successfully!");
p::kv("Recorded deployment", &record_id[..8.min(record_id.len())]);
println!("{}", stdout);
} else {
p::info("Dry-run complete. Use --execute to deploy for real.");
}
Ok(())
}
/// On a failed `--execute`, automatically record a rollback to the previous
/// successful deployment (unless disabled) and print the on-chain revert command.
fn handle_failed_deploy_rollback(
disabled: bool,
previous: Option<DeployRecord>,
wallet: &str,
network: &str,
) -> Result<()> {
if disabled {
p::info("Automatic rollback disabled (--no-auto-rollback). No revert performed.");
return Ok(());
}
let Some(target) = previous else {
p::warn("No previous successful deployment on this network to roll back to.");
return Ok(());
};
let rollback_id = deploy_history::record_rollback(&target, wallet)?;
p::separator();
p::warn("Automatic rollback engaged — reverting to last successful deployment:");
p::kv("Rolled back to", &target.id[..8.min(target.id.len())]);
p::kv("Rollback record", &rollback_id[..8.min(rollback_id.len())]);
if let Some(contract_id) = target.contract_id.as_deref() {
println!();
p::info("Run this to revert the contract on-chain:");
println!(
" {}",
format!(
"stellar contract invoke --id {} --source {} --network {} -- upgrade --new-wasm-hash {}",
contract_id, wallet, network, target.wasm_hash
)
.cyan()
);
}
p::separator();
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_contract_id_from_cli_output() {
// Soroban contract ids are 56-char strkeys beginning with 'C'.
let id = format!("C{}", "A".repeat(55));
assert_eq!(id.len(), 56);
let stdout = format!("ℹ️ Simulating deploy...\nℹ️ Submitting...\n{}\n", id);
assert_eq!(
parse_contract_id_from_stdout(&stdout).as_deref(),
Some(id.as_str())
);
}
#[test]
fn returns_none_when_no_contract_id_present() {
assert_eq!(
parse_contract_id_from_stdout("deploy failed: timeout"),
None
);
// A 56-char wallet public key (G...) must not be mistaken for a contract id.
let gkey = format!("G{}", "A".repeat(55));
assert_eq!(gkey.len(), 56);
assert_eq!(parse_contract_id_from_stdout(&gkey), None);
}
#[test]
fn wasm_size_limit_boundary() {
assert!(!is_wasm_above_size_limit(128.0));
assert!(is_wasm_above_size_limit(128.1));
}
}