-
Notifications
You must be signed in to change notification settings - Fork 527
feat: base sql api query action provider #843
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
gtspencer
wants to merge
4
commits into
coinbase:main
Choose a base branch
from
gtspencer:feat/base-sql-api-query
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
"@coinbase/agentkit": patch | ||
--- | ||
|
||
Added a new action provider to support Base SQL API queries |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
130 changes: 130 additions & 0 deletions
130
typescript/agentkit/src/action-providers/cdp/cdpSqlApiActionProvider.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
import { cdpSqlApiActionProvider } from "./cdpSqlApiActionProvider"; | ||
import { CdpSqlApiSchema } from "./schemas"; | ||
import { CDP_SQL_API_URL } from "./constants"; | ||
|
||
describe("CDP SQL API Action Provider", () => { | ||
let originalFetch: typeof fetch | undefined; | ||
let mockFetch: jest.MockedFunction<typeof fetch>; | ||
|
||
const mockApiKey = "test-token"; | ||
|
||
beforeEach(() => { | ||
process.env.CDP_API_CLIENT_KEY = mockApiKey; | ||
|
||
originalFetch = globalThis.fetch; | ||
mockFetch = jest.fn() as jest.MockedFunction<typeof fetch>; | ||
globalThis.fetch = mockFetch; | ||
}); | ||
|
||
afterEach(() => { | ||
mockFetch.mockReset(); | ||
if (originalFetch) { | ||
globalThis.fetch = originalFetch; | ||
} | ||
delete process.env.CDP_API_CLIENT_KEY; | ||
}); | ||
|
||
it("should throw if no API key is provided", () => { | ||
delete process.env.CDP_API_CLIENT_KEY; | ||
expect(() => cdpSqlApiActionProvider()).toThrow("CDP_API_CLIENT_KEY is not configured."); | ||
}); | ||
|
||
it("should use provided API key from config", () => { | ||
const provider = cdpSqlApiActionProvider({ cdpApiClientKey: "foo" }); | ||
expect(provider).toBeDefined(); | ||
}); | ||
|
||
const provider = cdpSqlApiActionProvider({ cdpApiClientKey: "test-token" }); | ||
|
||
describe("schema validation", () => { | ||
it("validates a correct payload", () => { | ||
const validInput = { sqlQuery: "SELECT 1" }; | ||
const parsed = CdpSqlApiSchema.safeParse(validInput); | ||
expect(parsed.success).toBe(true); | ||
if (parsed.success) { | ||
expect(parsed.data.sqlQuery).toBe("SELECT 1"); | ||
} | ||
}); | ||
|
||
it("rejects an incorrect payload", () => { | ||
const invalidInput = { fieldName: "", amount: "invalid" }; | ||
const parsed = CdpSqlApiSchema.safeParse(invalidInput); | ||
expect(parsed.success).toBe(false); | ||
}); | ||
}); | ||
|
||
describe("executeCdpSqlQuery", () => { | ||
it("POSTs to the CDP SQL API with headers/body and returns the text result", async () => { | ||
const args = { sqlQuery: "SELECT 1" }; | ||
const resultPayload = { columns: ["one"], rows: [[1]] }; | ||
|
||
mockFetch.mockResolvedValue( | ||
new Response(JSON.stringify({ result: resultPayload }), { | ||
status: 200, | ||
headers: { "Content-Type": "application/json" }, | ||
}), | ||
); | ||
|
||
const result = await provider.executeCdpSqlQuery(args); | ||
|
||
expect(mockFetch).toHaveBeenCalledTimes(1); | ||
expect(mockFetch).toHaveBeenCalledWith( | ||
CDP_SQL_API_URL, | ||
expect.objectContaining({ | ||
method: "POST", | ||
headers: expect.objectContaining({ | ||
Authorization: "Bearer test-token", | ||
"Content-Type": "application/json", | ||
Accept: "application/json", | ||
}), | ||
body: JSON.stringify({ sql: args.sqlQuery }), | ||
}), | ||
); | ||
|
||
expect(result).toBe(JSON.stringify(resultPayload)); | ||
}); | ||
|
||
it("returns a readable error string when response.ok is false", async () => { | ||
const args = { sqlQuery: "SELECT * FROM nope" }; | ||
const errorBody = { errorMessage: "Unauthorized" }; | ||
|
||
mockFetch.mockResolvedValue( | ||
new Response(JSON.stringify(errorBody), { | ||
status: 401, | ||
headers: { "Content-Type": "application/json" }, | ||
}), | ||
); | ||
|
||
const result = await provider.executeCdpSqlQuery(args); | ||
|
||
expect(result).toContain("Error 401 executing CDP SQL query:"); | ||
expect(result).toContain("Unauthorized"); | ||
}); | ||
|
||
it("returns a readable error string when fetch throws", async () => { | ||
const args = { sqlQuery: "SELECT * FROM throws" }; | ||
mockFetch.mockRejectedValue(new Error("boom")); | ||
|
||
const result = await provider.executeCdpSqlQuery(args); | ||
expect(result).toBe("Error executing CDP SQL query: Error: boom"); | ||
}); | ||
}); | ||
|
||
describe("supportsNetwork", () => { | ||
it("returns true for base network", () => { | ||
expect( | ||
provider.supportsNetwork({ | ||
protocolFamily: "evm", | ||
networkId: "base-mainnet", | ||
}), | ||
).toBe(true); | ||
|
||
expect( | ||
provider.supportsNetwork({ | ||
protocolFamily: "evm", | ||
networkId: "ethereum-mainnet", | ||
}), | ||
).toBe(false); | ||
}); | ||
}); | ||
}); |
100 changes: 100 additions & 0 deletions
100
typescript/agentkit/src/action-providers/cdp/cdpSqlApiActionProvider.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
import { z } from "zod"; | ||
import { ActionProvider } from "../actionProvider"; | ||
import { Network } from "../../network"; | ||
import { CreateAction } from "../actionDecorator"; | ||
import { EvmWalletProvider } from "../../wallet-providers"; | ||
import { CdpSqlApiSchema } from "./schemas"; | ||
import { description } from "./cdpSqlApiDescription"; | ||
import { CDP_SQL_API_URL } from "./constants"; | ||
|
||
/** | ||
* Configuration options for the CdpSqlApiActionProvider. | ||
*/ | ||
export interface CdpSqlApiActionProviderConfig { | ||
/** | ||
* CDP Client API Key. Request new at https://portal.cdp.coinbase.com/projects/api-keys/client-key/ | ||
*/ | ||
cdpApiClientKey?: string; | ||
} | ||
|
||
/** | ||
* CdpSqlApiActionProvider provides actions for cdpSqlApi operations. | ||
* | ||
* @description | ||
* This provider supports SQL querying on the Base Sepolia Base network. | ||
*/ | ||
export class CdpSqlApiActionProvider extends ActionProvider<EvmWalletProvider> { | ||
private readonly cdpApiClientKey: string; | ||
|
||
/** | ||
* Constructor for the CdpSqlApiActionProvider. | ||
* | ||
* @param config - The configuration options for the CdpSqlApiActionProvider. | ||
*/ | ||
constructor(config: CdpSqlApiActionProviderConfig = {}) { | ||
super("cdpSqlApi", []); | ||
|
||
const cdpApiClientKey = config.cdpApiClientKey || process.env.CDP_API_CLIENT_KEY; | ||
if (!cdpApiClientKey) { | ||
throw new Error("CDP_API_CLIENT_KEY is not configured."); | ||
} | ||
this.cdpApiClientKey = cdpApiClientKey; | ||
} | ||
|
||
/** | ||
* CDP SQL API action provider | ||
* | ||
* @description | ||
* This action queries the Coinbase SQL API endpoint to efficiently retrieve onchain data on Base or Base Sepolia. | ||
* | ||
* @param args - Arguments defined by CdpSqlApiSchema, i.e. the SQL query to execute | ||
* @returns A promise that resolves to a string describing the query result | ||
*/ | ||
@CreateAction({ | ||
name: "execute_cdp_sql_query", | ||
description, | ||
schema: CdpSqlApiSchema, | ||
}) | ||
async executeCdpSqlQuery(args: z.infer<typeof CdpSqlApiSchema>): Promise<string> { | ||
try { | ||
const response = await fetch(CDP_SQL_API_URL, { | ||
method: "POST", | ||
headers: { | ||
Authorization: `Bearer ${this.cdpApiClientKey}`, | ||
"Content-Type": "application/json", | ||
Accept: "application/json", | ||
}, | ||
body: JSON.stringify({ sql: args.sqlQuery }), | ||
}); | ||
|
||
if (!response.ok) { | ||
const errorData = await response.json(); | ||
return `Error ${response.status} executing CDP SQL query: ${errorData.errorMessage || response.statusText}`; | ||
} | ||
|
||
const data = await response.json(); | ||
return JSON.stringify(data.result); | ||
} catch (error) { | ||
return `Error executing CDP SQL query: ${error}`; | ||
} | ||
} | ||
|
||
/** | ||
* Checks if this provider supports the given network. | ||
* | ||
* @param network - The network to check support for | ||
* @returns True if the network is supported | ||
*/ | ||
supportsNetwork(network: Network): boolean { | ||
return network.networkId === "base-mainnet" || network.networkId === "base-sepolia"; | ||
} | ||
} | ||
|
||
/** | ||
* Factory function to create a new CdpSqlApiActionProvider instance. | ||
* | ||
* @param config - the config of the cdp sql api action provider, contains the cdp client api key | ||
* @returns A new CdpSqlApiActionProvider instance | ||
*/ | ||
export const cdpSqlApiActionProvider = (config?: CdpSqlApiActionProviderConfig) => | ||
new CdpSqlApiActionProvider(config); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
baseSqlApiDescription -> cdpSqlApiDescription