1use crate::commands::contract::deploy::utils::alias_validator;
2use crate::resources;
3use std::array::TryFromSliceError;
4use std::ffi::OsString;
5use std::fmt::Debug;
6use std::num::ParseIntError;
7
8use crate::xdr::{
9 AccountId, ContractExecutable, ContractIdPreimage, ContractIdPreimageFromAddress,
10 CreateContractArgs, CreateContractArgsV2, Error as XdrError, Hash, HostFunction,
11 InvokeContractArgs, InvokeHostFunctionOp, Limits, Memo, MuxedAccount, Operation, OperationBody,
12 Preconditions, PublicKey, ScAddress, SequenceNumber, Transaction, TransactionExt, Uint256,
13 VecM, WriteXdr,
14};
15use clap::Parser;
16use rand::Rng;
17
18use crate::commands::tx::fetch;
19use crate::{
20 assembled::simulate_and_assemble_transaction,
21 commands::{
22 contract::{self, arg_parsing, id::wasm::get_contract_id, upload},
23 global,
24 txn_result::{TxnEnvelopeResult, TxnResult},
25 },
26 config::{self, data, locator, network},
27 print::Print,
28 rpc,
29 utils::{self, rpc::get_remote_wasm_from_hash},
30 wasm,
31};
32use soroban_spec_tools::contract as contract_spec;
33
34pub const CONSTRUCTOR_FUNCTION_NAME: &str = "__constructor";
35
36#[derive(Parser, Debug, Clone)]
37#[command(group(
38 clap::ArgGroup::new("wasm_src")
39 .required(true)
40 .args(&["wasm", "wasm_hash"]),
41))]
42#[group(skip)]
43pub struct Cmd {
44 #[arg(long, group = "wasm_src")]
46 pub wasm: Option<std::path::PathBuf>,
47 #[arg(long = "wasm-hash", conflicts_with = "wasm", group = "wasm_src")]
49 pub wasm_hash: Option<String>,
50 #[arg(long)]
52 pub salt: Option<String>,
53 #[command(flatten)]
54 pub config: config::Args,
55 #[arg(long, short = 'i', default_value = "false")]
56 pub ignore_checks: bool,
58 #[arg(long, value_parser = clap::builder::ValueParser::new(alias_validator))]
62 pub alias: Option<String>,
63 #[command(flatten)]
64 pub resources: resources::Args,
65 #[arg(long)]
67 pub build_only: bool,
68 #[arg(last = true, id = "CONTRACT_CONSTRUCTOR_ARGS")]
70 pub slop: Vec<OsString>,
71}
72
73#[derive(thiserror::Error, Debug)]
74pub enum Error {
75 #[error(transparent)]
76 Install(#[from] upload::Error),
77
78 #[error("error parsing int: {0}")]
79 ParseIntError(#[from] ParseIntError),
80
81 #[error("internal conversion error: {0}")]
82 TryFromSliceError(#[from] TryFromSliceError),
83
84 #[error("xdr processing error: {0}")]
85 Xdr(#[from] XdrError),
86
87 #[error("jsonrpc error: {0}")]
88 JsonRpc(#[from] jsonrpsee_core::Error),
89
90 #[error("cannot parse salt: {salt}")]
91 CannotParseSalt { salt: String },
92
93 #[error("cannot parse contract ID {contract_id}: {error}")]
94 CannotParseContractId {
95 contract_id: String,
96 error: stellar_strkey::DecodeError,
97 },
98
99 #[error("cannot parse WASM hash {wasm_hash}: {error}")]
100 CannotParseWasmHash {
101 wasm_hash: String,
102 error: stellar_strkey::DecodeError,
103 },
104
105 #[error("Must provide either --wasm or --wash-hash")]
106 WasmNotProvided,
107
108 #[error(transparent)]
109 Rpc(#[from] rpc::Error),
110
111 #[error(transparent)]
112 Config(#[from] config::Error),
113
114 #[error(transparent)]
115 StrKey(#[from] stellar_strkey::DecodeError),
116
117 #[error(transparent)]
118 Infallible(#[from] std::convert::Infallible),
119
120 #[error(transparent)]
121 WasmId(#[from] contract::id::wasm::Error),
122
123 #[error(transparent)]
124 Data(#[from] data::Error),
125
126 #[error(transparent)]
127 Network(#[from] network::Error),
128
129 #[error(transparent)]
130 Wasm(#[from] wasm::Error),
131
132 #[error(transparent)]
133 Locator(#[from] locator::Error),
134
135 #[error(transparent)]
136 ContractSpec(#[from] contract_spec::Error),
137
138 #[error(transparent)]
139 ArgParse(#[from] arg_parsing::Error),
140
141 #[error("Only ed25519 accounts are allowed")]
142 OnlyEd25519AccountsAllowed,
143
144 #[error(transparent)]
145 Fee(#[from] fetch::fee::Error),
146
147 #[error(transparent)]
148 Fetch(#[from] fetch::Error),
149}
150
151impl Cmd {
152 pub async fn run(&self, global_args: &global::Args) -> Result<(), Error> {
153 let res = self
154 .execute(&self.config, global_args.quiet, global_args.no_cache)
155 .await?
156 .to_envelope();
157 match res {
158 TxnEnvelopeResult::TxnEnvelope(tx) => println!("{}", tx.to_xdr_base64(Limits::none())?),
159 TxnEnvelopeResult::Res(contract) => {
160 let network = self.config.get_network()?;
161
162 if let Some(alias) = self.alias.clone() {
163 if let Some(existing_contract) = self
164 .config
165 .locator
166 .get_contract_id(&alias, &network.network_passphrase)?
167 {
168 let print = Print::new(global_args.quiet);
169 print.warnln(format!(
170 "Overwriting existing alias {alias:?} that currently links to contract ID: {existing_contract}"
171 ));
172 }
173
174 self.config.locator.save_contract_id(
175 &network.network_passphrase,
176 &contract,
177 &alias,
178 )?;
179 }
180
181 println!("{contract}");
182 }
183 }
184 Ok(())
185 }
186
187 #[allow(clippy::too_many_lines)]
188 #[allow(unused_variables)]
189 pub async fn execute(
190 &self,
191 config: &config::Args,
192 quiet: bool,
193 no_cache: bool,
194 ) -> Result<TxnResult<stellar_strkey::Contract>, Error> {
195 let print = Print::new(quiet);
196 let wasm_hash = if let Some(wasm) = &self.wasm {
197 let is_build = self.build_only;
198 let hash = if is_build {
199 wasm::Args { wasm: wasm.clone() }.hash()?
200 } else {
201 upload::Cmd {
202 wasm: wasm::Args { wasm: wasm.clone() },
203 config: config.clone(),
204 resources: self.resources.clone(),
205 ignore_checks: self.ignore_checks,
206 build_only: is_build,
207 }
208 .execute(config, quiet, no_cache)
209 .await?
210 .into_result()
211 .expect("the value (hash) is expected because it should always be available since build-only is a shared parameter")
212 };
213 hex::encode(hash)
214 } else {
215 self.wasm_hash
216 .as_ref()
217 .ok_or(Error::WasmNotProvided)?
218 .clone()
219 };
220
221 let wasm_hash = Hash(
222 utils::contract_id_from_str(&wasm_hash)
223 .map_err(|e| Error::CannotParseWasmHash {
224 wasm_hash: wasm_hash.clone(),
225 error: e,
226 })?
227 .0,
228 );
229
230 print.infoln(format!("Using wasm hash {wasm_hash}").as_str());
231
232 let network = config.get_network()?;
233 let salt: [u8; 32] = match &self.salt {
234 Some(h) => soroban_spec_tools::utils::padded_hex_from_str(h, 32)
235 .map_err(|_| Error::CannotParseSalt { salt: h.clone() })?
236 .try_into()
237 .map_err(|_| Error::CannotParseSalt { salt: h.clone() })?,
238 None => rand::thread_rng().gen::<[u8; 32]>(),
239 };
240
241 let client = network.rpc_client()?;
242 let MuxedAccount::Ed25519(bytes) = config.source_account().await? else {
243 return Err(Error::OnlyEd25519AccountsAllowed);
244 };
245 let source_account = AccountId(PublicKey::PublicKeyTypeEd25519(bytes));
246 let contract_id_preimage = ContractIdPreimage::Address(ContractIdPreimageFromAddress {
247 address: ScAddress::Account(source_account.clone()),
248 salt: Uint256(salt),
249 });
250 let contract_id =
251 get_contract_id(contract_id_preimage.clone(), &network.network_passphrase)?;
252 let raw_wasm = if let Some(wasm) = self.wasm.as_ref() {
253 wasm::Args { wasm: wasm.clone() }.read()?
254 } else {
255 if self.build_only {
256 return Err(Error::WasmNotProvided);
257 }
258 get_remote_wasm_from_hash(&client, &wasm_hash).await?
259 };
260 let entries = soroban_spec_tools::contract::Spec::new(&raw_wasm)?.spec;
261 let res = soroban_spec_tools::Spec::new(entries.clone().as_slice());
262 let constructor_params = if let Ok(func) = res.find_function(CONSTRUCTOR_FUNCTION_NAME) {
263 if func.inputs.is_empty() {
264 None
265 } else {
266 let mut slop = vec![OsString::from(CONSTRUCTOR_FUNCTION_NAME)];
267 slop.extend_from_slice(&self.slop);
268 Some(
269 arg_parsing::build_constructor_parameters(
270 &stellar_strkey::Contract(contract_id.0),
271 &slop,
272 &entries,
273 config,
274 )
275 .await?
276 .2,
277 )
278 }
279 } else {
280 None
281 };
282
283 client
285 .verify_network_passphrase(Some(&network.network_passphrase))
286 .await?;
287
288 let account_details = client.get_account(&source_account.to_string()).await?;
290 let sequence: i64 = account_details.seq_num.into();
291 let txn = Box::new(build_create_contract_tx(
292 wasm_hash,
293 sequence + 1,
294 config.get_inclusion_fee()?,
295 source_account,
296 contract_id_preimage,
297 constructor_params.as_ref(),
298 )?);
299
300 if self.build_only {
301 print.checkln("Transaction built!");
302 return Ok(TxnResult::Txn(txn));
303 }
304
305 print.infoln("Simulating deploy transaction…");
306
307 let assembled = simulate_and_assemble_transaction(
308 &client,
309 &txn,
310 self.resources.resource_config(),
311 self.resources.resource_fee,
312 )
313 .await?;
314 let assembled = self.resources.apply_to_assembled_txn(assembled);
315 let txn = Box::new(assembled.transaction().clone());
316
317 print.log_transaction(&txn, &network, true)?;
318 let signed_txn = &config.sign(*txn, quiet).await?;
319 print.globeln("Submitting deploy transaction…");
320
321 let get_txn_resp = client.send_transaction_polling(signed_txn).await?;
322
323 self.resources.print_cost_info(&get_txn_resp)?;
324
325 if !no_cache {
326 data::write(get_txn_resp.clone().try_into()?, &network.rpc_uri()?)?;
327 }
328
329 if let Some(url) = utils::lab_url_for_contract(&network, &contract_id) {
330 print.linkln(url);
331 }
332
333 print.checkln("Deployed!");
334
335 Ok(TxnResult::Res(contract_id))
336 }
337}
338
339fn build_create_contract_tx(
340 wasm_hash: Hash,
341 sequence: i64,
342 fee: u32,
343 key: AccountId,
344 contract_id_preimage: ContractIdPreimage,
345 constructor_params: Option<&InvokeContractArgs>,
346) -> Result<Transaction, Error> {
347 let op = if let Some(InvokeContractArgs { args, .. }) = constructor_params {
348 Operation {
349 source_account: None,
350 body: OperationBody::InvokeHostFunction(InvokeHostFunctionOp {
351 host_function: HostFunction::CreateContractV2(CreateContractArgsV2 {
352 contract_id_preimage,
353 executable: ContractExecutable::Wasm(wasm_hash),
354 constructor_args: args.clone(),
355 }),
356 auth: VecM::default(),
357 }),
358 }
359 } else {
360 Operation {
361 source_account: None,
362 body: OperationBody::InvokeHostFunction(InvokeHostFunctionOp {
363 host_function: HostFunction::CreateContract(CreateContractArgs {
364 contract_id_preimage,
365 executable: ContractExecutable::Wasm(wasm_hash),
366 }),
367 auth: VecM::default(),
368 }),
369 }
370 };
371 let tx = Transaction {
372 source_account: key.into(),
373 fee,
374 seq_num: SequenceNumber(sequence),
375 cond: Preconditions::None,
376 memo: Memo::None,
377 operations: vec![op].try_into()?,
378 ext: TransactionExt::V0,
379 };
380
381 Ok(tx)
382}
383
384#[cfg(test)]
385mod tests {
386 use super::*;
387
388 #[test]
389 fn test_build_create_contract() {
390 let hash = hex::decode("0000000000000000000000000000000000000000000000000000000000000000")
391 .unwrap()
392 .try_into()
393 .unwrap();
394 let salt = [0u8; 32];
395 let key =
396 &utils::parse_secret_key("SBFGFF27Y64ZUGFAIG5AMJGQODZZKV2YQKAVUUN4HNE24XZXD2OEUVUP")
397 .unwrap();
398 let source_account = AccountId(PublicKey::PublicKeyTypeEd25519(Uint256(
399 key.verifying_key().to_bytes(),
400 )));
401
402 let contract_id_preimage = ContractIdPreimage::Address(ContractIdPreimageFromAddress {
403 address: ScAddress::Account(source_account.clone()),
404 salt: Uint256(salt),
405 });
406
407 let result = build_create_contract_tx(
408 Hash(hash),
409 300,
410 1,
411 source_account,
412 contract_id_preimage,
413 None,
414 );
415
416 assert!(result.is_ok());
417 }
418}