> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cow.bleu.builders/llms.txt
> Use this file to discover all available pages before exploring further.

# Subgraph SDK

> TypeScript client for querying CoW Protocol's historical trading data and metrics from TheGraph

The SubgraphApi provides a TypeScript client for querying historical trading data, volume statistics, and protocol metrics from CoW Protocol subgraphs across multiple chains.

## Installation

```shellscript theme={null}
npm install @cowprotocol/sdk-subgraph
# or
pnpm add @cowprotocol/sdk-subgraph
# or
yarn add @cowprotocol/sdk-subgraph
```

## Features

* **SubgraphApi Client** - Dedicated client for subgraph querying
* **Pre-built Queries** - Common queries for protocol statistics
* **Multi-chain Support** - Currently available on Ethereum, Gnosis Chain, Arbitrum One, Base, and Sepolia (subset of all supported CoW Protocol chains)
* **Type-safe Responses** - All GraphQL responses are fully typed
* **Custom Query Support** - Execute custom GraphQL queries with type safety

## Constructor

```typescript theme={null}
new SubgraphApi(apiKey: string, options?: SubgraphApiOptions)
```

<ResponseField name="apiKey" type="string" required>
  API key from [TheGraph Studio](https://thegraph.com/studio/)
</ResponseField>

<ResponseField name="options" type="SubgraphApiOptions">
  Optional configuration

  <Expandable>
    <ResponseField name="chainId" type="SupportedChainId">
      Chain ID for queries (defaults to Mainnet)
    </ResponseField>
  </Expandable>
</ResponseField>

## Methods

### getTotals

Get overall protocol statistics including tokens, orders, traders, settlements, volume, and fees.

```typescript theme={null}
const subgraphApi = new SubgraphApi('YOUR_GRAPH_API_KEY')

const totals = await subgraphApi.getTotals()
console.log('Total tokens:', totals.tokens)
console.log('Total orders:', totals.orders)
console.log('Total volume USD:', totals.volumeUsd)
console.log('Total fees USD:', totals.feesUsd)
```

<ResponseField name="tokens" type="string">
  Total number of unique tokens traded
</ResponseField>

<ResponseField name="orders" type="string">
  Total number of orders placed
</ResponseField>

<ResponseField name="traders" type="string">
  Total number of unique traders
</ResponseField>

<ResponseField name="settlements" type="string">
  Total number of settlements
</ResponseField>

<ResponseField name="volumeUsd" type="string">
  Total trading volume in USD
</ResponseField>

<ResponseField name="feesUsd" type="string">
  Total fees collected in USD
</ResponseField>

### getLastDaysVolume

Get historical volume data for a specified number of days.

<ResponseField name="days" type="number" required>
  Number of days to query (e.g., 7, 30)
</ResponseField>

```typescript theme={null}
const last7DaysVolume = await subgraphApi.getLastDaysVolume(7)
console.log('Daily volumes:', last7DaysVolume.dailyTotals)
```

<ResponseField name="dailyTotals" type="DailyTotal[]">
  Array of daily volume totals

  <Expandable>
    <ResponseField name="timestamp" type="string">
      Day timestamp
    </ResponseField>

    <ResponseField name="volumeUsd" type="string">
      Volume in USD for the day
    </ResponseField>

    <ResponseField name="trades" type="string">
      Number of trades
    </ResponseField>
  </Expandable>
</ResponseField>

### getLastHoursVolume

Get historical volume data for a specified number of hours.

<ResponseField name="hours" type="number" required>
  Number of hours to query (e.g., 24, 48)
</ResponseField>

```typescript theme={null}
const last24HoursVolume = await subgraphApi.getLastHoursVolume(24)
console.log('Hourly volumes:', last24HoursVolume.hourlyTotals)
```

<ResponseField name="hourlyTotals" type="HourlyTotal[]">
  Array of hourly volume totals

  <Expandable>
    <ResponseField name="timestamp" type="string">
      Hour timestamp
    </ResponseField>

    <ResponseField name="volumeUsd" type="string">
      Volume in USD for the hour
    </ResponseField>

    <ResponseField name="trades" type="string">
      Number of trades
    </ResponseField>
  </Expandable>
</ResponseField>

### runQuery

Execute a custom GraphQL query with full type safety.

<ResponseField name="query" type="string | DocumentNode" required>
  GraphQL query string or parsed DocumentNode
</ResponseField>

<ResponseField name="variables" type="object">
  Optional query variables
</ResponseField>

```typescript theme={null}
import { gql } from 'graphql-request'

const query = gql`
  query TokensByVolume {
    tokens(first: 5, orderBy: totalVolumeUsd, orderDirection: desc) {
      address
      symbol
      totalVolumeUsd
      priceUsd
    }
  }
`

const result = await subgraphApi.runQuery(query)
console.log('Top tokens:', result.tokens)
```

## Usage Examples

### Basic Setup

```typescript theme={null}
import { SubgraphApi } from '@cowprotocol/sdk-subgraph'
import { SupportedChainId } from '@cowprotocol/sdk-config'

// Initialize with your API key
const subgraphApi = new SubgraphApi('YOUR_GRAPH_API_KEY')

// Configure for specific chain
const mainnetApi = new SubgraphApi('YOUR_GRAPH_API_KEY', {
  chainId: SupportedChainId.MAINNET,
})
```

### Query Protocol Metrics

```typescript theme={null}
// Get overall protocol stats
const totals = await subgraphApi.getTotals()

console.log(`Total Trading Volume: $${totals.volumeUsd}`)
console.log(`Total Orders: ${totals.orders}`)
console.log(`Unique Traders: ${totals.traders}`)
console.log(`Total Settlements: ${totals.settlements}`)
```

### Query Historical Data

```typescript theme={null}
// Last 7 days volume
const weeklyData = await subgraphApi.getLastDaysVolume(7)

weeklyData.dailyTotals.forEach(day => {
  console.log(`${day.timestamp}: $${day.volumeUsd} (${day.trades} trades)`)
})

// Last 24 hours volume
const dailyData = await subgraphApi.getLastHoursVolume(24)

dailyData.hourlyTotals.forEach(hour => {
  console.log(`${hour.timestamp}: $${hour.volumeUsd}`)
})
```

### Custom Queries

```typescript theme={null}
import { gql } from 'graphql-request'

// Query top traders by volume
const topTradersQuery = gql`
  query TopTraders($first: Int!) {
    users(first: $first, orderBy: volumeUsd, orderDirection: desc) {
      address
      volumeUsd
      numberOfTrades
      solvedAmountUsd
    }
  }
`

const result = await subgraphApi.runQuery(topTradersQuery, { first: 10 })

result.users.forEach(user => {
  console.log(`${user.address}: $${user.volumeUsd} volume`)
})
```

### Multi-Chain Queries

```typescript theme={null}
import { SubgraphApi } from '@cowprotocol/sdk-subgraph'
import { SupportedChainId } from '@cowprotocol/sdk-config'

const chains = [
  SupportedChainId.MAINNET,
  SupportedChainId.GNOSIS_CHAIN,
  SupportedChainId.ARBITRUM_ONE,
]

const apiKey = 'YOUR_GRAPH_API_KEY'

// Query multiple chains
const results = await Promise.all(
  chains.map(async chainId => {
    const api = new SubgraphApi(apiKey, { chainId })
    const totals = await api.getTotals()
    return { chainId, totals }
  })
)

results.forEach(({ chainId, totals }) => {
  console.log(`Chain ${chainId}: $${totals.volumeUsd} volume`)
})
```

## Supported Chains

The SubgraphApi currently supports the following networks (a subset of the full CoW Protocol chain list):

* Ethereum Mainnet
* Gnosis Chain
* Arbitrum One
* Base
* Sepolia Testnet

## API Key Requirements

To use this package, you need a Graph API key from [TheGraph Studio](https://thegraph.com/studio/).

<Warning>
  Keep your API key secure and never expose it in client-side code. Consider using environment variables.
</Warning>

## Related APIs

* [TradingSdk](/cow-sdk/api/trading-sdk)
* [OrderBookApi](/cow-sdk/api/order-book-api)
* [Config](/cow-sdk/api/config)
