soroban_cli/commands/contract/
extend.rs1use std::{fmt::Debug, num::TryFromIntError, path::Path, str::FromStr};
2
3use crate::{
4 log::extract_events,
5 print::Print,
6 xdr::{
7 ConfigSettingEntry, ConfigSettingId, Error as XdrError, ExtendFootprintTtlOp,
8 ExtensionPoint, LedgerEntry, LedgerEntryChange, LedgerEntryData, LedgerFootprint,
9 LedgerKey, LedgerKeyConfigSetting, Limits, Memo, Operation, OperationBody, Preconditions,
10 SequenceNumber, SorobanResources, SorobanTransactionData, SorobanTransactionDataExt,
11 Transaction, TransactionExt, TransactionMeta, TransactionMetaV3, TransactionMetaV4,
12 TtlEntry, WriteXdr,
13 },
14};
15use clap::{command, Parser};
16
17use crate::commands::tx::fetch;
18use crate::{
19 assembled::simulate_and_assemble_transaction,
20 commands::{
21 global,
22 txn_result::{TxnEnvelopeResult, TxnResult},
23 NetworkRunnable,
24 },
25 config::{self, data, locator, network},
26 key, rpc, wasm, Pwd,
27};
28
29#[derive(Parser, Debug, Clone)]
30#[group(skip)]
31pub struct Cmd {
32 #[arg(long, required = true)]
34 pub ledgers_to_extend: u32,
35
36 #[arg(long)]
38 pub ttl_ledger_only: bool,
39
40 #[command(flatten)]
41 pub key: key::Args,
42
43 #[command(flatten)]
44 pub config: config::Args,
45
46 #[command(flatten)]
47 pub fee: crate::fee::Args,
48}
49
50impl FromStr for Cmd {
51 type Err = clap::error::Error;
52
53 fn from_str(s: &str) -> Result<Self, Self::Err> {
54 use clap::{CommandFactory, FromArgMatches};
55 Self::from_arg_matches_mut(&mut Self::command().get_matches_from(s.split_whitespace()))
56 }
57}
58
59impl Pwd for Cmd {
60 fn set_pwd(&mut self, pwd: &Path) {
61 self.config.set_pwd(pwd);
62 }
63}
64
65#[derive(thiserror::Error, Debug)]
66pub enum Error {
67 #[error("parsing key {key}: {error}")]
68 CannotParseKey {
69 key: String,
70 error: soroban_spec_tools::Error,
71 },
72
73 #[error("parsing XDR key {key}: {error}")]
74 CannotParseXdrKey { key: String, error: XdrError },
75
76 #[error(transparent)]
77 Config(#[from] config::Error),
78
79 #[error("either `--key` or `--key-xdr` are required")]
80 KeyIsRequired,
81
82 #[error("xdr processing error: {0}")]
83 Xdr(#[from] XdrError),
84
85 #[error("Ledger entry not found")]
86 LedgerEntryNotFound,
87
88 #[error("missing operation result")]
89 MissingOperationResult,
90
91 #[error(transparent)]
92 Rpc(#[from] rpc::Error),
93
94 #[error(transparent)]
95 Wasm(#[from] wasm::Error),
96
97 #[error(transparent)]
98 Key(#[from] key::Error),
99
100 #[error(transparent)]
101 Data(#[from] data::Error),
102
103 #[error(transparent)]
104 Network(#[from] network::Error),
105
106 #[error(transparent)]
107 Locator(#[from] locator::Error),
108
109 #[error(transparent)]
110 IntError(#[from] TryFromIntError),
111
112 #[error("Failed to fetch state archival settings from network")]
113 StateArchivalSettingsNotFound,
114
115 #[error("Ledgers to extend ({requested}) exceeds network maximum ({max})")]
116 LedgersToExtendTooLarge { requested: u32, max: u32 },
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) -> Result<(), Error> {
128 let res = self.run_against_rpc_server(None, None).await?.to_envelope();
129 match res {
130 TxnEnvelopeResult::TxnEnvelope(tx) => println!("{}", tx.to_xdr_base64(Limits::none())?),
131 TxnEnvelopeResult::Res(ttl_ledger) => {
132 if self.ttl_ledger_only {
133 println!("{ttl_ledger}");
134 } else {
135 println!("New ttl ledger: {ttl_ledger}");
136 }
137 }
138 }
139
140 Ok(())
141 }
142
143 async fn get_max_entry_ttl(client: &rpc::Client) -> Result<u32, Error> {
144 let key = LedgerKey::ConfigSetting(LedgerKeyConfigSetting {
145 config_setting_id: ConfigSettingId::StateArchival,
146 });
147
148 let entries = client.get_full_ledger_entries(&[key]).await?;
149
150 if let Some(entry) = entries.entries.first() {
151 if let LedgerEntryData::ConfigSetting(ConfigSettingEntry::StateArchival(settings)) =
152 &entry.val
153 {
154 return Ok(settings.max_entry_ttl);
155 }
156 }
157
158 Err(Error::StateArchivalSettingsNotFound)
159 }
160
161 async fn ledgers_to_extend(&self, client: &rpc::Client) -> Result<u32, Error> {
162 let max_entry_ttl = Self::get_max_entry_ttl(client).await?;
163
164 tracing::trace!(
165 "Checking ledgers_to_extend: requested={}, max_entry_ttl={}",
166 self.ledgers_to_extend,
167 max_entry_ttl
168 );
169
170 if self.ledgers_to_extend > max_entry_ttl {
171 return Err(Error::LedgersToExtendTooLarge {
172 requested: self.ledgers_to_extend,
173 max: max_entry_ttl,
174 });
175 }
176
177 Ok(self.ledgers_to_extend)
178 }
179}
180
181#[async_trait::async_trait]
182impl NetworkRunnable for Cmd {
183 type Error = Error;
184 type Result = TxnResult<u32>;
185
186 #[allow(clippy::too_many_lines)]
187 async fn run_against_rpc_server(
188 &self,
189 args: Option<&global::Args>,
190 config: Option<&config::Args>,
191 ) -> Result<TxnResult<u32>, Self::Error> {
192 let config = config.unwrap_or(&self.config);
193 let print = Print::new(args.is_some_and(|a| a.quiet));
194 let network = config.get_network()?;
195 tracing::trace!(?network);
196 let keys = self.key.parse_keys(&config.locator, &network)?;
197 let client = network.rpc_client()?;
198 let source_account = config.source_account().await?;
199 let extend_to = self.ledgers_to_extend(&client).await?;
200
201 let account_details = client
203 .get_account(&source_account.clone().to_string())
204 .await?;
205 let sequence: i64 = account_details.seq_num.into();
206
207 let tx = Box::new(Transaction {
208 source_account,
209 fee: self.fee.fee,
210 seq_num: SequenceNumber(sequence + 1),
211 cond: Preconditions::None,
212 memo: Memo::None,
213 operations: vec![Operation {
214 source_account: None,
215 body: OperationBody::ExtendFootprintTtl(ExtendFootprintTtlOp {
216 ext: ExtensionPoint::V0,
217 extend_to,
218 }),
219 }]
220 .try_into()?,
221 ext: TransactionExt::V1(SorobanTransactionData {
222 ext: SorobanTransactionDataExt::V0,
223 resources: SorobanResources {
224 footprint: LedgerFootprint {
225 read_only: keys.clone().try_into()?,
226 read_write: vec![].try_into()?,
227 },
228 instructions: self.fee.instructions.unwrap_or_default(),
229 disk_read_bytes: 0,
230 write_bytes: 0,
231 },
232 resource_fee: 0,
233 }),
234 });
235 if self.fee.build_only {
236 return Ok(TxnResult::Txn(tx));
237 }
238 let assembled =
239 simulate_and_assemble_transaction(&client, &tx, self.fee.resource_config()).await?;
240
241 let tx = assembled.transaction().clone();
242 let res = client
243 .send_transaction_polling(&config.sign(tx).await?)
244 .await?;
245 self.fee.print_cost_info(&res)?;
246
247 if args.is_none_or(|a| !a.no_cache) {
248 data::write(res.clone().try_into()?, &network.rpc_uri()?)?;
249 }
250
251 let meta = res.result_meta.ok_or(Error::MissingOperationResult)?;
252 let events = extract_events(&meta);
253
254 crate::log::event::all(&events);
255 crate::log::event::contract(&events, &print);
256
257 let changes = match meta {
260 TransactionMeta::V4(TransactionMetaV4 { operations, .. }) => {
261 if operations.is_empty() {
264 return Err(Error::LedgerEntryNotFound);
265 }
266
267 operations[0].changes.clone()
268 }
269 TransactionMeta::V3(TransactionMetaV3 { operations, .. }) => {
270 if operations.is_empty() {
273 return Err(Error::LedgerEntryNotFound);
274 }
275
276 operations[0].changes.clone()
277 }
278 _ => return Err(Error::LedgerEntryNotFound),
279 };
280
281 if changes.is_empty() {
282 print.infoln("No changes detected, transaction was a no-op.");
283 let entry = client.get_full_ledger_entries(&keys).await?;
284 let extension = entry.entries[0].live_until_ledger_seq.unwrap_or_default();
285
286 return Ok(TxnResult::Res(extension));
287 }
288
289 match (&changes[0], &changes[1]) {
290 (
291 LedgerEntryChange::State(_),
292 LedgerEntryChange::Updated(LedgerEntry {
293 data:
294 LedgerEntryData::Ttl(TtlEntry {
295 live_until_ledger_seq,
296 ..
297 }),
298 ..
299 }),
300 ) => Ok(TxnResult::Res(*live_until_ledger_seq)),
301 _ => Err(Error::LedgerEntryNotFound),
302 }
303 }
304}