soroban_cli/commands/contract/
invoke.rs

1use std::convert::{Infallible, TryInto};
2use std::ffi::OsString;
3use std::num::ParseIntError;
4use std::path::{Path, PathBuf};
5use std::str::FromStr;
6use std::{fmt::Debug, fs, io};
7
8use clap::{Parser, ValueEnum};
9use soroban_rpc::{Client, SimulateHostFunctionResult, SimulateTransactionResponse};
10use soroban_spec::read::FromWasmError;
11
12use super::super::events;
13use super::arg_parsing;
14use crate::assembled::Assembled;
15use crate::commands::tx::fetch;
16use crate::log::extract_events;
17use crate::print::Print;
18use crate::utils::deprecate_message;
19use crate::{
20    assembled::simulate_and_assemble_transaction,
21    commands::{
22        contract::arg_parsing::{build_host_function_parameters, output_to_string},
23        global,
24        tx::fetch::fee,
25        txn_result::{TxnEnvelopeResult, TxnResult},
26        NetworkRunnable,
27    },
28    config::{self, data, locator, network},
29    get_spec::{self, get_remote_contract_spec},
30    print, rpc,
31    xdr::{
32        self, AccountEntry, AccountEntryExt, AccountId, ContractEvent, ContractEventType,
33        DiagnosticEvent, HostFunction, InvokeContractArgs, InvokeHostFunctionOp, Limits, Memo,
34        MuxedAccount, Operation, OperationBody, Preconditions, PublicKey, ScSpecEntry,
35        SequenceNumber, String32, StringM, Thresholds, Transaction, TransactionExt, Uint256, VecM,
36        WriteXdr,
37    },
38    Pwd,
39};
40use soroban_spec_tools::contract;
41
42#[derive(Parser, Debug, Default, Clone)]
43#[allow(clippy::struct_excessive_bools)]
44#[group(skip)]
45pub struct Cmd {
46    /// Contract ID to invoke
47    #[arg(long = "id", env = "STELLAR_CONTRACT_ID")]
48    pub contract_id: config::UnresolvedContract,
49
50    // For testing only
51    #[arg(skip)]
52    pub wasm: Option<std::path::PathBuf>,
53
54    /// ⚠️ Deprecated, use `--send=no`. View the result simulating and do not sign and submit transaction.
55    #[arg(long, env = "STELLAR_INVOKE_VIEW")]
56    pub is_view: bool,
57
58    /// Function name as subcommand, then arguments for that function as `--arg-name value`
59    #[arg(last = true, id = "CONTRACT_FN_AND_ARGS")]
60    pub slop: Vec<OsString>,
61
62    #[command(flatten)]
63    pub config: config::Args,
64
65    #[command(flatten)]
66    pub resources: crate::resources::Args,
67
68    /// Whether or not to send a transaction
69    #[arg(long, value_enum, default_value_t, env = "STELLAR_SEND")]
70    pub send: Send,
71
72    /// Build the transaction and only write the base64 xdr to stdout
73    #[arg(long)]
74    pub build_only: bool,
75}
76
77impl FromStr for Cmd {
78    type Err = clap::error::Error;
79
80    fn from_str(s: &str) -> Result<Self, Self::Err> {
81        use clap::{CommandFactory, FromArgMatches};
82        Self::from_arg_matches_mut(&mut Self::command().get_matches_from(s.split_whitespace()))
83    }
84}
85
86impl Pwd for Cmd {
87    fn set_pwd(&mut self, pwd: &Path) {
88        self.config.set_pwd(pwd);
89    }
90}
91
92#[derive(thiserror::Error, Debug)]
93pub enum Error {
94    #[error("cannot add contract to ledger entries: {0}")]
95    CannotAddContractToLedgerEntries(xdr::Error),
96
97    #[error("reading file {0:?}: {1}")]
98    CannotReadContractFile(PathBuf, io::Error),
99
100    #[error("committing file {filepath}: {error}")]
101    CannotCommitEventsFile {
102        filepath: std::path::PathBuf,
103        error: events::Error,
104    },
105
106    #[error("parsing contract spec: {0}")]
107    CannotParseContractSpec(FromWasmError),
108
109    #[error(transparent)]
110    Xdr(#[from] xdr::Error),
111
112    #[error("error parsing int: {0}")]
113    ParseIntError(#[from] ParseIntError),
114
115    #[error(transparent)]
116    Rpc(#[from] rpc::Error),
117
118    #[error("missing operation result")]
119    MissingOperationResult,
120
121    #[error("error loading signing key: {0}")]
122    SignatureError(#[from] ed25519_dalek::SignatureError),
123
124    #[error(transparent)]
125    Config(#[from] config::Error),
126
127    #[error("unexpected ({length}) simulate transaction result length")]
128    UnexpectedSimulateTransactionResultSize { length: usize },
129
130    #[error(transparent)]
131    Clap(#[from] clap::Error),
132
133    #[error(transparent)]
134    Locator(#[from] locator::Error),
135
136    #[error("Contract Error\n{0}: {1}")]
137    ContractInvoke(String, String),
138
139    #[error(transparent)]
140    StrKey(#[from] stellar_strkey::DecodeError),
141
142    #[error(transparent)]
143    ContractSpec(#[from] contract::Error),
144
145    #[error(transparent)]
146    Io(#[from] std::io::Error),
147
148    #[error(transparent)]
149    Data(#[from] data::Error),
150
151    #[error(transparent)]
152    Network(#[from] network::Error),
153
154    #[error(transparent)]
155    GetSpecError(#[from] get_spec::Error),
156
157    #[error(transparent)]
158    ArgParsing(#[from] arg_parsing::Error),
159
160    #[error(transparent)]
161    Fee(#[from] fee::Error),
162
163    #[error(transparent)]
164    Fetch(#[from] fetch::Error),
165}
166
167impl From<Infallible> for Error {
168    fn from(_: Infallible) -> Self {
169        unreachable!()
170    }
171}
172
173impl Cmd {
174    pub async fn run(&self, global_args: &global::Args) -> Result<(), Error> {
175        let print = Print::new(global_args.quiet);
176        let res = self.invoke(global_args).await?.to_envelope();
177
178        if self.is_view {
179            deprecate_message(print, "--is-view", "Use `--send=no` instead.");
180        }
181
182        match res {
183            TxnEnvelopeResult::TxnEnvelope(tx) => println!("{}", tx.to_xdr_base64(Limits::none())?),
184            TxnEnvelopeResult::Res(output) => {
185                println!("{output}");
186            }
187        }
188        Ok(())
189    }
190
191    pub async fn invoke(&self, global_args: &global::Args) -> Result<TxnResult<String>, Error> {
192        self.run_against_rpc_server(Some(global_args), None).await
193    }
194
195    pub fn read_wasm(&self) -> Result<Option<Vec<u8>>, Error> {
196        Ok(if let Some(wasm) = self.wasm.as_ref() {
197            Some(fs::read(wasm).map_err(|e| Error::CannotReadContractFile(wasm.clone(), e))?)
198        } else {
199            None
200        })
201    }
202
203    pub fn spec_entries(&self) -> Result<Option<Vec<ScSpecEntry>>, Error> {
204        self.read_wasm()?
205            .map(|wasm| {
206                soroban_spec::read::from_wasm(&wasm).map_err(Error::CannotParseContractSpec)
207            })
208            .transpose()
209    }
210
211    fn should_send_tx(&self, sim_res: &SimulateTransactionResponse) -> Result<ShouldSend, Error> {
212        Ok(match self.send {
213            Send::Default => {
214                if self.is_view {
215                    ShouldSend::No
216                } else if has_write(sim_res)? || has_published_event(sim_res)? || has_auth(sim_res)?
217                {
218                    ShouldSend::Yes
219                } else {
220                    ShouldSend::DefaultNo
221                }
222            }
223            Send::No => ShouldSend::No,
224            Send::Yes => ShouldSend::Yes,
225        })
226    }
227
228    /// Uses a default account to check if the tx should be sent after the simulation. The transaction
229    /// should be recreated with the real source account later.
230    async fn simulate(
231        &self,
232        host_function_params: &InvokeContractArgs,
233        account_details: &AccountEntry,
234        rpc_client: &Client,
235    ) -> Result<Assembled, Error> {
236        let sequence: i64 = account_details.seq_num.0;
237        let AccountId(PublicKey::PublicKeyTypeEd25519(account_id)) =
238            account_details.account_id.clone();
239
240        let tx =
241            build_invoke_contract_tx(host_function_params.clone(), sequence + 1, 100, account_id)?;
242        Ok(simulate_and_assemble_transaction(
243            rpc_client,
244            &tx,
245            self.resources.resource_config(),
246            self.resources.resource_fee,
247        )
248        .await?)
249    }
250}
251
252#[async_trait::async_trait]
253impl NetworkRunnable for Cmd {
254    type Error = Error;
255    type Result = TxnResult<String>;
256
257    async fn run_against_rpc_server(
258        &self,
259        global_args: Option<&global::Args>,
260        config: Option<&config::Args>,
261    ) -> Result<TxnResult<String>, Error> {
262        let config = config.unwrap_or(&self.config);
263        let quiet = global_args.is_some_and(|g| g.quiet);
264        let print = print::Print::new(quiet);
265        let network = config.get_network()?;
266
267        tracing::trace!(?network);
268
269        let contract_id = self
270            .contract_id
271            .resolve_contract_id(&config.locator, &network.network_passphrase)?;
272
273        let spec_entries = self.spec_entries()?;
274
275        if let Some(spec_entries) = &spec_entries {
276            // For testing wasm arg parsing
277            build_host_function_parameters(&contract_id, &self.slop, spec_entries, config).await?;
278        }
279
280        let client = network.rpc_client()?;
281
282        let spec_entries = get_remote_contract_spec(
283            &contract_id.0,
284            &config.locator,
285            &config.network,
286            global_args,
287            Some(config),
288        )
289        .await
290        .map_err(Error::from)?;
291
292        let params =
293            build_host_function_parameters(&contract_id, &self.slop, &spec_entries, config).await?;
294
295        let (function, spec, host_function_params, signers) = params;
296
297        // `self.build_only` will be checked again below and the fn will return a TxnResult::Txn
298        // if the user passed the --build-only flag
299        let (should_send, cached_simulation) = if self.build_only {
300            (ShouldSend::Yes, None)
301        } else {
302            let assembled = self
303                .simulate(&host_function_params, &default_account_entry(), &client)
304                .await?;
305            let should_send = self.should_send_tx(&assembled.sim_res)?;
306            (should_send, Some(assembled))
307        };
308
309        let account_details = if should_send == ShouldSend::Yes {
310            client
311                .verify_network_passphrase(Some(&network.network_passphrase))
312                .await?;
313
314            client
315                .get_account(&config.source_account().await?.to_string())
316                .await?
317        } else {
318            if should_send == ShouldSend::DefaultNo {
319                print.infoln(
320                    "Simulation identified as read-only. Send by rerunning with `--send=yes`.",
321                );
322            }
323
324            let assembled = cached_simulation.expect(
325                "cached_simulation should be available when should_send != Yes and not build_only",
326            );
327            let sim_res = assembled.sim_response();
328            let return_value = sim_res.results()?;
329            let events = sim_res.events()?;
330
331            crate::log::event::all(&events);
332            crate::log::event::contract(&events, &print);
333
334            return Ok(output_to_string(&spec, &return_value[0].xdr, &function)?);
335        };
336
337        let sequence: i64 = account_details.seq_num.into();
338        let AccountId(PublicKey::PublicKeyTypeEd25519(account_id)) = account_details.account_id;
339
340        let tx = Box::new(build_invoke_contract_tx(
341            host_function_params.clone(),
342            sequence + 1,
343            config.get_inclusion_fee()?,
344            account_id,
345        )?);
346
347        if self.build_only {
348            return Ok(TxnResult::Txn(tx));
349        }
350
351        let txn = simulate_and_assemble_transaction(
352            &client,
353            &tx,
354            self.resources.resource_config(),
355            self.resources.resource_fee,
356        )
357        .await?;
358        let assembled = self.resources.apply_to_assembled_txn(txn);
359        let mut txn = Box::new(assembled.transaction().clone());
360        let sim_res = assembled.sim_response();
361
362        if global_args.is_none_or(|a| !a.no_cache) {
363            data::write(sim_res.clone().into(), &network.rpc_uri()?)?;
364        }
365
366        let global::Args { no_cache, .. } = global_args.cloned().unwrap_or_default();
367
368        // Need to sign all auth entries
369        if let Some(tx) = config.sign_soroban_authorizations(&txn, &signers).await? {
370            *txn = tx;
371        }
372
373        let res = client
374            .send_transaction_polling(&config.sign(*txn, quiet).await?)
375            .await?;
376
377        self.resources.print_cost_info(&res)?;
378
379        if !no_cache {
380            data::write(res.clone().try_into()?, &network.rpc_uri()?)?;
381        }
382
383        let return_value = res.return_value()?;
384        let events = extract_events(&res.result_meta.unwrap_or_default());
385
386        crate::log::event::all(&events);
387        crate::log::event::contract(&events, &print);
388
389        Ok(output_to_string(&spec, &return_value, &function)?)
390    }
391}
392
393const DEFAULT_ACCOUNT_ID: AccountId = AccountId(PublicKey::PublicKeyTypeEd25519(Uint256([0; 32])));
394
395fn default_account_entry() -> AccountEntry {
396    AccountEntry {
397        account_id: DEFAULT_ACCOUNT_ID,
398        balance: 0,
399        seq_num: SequenceNumber(0),
400        num_sub_entries: 0,
401        inflation_dest: None,
402        flags: 0,
403        home_domain: String32::from(unsafe { StringM::<32>::from_str("TEST").unwrap_unchecked() }),
404        thresholds: Thresholds([0; 4]),
405        signers: unsafe { [].try_into().unwrap_unchecked() },
406        ext: AccountEntryExt::V0,
407    }
408}
409
410fn build_invoke_contract_tx(
411    parameters: InvokeContractArgs,
412    sequence: i64,
413    fee: u32,
414    source_account_id: Uint256,
415) -> Result<Transaction, Error> {
416    let op = Operation {
417        source_account: None,
418        body: OperationBody::InvokeHostFunction(InvokeHostFunctionOp {
419            host_function: HostFunction::InvokeContract(parameters),
420            auth: VecM::default(),
421        }),
422    };
423    Ok(Transaction {
424        source_account: MuxedAccount::Ed25519(source_account_id),
425        fee,
426        seq_num: SequenceNumber(sequence),
427        cond: Preconditions::None,
428        memo: Memo::None,
429        operations: vec![op].try_into()?,
430        ext: TransactionExt::V0,
431    })
432}
433
434#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, ValueEnum, Default)]
435pub enum Send {
436    /// Send transaction if simulation indicates there are ledger writes,
437    /// published events, or auth required, otherwise return simulation result
438    #[default]
439    Default,
440    /// Do not send transaction, return simulation result
441    No,
442    /// Always send transaction
443    Yes,
444}
445
446#[derive(Debug, PartialEq)]
447enum ShouldSend {
448    DefaultNo,
449    No,
450    Yes,
451}
452
453fn has_write(sim_res: &SimulateTransactionResponse) -> Result<bool, Error> {
454    Ok(!sim_res
455        .transaction_data()?
456        .resources
457        .footprint
458        .read_write
459        .is_empty())
460}
461
462fn has_published_event(sim_res: &SimulateTransactionResponse) -> Result<bool, Error> {
463    Ok(sim_res.events()?.iter().any(
464        |DiagnosticEvent {
465             event: ContractEvent { type_, .. },
466             ..
467         }| matches!(type_, ContractEventType::Contract),
468    ))
469}
470
471fn has_auth(sim_res: &SimulateTransactionResponse) -> Result<bool, Error> {
472    Ok(sim_res
473        .results()?
474        .iter()
475        .any(|SimulateHostFunctionResult { auth, .. }| !auth.is_empty()))
476}