Skip to main content

soroban_cli/commands/contract/
restore.rs

1use std::{fmt::Debug, path::Path, str::FromStr};
2
3use crate::{
4    log::extract_events,
5    xdr::{
6        Error as XdrError, ExtensionPoint, LedgerEntry, LedgerEntryChange, LedgerEntryData,
7        LedgerFootprint, Limits, Memo, Operation, OperationBody, Preconditions, RestoreFootprintOp,
8        SequenceNumber, SorobanResources, SorobanTransactionData, SorobanTransactionDataExt,
9        Transaction, TransactionExt, TransactionMeta, TransactionMetaV3, TransactionMetaV4,
10        TtlEntry, WriteXdr,
11    },
12};
13use clap::Parser;
14use stellar_strkey::DecodeError;
15
16use crate::commands::tx::fetch;
17use crate::{
18    assembled::simulate_and_assemble_transaction,
19    commands::{
20        contract::extend,
21        global,
22        txn_result::{TxnEnvelopeResult, TxnResult},
23    },
24    config::{self, data, locator, network},
25    key, rpc, wasm, Pwd,
26};
27
28#[derive(Parser, Debug, Clone)]
29#[group(skip)]
30pub struct Cmd {
31    #[command(flatten)]
32    pub key: key::Args,
33
34    /// Number of ledgers to extend the entry
35    #[arg(long)]
36    pub ledgers_to_extend: Option<u32>,
37
38    /// Only print the new Time To Live ledger
39    #[arg(long)]
40    pub ttl_ledger_only: bool,
41
42    #[command(flatten)]
43    pub config: config::Args,
44
45    #[command(flatten)]
46    pub resources: crate::resources::Args,
47
48    /// Build the transaction and only write the base64 xdr to stdout
49    #[arg(long)]
50    pub build_only: bool,
51}
52
53impl FromStr for Cmd {
54    type Err = clap::error::Error;
55
56    fn from_str(s: &str) -> Result<Self, Self::Err> {
57        use clap::{CommandFactory, FromArgMatches};
58        Self::from_arg_matches_mut(&mut Self::command().get_matches_from(s.split_whitespace()))
59    }
60}
61
62impl Pwd for Cmd {
63    fn set_pwd(&mut self, pwd: &Path) {
64        self.config.set_pwd(pwd);
65    }
66}
67
68#[derive(thiserror::Error, Debug)]
69pub enum Error {
70    #[error("parsing key {key}: {error}")]
71    CannotParseKey {
72        key: String,
73        error: soroban_spec_tools::Error,
74    },
75
76    #[error("parsing XDR key {key}: {error}")]
77    CannotParseXdrKey { key: String, error: XdrError },
78
79    #[error("cannot parse contract ID {0}: {1}")]
80    CannotParseContractId(String, DecodeError),
81
82    #[error(transparent)]
83    Config(#[from] config::Error),
84
85    #[error("either `--key` or `--key-xdr` are required")]
86    KeyIsRequired,
87
88    #[error("xdr processing error: {0}")]
89    Xdr(#[from] XdrError),
90
91    #[error("Ledger entry not found")]
92    LedgerEntryNotFound,
93
94    #[error(transparent)]
95    Locator(#[from] locator::Error),
96
97    #[error("missing operation result")]
98    MissingOperationResult,
99
100    #[error(transparent)]
101    Rpc(#[from] rpc::Error),
102
103    #[error(transparent)]
104    Wasm(#[from] wasm::Error),
105
106    #[error(transparent)]
107    Key(#[from] key::Error),
108
109    #[error(transparent)]
110    Extend(#[from] extend::Error),
111
112    #[error(transparent)]
113    Data(#[from] data::Error),
114
115    #[error(transparent)]
116    Network(#[from] network::Error),
117
118    #[error(transparent)]
119    Fee(#[from] fetch::fee::Error),
120
121    #[error(transparent)]
122    Fetch(#[from] fetch::Error),
123}
124
125impl Cmd {
126    #[allow(clippy::too_many_lines)]
127    pub async fn run(&self, global_args: &global::Args) -> Result<(), Error> {
128        let res = self
129            .execute(&self.config, global_args.quiet, global_args.no_cache)
130            .await?
131            .to_envelope();
132        let expiration_ledger_seq = match res {
133            TxnEnvelopeResult::TxnEnvelope(tx) => {
134                println!("{}", tx.to_xdr_base64(Limits::none())?);
135                return Ok(());
136            }
137            TxnEnvelopeResult::Res(res) => res,
138        };
139        if let Some(ledgers_to_extend) = self.ledgers_to_extend {
140            extend::Cmd {
141                key: self.key.clone(),
142                ledgers_to_extend,
143                config: self.config.clone(),
144                resources: self.resources.clone(),
145                ttl_ledger_only: false,
146                build_only: self.build_only,
147            }
148            .run(global_args)
149            .await?;
150        } else {
151            println!("New ttl ledger: {expiration_ledger_seq}");
152        }
153
154        Ok(())
155    }
156
157    pub async fn execute(
158        &self,
159        config: &config::Args,
160        quiet: bool,
161        no_cache: bool,
162    ) -> Result<TxnResult<u32>, Error> {
163        let print = crate::print::Print::new(quiet);
164        let network = config.get_network()?;
165        tracing::trace!(?network);
166        let entry_keys = self.key.parse_keys(&config.locator, &network)?;
167        let client = network.rpc_client()?;
168        let source_account = config.source_account().await?;
169
170        // Get the account sequence number
171        let account_details = client
172            .get_account(&source_account.clone().to_string())
173            .await?;
174        let sequence: i64 = account_details.seq_num.into();
175
176        let tx = Box::new(Transaction {
177            source_account,
178            fee: config.get_inclusion_fee()?,
179            seq_num: SequenceNumber(sequence + 1),
180            cond: Preconditions::None,
181            memo: Memo::None,
182            operations: vec![Operation {
183                source_account: None,
184                body: OperationBody::RestoreFootprint(RestoreFootprintOp {
185                    ext: ExtensionPoint::V0,
186                }),
187            }]
188            .try_into()?,
189            ext: TransactionExt::V1(SorobanTransactionData {
190                ext: SorobanTransactionDataExt::V0,
191                resources: SorobanResources {
192                    footprint: LedgerFootprint {
193                        read_only: vec![].try_into()?,
194                        read_write: entry_keys.clone().try_into()?,
195                    },
196                    instructions: self.resources.instructions.unwrap_or_default(),
197                    disk_read_bytes: 0,
198                    write_bytes: 0,
199                },
200                resource_fee: 0,
201            }),
202        });
203        if self.build_only {
204            return Ok(TxnResult::Txn(tx));
205        }
206        let assembled = simulate_and_assemble_transaction(
207            &client,
208            &tx,
209            self.resources.resource_config(),
210            self.resources.resource_fee,
211        )
212        .await?;
213
214        let tx = assembled.transaction().clone();
215        let res = client
216            .send_transaction_polling(&config.sign(tx, quiet).await?)
217            .await?;
218        self.resources.print_cost_info(&res)?;
219        if !no_cache {
220            data::write(res.clone().try_into()?, &network.rpc_uri()?)?;
221        }
222        let meta = res
223            .result_meta
224            .as_ref()
225            .ok_or(Error::MissingOperationResult)?;
226
227        tracing::trace!(?meta);
228
229        let events = extract_events(meta);
230
231        crate::log::event::all(&events);
232        crate::log::event::contract(&events, &print);
233
234        // The transaction from core will succeed regardless of whether it actually found &
235        // restored the entry, so we have to inspect the result meta to tell if it worked or not.
236        let changes = match meta {
237            TransactionMeta::V4(TransactionMetaV4 { operations, .. }) => {
238                // Simply check if there is exactly one entry here. We only support restoring a single
239                // entry via this command (which we should fix separately, but).
240                if operations.is_empty() {
241                    return Err(Error::LedgerEntryNotFound);
242                }
243
244                operations[0].changes.clone()
245            }
246            TransactionMeta::V3(TransactionMetaV3 { operations, .. }) => {
247                // Simply check if there is exactly one entry here. We only support restoring a single
248                // entry via this command (which we should fix separately, but).
249                if operations.is_empty() {
250                    return Err(Error::LedgerEntryNotFound);
251                }
252
253                operations[0].changes.clone()
254            }
255            _ => return Err(Error::LedgerEntryNotFound),
256        };
257        tracing::debug!("Changes:\nlen:{}\n{changes:#?}", changes.len());
258
259        if changes.is_empty() {
260            print.infoln("No changes detected, transaction was a no-op.");
261            let entry = client.get_full_ledger_entries(&entry_keys).await?;
262            let extension = entry.entries[0].live_until_ledger_seq.unwrap_or_default();
263
264            return Ok(TxnResult::Res(extension));
265        }
266
267        Ok(TxnResult::Res(
268            parse_changes(&changes.to_vec()).ok_or(Error::LedgerEntryNotFound)?,
269        ))
270    }
271}
272
273fn parse_changes(changes: &[LedgerEntryChange]) -> Option<u32> {
274    changes
275        .iter()
276        .filter_map(|change| match change {
277            LedgerEntryChange::Restored(LedgerEntry {
278                data:
279                    LedgerEntryData::Ttl(TtlEntry {
280                        live_until_ledger_seq,
281                        ..
282                    }),
283                ..
284            })
285            | LedgerEntryChange::Updated(LedgerEntry {
286                data:
287                    LedgerEntryData::Ttl(TtlEntry {
288                        live_until_ledger_seq,
289                        ..
290                    }),
291                ..
292            })
293            | LedgerEntryChange::Created(LedgerEntry {
294                data:
295                    LedgerEntryData::Ttl(TtlEntry {
296                        live_until_ledger_seq,
297                        ..
298                    }),
299                ..
300            }) => Some(*live_until_ledger_seq),
301            _ => None,
302        })
303        .max()
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309    use crate::xdr::{
310        ContractDataDurability::Persistent, ContractDataEntry, ContractId, Hash, LedgerEntry,
311        LedgerEntryChange, LedgerEntryData, ScAddress, ScSymbol, ScVal, SequenceNumber, StringM,
312        TtlEntry,
313    };
314
315    #[test]
316    fn test_parse_changes_two_changes_restored() {
317        // Test the original expected format with 2 changes
318        let ttl_entry = TtlEntry {
319            live_until_ledger_seq: 12345,
320            key_hash: Hash([0; 32]),
321        };
322
323        let changes = vec![
324            LedgerEntryChange::State(LedgerEntry {
325                data: LedgerEntryData::Ttl(ttl_entry.clone()),
326                last_modified_ledger_seq: 0,
327                ext: crate::xdr::LedgerEntryExt::V0,
328            }),
329            LedgerEntryChange::Restored(LedgerEntry {
330                data: LedgerEntryData::Ttl(ttl_entry),
331                last_modified_ledger_seq: 0,
332                ext: crate::xdr::LedgerEntryExt::V0,
333            }),
334        ];
335
336        let result = parse_changes(&changes);
337        assert_eq!(result, Some(12345));
338    }
339
340    #[test]
341    fn test_parse_two_changes_that_had_expired() {
342        let ttl_entry = TtlEntry {
343            live_until_ledger_seq: 55555,
344            key_hash: Hash([0; 32]),
345        };
346
347        let counter = "COUNTER".parse::<StringM<32>>().unwrap();
348        let contract_data_entry = ContractDataEntry {
349            ext: ExtensionPoint::default(),
350            contract: ScAddress::Contract(ContractId(Hash([0; 32]))),
351            key: ScVal::Symbol(ScSymbol(counter)),
352            durability: Persistent,
353            val: ScVal::U32(1),
354        };
355
356        let changes = vec![
357            LedgerEntryChange::Restored(LedgerEntry {
358                data: LedgerEntryData::Ttl(ttl_entry.clone()),
359                last_modified_ledger_seq: 37429,
360                ext: crate::xdr::LedgerEntryExt::V0,
361            }),
362            LedgerEntryChange::Restored(LedgerEntry {
363                data: LedgerEntryData::ContractData(contract_data_entry.clone()),
364                last_modified_ledger_seq: 37429,
365                ext: crate::xdr::LedgerEntryExt::V0,
366            }),
367        ];
368
369        let result = parse_changes(&changes);
370        assert_eq!(result, Some(55555));
371    }
372
373    #[test]
374    fn test_parse_changes_two_changes_updated() {
375        // Test the original expected format with 2 changes, but second change is Updated
376        let ttl_entry = TtlEntry {
377            live_until_ledger_seq: 67890,
378            key_hash: Hash([0; 32]),
379        };
380
381        let changes = vec![
382            LedgerEntryChange::State(LedgerEntry {
383                data: LedgerEntryData::Ttl(ttl_entry.clone()),
384                last_modified_ledger_seq: 0,
385                ext: crate::xdr::LedgerEntryExt::V0,
386            }),
387            LedgerEntryChange::Updated(LedgerEntry {
388                data: LedgerEntryData::Ttl(ttl_entry),
389                last_modified_ledger_seq: 0,
390                ext: crate::xdr::LedgerEntryExt::V0,
391            }),
392        ];
393
394        let result = parse_changes(&changes);
395        assert_eq!(result, Some(67890));
396    }
397
398    #[test]
399    fn test_parse_changes_two_changes_created() {
400        // Test the original expected format with 2 changes, but second change is Created
401        let ttl_entry = TtlEntry {
402            live_until_ledger_seq: 11111,
403            key_hash: Hash([0; 32]),
404        };
405
406        let changes = vec![
407            LedgerEntryChange::State(LedgerEntry {
408                data: LedgerEntryData::Ttl(ttl_entry.clone()),
409                last_modified_ledger_seq: 0,
410                ext: crate::xdr::LedgerEntryExt::V0,
411            }),
412            LedgerEntryChange::Created(LedgerEntry {
413                data: LedgerEntryData::Ttl(ttl_entry),
414                last_modified_ledger_seq: 0,
415                ext: crate::xdr::LedgerEntryExt::V0,
416            }),
417        ];
418
419        let result = parse_changes(&changes);
420        assert_eq!(result, Some(11111));
421    }
422
423    #[test]
424    fn test_parse_changes_single_change_restored() {
425        // Test the new single change format with Restored type
426        let ttl_entry = TtlEntry {
427            live_until_ledger_seq: 22222,
428            key_hash: Hash([0; 32]),
429        };
430
431        let changes = vec![LedgerEntryChange::Restored(LedgerEntry {
432            data: LedgerEntryData::Ttl(ttl_entry),
433            last_modified_ledger_seq: 0,
434            ext: crate::xdr::LedgerEntryExt::V0,
435        })];
436
437        let result = parse_changes(&changes);
438        assert_eq!(result, Some(22222));
439    }
440
441    #[test]
442    fn test_parse_changes_single_change_updated() {
443        // Test the new single change format with Updated type
444        let ttl_entry = TtlEntry {
445            live_until_ledger_seq: 33333,
446            key_hash: Hash([0; 32]),
447        };
448
449        let changes = vec![LedgerEntryChange::Updated(LedgerEntry {
450            data: LedgerEntryData::Ttl(ttl_entry),
451            last_modified_ledger_seq: 0,
452            ext: crate::xdr::LedgerEntryExt::V0,
453        })];
454
455        let result = parse_changes(&changes);
456        assert_eq!(result, Some(33333));
457    }
458
459    #[test]
460    fn test_parse_changes_single_change_created() {
461        // Test the new single change format with Created type
462        let ttl_entry = TtlEntry {
463            live_until_ledger_seq: 44444,
464            key_hash: Hash([0; 32]),
465        };
466
467        let changes = vec![LedgerEntryChange::Created(LedgerEntry {
468            data: LedgerEntryData::Ttl(ttl_entry),
469            last_modified_ledger_seq: 0,
470            ext: crate::xdr::LedgerEntryExt::V0,
471        })];
472
473        let result = parse_changes(&changes);
474        assert_eq!(result, Some(44444));
475    }
476
477    #[test]
478    fn test_parse_changes_invalid_two_changes() {
479        // Test invalid 2-change format (not TTL data)
480        let not_ttl_change = LedgerEntryChange::Restored(LedgerEntry {
481            data: LedgerEntryData::Account(crate::xdr::AccountEntry {
482                account_id: crate::xdr::AccountId(crate::xdr::PublicKey::PublicKeyTypeEd25519(
483                    crate::xdr::Uint256([0; 32]),
484                )),
485                balance: 0,
486                seq_num: SequenceNumber(0),
487                num_sub_entries: 0,
488                inflation_dest: None,
489                flags: 0,
490                home_domain: crate::xdr::String32::default(),
491                thresholds: crate::xdr::Thresholds::default(),
492                signers: crate::xdr::VecM::default(),
493                ext: crate::xdr::AccountEntryExt::V0,
494            }),
495            last_modified_ledger_seq: 0,
496            ext: crate::xdr::LedgerEntryExt::V0,
497        });
498
499        let changes = vec![not_ttl_change.clone(), not_ttl_change];
500        let result = parse_changes(&changes);
501        assert_eq!(result, None);
502    }
503
504    #[test]
505    fn test_parse_changes_invalid_single_change() {
506        // Test invalid single change format (not TTL data)
507        let changes = vec![LedgerEntryChange::Restored(LedgerEntry {
508            data: LedgerEntryData::Account(crate::xdr::AccountEntry {
509                account_id: crate::xdr::AccountId(crate::xdr::PublicKey::PublicKeyTypeEd25519(
510                    crate::xdr::Uint256([0; 32]),
511                )),
512                balance: 0,
513                seq_num: SequenceNumber(0),
514                num_sub_entries: 0,
515                inflation_dest: None,
516                flags: 0,
517                home_domain: crate::xdr::String32::default(),
518                thresholds: crate::xdr::Thresholds::default(),
519                signers: crate::xdr::VecM::default(),
520                ext: crate::xdr::AccountEntryExt::V0,
521            }),
522            last_modified_ledger_seq: 0,
523            ext: crate::xdr::LedgerEntryExt::V0,
524        })];
525
526        let result = parse_changes(&changes);
527        assert_eq!(result, None);
528    }
529
530    #[test]
531    fn test_parse_changes_empty_changes() {
532        // Test empty changes array
533        let changes = vec![];
534
535        let result = parse_changes(&changes);
536        assert_eq!(result, None);
537    }
538}