soroban_cli/commands/contract/
extend.rs1use std::{fmt::Debug, path::Path, str::FromStr};
2
3use crate::{
4 log::extract_events,
5 print::Print,
6 xdr::{
7 Error as XdrError, ExtendFootprintTtlOp, ExtensionPoint, LedgerEntry, LedgerEntryChange,
8 LedgerEntryData, LedgerFootprint, Limits, Memo, Operation, OperationBody, Preconditions,
9 SequenceNumber, SorobanResources, SorobanTransactionData, SorobanTransactionDataExt,
10 Transaction, TransactionExt, TransactionMeta, TransactionMetaV3, TransactionMetaV4,
11 TtlEntry, WriteXdr,
12 },
13};
14use clap::{command, Parser};
15
16use crate::{
17 assembled::simulate_and_assemble_transaction,
18 commands::{
19 global,
20 txn_result::{TxnEnvelopeResult, TxnResult},
21 NetworkRunnable,
22 },
23 config::{self, data, locator, network},
24 key, rpc, wasm, Pwd,
25};
26
27const MAX_LEDGERS_TO_EXTEND: u32 = 535_679;
28
29#[derive(Parser, Debug, Clone)]
30#[group(skip)]
31pub struct Cmd {
32 #[arg(long, required = true)]
34 pub ledgers_to_extend: u32,
35 #[arg(long)]
37 pub ttl_ledger_only: bool,
38 #[command(flatten)]
39 pub key: key::Args,
40 #[command(flatten)]
41 pub config: config::Args,
42 #[command(flatten)]
43 pub fee: crate::fee::Args,
44}
45
46impl FromStr for Cmd {
47 type Err = clap::error::Error;
48
49 fn from_str(s: &str) -> Result<Self, Self::Err> {
50 use clap::{CommandFactory, FromArgMatches};
51 Self::from_arg_matches_mut(&mut Self::command().get_matches_from(s.split_whitespace()))
52 }
53}
54
55impl Pwd for Cmd {
56 fn set_pwd(&mut self, pwd: &Path) {
57 self.config.set_pwd(pwd);
58 }
59}
60
61#[derive(thiserror::Error, Debug)]
62pub enum Error {
63 #[error("parsing key {key}: {error}")]
64 CannotParseKey {
65 key: String,
66 error: soroban_spec_tools::Error,
67 },
68 #[error("parsing XDR key {key}: {error}")]
69 CannotParseXdrKey { key: String, error: XdrError },
70
71 #[error(transparent)]
72 Config(#[from] config::Error),
73 #[error("either `--key` or `--key-xdr` are required")]
74 KeyIsRequired,
75 #[error("xdr processing error: {0}")]
76 Xdr(#[from] XdrError),
77 #[error("Ledger entry not found")]
78 LedgerEntryNotFound,
79 #[error("missing operation result")]
80 MissingOperationResult,
81 #[error(transparent)]
82 Rpc(#[from] rpc::Error),
83 #[error(transparent)]
84 Wasm(#[from] wasm::Error),
85 #[error(transparent)]
86 Key(#[from] key::Error),
87 #[error(transparent)]
88 Data(#[from] data::Error),
89 #[error(transparent)]
90 Network(#[from] network::Error),
91 #[error(transparent)]
92 Locator(#[from] locator::Error),
93}
94
95impl Cmd {
96 #[allow(clippy::too_many_lines)]
97 pub async fn run(&self) -> Result<(), Error> {
98 let res = self.run_against_rpc_server(None, None).await?.to_envelope();
99 match res {
100 TxnEnvelopeResult::TxnEnvelope(tx) => println!("{}", tx.to_xdr_base64(Limits::none())?),
101 TxnEnvelopeResult::Res(ttl_ledger) => {
102 if self.ttl_ledger_only {
103 println!("{ttl_ledger}");
104 } else {
105 println!("New ttl ledger: {ttl_ledger}");
106 }
107 }
108 }
109
110 Ok(())
111 }
112
113 fn ledgers_to_extend(&self) -> u32 {
114 let res = u32::min(self.ledgers_to_extend, MAX_LEDGERS_TO_EXTEND);
115 if res < self.ledgers_to_extend {
116 tracing::warn!(
117 "Ledgers to extend is too large, using max value of {MAX_LEDGERS_TO_EXTEND}"
118 );
119 }
120 res
121 }
122}
123
124#[async_trait::async_trait]
125impl NetworkRunnable for Cmd {
126 type Error = Error;
127 type Result = TxnResult<u32>;
128
129 async fn run_against_rpc_server(
130 &self,
131 args: Option<&global::Args>,
132 config: Option<&config::Args>,
133 ) -> Result<TxnResult<u32>, Self::Error> {
134 let config = config.unwrap_or(&self.config);
135 let print = Print::new(args.is_some_and(|a| a.quiet));
136 let network = config.get_network()?;
137 tracing::trace!(?network);
138 let keys = self.key.parse_keys(&config.locator, &network)?;
139 let client = network.rpc_client()?;
140 let source_account = config.source_account().await?;
141 let extend_to = self.ledgers_to_extend();
142
143 let account_details = client
145 .get_account(&source_account.clone().to_string())
146 .await?;
147 let sequence: i64 = account_details.seq_num.into();
148
149 let tx = Box::new(Transaction {
150 source_account,
151 fee: self.fee.fee,
152 seq_num: SequenceNumber(sequence + 1),
153 cond: Preconditions::None,
154 memo: Memo::None,
155 operations: vec![Operation {
156 source_account: None,
157 body: OperationBody::ExtendFootprintTtl(ExtendFootprintTtlOp {
158 ext: ExtensionPoint::V0,
159 extend_to,
160 }),
161 }]
162 .try_into()?,
163 ext: TransactionExt::V1(SorobanTransactionData {
164 ext: SorobanTransactionDataExt::V0,
165 resources: SorobanResources {
166 footprint: LedgerFootprint {
167 read_only: keys.clone().try_into()?,
168 read_write: vec![].try_into()?,
169 },
170 instructions: self.fee.instructions.unwrap_or_default(),
171 disk_read_bytes: 0,
172 write_bytes: 0,
173 },
174 resource_fee: 0,
175 }),
176 });
177 if self.fee.build_only {
178 return Ok(TxnResult::Txn(tx));
179 }
180 let tx = simulate_and_assemble_transaction(&client, &tx)
181 .await?
182 .transaction()
183 .clone();
184 let res = client
185 .send_transaction_polling(&config.sign(tx).await?)
186 .await?;
187 if args.is_none_or(|a| !a.no_cache) {
188 data::write(res.clone().try_into()?, &network.rpc_uri()?)?;
189 }
190
191 let meta = res.result_meta.ok_or(Error::MissingOperationResult)?;
192 let events = extract_events(&meta);
193
194 crate::log::event::all(&events);
195 crate::log::event::contract(&events, &print);
196
197 let changes = match meta {
200 TransactionMeta::V4(TransactionMetaV4 { operations, .. }) => {
201 if operations.is_empty() {
204 return Err(Error::LedgerEntryNotFound);
205 }
206
207 operations[0].changes.clone()
208 }
209 TransactionMeta::V3(TransactionMetaV3 { operations, .. }) => {
210 if operations.is_empty() {
213 return Err(Error::LedgerEntryNotFound);
214 }
215
216 operations[0].changes.clone()
217 }
218 _ => return Err(Error::LedgerEntryNotFound),
219 };
220
221 if changes.is_empty() {
222 let entry = client.get_full_ledger_entries(&keys).await?;
223 let extension = entry.entries[0].live_until_ledger_seq;
224
225 if entry.latest_ledger + i64::from(extend_to) < i64::from(extension) {
226 return Ok(TxnResult::Res(extension));
227 }
228 }
229
230 match (&changes[0], &changes[1]) {
231 (
232 LedgerEntryChange::State(_),
233 LedgerEntryChange::Updated(LedgerEntry {
234 data:
235 LedgerEntryData::Ttl(TtlEntry {
236 live_until_ledger_seq,
237 ..
238 }),
239 ..
240 }),
241 ) => Ok(TxnResult::Res(*live_until_ledger_seq)),
242 _ => Err(Error::LedgerEntryNotFound),
243 }
244 }
245}