soroban_cli/commands/contract/deploy/
wasm.rs

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