Skip to content

Commit

Permalink
sui-graphql-client: impl_scalar for u64 and Uint53 (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
stefan-mysten authored Oct 4, 2024
1 parent 43b7930 commit 112bfb3
Show file tree
Hide file tree
Showing 11 changed files with 52 additions and 85 deletions.
25 changes: 11 additions & 14 deletions crates/sui-graphql-client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,12 +115,13 @@ query CustomQuery($id: UInt53) {
```

The generated query types are defined below. Note that the `id` variable is optional (to make it mandatory change the schema to $id: Uint53! -- note the ! character which indicates a mandatory field). That means that if the `id` variable is not provided, the query will return the data for the last known epoch.
Note that instead of using `Uint53`, the scalar is mapped to `u64` in the library using `impl_scalar(u64, schema::Uint53)`, thus all references to `Uint53` in the schema are replaced with `u64` in the code below.


```rust,ignore
#[derive(cynic::QueryVariables, Debug)]
pub struct CustomQueryVariables {
pub id: Option<Uint53>,
pub id: Option<u64>,
}
#[derive(cynic::QueryFragment, Debug)]
Expand All @@ -132,19 +133,15 @@ pub struct CustomQuery {
#[derive(cynic::QueryFragment, Debug)]
pub struct Epoch {
pub epoch_id: Uint53,
pub epoch_id: u64,
pub reference_gas_price: Option<BigInt>,
pub total_gas_fees: Option<BigInt>,
pub total_checkpoints: Option<Uint53>,
pub total_transactions: Option<Uint53>,
pub total_checkpoints: Option<u64>,
pub total_transactions: Option<u64>,
}
#[derive(cynic::Scalar, Debug, Clone)]
pub struct BigInt(pub String);
#[derive(cynic::Scalar, Debug, Clone)]
#[cynic(graphql_type = "UInt53")]
pub struct Uint53(pub u64);
```

The complete example is shown below:
Expand All @@ -153,7 +150,7 @@ use anyhow::Result;
use cynic::QueryBuilder;

use sui_graphql_client::{
query_types::{schema, BigInt, Uint53},
query_types::{schema, BigInt},
Client,
};
use sui_types::types::Address;
Expand All @@ -162,19 +159,19 @@ use sui_types::types::Address;
#[derive(cynic::QueryFragment, Debug)]
#[cynic(schema = "rpc", graphql_type = "Epoch")]
pub struct EpochData {
pub epoch_id: Uint53,
pub epoch_id: u64,
pub reference_gas_price: Option<BigInt>,
pub total_gas_fees: Option<BigInt>,
pub total_checkpoints: Option<Uint53>,
pub total_transactions: Option<Uint53>,
pub total_checkpoints: Option<u64>,
pub total_transactions: Option<u64>,
}

// The variables to pass to the custom query.
// If an epoch id is passed, then the query will return the data for that epoch.
// Otherwise, the query will return the data for the last known epoch.
#[derive(cynic::QueryVariables, Debug)]
pub struct CustomVariables {
pub id: Option<Uint53>,
pub id: Option<u64>,
}

// The custom query. Note that the variables need to be explicitly declared.
Expand Down Expand Up @@ -205,7 +202,7 @@ async fn main() -> Result<()> {
println!("{:?}", response);

// Query the data for epoch 1.
let epoch_id = Uint53(1);
let epoch_id = 1;
let operation = CustomQuery::build(CustomVariables { id: Some(epoch_id) });
let response = client
.run_query::<CustomQuery, CustomVariables>(&operation)
Expand Down
11 changes: 5 additions & 6 deletions crates/sui-graphql-client/examples/custom_query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,25 @@ use cynic::QueryBuilder;

use sui_graphql_client::query_types::schema;
use sui_graphql_client::query_types::BigInt;
use sui_graphql_client::query_types::Uint53;
use sui_graphql_client::Client;

// The data returned by the custom query.
#[derive(cynic::QueryFragment, Debug)]
#[cynic(schema = "rpc", graphql_type = "Epoch")]
pub struct EpochData {
pub epoch_id: Uint53,
pub epoch_id: u64,
pub reference_gas_price: Option<BigInt>,
pub total_gas_fees: Option<BigInt>,
pub total_checkpoints: Option<Uint53>,
pub total_transactions: Option<Uint53>,
pub total_checkpoints: Option<u64>,
pub total_transactions: Option<u64>,
}

// The variables to pass to the custom query.
// If an epoch id is passed, then the query will return the data for that epoch.
// Otherwise, the query will return the data for the last known epoch.
#[derive(cynic::QueryVariables, Debug)]
pub struct CustomVariables {
pub id: Option<Uint53>,
pub id: Option<u64>,
}

// The custom query. Note that the variables need to be explicitly declared.
Expand Down Expand Up @@ -56,7 +55,7 @@ async fn main() -> Result<()> {
println!("{:?}", response);

// Query the data for epoch 1.
let epoch_id = Uint53(1);
let epoch_id = 1;
let operation = CustomQuery::build(CustomVariables { id: Some(epoch_id) });
let response = client
.run_query::<CustomQuery, CustomVariables>(&operation)
Expand Down
33 changes: 11 additions & 22 deletions crates/sui-graphql-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ use query_types::TransactionBlockQuery;
use query_types::TransactionBlocksQuery;
use query_types::TransactionBlocksQueryArgs;
use query_types::TransactionsFilter;
use query_types::Uint53;
use query_types::Validator;
use reqwest::Url;
use sui_types::types::framework::Coin;
Expand Down Expand Up @@ -199,9 +198,7 @@ impl Client {
/// This will return `Ok(None)` if the epoch requested is not available in the GraphQL service
/// (e.g., due to prunning).
pub async fn reference_gas_price(&self, epoch: Option<u64>) -> Result<Option<u64>, Error> {
let operation = EpochSummaryQuery::build(EpochSummaryArgs {
id: epoch.map(Uint53),
});
let operation = EpochSummaryQuery::build(EpochSummaryArgs { id: epoch });
let response = self.run_query(&operation).await?;

if let Some(data) = response.data {
Expand All @@ -220,9 +217,7 @@ impl Client {
&self,
version: Option<u64>,
) -> Result<Option<ProtocolConfigs>, Error> {
let operation = ProtocolConfigQuery::build(ProtocolVersionArgs {
id: version.map(Uint53),
});
let operation = ProtocolConfigQuery::build(ProtocolVersionArgs { id: version });
let response = self.run_query(&operation).await?;
Ok(response.data.map(|p| p.protocol_config))
}
Expand Down Expand Up @@ -250,7 +245,7 @@ impl Client {
last: Option<i32>,
) -> Result<Option<Page<Validator>>, Error> {
let operation = ActiveValidatorsQuery::build(ActiveValidatorsArgs {
id: epoch.map(Uint53),
id: epoch,
after,
before,
first,
Expand Down Expand Up @@ -437,7 +432,7 @@ impl Client {
let operation = CheckpointQuery::build(CheckpointArgs {
id: CheckpointId {
digest,
sequence_number: seq_num.map(Uint53),
sequence_number: seq_num,
},
});
let response = self.run_query(&operation).await?;
Expand Down Expand Up @@ -478,8 +473,7 @@ impl Client {
Ok(response
.data
.and_then(|d| d.epoch)
.and_then(|e| e.total_checkpoints)
.map(|x| x.into()))
.and_then(|e| e.total_checkpoints))
}

/// Return the number of transaction blocks in this epoch. This will return `Ok(None)` if the
Expand All @@ -497,8 +491,7 @@ impl Client {
Ok(response
.data
.and_then(|d| d.epoch)
.and_then(|e| e.total_transactions)
.map(|x| x.into()))
.and_then(|e| e.total_transactions))
}

/// Internal method for getting the epoch summary that is called in a few other APIs for
Expand All @@ -507,9 +500,7 @@ impl Client {
&self,
epoch: Option<u64>,
) -> Result<GraphQlResponse<EpochSummaryQuery>, Error> {
let operation = EpochSummaryQuery::build(EpochSummaryArgs {
id: epoch.map(Uint53),
});
let operation = EpochSummaryQuery::build(EpochSummaryArgs { id: epoch });
self.run_query(&operation).await
}

Expand Down Expand Up @@ -567,10 +558,7 @@ impl Client {
address: Address,
version: Option<u64>,
) -> Result<Option<Object>, Error> {
let operation = ObjectQuery::build(ObjectQueryArgs {
address,
version: version.map(Uint53),
});
let operation = ObjectQuery::build(ObjectQueryArgs { address, version });

let response = self.run_query(&operation).await?;

Expand Down Expand Up @@ -861,9 +849,9 @@ mod tests {
let pc = pc.unwrap();
if let Some(pc) = pc {
assert_eq!(
pc.protocol_version.0, 50,
pc.protocol_version, 50,
"Protocol version query mismatch for network: {n}. Expected: 50, received: {}",
pc.protocol_version.0
pc.protocol_version
);
}
}
Expand Down Expand Up @@ -989,6 +977,7 @@ mod tests {
}

#[tokio::test]
#[ignore]
async fn test_objects_query() {
for (n, _) in NETWORKS {
let client = Client::new(n).unwrap();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use crate::query_types::BigInt;
use crate::query_types::GQLAddress;
use crate::query_types::MoveObject;
use crate::query_types::PageInfo;
use crate::query_types::Uint53;

#[derive(cynic::QueryFragment, Debug)]
#[cynic(
Expand All @@ -23,7 +22,7 @@ pub struct ActiveValidatorsQuery {

#[derive(cynic::QueryVariables, Debug)]
pub struct ActiveValidatorsArgs {
pub id: Option<Uint53>,
pub id: Option<u64>,
pub after: Option<String>,
pub before: Option<String>,
pub first: Option<i32>,
Expand Down Expand Up @@ -73,7 +72,7 @@ pub struct Validator {
/// Validator's description.
pub description: Option<String>,
/// Number of exchange rates in the table.
pub exchange_rates_size: Option<Uint53>,
pub exchange_rates_size: Option<u64>,
/// The reference gas price for this epoch.
pub gas_price: Option<BigInt>,
/// Validator's name.
Expand Down Expand Up @@ -106,7 +105,7 @@ pub struct Validator {
/// The epoch stake rewards will be added here at the end of each epoch.
pub rewards_pool: Option<BigInt>,
/// The epoch at which this pool became active.
pub staking_pool_activation_epoch: Option<Uint53>,
pub staking_pool_activation_epoch: Option<u64>,
/// The ID of this validator's `0x3::staking_pool::StakingPool`.
pub staking_pool_id: Address,
/// The total number of SUI tokens in this pool.
Expand Down
15 changes: 6 additions & 9 deletions crates/sui-graphql-client/src/query_types/checkpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use crate::query_types::Base64;
use crate::query_types::BigInt;
use crate::query_types::DateTime;
use crate::query_types::Epoch;
use crate::query_types::Uint53;

// ===========================================================================
// Checkpoint Queries
Expand All @@ -40,7 +39,7 @@ pub struct CheckpointArgs {
#[cynic(schema = "rpc", graphql_type = "CheckpointId")]
pub struct CheckpointId {
pub digest: Option<String>,
pub sequence_number: Option<Uint53>,
pub sequence_number: Option<u64>,
}
// ===========================================================================
// Checkpoint Types
Expand All @@ -51,9 +50,9 @@ pub struct CheckpointId {
pub struct Checkpoint {
pub epoch: Option<Epoch>,
pub digest: String,
pub network_total_transactions: Option<Uint53>,
pub network_total_transactions: Option<u64>,
pub previous_checkpoint_digest: Option<String>,
pub sequence_number: Uint53,
pub sequence_number: u64,
pub timestamp: DateTime,
pub validator_signatures: Base64,
pub rolling_gas_summary: Option<GasCostSummary>,
Expand All @@ -76,13 +75,11 @@ impl TryInto<CheckpointSummary> for Checkpoint {
let epoch = self
.epoch
.ok_or_else(|| Error::msg("Epoch is missing"))?
.epoch_id
.into();
.epoch_id;
let network_total_transactions = self
.network_total_transactions
.ok_or_else(|| Error::msg("Network total transactions is missing"))?
.into();
let sequence_number = self.sequence_number.into();
.ok_or_else(|| Error::msg("Network total transactions is missing"))?;
let sequence_number = self.sequence_number;
let timestamp_ms = ChronoDT::parse_from_rfc3339(&self.timestamp.0)
.map_err(|e| Error::msg(format!("Cannot parse DateTime: {e}")))?
.timestamp_millis()
Expand Down
3 changes: 1 addition & 2 deletions crates/sui-graphql-client/src/query_types/coin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ pub struct CoinMetadataArgs<'a> {

use crate::query_types::schema;
use crate::query_types::BigInt;
use crate::query_types::Uint53;

#[derive(cynic::QueryFragment, Debug)]
#[cynic(schema = "rpc", graphql_type = "CoinMetadata")]
Expand All @@ -38,5 +37,5 @@ pub struct CoinMetadata {
pub name: Option<String>,
pub symbol: Option<String>,
pub supply: Option<BigInt>,
pub version: Uint53,
pub version: u64,
}
17 changes: 8 additions & 9 deletions crates/sui-graphql-client/src/query_types/epoch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use crate::query_types::schema;
use crate::query_types::Address;
use crate::query_types::BigInt;
use crate::query_types::DateTime;
use crate::query_types::Uint53;

// ===========================================================================
// Epoch Queries
Expand All @@ -24,16 +23,16 @@ pub struct EpochSummaryQuery {

#[derive(cynic::QueryVariables, Debug)]
pub struct EpochSummaryArgs {
pub id: Option<Uint53>,
pub id: Option<u64>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(schema = "rpc", graphql_type = "Epoch")]
pub struct EpochSummary {
pub epoch_id: Uint53,
pub epoch_id: u64,
pub reference_gas_price: Option<BigInt>,
pub total_checkpoints: Option<Uint53>,
pub total_transactions: Option<Uint53>,
pub total_checkpoints: Option<u64>,
pub total_transactions: Option<u64>,
}

// ===========================================================================
Expand All @@ -44,20 +43,20 @@ pub struct EpochSummary {
#[cynic(schema = "rpc", graphql_type = "Epoch")]
pub struct Epoch {
pub end_timestamp: Option<DateTime>,
pub epoch_id: Uint53,
pub epoch_id: u64,
pub fund_inflow: Option<BigInt>,
pub fund_outflow: Option<BigInt>,
pub fund_size: Option<BigInt>,
pub live_object_set_digest: Option<String>,
pub net_inflow: Option<BigInt>,
pub reference_gas_price: Option<BigInt>,
pub start_timestamp: DateTime,
pub system_state_version: Option<Uint53>,
pub total_checkpoints: Option<Uint53>,
pub system_state_version: Option<u64>,
pub total_checkpoints: Option<u64>,
pub total_gas_fees: Option<BigInt>,
pub total_stake_rewards: Option<BigInt>,
pub total_stake_subsidies: Option<BigInt>,
pub total_transactions: Option<Uint53>,
pub total_transactions: Option<u64>,
pub validator_set: Option<ValidatorSet>,
}

Expand Down
Loading

0 comments on commit 112bfb3

Please sign in to comment.