Skip to main content

Client

Struct Client 

Source
pub struct Client { /* private fields */ }
Expand description

GraphQL client for Sui blockchain.

Implementations§

Source§

impl Client

Source

pub async fn chain_identifier(&self) -> Result<Digest, Error>

Get the chain identifier (e.g., “35834a8a” for mainnet).

§Example
use sui_graphql::Client;

let client = Client::new("https://graphql.mainnet.sui.io/graphql")?;
let chain_id = client.chain_identifier().await?;
println!("Connected to chain: {}", chain_id);
Source

pub async fn protocol_version(&self) -> Result<u64, Error>

Get the current protocol version.

§Example
use sui_graphql::Client;

let client = Client::new("https://graphql.mainnet.sui.io/graphql")?;
let version = client.protocol_version().await?;
println!("Protocol version: {}", version);
Source

pub async fn epoch(&self, epoch_id: Option<u64>) -> Result<Option<Epoch>, Error>

Get epoch information by ID, or the current epoch if no ID is provided.

Returns None if the epoch does not exist or was pruned.

§Example
use sui_graphql::Client;

let client = Client::new("https://graphql.mainnet.sui.io/graphql")?;

// Get current epoch
let epoch = client.epoch(None).await?;

// Get specific epoch
let epoch = client.epoch(Some(100)).await?;
Source§

impl Client

Source

pub async fn get_checkpoint( &self, sequence_number: Option<u64>, ) -> Result<Option<CheckpointResponse>, Error>

Fetch a checkpoint by its sequence number, or the latest checkpoint if not specified.

Returns:

  • Ok(Some(response)) if the checkpoint exists
  • Ok(None) if the checkpoint does not exist
  • Err(Error::Request) for network errors
  • Err(Error::Base64) / Err(Error::Bcs) for decoding errors
Source§

impl Client

Source

pub async fn get_balance( &self, owner: Address, coin_type: &StructTag, ) -> Result<Option<Balance>, Error>

Get the balance for a specific coin type owned by an address.

§Example
use sui_graphql::Client;
use sui_sdk_types::Address;
use sui_sdk_types::StructTag;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(Client::MAINNET)?;
    let owner: Address = "0x123...".parse()?;

    // Get SUI balance using the helper
    let sui_balance = client.get_balance(owner, &StructTag::sui()).await?;
    if let Some(bal) = sui_balance {
        println!("SUI balance: {}", bal.total_balance);
    }

    // Get balance for other coin types by parsing the type string
    let usdc_type: StructTag = "0xdba...::usdc::USDC".parse()?;
    let usdc_balance = client.get_balance(owner, &usdc_type).await?;
    if let Some(bal) = usdc_balance {
        println!("USDC balance: {}", bal.total_balance);
    }

    Ok(())
}
Source

pub fn list_balances( &self, owner: Address, ) -> impl Stream<Item = Result<Balance, Error>> + '_

Stream all coin balances owned by an address.

§Example
use futures::StreamExt;
use std::pin::pin;
use sui_graphql::Client;
use sui_sdk_types::Address;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(Client::MAINNET)?;
    let owner: Address = "0x123...".parse()?;

    let mut stream = pin!(client.list_balances(owner));
    while let Some(result) = stream.next().await {
        let balance = result?;
        println!("{}: {}", balance.coin_type, balance.total_balance);
    }
    Ok(())
}
Source§

impl Client

Source

pub fn dynamic_fields(&self, parent: Address) -> DynamicFieldsRequest<'_>

Create a request builder for listing dynamic fields on an object.

Source

pub fn dynamic_field<N: Serialize>( &self, parent: Address, name_type: TypeTag, name: Bcs<N>, ) -> DynamicFieldRequest<'_, N>

Create a request builder for fetching a single dynamic field by name.

Source

pub fn dynamic_object_field<N: Serialize>( &self, parent: Address, name_type: TypeTag, name: Bcs<N>, ) -> DynamicFieldRequest<'_, N>

Create a request builder for fetching a single dynamic object field by name.

Source§

impl Client

Source

pub async fn execute_transaction( &self, transaction: &Transaction, signatures: &[UserSignature], ) -> Result<ExecutionResult, Error>

Execute a signed transaction on chain.

This commits the transaction to the blockchain and waits for finality.

Execution errors (e.g., invalid signatures, insufficient gas) are returned as GraphQL errors with code BAD_USER_INPUT, accessible via Response::errors().

§Arguments
  • transaction - The transaction to execute
  • signatures - List of signatures authorizing the transaction
§Returns
  • Ok(result) with effects and balance_changes if successful
  • Err(...) for network or decoding errors
Source§

impl Client

Source

pub async fn get_object( &self, object_id: Address, ) -> Result<Option<Object>, Error>

