1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
use clap::{arg, command, Parser};
use std::io;
use soroban_env_host::xdr::{self, Limits, ReadXdr};
use super::{config::locator, network};
use crate::{rpc, utils};
#[derive(Parser, Debug, Clone)]
#[group(skip)]
pub struct Cmd {
/// The first ledger sequence number in the range to pull events
/// https://developers.stellar.org/docs/encyclopedia/ledger-headers#ledger-sequence
#[arg(long, conflicts_with = "cursor", required_unless_present = "cursor")]
start_ledger: Option<u32>,
/// The cursor corresponding to the start of the event range.
#[arg(
long,
conflicts_with = "start_ledger",
required_unless_present = "start_ledger"
)]
cursor: Option<String>,
/// Output formatting options for event stream
#[arg(long, value_enum, default_value = "pretty")]
output: OutputFormat,
/// The maximum number of events to display (defer to the server-defined limit).
#[arg(short, long, default_value = "10")]
count: usize,
/// A set of (up to 5) contract IDs to filter events on. This parameter can
/// be passed multiple times, e.g. `--id C123.. --id C456..`, or passed with
/// multiple parameters, e.g. `--id C123 C456`.
///
/// Though the specification supports multiple filter objects (i.e.
/// combinations of type, IDs, and topics), only one set can be specified on
/// the command-line today, though that set can have multiple IDs/topics.
#[arg(
long = "id",
num_args = 1..=6,
help_heading = "FILTERS"
)]
contract_ids: Vec<String>,
/// A set of (up to 4) topic filters to filter event topics on. A single
/// topic filter can contain 1-4 different segment filters, separated by
/// commas, with an asterisk (* character) indicating a wildcard segment.
///
/// For example, this is one topic filter with two segments:
///
/// --topic "AAAABQAAAAdDT1VOVEVSAA==,*"
///
/// This is two topic filters with one and two segments each:
///
/// --topic "AAAABQAAAAdDT1VOVEVSAA==" --topic '*,*'
///
/// Note that all of these topic filters are combined with the contract IDs
/// into a single filter (i.e. combination of type, IDs, and topics).
#[arg(
long = "topic",
num_args = 1..=5,
help_heading = "FILTERS"
)]
topic_filters: Vec<String>,
/// Specifies which type of contract events to display.
#[arg(
long = "type",
value_enum,
default_value = "all",
help_heading = "FILTERS"
)]
event_type: rpc::EventType,
#[command(flatten)]
locator: locator::Args,
#[command(flatten)]
network: network::Args,
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("cursor is not valid")]
InvalidCursor,
#[error("filepath does not exist: {path}")]
InvalidFile { path: String },
#[error("filepath ({path}) cannot be read: {error}")]
CannotReadFile { path: String, error: String },
#[error("cannot parse topic filter {topic} into 1-4 segments")]
InvalidTopicFilter { topic: String },
#[error("invalid segment ({segment}) in topic filter ({topic}): {error}")]
InvalidSegment {
topic: String,
segment: String,
error: xdr::Error,
},
#[error("cannot parse contract ID {contract_id}: {error}")]
InvalidContractId {
contract_id: String,
error: stellar_strkey::DecodeError,
},
#[error("invalid JSON string: {error} ({debug})")]
InvalidJson {
debug: String,
error: serde_json::Error,
},
#[error("invalid timestamp in event: {ts}")]
InvalidTimestamp { ts: String },
#[error("missing start_ledger and cursor")]
MissingStartLedgerAndCursor,
#[error("missing target")]
MissingTarget,
#[error(transparent)]
Rpc(#[from] rpc::Error),
#[error(transparent)]
Generic(#[from] Box<dyn std::error::Error>),
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Xdr(#[from] xdr::Error),
#[error(transparent)]
Serde(#[from] serde_json::Error),
#[error(transparent)]
Network(#[from] network::Error),
#[error(transparent)]
Locator(#[from] locator::Error),
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, clap::ValueEnum)]
pub enum OutputFormat {
/// Colorful, human-oriented console output
Pretty,
/// Human-oriented console output without colors
Plain,
/// JSONified console output
Json,
}
impl Cmd {
pub async fn run(&mut self) -> Result<(), Error> {
// Validate that topics are made up of segments.
for topic in &self.topic_filters {
for (i, segment) in topic.split(',').enumerate() {
if i > 4 {
return Err(Error::InvalidTopicFilter {
topic: topic.to_string(),
});
}
if segment != "*" {
if let Err(e) = xdr::ScVal::from_xdr_base64(segment, Limits::none()) {
return Err(Error::InvalidSegment {
topic: topic.to_string(),
segment: segment.to_string(),
error: e,
});
}
}
}
}
// Validate contract_ids
for id in &mut self.contract_ids {
utils::contract_id_from_str(id).map_err(|e| Error::InvalidContractId {
contract_id: id.clone(),
error: e,
})?;
}
let response = self.run_against_rpc_server().await?;
for event in &response.events {
match self.output {
// Should we pretty-print the JSON like we're doing here or just
// dump an event in raw JSON on each line? The latter is easier
// to consume programmatically.
OutputFormat::Json => {
println!(
"{}",
serde_json::to_string_pretty(&event).map_err(|e| {
Error::InvalidJson {
debug: format!("{event:#?}"),
error: e,
}
})?,
);
}
OutputFormat::Plain => println!("{event}"),
OutputFormat::Pretty => event.pretty_print()?,
}
}
println!("Latest Ledger: {}", response.latest_ledger);
Ok(())
}
async fn run_against_rpc_server(&self) -> Result<rpc::GetEventsResponse, Error> {
let start = self.start()?;
let network = self.network.get(&self.locator)?;
let client = rpc::Client::new(&network.rpc_url)?;
client
.verify_network_passphrase(Some(&network.network_passphrase))
.await?;
client
.get_events(
start,
Some(self.event_type),
&self.contract_ids,
&self.topic_filters,
Some(self.count),
)
.await
.map_err(Error::Rpc)
}
fn start(&self) -> Result<rpc::EventStart, Error> {
let start = match (self.start_ledger, self.cursor.clone()) {
(Some(start), _) => rpc::EventStart::Ledger(start),
(_, Some(c)) => rpc::EventStart::Cursor(c),
// should never happen because of required_unless_present flags
_ => return Err(Error::MissingStartLedgerAndCursor),
};
Ok(start)
}
}