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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
use clap::{arg, command, Parser};
use std::io;

use soroban_env_host::xdr::{self, ReadXdr};

use super::config::{events_file, locator, network};
use crate::commands::config::network::Network;
use crate::{rpc, toid, utils};

#[derive(Parser, Debug, Clone)]
#[group(skip)]
pub struct Cmd {
    /// The first ledger sequence number in the range to pull events (required
    /// if not in sandbox mode).
    /// 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 (specify "0" to show all events
    /// when using sandbox, or to defer to the server-defined limit if using
    /// RPC).
    #[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 abc --id def`, or passed with
    /// multiple parameters, e.g. `--id abd def`.
    ///
    /// 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,

    #[command(flatten)]
    events_file: events_file::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: hex::FromHexError,
    },

    #[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)]
    EventsFile(#[from] events_file::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(&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) {
                        return Err(Error::InvalidSegment {
                            topic: topic.to_string(),
                            segment: segment.to_string(),
                            error: e,
                        });
                    }
                }
            }
        }

        let response = if self.network.is_no_network() {
            self.run_in_sandbox()
        } else {
            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 { rpc_url, .. } = self.network.get(&self.locator)?;

        for raw_contract_id in &self.contract_ids {
            // We parse the contract IDs to ensure they're the correct format,
            // but since we'll be passing them as-is to the RPC server anyway,
            // we disregard the return value.
            utils::id_from_str::<32>(raw_contract_id).map_err(|e| Error::InvalidContractId {
                contract_id: raw_contract_id.clone(),
                error: e,
            })?;
        }

        let client = rpc::Client::new(&rpc_url)?;
        client
            .get_events(
                start,
                Some(self.event_type),
                &self.contract_ids,
                &self.topic_filters,
                Some(self.count),
            )
            .await
            .map_err(Error::Rpc)
    }

    pub fn run_in_sandbox(&self) -> Result<rpc::GetEventsResponse, Error> {
        let start = self.start()?;
        let count: usize = if self.count == 0 {
            std::usize::MAX
        } else {
            self.count
        };

        let start_cursor = match start {
            rpc::EventStart::Ledger(l) => (toid::Toid::new(l, 0, 0).into(), -1),
            rpc::EventStart::Cursor(c) => rpc::parse_cursor(&c)?,
        };
        let path = self.locator.config_dir()?;
        let file = self.events_file.read(&path)?;

        // Read the JSON events from disk and find the ones that match the
        // contract ID filter(s) that were passed in.
        Ok(rpc::GetEventsResponse {
            events: events_file::Args::filter_events(
                &file.events,
                &path,
                start_cursor,
                &self.contract_ids,
                &self.topic_filters,
                count,
            ),
            latest_ledger: file.latest_ledger,
        })
    }

    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)
    }
}

#[cfg(test)]
mod tests {
    use std::path;

    use assert_fs::NamedTempFile;
    use soroban_env_host::events;

    use super::*;

    use events_file::Args;
    #[test]
    fn test_does_event_serialization_match() {
        let temp = NamedTempFile::new("events.json").unwrap();
        let events_file = Args {
            events_file: Some(temp.to_path_buf()),
        };
        // Make a couple of fake events with slightly different properties and
        // write them to disk, then read the serialized versions from disk and
        // ensure the properties match.

        let events: Vec<events::HostEvent> = vec![
            events::HostEvent {
                event: events::Event::Contract(xdr::ContractEvent {
                    ext: xdr::ExtensionPoint::V0,
                    contract_id: Some(xdr::Hash([0; 32])),
                    type_: xdr::ContractEventType::Contract,
                    body: xdr::ContractEventBody::V0(xdr::ContractEventV0 {
                        topics: xdr::ScVec(vec![].try_into().unwrap()),
                        data: xdr::ScVal::U32(12345),
                    }),
                }),
                failed_call: false,
            },
            events::HostEvent {
                event: events::Event::Contract(xdr::ContractEvent {
                    ext: xdr::ExtensionPoint::V0,
                    contract_id: Some(xdr::Hash([0x1; 32])),
                    type_: xdr::ContractEventType::Contract,
                    body: xdr::ContractEventBody::V0(xdr::ContractEventV0 {
                        topics: xdr::ScVec(vec![].try_into().unwrap()),
                        data: xdr::ScVal::I32(67890),
                    }),
                }),
                failed_call: false,
            },
        ];

        let ledger_info = soroban_ledger_snapshot::LedgerSnapshot {
            protocol_version: 1,
            sequence_number: 2, // this is the only value that matters
            timestamp: 3,
            network_id: [0x1; 32],
            base_reserve: 5,
            ledger_entries: vec![],
        };

        events_file.commit(&events, &ledger_info, &temp).unwrap();

        let file = events_file.read(&std::env::current_dir().unwrap()).unwrap();
        assert_eq!(file.events.len(), 2);
        assert_eq!(file.events[0].ledger, "2");
        assert_eq!(file.events[1].ledger, "2");
        assert_eq!(file.events[0].contract_id, "0".repeat(64));
        assert_eq!(file.events[1].contract_id, "01".repeat(32));
        assert_eq!(file.latest_ledger, 2);
    }

    #[test]
    fn test_does_event_fixture_load() {
        // This test ensures that the included JSON fixture file matches the
        // correct event format (for the purposes of human readability).
        let filename =
            path::PathBuf::from("../crates/soroban-test/tests/fixtures/test-jsons/get-events.json");
        let events_file = Args {
            events_file: Some(filename),
        };
        let result = events_file.read(&std::env::current_dir().unwrap());
        println!("{result:?}");
        assert!(result.is_ok());
    }
}