Fetch an object by its ID and deserialize from BCS.

Returns:

  • Ok(Some(object)) if the object exists
  • Ok(None) if the object does not exist
  • Err(Error::Request) for network errors
  • Err(Error::Base64) / Err(Error::Bcs) for decoding errors
§Example
use sui_graphql::Client;
use sui_sdk_types::Address;

let client = Client::new(Client::MAINNET)?;
let object_id: Address = "0x5".parse()?;

match client.get_object(object_id).await? {
    Some(object) => println!("Object version: {}", object.version()),
    None => println!("Object not found"),
}
Source

pub async fn get_object_at_version( &self, object_id: Address, version: u64, ) -> Result<Option<Object>, Error>

Fetch an object at a specific version.

Source

pub async fn get_object_at_checkpoint( &self, object_id: Address, checkpoint: u64, ) -> Result<Option<Object>, Error>

Fetch an object at a specific checkpoint.

Returns the object’s state as of the given checkpoint.

Source

pub async fn get_object_with_root_version( &self, object_id: Address, root_version: u64, ) -> Result<Option<Object>, Error>

Fetch an object with a root version bound.

This is useful for fetching child or wrapped objects bounded by their root object’s version. The object will be fetched at the latest version at or before the given root version.

Source

pub fn list_objects( &self, owner: Address, ) -> impl Stream<Item = Result<Object, Error>> + '_

Stream all objects owned by an address.

Handles pagination automatically, fetching pages as needed.

§Example
use futures::StreamExt;
use std::pin::pin;
use sui_graphql::Client;
use sui_sdk_types::Address;

let client = Client::new(Client::TESTNET)?;
let owner: Address = "0x123...".parse()?;

let mut stream = pin!(client.list_objects(owner));
while let Some(result) = stream.next().await {
    let object = result?;
    println!("Object version: {}", object.version());
}
Source§

impl Client

Source

pub async fn get_transaction( &self, digest: &str, ) -> Result<Option<TransactionResponse>, Error>

Fetch a transaction by its digest and deserialize from BCS.

Returns:

  • Ok(Some(response)) if the transaction exists
  • Ok(None) if the transaction does not exist
  • Err(Error::Request) for network errors
  • Err(Error::Base64) / Err(Error::Bcs) for decoding errors
§Example
use sui_graphql::Client;

let client = Client::new("https://graphql.mainnet.sui.io/graphql")?;
let digest = "ABC123..."; // transaction digest

match client.get_transaction(digest).await? {
    Some(tx) => {
        println!("Sender: {}", tx.transaction.sender);
        println!("Status: {:?}", tx.effects.status());
    }
    None => println!("Transaction not found"),
}
Source§

impl Client

Source

pub const MAINNET: &str = "https://graphql.mainnet.sui.io/graphql"

URL for the Sui Foundation provided GraphQL service for mainnet.

Source

pub const TESTNET: &str = "https://graphql.testnet.sui.io/graphql"

URL for the Sui Foundation provided GraphQL service for testnet.

Source

pub const DEVNET: &str = "https://graphql.devnet.sui.io/graphql"

URL for the Sui Foundation provided GraphQL service for devnet.

Source

pub fn new(endpoint: &str) -> Result<Self, Error>

Create a new GraphQL client with the given endpoint.

§Example
use sui_graphql::Client;

let client = Client::new(Client::MAINNET).unwrap();
Source

pub async fn query<T: DeserializeOwned>( &self, query: &str, variables: Value, ) -> Result<Response<T>, Error>

Execute a GraphQL query and return the response.

The response contains both data and any errors (GraphQL supports partial success).

§Example
use serde::Deserialize;
use sui_graphql::Client;

#[derive(Deserialize)]
struct MyResponse {
    #[serde(rename = "chainIdentifier")]
    chain_identifier: String,
}

#[tokio::main]
async fn main() -> Result<(), sui_graphql::Error> {
    let client = Client::new(Client::MAINNET)?;
    let response = client
        .query::<MyResponse>("query { chainIdentifier }", serde_json::json!({}))
        .await?;

    // Check for partial errors
    if response.has_errors() {
        for err in response.errors() {
            eprintln!("GraphQL error: {}", err.message());
        }
    }

    // Access the data
    if let Some(data) = response.data() {
        println!("Chain: {}", data.chain_identifier);
    }

    Ok(())
}

Trait Implementations§

Source§

impl Clone for Client

Source§

fn clone(&self) -> Client

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Client

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<U> As for U

Source§

fn as_<T>(self) -> T
where T: CastFrom<U>,

Casts self to type T. The semantics of numeric casting with the as operator are followed, so <T as As>::as_::<U> can be used in the same way as T as U for numeric conversions. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T