### Install Dune Client SDK Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/00-INDEX.md Install the Dune Client SDK using npm. This command is required before using the SDK in your project. ```bash npm install @duneanalytics/client-sdk ``` -------------------------------- ### Install Dune Client TS Package Source: https://github.com/duneanalytics/ts-dune-client/blob/main/README.md Install the client SDK using pnpm. Ensure you have Node.js and pnpm installed. ```sh pnpm add @duneanalytics/client-sdk ``` -------------------------------- ### Complete Real-World Example with Dune Client SDK Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/12-examples.md This example demonstrates a full workflow for interacting with the Dune API using the client SDK. It covers checking usage, creating, executing, and polling for query results, paginating through data, downloading as CSV, and publishing a query. Ensure you have your DUNE_API_KEY set as an environment variable. ```typescript import { DuneClient, QueryParameter, QueryEngine, ExecutionState, Paginator } from "@duneanalytics/client-sdk"; const client = new DuneClient(process.env.DUNE_API_KEY || ""); async function completeExample() { try { // 1. Check usage console.log("=== Checking API Usage ==="); const usage = await client.usage.getUsage(); const creditsRemaining = usage.billing_periods[0].credits_included - usage.billing_periods[0].credits_used; if (creditsRemaining < 100) { throw new Error("Insufficient credits"); } console.log(`Credits available: ${creditsRemaining}`); // 2. Create a query console.log("\n=== Creating Query ==="); const queryId = await client.query.createQuery({ name: "Ethereum DEX Trades Analysis", description: "Analyze DEX trading patterns", query_sql: "\n SELECT\n block_time,\n token_bought,\n token_sold,\n amount_bought,\n amount_sold,\n usd_amount\n FROM dex.trades\n WHERE block_time > now() - interval '{{days}}' days\n AND usd_amount > {{min_amount}}\n ORDER BY block_time DESC\n ", query_parameters: [ QueryParameter.text("days", "7"), QueryParameter.number("min_amount", 1000), ], is_private: true, }); console.log(`Created query: ${queryId}`); // 3. Execute the query console.log("\n=== Executing Query ==="); const execution = await client.exec.executeQuery(queryId, { query_parameters: [ QueryParameter.text("days", "7"), QueryParameter.number("min_amount", 1000), ], performance: QueryEngine.Large, }); console.log(`Execution started: ${execution.execution_id}`); // 4. Wait for completion with polling console.log("\n=== Polling for Results ==="); let status = await client.exec.getExecutionStatus(execution.execution_id); let pollCount = 0; while (!["QUERY_STATE_COMPLETED", "QUERY_STATE_FAILED", "QUERY_STATE_EXPIRED"] .includes(status.state)) { pollCount++; console.log(`Poll ${pollCount}: ${status.state}`); if (status.queue_position !== null && status.queue_position !== undefined) { console.log(` Queue position: ${status.queue_position}`); } await new Promise(resolve => setTimeout(resolve, 1000)); status = await client.exec.getExecutionStatus(execution.execution_id); } console.log(`Final state: ${status.state}`); if (status.state !== ExecutionState.COMPLETED) { throw new Error(`Execution failed with state: ${status.state}`); } // 5. Paginate through results console.log("\n=== Processing Results ==="); const paginator = await Paginator.new(client.exec, status, 5000); console.log(`Total rows: ${paginator.totalRows}`); let rowCount = 0; let currentPage = paginator.getCurrentPageValues(); console.log(`Page ${currentPage.number}: Processing ${currentPage.values.length} rows`); rowCount += currentPage.values.length; // Process page... while (currentPage.number < paginator.maxPage()) { const next = await paginator.nextPage(); if (!next) break; console.log(`Page ${next.number}: Processing ${next.values.length} rows`); rowCount += next.values.length; currentPage = next; } console.log(`Total rows processed: ${rowCount}`); // 6. Download results as CSV console.log("\n=== Downloading CSV ==="); await client.downloadCSV( { queryId }, "./dex_trades_analysis.csv" ); console.log("CSV saved to ./dex_trades_analysis.csv"); // 7. Make query public for sharing console.log("\n=== Publishing Query ==="); await client.query.makePublic(queryId); console.log("Query is now public"); console.log("\nāœ… Complete example finished successfully"); } catch (error) { console.error("āŒ Error:", error instanceof Error ? error.message : error); process.exit(1); } } completeExample(); ``` -------------------------------- ### List Datasets Response Example Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/11-API-endpoints.md This is an example of the JSON response when listing datasets. It includes dataset details such as full name, type, columns, owner, and creation/update timestamps. ```json { "datasets": [ { "full_name": "ethereum.transactions", "type": "decoded_table", "columns": [ { "name": "block_time", "type": "timestamp" } ], "owner": { "handle": "dune", "type": "team" }, "is_private": false, "created_at": "2023-01-01T00:00:00Z", "updated_at": "2024-01-15T10:00:00Z" } ], "total": 1000 } ``` -------------------------------- ### Complete Data Management Example Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/05-DataUploadAPIs.md This comprehensive example demonstrates the full lifecycle of data management using the Dune Client SDK. It covers creating a table, inserting data via CSV and JSON, listing tables, running a query, and finally clearing and deleting the table. Ensure you have your API key and necessary imports. ```typescript import { DuneClient, ColumnType, ContentType } from "@duneanalytics/client-sdk"; import * as fs from "fs/promises"; const client = new DuneClient(apiKey); try { // Step 1: Create a table with schema const tableResult = await client.uploads.create({ namespace: "my_user", table_name: "token_holders", description: "Token holder snapshots", schema: [ { name: "token_address", type: ColumnType.Varchar, nullable: false }, { name: "holder_address", type: ColumnType.Varchar, nullable: false }, { name: "balance", type: ColumnType.Uint256, nullable: false }, { name: "snapshot_date", type: ColumnType.Date, nullable: false }, ], is_private: false, }); console.log(`Created: ${tableResult.full_name}`); // Step 2: Insert data as CSV const csvData = `token_address,holder_address,balance,snapshot_date 0x6b175474e89094c44da98b954eedeac495271d0f,0x123...,1000000,2024-01-15 0x6b175474e89094c44da98b954eedeac495271d0f,0x456...,500000,2024-01-15`; const insertResult = await client.uploads.insert({ namespace: "my_user", table_name: "token_holders", data: Buffer.from(csvData), content_type: ContentType.Csv, }); console.log(`Inserted ${insertResult.rows_written} rows`); // Step 3: List all tables const tables = await client.uploads.list({ limit: 50 }); console.log(`Found ${tables.tables.length} tables`); // Step 4: Insert more data from JSON const jsonData = JSON.stringify([ { token_address: "0x6b175474e89094c44da98b954eedeac495271d0f", holder_address: "0x789...", balance: 250000, snapshot_date: "2024-01-15" }, ]); const jsonInsert = await client.uploads.insert({ namespace: "my_user", table_name: "token_holders", data: Buffer.from(jsonData), content_type: ContentType.Json, }); console.log(`Inserted ${jsonInsert.rows_written} more rows`); // Step 5: Query the uploaded data const queryId = await client.query.createQuery({ name: "Analyze Token Holders", query_sql: " SELECT token_address, COUNT(*) as holder_count, SUM(CAST(balance AS DECIMAL(38,0))) as total_balance FROM my_user.token_holders GROUP BY token_address ", }); const results = await client.runQuery({ queryId }); console.log("Analysis results:", results.result?.rows); // Step 6: Clear and delete tables when done await client.uploads.clear({ namespace: "my_user", table_name: "token_holders", }); console.log("Table cleared"); await client.uploads.delete({ namespace: "my_user", table_name: "token_holders", }); console.log("Table deleted"); } catch (error) { console.error("Data management failed:", error); } ``` -------------------------------- ### Build a Data Pipeline with Dune API Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/06-OtherAPIs.md This function demonstrates how to build a data pipeline by checking API usage, listing datasets, getting dataset schemas, executing a query, and checking usage after execution. Ensure you have sufficient credits before starting the pipeline. ```typescript async function buildDataPipeline() { // Check API usage before starting const usage = await client.usage.getUsage(); const creditsRemaining = usage.billing_periods[0].credits_included - usage.billing_periods[0].credits_used; if (creditsRemaining < 5000) { throw new Error("Insufficient credits to run pipeline"); } // List available datasets const datasets = await client.dataset.list({ limit: 10 }); console.log(`Available datasets: ${datasets.total}`); // Get schema of a dataset const txDataset = await client.dataset.getBySlug("ethereum.transactions"); console.log(`Columns in transactions: ${txDataset.columns.map(c => c.name).join(", ")}`); // Execute a query using the dataset const results = await client.runQuery({ queryId: 1234567, }); // Check usage after execution const updatedUsage = await client.usage.getUsage(); console.log(`Credits used in this session: ${creditsRemaining - (updatedUsage.billing_periods[0].credits_included - updatedUsage.billing_periods[0].credits_used)}`); } ``` -------------------------------- ### Get Dataset Response Example Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/11-API-endpoints.md This JSON structure represents the metadata returned for a specific dataset, including its columns and ownership details. ```json { "full_name": "ethereum.transactions", "type": "decoded_table", "columns": [ { "name": "block_time", "type": "timestamp", "nullable": false }, { "name": "tx_hash", "type": "varchar", "nullable": false } ], "owner": { "handle": "dune", "type": "team" }, "is_private": false, "created_at": "2023-01-01T00:00:00Z", "updated_at": "2024-01-15T10:00:00Z" } ``` -------------------------------- ### QueryParameter Static Methods Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/08-types.md Examples of creating QueryParameter instances using static methods for different parameter types. ```typescript QueryParameter.text("param_name", "value") QueryParameter.number("count", 42) QueryParameter.date("start_date", "2024-01-01") QueryParameter.enum("category", "Option 1") ``` -------------------------------- ### Example: Check Pipeline Status - TypeScript Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/06-OtherAPIs.md Demonstrates how to execute a pipeline and then check its status and individual node statuses. Ensure the client is initialized before use. ```typescript // First, execute a pipeline const pipelineExecution = await client.exec.executeQueryPipeline(mainQueryId); const pipelineId = pipelineExecution.pipeline_execution_id; // Then check its status const pipelineStatus = await client.pipeline.getPipelineStatus(pipelineId); console.log(`Pipeline status: ${pipelineStatus.status}`); console.log("Node executions:"); pipelineStatus.node_executions.forEach(node => { console.log(` Query ${node.query_execution_status.query_id}: ${node.query_execution_status.status}`); console.log(` Execution ID: ${node.query_execution_status.execution_id}`); }); ``` -------------------------------- ### Complete Dune Client Workflow Example Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/02-DuneClient.md Illustrates a comprehensive workflow using the DuneClient, including executing a query with various parameter types, setting performance and options, downloading results as CSV, and fetching cached results. Ensure your DUNE_API_KEY is set in your environment variables. ```typescript import { DuneClient, QueryParameter, QueryEngine } from "@duneanalytics/client-sdk"; const client = new DuneClient(process.env.DUNE_API_KEY); try { // Execute query with parameters const results = await client.runQuery({ queryId: 1215383, query_parameters: [ QueryParameter.text("TextField", "Plain Text"), QueryParameter.number("NumberField", 3.14), QueryParameter.date("DateField", "2022-05-04 00:00:00"), QueryParameter.enum("ListField", "Option 1"), ], performance: QueryEngine.Medium, limit: 1000, opts: { pingFrequency: 2, // Check every 2 seconds batchSize: 5000, // Get 5000 rows per request }, }); // Access results console.log(`Rows returned: ${results.result?.rows.length}`); console.log(`Total rows: ${results.result?.metadata.total_row_count}`); // Download as CSV await client.downloadCSV({ queryId: 1215383 }, "./output.csv"); // Get latest results without re-executing const cached = await client.getLatestResult({ queryId: 1215383, opts: { maxAgeHours: 24 }, }); } catch (error) { console.error("Query execution failed:", error); } ``` -------------------------------- ### Get Usage Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/06-OtherAPIs.md Retrieves usage information for the Dune client. ```APIDOC ## Get Usage ### Description Retrieves usage information for the Dune client. ### Method POST ### Endpoint `/v1/usage` ``` -------------------------------- ### Get Usage Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/11-API-endpoints.md Retrieves API usage and billing information for the account. ```APIDOC ## POST /v1/usage ### Description Gets API usage and billing information. ### Method POST ### Endpoint /v1/usage ### Response #### Success Response (200) - **private_queries** (integer) - Number of private queries used. - **private_dashboards** (integer) - Number of private dashboards used. - **bytes_used** (integer) - Total bytes used. - **bytes_allowed** (integer) - Total bytes allowed. - **billing_periods** (array) - An array of billing period objects, each containing: - **start_date** (string) - The start date of the billing period. - **end_date** (string) - The end date of the billing period. - **credits_used** (integer) - Credits used during the period. - **credits_included** (integer) - Credits included in the plan for the period. ### Request Example { "example": "No request body is required for this endpoint." } ``` -------------------------------- ### Create Table Request Body Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/11-API-endpoints.md Example request body for creating a new table, specifying schema and privacy. ```json { "namespace": "my_user", "table_name": "my_table", "description": "Table description", "schema": [ { "name": "col1", "type": "varchar" }, { "name": "col2", "type": "integer" } ], "is_private": false } ``` -------------------------------- ### Upload and Manage Tables with Dune Client SDK Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/12-examples.md This comprehensive example shows how to create a table, upload data via CSV and JSON, run a query, list tables, clear table data, and delete a table using the Dune Client SDK. ```typescript import { DuneClient, ColumnType, ContentType } from "@duneanalytics/client-sdk"; import * as fs from "fs/promises"; const client = new DuneClient(process.env.DUNE_API_KEY || ""); async function uploadData() { // Create a table const tableResult = await client.uploads.create({ namespace: "my_user", table_name: "token_prices", description: "Historical token prices", schema: [ { name: "token_symbol", type: ColumnType.Varchar, nullable: false }, { name: "price_usd", type: ColumnType.Double, nullable: false }, { name: "timestamp", type: ColumnType.Timestamp, nullable: false }, ], is_private: false, }); console.log(`Table: ${tableResult.full_name}`); console.log(`Example: ${tableResult.example_query}`); // Upload CSV data const csvData = `token_symbol,price_usd,timestamp BTC,45000,2024-01-15T10:00:00Z ETH,2500,2024-01-15T10:00:00Z USDC,1.00,2024-01-15T10:00:00Z`; const csvSuccess = await client.uploads.uploadCsv({ table_name: "token_prices", data: csvData, }); console.log(`CSV upload success: ${csvSuccess}`); // Insert JSON data const jsonData = JSON.stringify([ { token_symbol: "SOL", price_usd: 100, timestamp: "2024-01-15T11:00:00Z" }, { token_symbol: "ADA", price_usd: 0.50, timestamp: "2024-01-15T11:00:00Z" }, ]); const insertResult = await client.uploads.insert({ namespace: "my_user", table_name: "token_prices", data: Buffer.from(jsonData), content_type: ContentType.Json, }); console.log(`Inserted ${insertResult.rows_written} rows`); // Query the uploaded data const queryId = await client.query.createQuery({ name: "Price Analysis", query_sql: ` SELECT token_symbol, price_usd, timestamp FROM my_user.token_prices WHERE timestamp > now() - interval '1' day ORDER BY timestamp DESC `, }); const results = await client.runQuery({ queryId }); console.log("Analysis results:", results.result?.rows); // List all tables const tables = await client.uploads.list({ limit: 50 }); console.log(`Total tables: ${tables.tables.length}`); // Clear table data (keep schema) await client.uploads.clear({ namespace: "my_user", table_name: "token_prices", }); console.log("Table cleared"); // Delete table await client.uploads.delete({ namespace: "my_user", table_name: "token_prices", }); console.log("Table deleted"); } uploadData(); ``` -------------------------------- ### Run a Dune Query with Parameters Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/00-INDEX.md Execute a Dune query using the DuneClient. Ensure your DUNE_API_KEY is set in the environment variables. This example demonstrates how to pass query parameters. ```typescript import { DuneClient, QueryParameter } from "@duneanalytics/client-sdk"; const client = new DuneClient(process.env.DUNE_API_KEY); const results = await client.runQuery({ queryId: 1215383, query_parameters: [ QueryParameter.text("param", "value"), ], }); console.log(results.result?.rows); ``` -------------------------------- ### getUsage() Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/06-OtherAPIs.md Gets current API usage, storage, and billing information. ```APIDOC ## getUsage() ### Description Gets current API usage, storage, and billing information. ### Method GET ### Endpoint /usage ### Response #### Success Response (200) - **private_queries** (number) - The number of private queries used. - **private_dashboards** (number) - The number of private dashboards used. - **bytes_used** (number) - The amount of storage space used in bytes. - **bytes_allowed** (number) - The total amount of storage space allowed in bytes. - **billing_periods** (array) - An array of billing period objects. - **start_date** (string) - The start date of the billing period (ISO date string). - **end_date** (string) - The end date of the billing period (ISO date string). - **credits_used** (number) - The number of credits used during the billing period. - **credits_included** (number) - The number of credits included in the billing period. ### Request Example ```json { "example": "request body" } ``` ### Response Example ```json { "private_queries": 100, "private_dashboards": 5, "bytes_used": 1073741824, "bytes_allowed": 10737418240, "billing_periods": [ { "start_date": "2023-01-01T00:00:00Z", "end_date": "2023-01-31T23:59:59Z", "credits_used": 500, "credits_included": 1000 } ] } ``` ``` -------------------------------- ### Complete Pipeline Execution and Tracking - TypeScript Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/06-OtherAPIs.md Provides a complete example of executing a pipeline and then polling for its completion status. Includes logic to check individual node statuses and waits before re-polling. ```typescript async function executePipelineWithTracking(queryId: number) { // Execute the pipeline const execution = await client.exec.executeQueryPipeline(queryId, { performance: QueryEngine.Large, }); console.log(`Pipeline execution started: ${execution.pipeline_execution_id}`); // Poll for completion let isComplete = false; while (!isComplete) { const status = await client.pipeline.getPipelineStatus(execution.pipeline_execution_id); console.log(`Overall status: ${status.status}`); // Check individual nodes const allNodesComplete = status.node_executions.every(node => { const nodeStatus = node.query_execution_status.status; return ["COMPLETED", "FAILED", "CANCELLED"].includes(nodeStatus); }); if (allNodesComplete) { isComplete = true; console.log("Pipeline execution complete"); } else { // Wait before next check await new Promise(resolve => setTimeout(resolve, 2000)); } } } ``` -------------------------------- ### Execute Parameterized Query Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/01-OVERVIEW.md Example of executing a parameterized query using the DuneClient. It shows how to define query parameters of different types (text, number) and retrieve the results. ```typescript import { DuneClient, QueryParameter } from "@duneanalytics/client-sdk"; const client = new DuneClient(process.env.DUNE_API_KEY); // Execute a parameterized query const results = await client.runQuery({ queryId: 1234567, query_parameters: [ QueryParameter.text("param_name", "value"), QueryParameter.number("numeric_param", 42), ], }); console.log(results.result?.rows); ``` -------------------------------- ### Execute Query Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/03-ExecutionAPI.md Executes a Dune query with optional parameters and performance settings. This is the primary method to start a query execution. ```APIDOC ## POST /v1/execute ### Description Executes a Dune query. You can specify query parameters and choose a query engine for performance. ### Method POST ### Endpoint /v1/execute ### Parameters #### Request Body - **query_id** (integer) - Required - The ID of the Dune query to execute. - **query_parameters** (array) - Optional - An array of query parameters to be used. - **name** (string) - Required - The name of the parameter. - **type** (string) - Required - The type of the parameter (e.g., "text", "numeric", "date"). - **value** (any) - Required - The value of the parameter. - **performance** (string) - Optional - The query engine to use (e.g., "medium", "large"). Defaults to "medium". ### Request Example ```json { "query_id": 1215383, "query_parameters": [ { "name": "network", "type": "text", "value": "ethereum" } ], "performance": "large" } ``` ### Response #### Success Response (200) - **execution_id** (string) - The ID of the initiated execution. #### Response Example ```json { "execution_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### Execute Raw SQL Query Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/12-examples.md Execute arbitrary SQL directly without saving a query. This example demonstrates executing SQL, checking status, and fetching results, requiring a DUNE_API_KEY. ```typescript import { DuneClient, QueryEngine } from "@duneanalytics/client-sdk"; const client = new DuneClient(process.env.DUNE_API_KEY || ""); async function executeSqlExample() { const execution = await client.exec.executeSql({ sql: "SELECT * FROM dex.trades WHERE block_time > now() - interval '1' day LIMIT 10", performance: QueryEngine.Medium, }); const executionId = execution.execution_id; const status = await client.exec.getExecutionStatus(executionId); const results = await client.exec.getExecutionResults(executionId); console.log(`Total rows: ${results.result?.metadata.total_row_count}`); console.log(results.result?.rows); } executeSqlExample(); ``` -------------------------------- ### Run Query and Get CSV Results Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/02-DuneClient.md Execute a query and retrieve the results directly as a CSV formatted string. Useful for direct data export. ```typescript const csvResponse = await client.runQueryCSV({ queryId: 1215383, query_parameters: [QueryParameter.text("token", "USDC")], }); console.log(csvResponse.data); // CSV formatted string ``` -------------------------------- ### Get API Usage Information Source: https://github.com/duneanalytics/ts-dune-client/blob/main/README.md Fetch API usage details, including credits used, private query count, and storage limits. The API key must be configured. ```ts const { DUNE_API_KEY } = process.env; const client = new DuneClient(DUNE_API_KEY ?? ""); const usage = await client.usage.getUsage(); console.log(`Credits used: ${usage.billing_periods[0].credits_used}`); console.log(`Private queries: ${usage.private_queries}`); console.log(`Storage: ${usage.bytes_used} / ${usage.bytes_allowed} bytes`); ``` -------------------------------- ### Log API Usage Details Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/06-OtherAPIs.md Logs detailed API usage including private queries, dashboards, storage, and billing periods. This example demonstrates how to parse and display the UsageResponse object. ```typescript const usage = await client.usage.getUsage(); console.log(`Private queries: ${usage.private_queries}`); console.log(`Private dashboards: ${usage.private_dashboards}`); console.log(`Storage used: ${(usage.bytes_used / (1024 * 1024 * 1024)).toFixed(2)} GB`); console.log(`Storage limit: ${(usage.bytes_allowed / (1024 * 1024 * 1024)).toFixed(2)} GB`); usage.billing_periods.forEach(period => { const creditPercent = ((period.credits_used / period.credits_included) * 100).toFixed(1); console.log( `${period.start_date} to ${period.end_date}: ${period.credits_used}/${period.credits_included} credits (${creditPercent}%)` ); }); ``` -------------------------------- ### Execute Query Pipeline with Dune Client Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/12-examples.md Starts a query pipeline execution and monitors its status, including the status of individual node executions within the pipeline. Requires a valid query ID. ```typescript import { DuneClient, ExecutionState } from "@duneanalytics/client-sdk"; const client = new DuneClient(process.env.DUNE_API_KEY || ""); async function executePipeline() { // Start pipeline execution const pipelineExecution = await client.exec.executeQueryPipeline(queryId); console.log(`Pipeline started: ${pipelineExecution.pipeline_execution_id}`); // Check status const pipelineStatus = await client.pipeline.getPipelineStatus( pipelineExecution.pipeline_execution_id ); console.log(`Overall status: ${pipelineStatus.status}`); pipelineStatus.node_executions.forEach(node => { console.log( `Query ${node.query_execution_status.query_id}: ` + `${node.query_execution_status.status}` ); }); } executePipeline(); ``` -------------------------------- ### Executing a Query Directly with Large Performance Tier Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/10-configuration.md Example of executing a query directly using the `exec.executeQuery` method, specifying the 'large' performance tier. This demonstrates an alternative way to set query performance. ```typescript const execution = await client.exec.executeQuery(queryId, { performance: QueryEngine.Large, }); ``` -------------------------------- ### Monitor Dune API Usage Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/06-OtherAPIs.md A comprehensive example for monitoring Dune API usage, including checks for low credits and high storage utilization. This function returns key usage metrics. ```typescript const client = new DuneClient(apiKey); async function monitorUsage() { const usage = await client.usage.getUsage(); const currentPeriod = usage.billing_periods[0]; const creditsRemaining = currentPeriod.credits_included - currentPeriod.credits_used; if (creditsRemaining < 1000) { console.warn("Low credits warning: Less than 1000 credits remaining"); } const storagePercent = (usage.bytes_used / usage.bytes_allowed * 100).toFixed(1); if (parseFloat(storagePercent) > 80) { console.warn(`High storage usage: ${storagePercent}% of limit`); } return { creditsAvailable: creditsRemaining, storageUsed: usage.bytes_used, storageLimit: usage.bytes_allowed, privateQueries: usage.private_queries, }; } ``` -------------------------------- ### Get Latest Query Results Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/02-DuneClient.md Retrieves the latest execution results for a query. Results are considered expired after `maxAgeHours`. Use this to get cached or freshly executed results. ```typescript const results = await client.getLatestResult({ queryId: 1215383, opts: { maxAgeHours: 24 }, // Re-run if older than 24 hours }); ``` -------------------------------- ### Complete Query Lifecycle Management Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/04-QueryAPI.md This snippet demonstrates the full lifecycle of a query using the Dune Client SDK. It covers creating, reading, updating, making public, executing, archiving, and unarchiving a query. Ensure you have your API key set up. ```typescript import { DuneClient, QueryParameter } from "@duneanalytics/client-sdk"; const client = new DuneClient(apiKey); try { // Step 1: Create a new query const queryId = await client.query.createQuery({ name: "Daily DEX Trades Summary", description: "Aggregated DEX trading volume by day", query_sql: " SELECT DATE(block_time) as trade_date, COUNT(*) as trade_count, SUM(usd_amount) as total_volume FROM dex.trades WHERE block_time > now() - interval '90' days GROUP BY DATE(block_time) ORDER BY trade_date DESC ", query_parameters: [ QueryParameter.date("start_date", "2024-01-01"), ], is_private: true, }); console.log(`Created query: ${queryId}`); // Step 2: Read and verify the query const query = await client.query.readQuery(queryId); console.log(`Query name: ${query.name}`); console.log(`Owner: ${query.owner}`); console.log(`Private: ${query.is_private}`); // Step 3: Update the query to add more context await client.query.updateQuery(queryId, { query_sql: " SELECT DATE(block_time) as trade_date, protocol, COUNT(*) as trade_count, SUM(usd_amount) as total_volume FROM dex.trades WHERE block_time > now() - interval '90' days GROUP BY DATE(block_time), protocol ORDER BY trade_date DESC, total_volume DESC ", description: "DEX trades by protocol and date - Updated", tags: ["dex", "trading", "summary"], }); console.log("Query updated successfully"); // Step 4: Make it public for team sharing await client.query.makePublic(queryId); console.log("Query is now public"); // Step 5: Execute the query via ExecutionAPI const execution = await client.exec.executeQuery(queryId); console.log(`Execution started: ${execution.execution_id}`); // Step 6: Later, archive the query when it's no longer needed const isArchived = await client.query.archiveQuery(queryId); console.log(`Query archived: ${isArchived}`); // Step 7: If needed, unarchive it const isActive = await client.query.unarchiveQuery(queryId); console.log(`Query unarchived: ${isActive}`); } catch (error) { console.error("Query management failed:", error); } ``` -------------------------------- ### Get Dataset Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/06-OtherAPIs.md Retrieves details for a specific dataset using its slug. ```APIDOC ## Get Dataset ### Description Retrieves details for a specific dataset using its slug. ### Method GET ### Endpoint `/v1/datasets/{slug}` ### Parameters #### Path Parameters - **slug** (string) - Required - The slug of the dataset. ``` -------------------------------- ### Initialize DuneClient with API Key from Environment Variable Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/10-configuration.md This is the recommended pattern for initializing the DuneClient. It ensures the DUNE_API_KEY environment variable is set before creating the client instance. ```typescript const apiKey = process.env.DUNE_API_KEY; if (!apiKey) { throw new Error("DUNE_API_KEY environment variable is required"); } const client = new DuneClient(apiKey); ``` -------------------------------- ### Initialize DuneClient with API Key Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/01-OVERVIEW.md Demonstrates how to initialize the DuneClient by passing your API key during instantiation. This key is used for authenticating all subsequent requests to the Dune API. ```typescript const client = new DuneClient(apiKey); ``` -------------------------------- ### Get Pipeline Status Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/11-API-endpoints.md Fetches the current status of a specific pipeline execution. ```APIDOC ## GET /v1/pipelines/executions/{pipeline_execution_id}/status ### Description Gets the status of a pipeline execution. ### Method GET ### Endpoint /v1/pipelines/executions/{pipeline_execution_id}/status ### Parameters #### Path Parameters - **pipeline_execution_id** (string) - Required - The ID of the pipeline execution. ### Response #### Success Response (200) - **status** (string) - The overall status of the pipeline execution (e.g., "COMPLETED"). - **node_executions** (array) - An array of objects, each representing the status of a node execution within the pipeline: - **id** (integer) - The ID of the node execution. - **query_execution_status** (object) - The status of the associated query execution: - **status** (string) - The status of the query execution (e.g., "COMPLETED"). - **query_id** (integer) - The ID of the query. - **execution_id** (string) - The ID of the query execution. ``` -------------------------------- ### Initialize Dune Client with API Key Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/10-configuration.md Initializes the Dune client using an API key from environment variables. Ensure the DUNE_API_KEY is set before running. ```typescript import { DuneClient } from "@duneanalytics/client-sdk"; import log from "loglevel"; // Configure logging log.setLevel("info"); // Initialize client with API key const apiKey = process.env.DUNE_API_KEY; if (!apiKey) { throw new Error("DUNE_API_KEY not set"); } const client = new DuneClient(apiKey); ``` -------------------------------- ### Explore Datasets with Dune Client SDK Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/12-examples.md Demonstrates listing all datasets, filtering by owner and type, and retrieving detailed metadata for a specific dataset. Requires DUNE_API_KEY environment variable. ```typescript import { DuneClient } from "@duneanalytics/client-sdk"; const client = new DuneClient(process.env.DUNE_API_KEY || ""); async function exploreDatasets() { // List all datasets const allDatasets = await client.dataset.list({ limit: 100 }); console.log(`Total datasets: ${allDatasets.total}`); // Filter by owner const myDatasets = await client.dataset.list({ owner_handle: "my_username", limit: 50, }); console.log(`My datasets: ${myDatasets.datasets.length}`); // Filter by type const tables = await client.dataset.list({ type: "transformation_table", limit: 50, }); console.log(`Tables: ${tables.datasets.length}`); // Get detailed metadata const ethTx = await client.dataset.getBySlug("ethereum.transactions"); console.log(`Dataset: ${ethTx.full_name}`); console.log(`Owner: ${ethTx.owner.handle}`); console.log(`Type: ${ethTx.type}`); console.log("Columns:"); ethTx.columns.forEach(col => { const nullable = col.nullable ? "nullable" : "not null"; console.log(` ${col.name}: ${col.type} (${nullable})`); }); } exploreDatasets(); ``` -------------------------------- ### Get Dataset API Endpoint Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/11-API-endpoints.md Retrieve metadata for a specific dataset using its unique slug. ```http GET /v1/datasets/{slug} ``` -------------------------------- ### Load .env and Initialize Dune Client Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/12-examples.md Load environment variables using dotenv and initialize the DuneClient with your API key. The API key is required. ```typescript import dotenv from "dotenv"; dotenv.config(); const client = new DuneClient(process.env.DUNE_API_KEY!); ``` -------------------------------- ### Get Custom Endpoint Results Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/11-API-endpoints.md Retrieves results from a custom-defined API endpoint. Supports pagination. ```APIDOC ## GET /v1/endpoints/{handle}/{slug}/results?limit=32000&offset=0 ### Description Gets results from a custom endpoint. ### Method GET ### Endpoint /v1/endpoints/{handle}/{slug}/results ### Parameters #### Path Parameters - **handle** (string) - Required - The handle of the custom endpoint. - **slug** (string) - Required - The slug of the custom endpoint. #### Query Parameters - **limit** (integer) - Optional - Maximum number of rows to return. - **offset** (integer) - Optional - Number of rows to skip before starting to collect the result set. ### Response #### Success Response (200) - **results** (array) - The query results. - **metadata** (object) - Metadata about the results, including pagination information. ``` -------------------------------- ### Get Execution Results as CSV Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/11-API-endpoints.md Retrieves the results of a completed query execution in CSV format. ```APIDOC ## GET /v1/execution/{execution_id}/results/csv ### Description Retrieves results in CSV format. ### Method GET ### Endpoint /v1/execution/{execution_id}/results/csv ### Parameters #### Path Parameters - **execution_id** (string) - Required - The ID of the execution whose results are to be retrieved. #### Query Parameters - **limit** (number) - Optional - Maximum number of rows to return. Defaults to 32000. - **offset** (number) - Optional - Row offset for pagination. Defaults to 0. ### Response #### Success Response (200) - **Response Headers**: - **x-dune-next-uri** (string) - URI for the next page of results. - **x-dune-next-offset** (number) - Offset for the next page of results. - **Content-Type** (string) - Set to "text/csv". - **Response Body**: - CSV formatted data representing the query results. #### Response Example ```csv column1,column2 value1,value2 value3,value4 ``` ``` -------------------------------- ### Get Execution Status Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/11-API-endpoints.md Retrieves the current status of a query or pipeline execution using its unique ID. ```APIDOC ## GET /v1/execution/{execution_id}/status ### Description Retrieves the status of a query execution. ### Method GET ### Endpoint /v1/execution/{execution_id}/status ### Parameters #### Path Parameters - **execution_id** (string) - Required - The ID of the execution to check. ### Response #### Success Response (200) - **execution_id** (string) - The ID of the execution. - **query_id** (number) - The ID of the query (if applicable). - **state** (string) - The current state of the execution (e.g., "QUERY_STATE_PENDING", "QUERY_STATE_COMPLETED"). - **submitted_at** (string) - Timestamp when the execution was submitted. - **execution_started_at** (string) - Timestamp when the execution started. - **execution_ended_at** (string) - Timestamp when the execution ended (if completed). - **expires_at** (string) - Timestamp when the results will expire (if completed). - **queue_position** (number) - The position in the execution queue (if applicable). - **result_metadata** (object) - Metadata about the results (if completed). - **column_names** (array) - Names of the columns in the result set. - **datapoint_count** (number) - Total number of data points. - **execution_time_millis** (number) - Time taken for execution in milliseconds. - **pending_time_millis** (number) - Time spent in the queue in milliseconds. - **result_set_bytes** (number) - Size of the result set in bytes. - **row_count** (number) - Number of rows returned. - **total_result_set_bytes** (number) - Total size of the result set in bytes. - **total_row_count** (number) - Total number of rows. #### Response Example (Incomplete) ```json { "execution_id": "01234567-89ab-cdef-0123-456789abcdef", "query_id": 1234567, "state": "QUERY_STATE_EXECUTING", "submitted_at": "2024-01-15T10:00:00Z", "execution_started_at": "2024-01-15T10:00:01Z", "queue_position": null } ``` #### Response Example (Complete) ```json { "execution_id": "01234567-89ab-cdef-0123-456789abcdef", "query_id": 1234567, "state": "QUERY_STATE_COMPLETED", "submitted_at": "2024-01-15T10:00:00Z", "execution_started_at": "2024-01-15T10:00:01Z", "execution_ended_at": "2024-01-15T10:00:05Z", "expires_at": "2024-04-15T10:00:05Z", "result_metadata": { "column_names": ["column1", "column2"], "datapoint_count": 1000, "execution_time_millis": 4000, "pending_time_millis": 1000, "result_set_bytes": 50000, "row_count": 100, "total_result_set_bytes": 50000, "total_row_count": 100 } } ``` ``` -------------------------------- ### Get Execution Results Source: https://github.com/duneanalytics/ts-dune-client/blob/main/_autodocs/03-ExecutionAPI.md Fetches the results of a completed query execution. Supports pagination with limit and offset parameters. ```APIDOC ## GET /v1/executions/{execution_id}/results ### Description Retrieves the results for a completed query execution. Supports pagination. ### Method GET ### Endpoint /v1/executions/{execution_id}/results ### Parameters #### Path Parameters - **execution_id** (string) - Required - The ID of the execution whose results are to be fetched. #### Query Parameters - **limit** (integer) - Optional - The maximum number of rows to return. Defaults to 1000. - **offset** (integer) - Optional - The number of rows to skip. Defaults to 0. ### Response #### Success Response (200) - **result** (object) - Contains the query results. - **rows** (array) - An array of result rows. - **metadata** (object) - Metadata about the result set. - **total_row_count** (integer) - The total number of rows available. #### Response Example ```json { "result": { "rows": [ { "column1": "value1", "column2": 123 }, { "column1": "value2", "column2": 456 } ], "metadata": { "total_row_count": 10000 } } } ``` ```