Skip to main content

IotaGraphQLClient

warning

IotaGraphQLClient is still in development and may change rapidly as it is being developed.

To support GraphQL Queries, the Typescript SDK includes the IotaGraphQLClient which can help you write and execute GraphQL queries against the Iota GraphQL API that are type-safe and easy to use.

Writing your first query

We'll start by creating our client, and executing a very basic query:

import { IotaGraphQLClient } from '@iota/iota-sdk/graphql';
import { graphql } from '@iota/iota-sdk/graphql/schemas/2024.4';

const gqlClient = new IotaGraphQLClient({
url: 'https://graphql.testnet.iota.cafe/',
});

const chainIdentifierQuery = graphql(`
query {
chainIdentifier
}
`);

async function getChainIdentifier() {
const result = await gqlClient.query({
query: chainIdentifierQuery,
});

return result.data?.chainIdentifier;
}

Type-safety for GraphQL queries

You may have noticed the example above does not include any type definitions for the query. The graphql function used in the example is powered by gql.tada and will automatically provide the required type information to ensure that your queries are properly typed when executed through IotaGraphQLClient.

The graphql function itself is imported from a versioned schema file, and you should ensure that you are using the version that corresponds to the latest release of the GraphQL API.

The graphql also detects variables used by your query, and will ensure that the variables passed to your query are properly typed.

const queryTransactionBalanceChanges = graphql(`
query ($address: IOTAAddress!) {
transactionBlocks(filter: {
function: "0x3::iota_system::request_add_stake"
signAddress: $address
}) {
nodes {
digest
effects {
balanceChanges {
nodes {
owner {
address
}
amount
}
}
}
}
}
}
`);

async function getTransactionBalanceChanges(address: string) {
const result = await gqlClient.query({
query: queryTransactionBalanceChanges,
variables: {
address,
},
});

return result.data?.address?.defaultIotansName;
}

Using typed GraphQL queries with other GraphQL clients

The graphql function returns document nodes that implement the TypedDocumentNode standard, and will work with the majority of popular GraphQL clients to provide queries that are automatically typed.

import { useQuery } from '@apollo/client';

const chainIdentifierQuery = graphql(`
query {
chainIdentifier
}
`);

function ChainIdentifier() {
const { loading, error, data } = useQuery(getPokemonsQuery);

return <div>{data?.chainIdentifier}</div>;
}