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(
116        "alias must be 1-30 chars long, and have only letters, numbers, underscores and dashes"
117    )]
118    InvalidAliasFormat { alias: String },
119    #[error(transparent)]
120    Locator(#[from] locator::Error),
121    #[error(transparent)]
122    ContractSpec(#[from] contract_spec::Error),
123    #[error(transparent)]
124    ArgParse(#[from] arg_parsing::Error),
125    #[error("Only ed25519 accounts are allowed")]
126    OnlyEd25519AccountsAllowed,
127}
128
129impl Cmd {
130    pub async fn run(&self, global_args: &global::Args) -> Result<(), Error> {
131        let res = self
132            .run_against_rpc_server(Some(global_args), None)
133            .await?
134            .to_envelope();
135        match res {
136            TxnEnvelopeResult::TxnEnvelope(tx) => println!("{}", tx.to_xdr_base64(Limits::none())?),
137            TxnEnvelopeResult::Res(contract) => {
138                let network = self.config.get_network()?;
139
140                if let Some(alias) = self.alias.clone() {
141                    if let Some(existing_contract) = self
142                        .config
143                        .locator
144                        .get_contract_id(&alias, &network.network_passphrase)?
145                    {
146                        let print = Print::new(global_args.quiet);
147                        print.warnln(format!(
148                            "Overwriting existing contract id: {existing_contract}"
149                        ));
150                    };
151
152                    self.config.locator.save_contract_id(
153                        &network.network_passphrase,
154                        &contract,
155                        &alias,
156                    )?;
157                }
158
159                println!("{contract}");
160            }
161        }
162        Ok(())
163    }
164}
165
166#[async_trait::async_trait]
167impl NetworkRunnable for Cmd {
168    type Error = Error;
169    type Result = TxnResult<stellar_strkey::Contract>;
170
171    #[allow(clippy::too_many_lines)]
172    async fn run_against_rpc_server(
173        &self,
174        global_args: Option<&global::Args>,
175        config: Option<&config::Args>,
176    ) -> Result<TxnResult<stellar_strkey::Contract>, Error> {
177        let print = Print::new(global_args.map_or(false, |a| a.quiet));
178        let config = config.unwrap_or(&self.config);
179        let wasm_hash = if let Some(wasm) = &self.wasm {
180            #[cfg(feature = "version_lt_23")]
181            let is_build = self.fee.build_only || self.fee.sim_only;
182            #[cfg(feature = "version_gte_23")]
183            let is_build = self.fee.build_only;
184            let hash = if is_build {
185                wasm::Args { wasm: wasm.clone() }.hash()?
186            } else {
187                upload::Cmd {
188                    wasm: wasm::Args { wasm: wasm.clone() },
189                    config: config.clone(),
190                    fee: self.fee.clone(),
191                    ignore_checks: self.ignore_checks,
192                }
193                .run_against_rpc_server(global_args, Some(config))
194                .await?
195                .into_result()
196                .expect("the value (hash) is expected because it should always be available since build-only is a shared parameter")
197            };
198            hex::encode(hash)
199        } else {
200            self.wasm_hash
201                .as_ref()
202                .ok_or(Error::WasmNotProvided)?
203                .to_string()
204        };
205
206        let wasm_hash = Hash(
207            utils::contract_id_from_str(&wasm_hash)
208                .map_err(|e| Error::CannotParseWasmHash {
209                    wasm_hash: wasm_hash.clone(),
210                    error: e,
211                })?
212                .0,
213        );
214
215        print.infoln(format!("Using wasm hash {wasm_hash}").as_str());
216
217        let network = config.get_network()?;
218        let salt: [u8; 32] = match &self.salt {
219            Some(h) => soroban_spec_tools::utils::padded_hex_from_str(h, 32)
220                .map_err(|_| Error::CannotParseSalt { salt: h.clone() })?
221                .try_into()
222                .map_err(|_| Error::CannotParseSalt { salt: h.clone() })?,
223            None => rand::thread_rng().gen::<[u8; 32]>(),
224        };
225
226        let client = network.rpc_client()?;
227        client
228            .verify_network_passphrase(Some(&network.network_passphrase))
229            .await?;
230        let MuxedAccount::Ed25519(bytes) = config.source_account().await? else {
231            return Err(Error::OnlyEd25519AccountsAllowed);
232        };
233        let source_account = AccountId(PublicKey::PublicKeyTypeEd25519(bytes));
234        let contract_id_preimage = ContractIdPreimage::Address(ContractIdPreimageFromAddress {
235            address: ScAddress::Account(source_account.clone()),
236            salt: Uint256(salt),
237        });
238        let contract_id =
239            get_contract_id(contract_id_preimage.clone(), &network.network_passphrase)?;
240        let raw_wasm = if let Some(wasm) = self.wasm.as_ref() {
241            wasm::Args { wasm: wasm.clone() }.read()?
242        } else {
243            get_remote_wasm_from_hash(&client, &wasm_hash).await?
244        };
245        let entries = soroban_spec_tools::contract::Spec::new(&raw_wasm)?.spec;
246        let res = soroban_spec_tools::Spec::new(entries.clone());
247        let constructor_params = if let Ok(func) = res.find_function(CONSTRUCTOR_FUNCTION_NAME) {
248            if func.inputs.len() == 0 {
249                None
250            } else {
251                let mut slop = vec![OsString::from(CONSTRUCTOR_FUNCTION_NAME)];
252                slop.extend_from_slice(&self.slop);
253                Some(
254                    arg_parsing::build_host_function_parameters(
255                        &stellar_strkey::Contract(contract_id.0),
256                        &slop,
257                        &entries,
258                        config,
259                    )?
260                    .2,
261                )
262            }
263        } else {
264            None
265        };
266
267        // Get the account sequence number
268        let account_details = client.get_account(&source_account.to_string()).await?;
269        let sequence: i64 = account_details.seq_num.into();
270        let txn = Box::new(build_create_contract_tx(
271            wasm_hash,
272            sequence + 1,
273            self.fee.fee,
274            source_account,
275            contract_id_preimage,
276            constructor_params.as_ref(),
277        )?);
278
279        if self.fee.build_only {
280            print.checkln("Transaction built!");
281            return Ok(TxnResult::Txn(txn));
282        }
283
284        print.infoln("Simulating deploy transaction…");
285
286        let txn = simulate_and_assemble_transaction(&client, &txn).await?;
287        let txn = Box::new(self.fee.apply_to_assembled_txn(txn).transaction().clone());
288
289        #[cfg(feature = "version_lt_23")]
290        if self.fee.sim_only {
291            print.checkln("Done!");
292            return Ok(TxnResult::Txn(txn));
293        }
294
295        print.log_transaction(&txn, &network, true)?;
296        let signed_txn = &config.sign_with_local_key(*txn).await?;
297        print.globeln("Submitting deploy transaction…");
298
299        let get_txn_resp = client
300            .send_transaction_polling(signed_txn)
301            .await?
302            .try_into()?;
303
304        if global_args.map_or(true, |a| !a.no_cache) {
305            data::write(get_txn_resp, &network.rpc_uri()?)?;
306        }
307
308        if let Some(url) = utils::explorer_url_for_contract(&network, &contract_id) {
309            print.linkln(url);
310        }
311
312        print.checkln("Deployed!");
313
314        Ok(TxnResult::Res(contract_id))
315    }
316}
317
318fn build_create_contract_tx(
319    wasm_hash: Hash,
320    sequence: i64,
321    fee: u32,
322    key: AccountId,
323    contract_id_preimage: ContractIdPreimage,
324    constructor_params: Option<&InvokeContractArgs>,
325) -> Result<Transaction, Error> {
326    let op = if let Some(InvokeContractArgs { args, .. }) = constructor_params {
327        Operation {
328            source_account: None,
329            body: OperationBody::InvokeHostFunction(InvokeHostFunctionOp {
330                host_function: HostFunction::CreateContractV2(CreateContractArgsV2 {
331                    contract_id_preimage,
332                    executable: ContractExecutable::Wasm(wasm_hash),
333                    constructor_args: args.clone(),
334                }),
335                auth: VecM::default(),
336            }),
337        }
338    } else {
339        Operation {
340            source_account: None,
341            body: OperationBody::InvokeHostFunction(InvokeHostFunctionOp {
342                host_function: HostFunction::CreateContract(CreateContractArgs {
343                    contract_id_preimage,
344                    executable: ContractExecutable::Wasm(wasm_hash),
345                }),
346                auth: VecM::default(),
347            }),
348        }
349    };
350    let tx = Transaction {
351        source_account: key.into(),
352        fee,
353        seq_num: SequenceNumber(sequence),
354        cond: Preconditions::None,
355        memo: Memo::None,
356        operations: vec![op].try_into()?,
357        ext: TransactionExt::V0,
358    };
359
360    Ok(tx)
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    #[test]
368    fn test_build_create_contract() {
369        let hash = hex::decode("0000000000000000000000000000000000000000000000000000000000000000")
370            .unwrap()
371            .try_into()
372            .unwrap();
373        let salt = [0u8; 32];
374        let key =
375            &utils::parse_secret_key("SBFGFF27Y64ZUGFAIG5AMJGQODZZKV2YQKAVUUN4HNE24XZXD2OEUVUP")
376                .unwrap();
377        let source_account = AccountId(PublicKey::PublicKeyTypeEd25519(Uint256(
378            key.verifying_key().to_bytes(),
379        )));
380
381        let contract_id_preimage = ContractIdPreimage::Address(ContractIdPreimageFromAddress {
382            address: ScAddress::Account(source_account.clone()),
383            salt: Uint256(salt),
384        });
385
386        let result = build_create_contract_tx(
387            Hash(hash),
388            300,
389            1,
390            source_account,
391            contract_id_preimage,
392            None,
393        );
394
395        assert!(result.is_ok());
396    }
397}