SDK 子图
测试覆盖率
| 发言 | 分支 | 职能 | 行数 |
|---|---|---|---|
这个软件包提供了一个TypeScript客户端,用于从TheGraph子图查询CoW协议数据. 它为跨越多条链获取历史交易数据、量统计和其他协议计量提供了简单而安全的方式.
包括什么
- 子图Api 客户端 - 查询CoW协议子图的主要客户端
- 预建查询 - 对总数、数量和统计的共同查询
- 多链支持 - 支持埃特鲁姆、克诺斯链、阿比特鲁姆、基地和塞波利亚
- 类型安全对策 - 完整输入的图表QL回复
- 自定义查询支持 - 在全类型安全的情况下运行任何 GraphQL 查询
安装
npm install @cowprotocol/sdk-subgraph
or
pnpm add @cowprotocol/sdk-subgraph
or
yarn add @cowprotocol/sdk-subgraph
使用量
基本设置
你需要来自TheGraph的图形API密钥. 来一个 格拉夫工作室。 。 。 .
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')
// Optionally configure for specific chain
const mainnetApi = new SubgraphApi('YOUR_GRAPH_API_KEY', {
chainId: SupportedChainId.MAINNET,
})
查询协议总计
获得协议总统计数据,包括信物、订单、交易商、结算、数量和收费.
import { SubgraphApi } from '@cowprotocol/sdk-subgraph'
const subgraphApi = new SubgraphApi('YOUR_GRAPH_API_KEY')
// Get protocol totals
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)
查询卷数据
获取特定时间段的历史量数据.
// Get volume for last 7 days
const last7DaysVolume = await subgraphApi.getLastDaysVolume(7)
console.log('Daily volumes:', last7DaysVolume.dailyTotals)
// Get volume for last 24 hours
const last24HoursVolume = await subgraphApi.getLastHoursVolume(24)
console.log('Hourly volumes:', last24HoursVolume.hourlyTotals)
自定义查询
以全类型安全运行任何 GraphQL 查询 .
import { gql } from 'graphql-request'
// Custom query for top tokens by volume
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)
测试
运行测试
# Run all tests
pnpm test
# Run tests in watch mode
pnpm run test:watch
# Run tests with coverage
pnpm run test:coverage
测试配置
测试使用 jest-fetch-mock 以模拟 GraphQL 回复。 测试不需要私钥,因为所有API的通话都被嘲笑.
// Example test structure
import { SubgraphApi } from '@cowprotocol/sdk-subgraph'
import fetchMock from 'jest-fetch-mock'
describe('SubgraphApi', () => {
beforeEach(() => {
fetchMock.resetMocks()
})
test('should get totals', async () => {
fetchMock.mockResponseOnce(
JSON.stringify({
data: {
totals: [
{
tokens: '192',
orders: '365210',
volumeUsd: '49548634.23',
},
],
},
}),
)
const api = new SubgraphApi('FakeApiKey')
const totals = await api.getTotals()
expect(totals.tokens).toBe('192')
})
})
API 密钥要求
要使用此软件包, 您需要来自 TheGraph 的图形 API 密钥 :
- 转到 格拉夫工作室
- 创建新的 API 密钥
- 初始化子图时使用 API 键
const subgraphApi = new SubgraphApi('your-api-key-here')
说明: 所有子图查询都需要 API 键. 确保您的 API 密钥安全, 并且永远不要在客户端代码中曝光 .