1use std::collections::HashMap;
5use std::sync::Arc;
6
7use sui_sdk_types::{Address, Object, Version};
8use sui_sdk_types::{CheckpointSequenceNumber, EpochId, SignedTransaction, ValidatorCommittee};
9use sui_types::balance_change::BalanceChange;
10use sui_types::base_types::{ObjectID, ObjectType};
11use sui_types::storage::ObjectKey;
12use sui_types::storage::RpcStateReader;
13use sui_types::storage::error::{Error as StorageError, Result};
14use sui_types::storage::{ObjectStore, TransactionInfo};
15use tap::Pipe;
16
17use crate::Direction;
18
19#[derive(Clone)]
20pub struct StateReader {
21 inner: Arc<dyn RpcStateReader>,
22}
23
24impl StateReader {
25 pub fn new(inner: Arc<dyn RpcStateReader>) -> Self {
26 Self { inner }
27 }
28
29 pub fn inner(&self) -> &Arc<dyn RpcStateReader> {
30 &self.inner
31 }
32
33 #[tracing::instrument(skip(self))]
34 pub fn get_object(&self, object_id: Address) -> crate::Result<Option<Object>> {
35 self.inner
36 .get_object(&object_id.into())
37 .map(TryInto::try_into)
38 .transpose()
39 .map_err(Into::into)
40 }
41
42 #[tracing::instrument(skip(self))]
43 pub fn get_object_with_version(
44 &self,
45 object_id: Address,
46 version: Version,
47 ) -> crate::Result<Option<Object>> {
48 self.inner
49 .get_object_by_key(&object_id.into(), version.into())
50 .map(TryInto::try_into)
51 .transpose()
52 .map_err(Into::into)
53 }
54
55 #[tracing::instrument(skip(self))]
56 pub fn get_committee(&self, epoch: EpochId) -> Option<ValidatorCommittee> {
57 self.inner
58 .get_committee(epoch)
59 .map(|committee| (*committee).clone().into())
60 }
61
62 #[tracing::instrument(skip(self))]
63 pub fn get_system_state(&self) -> Result<sui_types::sui_system_state::SuiSystemState> {
64 sui_types::sui_system_state::get_sui_system_state(self.inner())
65 .map_err(StorageError::custom)
66 .map_err(StorageError::custom)
67 }
68
69 #[tracing::instrument(skip(self))]
70 pub fn get_system_state_summary(
71 &self,
72 ) -> Result<sui_types::sui_system_state::sui_system_state_summary::SuiSystemStateSummary> {
73 use sui_types::sui_system_state::SuiSystemStateTrait;
74
75 let system_state = self.get_system_state()?;
76 let summary = system_state.into_sui_system_state_summary();
77
78 Ok(summary)
79 }
80
81 pub fn get_authenticator_state(
82 &self,
83 ) -> Result<Option<sui_types::authenticator_state::AuthenticatorStateInner>> {
84 sui_types::authenticator_state::get_authenticator_state(self.inner())
85 .map_err(StorageError::custom)
86 }
87
88 #[tracing::instrument(skip(self))]
89 pub fn get_transaction(
90 &self,
91 digest: sui_sdk_types::Digest,
92 ) -> crate::Result<(
93 sui_sdk_types::SignedTransaction,
94 sui_sdk_types::TransactionEffects,
95 Option<sui_sdk_types::TransactionEvents>,
96 )> {
97 use sui_types::effects::TransactionEffectsAPI;
98
99 let transaction_digest = digest.into();
100
101 let transaction = (*self
102 .inner()
103 .get_transaction(&transaction_digest)
104 .ok_or(TransactionNotFoundError(digest))?)
105 .clone()
106 .into_inner();
107 let effects = self
108 .inner()
109 .get_transaction_effects(&transaction_digest)
110 .ok_or(TransactionNotFoundError(digest))?;
111 let events = if effects.events_digest().is_some() {
112 self.inner()
113 .get_events(effects.transaction_digest())
114 .ok_or(TransactionNotFoundError(digest))?
115 .pipe(Some)
116 } else {
117 None
118 };
119
120 Ok((
121 transaction.try_into()?,
122 effects.try_into()?,
123 events.map(TryInto::try_into).transpose()?,
124 ))
125 }
126
127 #[tracing::instrument(skip(self))]
128 pub fn get_transaction_info(
129 &self,
130 digest: &sui_types::digests::TransactionDigest,
131 ) -> Option<TransactionInfo> {
132 self.inner()
133 .indexes()?
134 .get_transaction_info(digest)
135 .ok()
136 .flatten()
137 }
138
139 #[tracing::instrument(skip(self))]
140 pub fn get_transaction_read(
141 &self,
142 digest: sui_sdk_types::Digest,
143 ) -> crate::Result<TransactionRead> {
144 let (
145 SignedTransaction {
146 transaction,
147 signatures,
148 },
149 effects,
150 events,
151 ) = self.get_transaction(digest)?;
152
153 let (checkpoint, balance_changes, object_types) =
154 if let Some(info) = self.get_transaction_info(&(digest.into())) {
155 (
156 Some(info.checkpoint),
157 Some(info.balance_changes),
158 Some(info.object_types),
159 )
160 } else {
161 (None, None, None)
162 };
163 let timestamp_ms = if let Some(checkpoint) = checkpoint {
164 self.inner()
165 .get_checkpoint_by_sequence_number(checkpoint)
166 .map(|checkpoint| checkpoint.timestamp_ms)
167 } else {
168 None
169 };
170
171 let unchanged_loaded_runtime_objects = self
172 .inner()
173 .get_unchanged_loaded_runtime_objects(&(digest.into()));
174
175 Ok(TransactionRead {
176 digest: transaction.digest(),
177 transaction,
178 signatures,
179 effects,
180 events,
181 checkpoint,
182 timestamp_ms,
183 balance_changes,
184 object_types,
185 unchanged_loaded_runtime_objects,
186 })
187 }
188
189 #[allow(unused)]
190 pub fn checkpoint_iter(
191 &self,
192 direction: Direction,
193 start: CheckpointSequenceNumber,
194 ) -> CheckpointIter {
195 CheckpointIter::new(self.clone(), direction, start)
196 }
197
198 #[allow(unused)]
199 pub fn transaction_iter(
200 &self,
201 direction: Direction,
202 cursor: (CheckpointSequenceNumber, Option<usize>),
203 ) -> CheckpointTransactionsIter {
204 CheckpointTransactionsIter::new(self.clone(), direction, cursor)
205 }
206}
207
208#[derive(Debug)]
209pub struct TransactionRead {
210 pub digest: sui_sdk_types::Digest,
211 pub transaction: sui_sdk_types::Transaction,
212 pub signatures: Vec<sui_sdk_types::UserSignature>,
213 pub effects: sui_sdk_types::TransactionEffects,
214 pub events: Option<sui_sdk_types::TransactionEvents>,
215 pub checkpoint: Option<u64>,
216 pub timestamp_ms: Option<u64>,
217 pub balance_changes: Option<Vec<BalanceChange>>,
218 pub object_types: Option<HashMap<ObjectID, ObjectType>>,
219 pub unchanged_loaded_runtime_objects: Option<Vec<ObjectKey>>,
220}
221
222pub struct CheckpointTransactionsIter {
223 reader: StateReader,
224 direction: Direction,
225
226 next_cursor: Option<(CheckpointSequenceNumber, Option<usize>)>,
227 checkpoint: Option<(
228 sui_types::messages_checkpoint::CheckpointSummary,
229 sui_types::messages_checkpoint::CheckpointContents,
230 )>,
231}
232
233impl CheckpointTransactionsIter {
234 #[allow(unused)]
235 pub fn new(
236 reader: StateReader,
237 direction: Direction,
238 start: (CheckpointSequenceNumber, Option<usize>),
239 ) -> Self {
240 Self {
241 reader,
242 direction,
243 next_cursor: Some(start),
244 checkpoint: None,
245 }
246 }
247}
248
249impl Iterator for CheckpointTransactionsIter {
250 type Item = Result<(CursorInfo, sui_types::digests::TransactionDigest)>;
251
252 fn next(&mut self) -> Option<Self::Item> {
253 loop {
254 let (current_checkpoint, transaction_index) = self.next_cursor?;
255
256 let (checkpoint, contents) = if let Some(checkpoint) = &self.checkpoint {
257 if checkpoint.0.sequence_number != current_checkpoint {
258 self.checkpoint = None;
259 continue;
260 } else {
261 checkpoint
262 }
263 } else {
264 let checkpoint = self
265 .reader
266 .inner()
267 .get_checkpoint_by_sequence_number(current_checkpoint)?;
268 let contents = self
269 .reader
270 .inner()
271 .get_checkpoint_contents_by_sequence_number(checkpoint.sequence_number)?;
272
273 self.checkpoint = Some((checkpoint.into_inner().into_data(), contents));
274 self.checkpoint.as_ref().unwrap()
275 };
276
277 let index = transaction_index
278 .map(|idx| idx.clamp(0, contents.size().saturating_sub(1)))
279 .unwrap_or_else(|| match self.direction {
280 Direction::Ascending => 0,
281 Direction::Descending => contents.size().saturating_sub(1),
282 });
283
284 self.next_cursor = {
285 let next_index = match self.direction {
286 Direction::Ascending => {
287 let next_index = index + 1;
288 if next_index >= contents.size() {
289 None
290 } else {
291 Some(next_index)
292 }
293 }
294 Direction::Descending => index.checked_sub(1),
295 };
296
297 let next_checkpoint = if next_index.is_some() {
298 Some(current_checkpoint)
299 } else {
300 match self.direction {
301 Direction::Ascending => current_checkpoint.checked_add(1),
302 Direction::Descending => current_checkpoint.checked_sub(1),
303 }
304 };
305
306 next_checkpoint.map(|checkpoint| (checkpoint, next_index))
307 };
308
309 if contents.size() == 0 {
310 continue;
311 }
312
313 let digest = contents.inner()[index].transaction;
314
315 let cursor_info = CursorInfo {
316 checkpoint: checkpoint.sequence_number,
317 timestamp_ms: checkpoint.timestamp_ms,
318 index: index as u64,
319 next_cursor: self.next_cursor,
320 };
321
322 return Some(Ok((cursor_info, digest)));
323 }
324 }
325}
326
327#[allow(unused)]
328pub struct CursorInfo {
329 pub checkpoint: CheckpointSequenceNumber,
330 pub timestamp_ms: u64,
331 #[allow(unused)]
332 pub index: u64,
333
334 pub next_cursor: Option<(CheckpointSequenceNumber, Option<usize>)>,
336}
337
338pub struct CheckpointIter {
339 reader: StateReader,
340 direction: Direction,
341
342 next_cursor: Option<CheckpointSequenceNumber>,
343}
344
345impl CheckpointIter {
346 #[allow(unused)]
347 pub fn new(reader: StateReader, direction: Direction, start: CheckpointSequenceNumber) -> Self {
348 Self {
349 reader,
350 direction,
351 next_cursor: Some(start),
352 }
353 }
354}
355
356impl Iterator for CheckpointIter {
357 type Item = Result<(
358 sui_types::messages_checkpoint::CertifiedCheckpointSummary,
359 sui_types::messages_checkpoint::CheckpointContents,
360 )>;
361
362 fn next(&mut self) -> Option<Self::Item> {
363 let current_checkpoint = self.next_cursor?;
364
365 let checkpoint = self
366 .reader
367 .inner()
368 .get_checkpoint_by_sequence_number(current_checkpoint)?
369 .into_inner();
370 let contents = self
371 .reader
372 .inner()
373 .get_checkpoint_contents_by_sequence_number(checkpoint.sequence_number)?;
374
375 self.next_cursor = match self.direction {
376 Direction::Ascending => current_checkpoint.checked_add(1),
377 Direction::Descending => current_checkpoint.checked_sub(1),
378 };
379
380 Some(Ok((checkpoint, contents)))
381 }
382}
383
384#[derive(Debug)]
385pub struct TransactionNotFoundError(pub sui_sdk_types::Digest);
386
387impl std::fmt::Display for TransactionNotFoundError {
388 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
389 write!(f, "Transaction {} not found", self.0)
390 }
391}
392
393impl std::error::Error for TransactionNotFoundError {}
394
395impl From<TransactionNotFoundError> for crate::RpcError {
396 fn from(value: TransactionNotFoundError) -> Self {
397 Self::new(tonic::Code::NotFound, value.to_string())
398 }
399}