Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion crates/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1998,7 +1998,21 @@ qn.kvstore.delete_list("my-list").await?;

### SQL Client

Accessed as `qn.sql`. Runs SQL queries against indexed blockchain data and fetches the database schema. Backed by `https://api.quicknode.com/sql/rest/v1/`.
Accessed as `qn.sql`. Lists the available clusters, runs SQL queries against indexed blockchain data, and fetches the database schema. Backed by `https://api.quicknode.com/sql/rest/v1/`.

##### `list_clusters`

Lists the clusters available to query. Pass a cluster's `id` as the `cluster_id` for `query` and `get_schema`.

**Parameters**: none.

**Returns**: `Vec<SqlCluster>`, each with `id` and `display_name`.

```rust
// Rust
let clusters = qn.sql.list_clusters().await?;
println!("{:?}", clusters.iter().map(|c| &c.id).collect::<Vec<_>>());
```

##### `query`

Expand Down
18 changes: 18 additions & 0 deletions crates/core/examples/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,24 @@ async fn main() {
let config = SdkFullConfig::from_env().expect("Config from env failed");
let qn = QuicknodeSdk::new(&config).expect("sdk failed to initialize");

// ── Clusters ──────────────────────────────────────────────────────────────

let clusters = qn.sql.list_clusters().await.expect("list_clusters failed");
println!(
"clusters: {:?}",
clusters.iter().map(|c| &c.id).collect::<Vec<_>>()
);
assert!(
clusters
.iter()
.all(|c| !c.id.is_empty() && !c.display_name.is_empty()),
"every cluster has an id and a display name"
);
assert!(
clusters.iter().any(|c| c.id == CLUSTER_ID),
"{CLUSTER_ID} is in the cluster list"
);

// ── Query ─────────────────────────────────────────────────────────────────

let params = QueryParams {
Expand Down
7 changes: 4 additions & 3 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub use rpc::{
pub use rpc::{ChannelState, ChannelStatus};
pub use sql::{
ChainSchema, ColumnMeta, ColumnSchema, QueryParams, QueryResponse, QueryStatistics,
SqlApiClient, TableSchema,
SqlApiClient, SqlCluster, TableSchema,
};

use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
Expand Down Expand Up @@ -285,8 +285,9 @@ pub struct QuicknodeSdk {
/// Key-Value Store client: manages sets (single values) and lists
/// (ordered collections) under string keys.
pub kvstore: kvstore::KvStoreApiClient,
/// SQL Explorer client: executes SQL queries against indexed blockchain
/// data and fetches the database schema.
/// SQL Explorer client: lists the available clusters, executes SQL
/// queries against indexed blockchain data, and fetches the database
/// schema.
pub sql: sql::SqlApiClient,
/// JSON-RPC client: makes on-chain calls against the account's Tooling
/// Access endpoint using short-lived session JWTs.
Expand Down
99 changes: 96 additions & 3 deletions crates/core/src/sql/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,31 @@ impl ResolvedSqlConfig {
}
}

// ── Catalog types ──────────────────────────────────────────────────────────

/// A cluster that SQL queries can target, as returned by `list_clusters`.
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SqlCluster {
/// Cluster identifier (e.g. `"hyperliquid-core-mainnet"`); pass it as
/// `cluster_id` to `query` and `get_schema`.
pub id: String,
/// Human-readable name (e.g. `"Hyperliquid (HyperCore)"`).
pub display_name: String,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl SqlCluster {
#[new]
pub fn new(id: String, display_name: String) -> Self {
Self { id, display_name }
}
}

// ── Request types ──────────────────────────────────────────────────────────

/// Parameters for `query`.
Expand Down Expand Up @@ -232,8 +257,9 @@ impl ChainSchema {

// ── Client ─────────────────────────────────────────────────────────────────

/// Client for the Quicknode SQL Explorer. Executes SQL queries against indexed
/// blockchain data and fetches the database schema.
/// Client for the Quicknode SQL Explorer. Lists the available clusters,
/// executes SQL queries against indexed blockchain data, and fetches the
/// database schema.
#[derive(Debug, Clone)]
pub struct SqlApiClient {
config: SdkConfig,
Expand All @@ -244,6 +270,24 @@ impl SqlApiClient {
Self { config }
}

/// Lists the clusters available to query.
pub async fn list_clusters(&self) -> Result<Vec<SqlCluster>, SdkError> {
let url = self.config.sql().base_url.join("clusters")?;
let resp = self
.config
.http_client()
.get(url)
.send()
.await
.map_err(SdkError::Http)?;
let status = resp.status();
let body = resp.text().await.map_err(SdkError::Http)?;
if !status.is_success() {
return Err(SdkError::Api { status, body });
}
serde_json::from_str(&body).map_err(|source| SdkError::Decode { source, body })
}

/// Executes a SQL query against the given cluster and returns the result
/// set.
pub async fn query(&self, params: &QueryParams) -> Result<QueryResponse, SdkError> {
Expand Down Expand Up @@ -295,7 +339,7 @@ impl SqlApiClient {
mod tests {
use super::*;
use crate::{QuicknodeSdk, SdkFullConfig, SqlConfig};
use wiremock::matchers::{body_json, method, path};
use wiremock::matchers::{body_json, header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

fn make_sdk(base_url: String) -> QuicknodeSdk {
Expand All @@ -321,6 +365,55 @@ mod tests {
}
}

// ── list_clusters ────────────────────────────────────────────────────────

#[tokio::test]
async fn list_clusters_success() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/clusters"))
.and(header("x-api-key", "test-key"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
{"id": "hyperliquid-core-mainnet", "display_name": "Hyperliquid (HyperCore)"},
{"id": "solana-mainnet", "display_name": "Solana"}
])))
.mount(&server)
.await;
let sdk = make_sdk(format!("{}/", server.uri()));
let clusters = sdk.sql.list_clusters().await.unwrap();
assert_eq!(clusters.len(), 2);
assert_eq!(clusters[0].id, "hyperliquid-core-mainnet");
assert_eq!(clusters[0].display_name, "Hyperliquid (HyperCore)");
assert_eq!(clusters[1].id, "solana-mainnet");
assert_eq!(clusters[1].display_name, "Solana");
}

#[tokio::test]
async fn list_clusters_api_error() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/clusters"))
.respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
.mount(&server)
.await;
let sdk = make_sdk(format!("{}/", server.uri()));
let err = sdk.sql.list_clusters().await.unwrap_err();
assert!(matches!(err, SdkError::Api { .. }));
}

#[tokio::test]
async fn list_clusters_decode_error() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/clusters"))
.respond_with(ResponseTemplate::new(200).set_body_string("not json"))
.mount(&server)
.await;
let sdk = make_sdk(format!("{}/", server.uri()));
let err = sdk.sql.list_clusters().await.unwrap_err();
assert!(matches!(err, SdkError::Decode { .. }));
}

// ── query ──────────────────────────────────────────────────────────────

#[tokio::test]
Expand Down
9 changes: 9 additions & 0 deletions crates/node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1923,6 +1923,15 @@ pub struct SqlApiClient {

#[napi]
impl SqlApiClient {
/// Lists the clusters available to query.
#[napi]
pub async fn list_clusters(&self) -> Result<Vec<core::sql::SqlCluster>> {
self.inner
.list_clusters()
.await
.map_err(errors::map_sdk_err)
}

/// Executes a SQL query against the given cluster and returns the result set.
#[napi]
pub async fn query(&self, query: String, cluster_id: String) -> Result<sql::QueryResponseNode> {
Expand Down
12 changes: 12 additions & 0 deletions crates/python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3349,6 +3349,17 @@ pub struct SqlApiClient {
#[gen_stub_pymethods]
#[pymethods]
impl SqlApiClient {
/// Lists the clusters available to query.
#[gen_stub(override_return_type(
type_repr = "typing.Coroutine[typing.Any, typing.Any, list[SqlCluster]]"
))]
fn list_clusters<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let client = self.inner.clone();
pyo3_async_runtimes::tokio::future_into_py(py, async move {
client.list_clusters().await.map_err(errors::map_sdk_err)
})
}

/// Executes a SQL query against the given cluster and returns the result
/// set.
#[pyo3(signature = (query, cluster_id))]
Expand Down Expand Up @@ -4230,6 +4241,7 @@ fn _core(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<core::kvstore::ListContainsItemResponse>()?;
// sql
m.add_class::<SqlApiClient>()?;
m.add_class::<core::sql::SqlCluster>()?;
m.add_class::<sql::PyQueryResponse>()?;
m.add_class::<core::sql::ColumnMeta>()?;
m.add_class::<core::sql::QueryStatistics>()?;
Expand Down
9 changes: 9 additions & 0 deletions crates/ruby/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2494,6 +2494,14 @@ pub struct SqlApiClient {

#[allow(clippy::needless_pass_by_value)]
impl SqlApiClient {
fn list_clusters(&self) -> Result<magnus::Value, Error> {
let client = self.inner.clone();
runtime()
.block_on(client.list_clusters())
.map_err(map_err)
.and_then(to_ruby)
}

fn query(&self, opts: RHash) -> Result<magnus::Value, Error> {
validate_keys(&opts, &["query", "cluster_id"])?;
let client = self.inner.clone();
Expand Down Expand Up @@ -3341,6 +3349,7 @@ fn init(ruby: &Ruby) -> Result<(), Error> {

// ── Sql ───────────────────────────────────────────────────
let sql = native.define_class("Sql", ruby.class_object())?;
sql.define_method("list_clusters", method!(SqlApiClient::list_clusters, 0))?;
sql.define_method("query", method!(SqlApiClient::query, 1))?;
sql.define_method("get_schema", method!(SqlApiClient::get_schema, 1))?;

Expand Down
16 changes: 15 additions & 1 deletion npm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1839,7 +1839,21 @@ await qn.kvstore.deleteList("my-list");

### SQL Client

Accessed as `qn.sql`. Runs SQL queries against indexed blockchain data and fetches the database schema. Backed by `https://api.quicknode.com/sql/rest/v1/`.
Accessed as `qn.sql`. Lists the available clusters, runs SQL queries against indexed blockchain data, and fetches the database schema. Backed by `https://api.quicknode.com/sql/rest/v1/`.

##### `list_clusters` / `listClusters`

Lists the clusters available to query. Pass a cluster's `id` as the `cluster_id` / `clusterId` for `query` and `getSchema`.

**Parameters**: none.

**Returns**: an array of `SqlCluster`, each with `id` and `display_name` / `displayName`.

```typescript
// Node.js
const clusters = await qn.sql.listClusters();
console.log(clusters.map((c) => c.id));
```

##### `query`

Expand Down
10 changes: 10 additions & 0 deletions npm/examples/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ const CLUSTER_ID = "hyperliquid-core-mainnet";
async function main() {
const qn = QuicknodeSdk.fromEnv();

// Clusters
const clusters = await qn.sql.listClusters();
console.log(`clusters: ${clusters.map((c) => c.id).join(", ")}`);
if (!clusters.every((c) => c.id && c.displayName)) {
throw new Error("every cluster must have an id and a displayName");
}
if (!clusters.some((c) => c.id === CLUSTER_ID)) {
throw new Error(`${CLUSTER_ID} not in cluster list`);
}

// Query
const resp = await qn.sql.query(
"SELECT toDateTime(block_time) AS time, action_type, user " +
Expand Down
18 changes: 16 additions & 2 deletions npm/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2337,6 +2337,17 @@ export interface SolanaWalletFilterTemplate {
accounts: Array<string>
}

/** A cluster that SQL queries can target, as returned by `list_clusters`. */
export interface SqlCluster {
/**
* Cluster identifier (e.g. `"hyperliquid-core-mainnet"`); pass it as
* `cluster_id` to `query` and `get_schema`.
*/
id: string
/** Human-readable name (e.g. `"Hyperliquid (HyperCore)"`). */
displayName: string
}

export interface SqlConfig {
baseUrl?: string
}
Expand Down Expand Up @@ -3647,8 +3658,9 @@ export declare class RpcApiClient {
gatewayBuyCredits(session: any, network: string): Promise<any>
/**
* Requests testnet tokens from the x402 faucet. Resolves to the funding
* transaction `{ accountId, transactionHash }` — NOT a balance; call
* `gatewayCredits` afterwards for that. Allowed once per account.
* transfer metadata containing either `transferId` or `transactionHash`.
* The former is asynchronous Circle settlement; the latter is a direct
* on-chain transfer. This is not a balance; call `gatewayCredits` for that.
*/
gatewayDrip(session: any): Promise<any>
/**
Expand Down Expand Up @@ -3698,6 +3710,8 @@ export declare class RpcApiClient {
}

export declare class SqlApiClient {
/** Lists the clusters available to query. */
listClusters(): Promise<Array<SqlCluster>>
/** Executes a SQL query against the given cluster and returns the result set. */
query(query: string, clusterId: string): Promise<QueryResponseNode>
/**
Expand Down
3 changes: 3 additions & 0 deletions npm/sdk.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
HyperliquidWalletEventsFilterTemplate,
StellarWalletTransactionsFilterTemplate,
RpcApiClient,
SqlCluster,
} from "./index";

// Stream destination attributes (input). The inner key is `attributes` rather
Expand Down Expand Up @@ -410,6 +411,7 @@ export type {
// sql
SqlConfig,
SqlApiClient,
SqlCluster,
QueryResponseNode,
ColumnMetaNode,
QueryStatisticsNode,
Expand Down Expand Up @@ -572,6 +574,7 @@ export interface QueryResult extends Omit<QueryResponseNode, "data"> {
}

export interface SqlApiClientTyped {
listClusters(): Promise<SqlCluster[]>;
query(query: string, clusterId: string): Promise<QueryResult>;
getSchema(clusterId: string): Promise<ChainSchemaNode>;
}
Expand Down
16 changes: 15 additions & 1 deletion python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1834,7 +1834,21 @@ await qn.kvstore.delete_list("my-list")

### SQL Client

Accessed as `qn.sql`. Runs SQL queries against indexed blockchain data and fetches the database schema. Backed by `https://api.quicknode.com/sql/rest/v1/`.
Accessed as `qn.sql`. Lists the available clusters, runs SQL queries against indexed blockchain data, and fetches the database schema. Backed by `https://api.quicknode.com/sql/rest/v1/`.

##### `list_clusters`

Lists the clusters available to query. Pass a cluster's `id` as the `cluster_id` for `query` and `get_schema`.

**Parameters**: none.

**Returns**: `list[SqlCluster]`, each with `id` and `display_name`.

```python
# Python
clusters = await qn.sql.list_clusters()
print([c.id for c in clusters])
```

##### `query`

Expand Down
Loading
Loading