sui_gql_client/queries/
mod.rs

1use std::collections::HashMap;
2
3use af_sui_types::{
4    Address as SuiAddress,
5    Object,
6    ObjectArg,
7    ObjectId,
8    ObjectRef,
9    StructTag,
10    TransactionData,
11    Version,
12};
13// For `object_args!` macro only
14#[doc(hidden)]
15pub use bimap::BiMap;
16use futures::Stream;
17use outputs::{DynamicField, ObjectKey, RawMoveStruct, RawMoveValue};
18
19use crate::{GraphQlClient, GraphQlErrors};
20
21mod current_epoch_id;
22mod epoch_final_checkpoint_num;
23mod events_backward;
24mod filtered_full_objects;
25pub mod fragments;
26mod full_object;
27mod full_objects;
28mod gas_payment;
29mod genesis_tx;
30mod latest_checkpoint;
31mod latest_object_version;
32mod latest_objects_version;
33mod latest_package;
34mod latest_version_at_checkpoint_v2;
35mod max_page_size;
36mod multi_get_objects;
37mod object_arg;
38mod object_args;
39mod object_args_and_content;
40mod object_content;
41mod object_type;
42mod objects_content;
43mod objects_flat;
44pub mod outputs;
45mod owner_df_content;
46mod owner_df_contents;
47mod owner_dof_content;
48mod package_at_version;
49mod packages_from_original;
50mod packages_published_epoch;
51mod reference_gas_price;
52pub(crate) mod stream;
53mod transaction_blocks_status;
54
55pub use self::events_backward::{EventEdge, EventFilter};
56pub use self::gas_payment::Error as GasPaymentError;
57pub use self::latest_version_at_checkpoint_v2::Error as LatestVersionAtCheckpointError;
58pub use self::object_args::Error as ObjectArgsError;
59pub use self::object_args_and_content::Error as ObjectArgsAndContentError;
60
61/// Standard query result type to aid in adding new queries.
62type Result<T, C> = std::result::Result<T, Error<<C as GraphQlClient>::Error>>;
63
64/// Extension trait to [`GraphQlClient`] collecting all defined queries in one place.
65#[trait_variant::make(Send)]
66pub trait GraphQlClientExt: GraphQlClient + Sized {
67    // NOTE: `.await` is not used in the implementations below because `trait_variant` de-sugars the
68    // method definitions removing their `async` prefixes
69
70    /// The latest epoch id.
71    async fn current_epoch_id(&self) -> Result<u64, Self> {
72        current_epoch_id::query(self)
73    }
74
75    /// The last checkpoint number of an epoch.
76    async fn epoch_final_checkpoint_num(&self, epoch_id: u64) -> Result<u64, Self> {
77        epoch_final_checkpoint_num::query(self, epoch_id)
78    }
79
80    /// Return a single page of events + cursors and a flag indicating if there's a previous page.
81    ///
82    /// If `page_size` is left `None`, the server decides the size of the page.
83    ///
84    /// The edges are returned in reverse order of which they where returned by the server
85    async fn events_backward(
86        &self,
87        filter: Option<EventFilter>,
88        cursor: Option<String>,
89        page_size: Option<u32>,
90    ) -> Result<(Vec<EventEdge>, bool), Self> {
91        events_backward::query(self, filter, cursor, page_size)
92    }
93
94    /// The latest full [`Object`] contents with the possibility to filter by owner or object type.
95    fn filtered_full_objects(
96        &self,
97        owner: Option<SuiAddress>,
98        type_: Option<String>,
99        page_size: Option<u32>,
100    ) -> impl Stream<Item = Result<Object, Self>> + '_ {
101        filtered_full_objects::query(self, owner, type_, page_size)
102    }
103
104    /// The full [`Object`] contents at a certain version or the latest if not specified.
105    async fn full_object(&self, object_id: ObjectId, version: Option<u64>) -> Result<Object, Self> {
106        full_object::query(self, object_id, version)
107    }
108
109    /// The full [`Object`] contents at their latest versions.
110    ///
111    /// Fails if any requested object id is not in the final map.
112    ///
113    /// # Note
114    ///
115    /// The check for returned object ids is just so that the caller can safely do `map[object_id]`
116    /// on the returned map. Keep in mind that the result if an object id is repeated in `objects`
117    /// is undefined. Avoid doing so.
118    async fn latest_full_objects(
119        &self,
120        objects: impl IntoIterator<Item = ObjectId> + Send,
121        page_size: Option<u32>,
122    ) -> Result<HashMap<ObjectId, Object>, Self> {
123        full_objects::query(self, objects, page_size)
124    }
125
126    /// The full [`Object`] contents at specific versions.
127    ///
128    /// Duplicate object keys are automatically discarded.
129    async fn multi_get_objects(
130        &self,
131        keys: impl IntoIterator<Item = (ObjectId, Version)> + Send,
132    ) -> Result<Vec<Object>, Self> {
133        self::multi_get_objects::query(self, keys)
134    }
135
136    /// Genesis transaction of the Sui network instance.
137    async fn genesis_tx(&self) -> Result<TransactionData, Self> {
138        genesis_tx::query(self)
139    }
140
141    /// Latest checkpoint number.
142    async fn latest_checkpoint(&self) -> Result<u64, Self> {
143        latest_checkpoint::query(self)
144    }
145
146    /// The latest checkpoint number and object version of an object.
147    async fn latest_object_version(&self, object_id: ObjectId) -> Result<(u64, u64), Self> {
148        latest_object_version::query(self, object_id)
149    }
150
151    /// The latest checkpoint number and the map of object ids to the their version at that
152    /// checkpoint.
153    ///
154    /// Fails if the server doesn't return the version for any of the requested objects.
155    async fn latest_objects_version(
156        &self,
157        object_ids: &[ObjectId],
158    ) -> Result<(u64, HashMap<ObjectId, u64>), Self> {
159        latest_objects_version::query(self, object_ids)
160    }
161
162    /// Version of the object at this checkpoint.
163    async fn latest_version_at_checkpoint(
164        &self,
165        id: ObjectId,
166        ckpt_num: u64,
167    ) -> std::result::Result<u64, LatestVersionAtCheckpointError<Self::Error>> {
168        latest_version_at_checkpoint_v2::query(self, id, ckpt_num)
169    }
170
171    /// Get the object argument for a programmable transaction.
172    async fn object_arg(&self, id: ObjectId) -> Result<ObjectArg, Self> {
173        object_arg::query(self, id)
174    }
175
176    /// Turn a bijective map of names and object ids into one of names and object args.
177    ///
178    /// Fails if the query response does not have the necessary data for the input map.
179    async fn object_args(
180        &self,
181        names: BiMap<String, ObjectId>,
182        page_size: Option<u32>,
183    ) -> std::result::Result<BiMap<String, ObjectArg>, ObjectArgsError<Self::Error>> {
184        object_args::query(self, names, page_size)
185    }
186
187    /// Get a sequence of object args and contents corresponding to `object_ids`, but not
188    /// necessarily in the same order.
189    ///
190    /// **NOTE**: prefer [`GraphQlClientExt::latest_full_objects`] instead and call `Object::object_arg`
191    /// on each returned object.
192    ///
193    /// The `mutable` argument controls whether we want to create mutable [`ObjectArg`]s, if they
194    /// are of the [`ObjectArg::SharedObject`] variant.
195    ///
196    /// Fails if any object in the response is missing data.
197    async fn object_args_and_content(
198        &self,
199        object_ids: impl IntoIterator<Item = ObjectId> + Send,
200        mutable: bool,
201        page_size: Option<u32>,
202    ) -> std::result::Result<Vec<(ObjectArg, RawMoveStruct)>, ObjectArgsAndContentError<Self::Error>>
203    {
204        object_args_and_content::query(self, object_ids, mutable, page_size)
205    }
206
207    /// Get the raw Move struct of an object's content.
208    async fn object_content(
209        &self,
210        object_id: ObjectId,
211        version: Option<u64>,
212    ) -> Result<RawMoveStruct, Self> {
213        object_content::query(self, object_id, version)
214    }
215
216    async fn objects_content(
217        &self,
218        object_ids: Vec<ObjectId>,
219    ) -> Result<HashMap<ObjectId, RawMoveStruct>, Self> {
220        objects_content::query(self, object_ids)
221    }
222
223    /// Get the raw Move value of a dynamic field's value.
224    async fn owner_df_content(
225        &self,
226        address: SuiAddress,
227        raw_move_value: RawMoveValue,
228        root_version: Option<u64>,
229    ) -> Result<RawMoveValue, Self> {
230        owner_df_content::query(self, address, raw_move_value, root_version)
231    }
232
233    /// Map of all keys to dynamic field values: [`RawMoveValue`] -> [`DynamicField`].
234    async fn owner_df_contents(
235        &self,
236        address: SuiAddress,
237        root_version: Option<u64>,
238        first: Option<i32>,
239        after: Option<String>,
240    ) -> Result<(HashMap<RawMoveValue, DynamicField>, Option<String>), Self> {
241        owner_df_contents::query(self, address, root_version, first, after)
242    }
243
244    /// Get the raw Move struct of a dynamic object field's value.
245    async fn owner_dof_content(
246        &self,
247        address: SuiAddress,
248        raw_move_value: RawMoveValue,
249        root_version: Option<u64>,
250    ) -> Result<(ObjectKey, RawMoveStruct), Self> {
251        owner_dof_content::query(self, address, raw_move_value, root_version)
252    }
253
254    /// Get the latest version of a package.
255    ///
256    /// Returns both its ID and version number.
257    async fn latest_package(&self, package_id: ObjectId) -> Result<(ObjectId, Version), Self> {
258        latest_package::query(self, package_id)
259    }
260
261    /// Get the address of a package at a specific version.
262    async fn package_at_version(
263        &self,
264        package_id: ObjectId,
265        version: Version,
266    ) -> Result<ObjectId, Self> {
267        package_at_version::query(self, package_id, version)
268    }
269
270    /// Get all the package ids and versions given the original package id.
271    async fn packages_from_original(
272        &self,
273        package_id: ObjectId,
274    ) -> Result<impl Iterator<Item = (ObjectId, u64)>, Self> {
275        packages_from_original::query(self, package_id)
276    }
277
278    /// The epoch and checkpoint number (in this order) for each package id.
279    async fn packages_published_epoch(
280        &self,
281        package_ids: Vec<ObjectId>,
282    ) -> Result<impl Iterator<Item = (ObjectId, u64, u64)>, Self> {
283        packages_published_epoch::query(self, package_ids)
284    }
285
286    /// The reference gas price for the latest epoch.
287    async fn reference_gas_price(&self) -> Result<u64, Self> {
288        reference_gas_price::query(self)
289    }
290
291    /// Get execution status for the input transaction digests
292    #[expect(deprecated, reason = "Internal module deprecation")]
293    async fn transaction_blocks_status(
294        &self,
295        transaction_digests: Vec<String>,
296    ) -> Result<impl Iterator<Item = crate::extract::Result<(String, bool)>>, Self> {
297        transaction_blocks_status::query(self, transaction_digests)
298    }
299
300    /// Gas coins to satisfy the budget, excluding some object ids.
301    ///
302    /// The `exclude` is here because it can be useful if a SUI coin is already being used in the
303    /// PTB itself. However in such a scenario one can use [`Argument::Gas`] instead.
304    ///
305    /// [`Argument::Gas`]: af_sui_types::Argument::Gas
306    async fn gas_payment(
307        &self,
308        sponsor: SuiAddress,
309        budget: u64,
310        exclude: Vec<ObjectId>,
311    ) -> std::result::Result<Vec<ObjectRef>, GasPaymentError<Self::Error>> {
312        gas_payment::query(self, sponsor, budget, exclude)
313    }
314
315    /// The maximum size for pagination allowed by the server.
316    async fn max_page_size(&self) -> Result<i32, Self> {
317        max_page_size::query(self)
318    }
319
320    /// Struct type of an object given its ID.
321    async fn object_type(&self, id: ObjectId) -> Result<StructTag, Self> {
322        object_type::query(self, id)
323    }
324}
325
326impl<T: GraphQlClient> GraphQlClientExt for T {}
327
328/// Generic error type for queries.
329#[derive(thiserror::Error, Clone, Debug)]
330pub enum Error<C: std::error::Error> {
331    #[error("Client error: {0:?}")]
332    Client(C),
333    #[error("In server response: {0}")]
334    Server(#[from] GraphQlErrors),
335    #[error("Missing data in response: {0}")]
336    MissingData(String),
337}
338
339#[expect(deprecated, reason = "Internal module deprecation")]
340impl<C: std::error::Error> From<crate::extract::Error> for Error<C> {
341    fn from(value: crate::extract::Error) -> Self {
342        Self::MissingData(value.0)
343    }
344}
345
346impl<C: std::error::Error> From<&'static str> for Error<C> {
347    fn from(value: &'static str) -> Self {
348        Self::MissingData(value.into())
349    }
350}
351
352/// Helper to generate [`Error::MissingData`].
353///
354/// Works very much like an `anyhow!`/`eyre!` macro, but intended for the case when trying to
355/// extract some data from the query.
356#[macro_export]
357macro_rules! missing_data {
358    ($($msg:tt)*) => {
359        $crate::queries::Error::MissingData(format!($($msg)*))
360    };
361}