### Install DuneAPI Go Client Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/README.md Command to add the DuneAPI client library to your Go project. ```bash go get github.com/duneanalytics/duneapi-client-go ``` -------------------------------- ### List and Get Datasets in Go Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Use this to list datasets with optional filters for owner and type, and to retrieve detailed information for a specific dataset. Ensure you have your API key configured. ```go package main import ( "fmt" "os" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" ) func main() { env := config.FromAPIKey("your_api_key") client := dune.NewDuneClient(env) // List datasets with filtering datasets, err := client.ListDatasets( 50, // limit 0, // offset "dune", // owner_handle (empty string for all owners) "spell", // dataset_type: "spell", "raw", "decoded", etc. (empty for all) ) if err != nil { fmt.Fprintf(os.Stderr, "Failed to list datasets: %v\n", err) os.Exit(1) } fmt.Printf("Found %d datasets (total: %d)\n", len(datasets.Datasets), datasets.Total) for _, ds := range datasets.Datasets { fmt.Printf("- %s (%s)\n", ds.FullName, ds.Type) if ds.Owner != nil { fmt.Printf(" Owner: %s (%s)\n", ds.Owner.Handle, ds.Owner.Type) } } // Get detailed information about a specific dataset dataset, err := client.GetDataset("dex.trades") if err != nil { fmt.Fprintf(os.Stderr, "Failed to get dataset: %v\n", err) os.Exit(1) } fmt.Printf("\nDataset: %s\n", dataset.FullName) fmt.Printf("Type: %s, Private: %v\n", dataset.Type, dataset.IsPrivate) fmt.Printf("Columns:\n") for _, col := range dataset.Columns { nullable := "" if col.Nullable { nullable = " (nullable)" } fmt.Printf(" - %s: %s%s\n", col.Name, col.Type, nullable) } } ``` -------------------------------- ### Execute Query Asynchronously and Manage Execution Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Starts a query execution asynchronously and provides an Execution object to monitor status, wait for results, retrieve them in various formats (like CSV), or cancel the operation. Useful for long-running queries or when fine-grained control is needed. ```go package main import ( "fmt" "io" "os" "time" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" "github.com/duneanalytics/duneapi-client-go/models" ) func main() { env := config.FromAPIKey("your_api_key") client := dune.NewDuneClient(env) // Start query execution (non-blocking) execution, err := client.RunQuery(models.ExecuteRequest{ QueryID: 1234567, QueryParameters: map[string]any{"limit": 100}, }) if err != nil { fmt.Fprintf(os.Stderr, "Failed to start query: %v\n", err) os.Exit(1) } fmt.Printf("Execution started with ID: %s\n", execution.GetID()) // Check status manually status, _ := execution.GetStatus() fmt.Printf("Current state: %s\n", status.State) // Wait for completion with custom polling (5s interval, max 10 retries) results, err := execution.WaitGetResults(5*time.Second, 10) if err != nil { // Cancel the execution if taking too long _ = execution.Cancel() fmt.Fprintf(os.Stderr, "Execution timed out: %v\n", err) os.Exit(1) } fmt.Printf("Query completed. Total rows: %d\n", results.Result.Metadata.TotalRowCount) fmt.Printf("Columns: %v\n", results.Result.Metadata.ColumnNames) // Get results as CSV csvReader, _ := execution.GetResultsCSV() csvData, _ := io.ReadAll(csvReader) fmt.Printf("CSV output:\n%s\n", string(csvData)) } ``` -------------------------------- ### Execute Saved Query and Get Rows Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Executes a saved query by its ID, optionally providing parameters, and waits for the results to be returned. This is suitable for simple, synchronous data retrieval. ```go package main import ( "fmt" "os" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" "github.com/duneanalytics/duneapi-client-go/models" ) func main() { env := config.FromAPIKey("your_api_key") client := dune.NewDuneClient(env) // Execute query with parameters and wait for results rows, err := client.RunQueryGetRows(models.ExecuteRequest{ QueryID: 1234567, QueryParameters: map[string]any{ "wallet_address": "0x1234567890abcdef1234567890abcdef12345678", "min_value": 1000, "start_date": "2024-01-01", }, Performance: "medium", // Options: "medium" (default) or "large" }) if err != nil { fmt.Fprintf(os.Stderr, "Query failed: %v\n", err) os.Exit(1) } // Iterate over result rows fmt.Printf("Retrieved %d rows\n", len(rows)) for i, row := range rows { fmt.Printf("Row %d: %v\n", i+1, row) // Access specific columns: row["column_name"] } } ``` -------------------------------- ### Configure and Initialize Dune Client Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/README.md Demonstrates authentication via environment variables, API key, or manual configuration, followed by executing a query. ```go import ( "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" ) func main() { // Use one of the following options // Read config from DUNE_API_KEY and DUNE_API_HOST environment variables env, err := config.FromEnvVars() if err != nil { // handle error } // Define it from your code env = config.FromAPIKey("Your_API_Key") // Define manually env = &config.Env{ APIKey: "Your_API_Key", // you can define a different domain to connect to, for example for a mocked API Host: "https://api.example.com", } // Next, instantiate and use a Dune client object client := dune.NewDuneClient(env) queryID := 1234 queryParameters := map[string]any{ "paramKey": "paramValue", } rows, err := client.RunQueryGetRows(queryID, queryParameters) if err != nil { // handle error } for row := range rows { // ... } } ``` -------------------------------- ### Initialize Dune Client Configuration Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Demonstrates three ways to initialize the Dune client configuration: from environment variables, directly from an API key, or with manual configuration including custom headers and host. ```go package main import ( "fmt" "os" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" ) func main() { // Option 1: Read from DUNE_API_KEY and DUNE_API_HOST environment variables env, err := config.FromEnvVars() if err != nil { fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err) os.Exit(1) } // Option 2: Create config directly from API key (uses default host: https://api.dune.com) env = config.FromAPIKey("your_api_key_here") // Option 3: Manual configuration with custom host env = &config.Env{ APIKey: "your_api_key_here", Host: "https://api.dune.com", // Or custom proxy URL Headers: map[string]string{ "X-Custom-Header": "value", }, } // Create the client client := dune.NewDuneClient(env) // Verify connection identity, err := client.WhoAmI() if err != nil { fmt.Fprintf(os.Stderr, "Failed to authenticate: %v\n", err) os.Exit(1) } fmt.Printf("Connected as: %s (ID: %s)\n", identity.Handle, identity.CustomerID) } ``` -------------------------------- ### Manage Query Visualizations with Go Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Demonstrates the full lifecycle of a visualization including creation, listing, retrieval, updating, and deletion. ```go package main import ( "fmt" "os" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" "github.com/duneanalytics/duneapi-client-go/models" ) func main() { env := config.FromAPIKey("your_api_key") client := dune.NewDuneClient(env) queryID := 1234567 // Create a bar chart visualization vizResp, err := client.CreateVisualization(models.CreateVisualizationRequest{ QueryID: queryID, Name: "Daily Trading Volume", Type: "bar_chart", Description: "Shows daily trading volume across DEX platforms", Options: map[string]any{ "xAxis": "block_date", "yAxis": "total_volume", "colorBy": "protocol", "showLegend": true, }, }) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create visualization: %v\n", err) os.Exit(1) } fmt.Printf("Created visualization ID: %d\n", vizResp.ID) // List all visualizations for a query vizList, err := client.ListQueryVisualizations(queryID, 50, 0) if err != nil { fmt.Fprintf(os.Stderr, "Failed to list visualizations: %v\n", err) os.Exit(1) } fmt.Printf("Query has %d visualizations\n", vizList.TotalCount) for _, v := range vizList.Results { fmt.Printf("- [%d] %s (%s)\n", v.ID, v.Name, v.Type) } // Get visualization details viz, err := client.GetVisualization(int(vizResp.ID)) if err != nil { fmt.Fprintf(os.Stderr, "Failed to get visualization: %v\n", err) os.Exit(1) } fmt.Printf("Visualization: %s\n", viz.Name) fmt.Printf("Type: %s, Options: %v\n", viz.Type, viz.Options) // Update visualization _, err = client.UpdateVisualization(int(vizResp.ID), models.UpdateVisualizationRequest{ Name: "Daily DEX Volume Chart", Type: "area_chart", Description: "Area chart showing daily DEX trading volume", Options: map[string]any{ "xAxis": "block_date", "yAxis": "total_volume", "stacked": true, "showLegend": true, }, }) if err != nil { fmt.Fprintf(os.Stderr, "Failed to update visualization: %v\n", err) } // Delete visualization deleteResp, err := client.DeleteVisualization(int(vizResp.ID)) if err != nil { fmt.Fprintf(os.Stderr, "Failed to delete visualization: %v\n", err) } else { fmt.Printf("Deleted: %v\n", deleteResp.OK) } } ``` -------------------------------- ### Manage Tables with Dune API Go Client Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Demonstrates listing existing tables, creating new tables with a custom schema, and deleting tables. ```go package main import ( "fmt" "os" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" "github.com/duneanalytics/duneapi-client-go/models" ) func main() { env := config.FromAPIKey("your_api_key") client := dune.NewDuneClient(env) // List existing uploaded tables tables, err := client.ListUploads(50, 0) if err != nil { fmt.Fprintf(os.Stderr, "Failed to list tables: %v\n", err) os.Exit(1) } fmt.Printf("You have %d uploaded tables\n", len(tables.Tables)) for _, t := range tables.Tables { fmt.Printf("- %s (%s bytes)\n", t.FullName, t.TableSizeBytes) } // Create a new table with defined schema createResp, err := client.CreateUpload(models.UploadsCreateRequest{ Namespace: "my_username", TableName: "defi_positions", Description: "Tracked DeFi positions across protocols", IsPrivate: false, Schema: []models.UploadsColumn{ {Name: "timestamp", Type: "timestamp", Nullable: false}, {Name: "protocol", Type: "varchar", Nullable: false}, {Name: "wallet", Type: "varchar", Nullable: false}, {Name: "asset", Type: "varchar", Nullable: true}, {Name: "amount", Type: "double", Nullable: true}, {Name: "value_usd", Type: "double", Nullable: true}, }, }) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create table: %v\n", err) os.Exit(1) } fmt.Printf("Created table: %s\n", createResp.FullName) fmt.Printf("Example query: %s\n", createResp.ExampleQuery) // Delete a table deleteResp, err := client.DeleteUpload("my_username", "old_table") if err != nil { fmt.Fprintf(os.Stderr, "Failed to delete: %v\n", err) } else { fmt.Printf("Deleted: %s\n", deleteResp.Message) } } ``` -------------------------------- ### Manage Dashboards with Go Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Demonstrates creating, retrieving, updating, and archiving dashboards using the Dune client. Requires valid API key configuration. ```go package main import ( "fmt" "os" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" "github.com/duneanalytics/duneapi-client-go/models" ) func main() { env := config.FromAPIKey("your_api_key") client := dune.NewDuneClient(env) isPrivate := false columnsPerRow := int32(12) // Create a new dashboard dashResp, err := client.CreateDashboard(models.CreateDashboardRequest{ Name: "DeFi Analytics Dashboard", IsPrivate: &isPrivate, VisualizationIDs: []int64{ 123456789, // Existing visualization IDs to add 987654321, }, TextWidgets: []models.TextWidgetInput{ { Text: "# DeFi Analytics\n\nReal-time metrics for decentralized finance.", Position: &models.WidgetPosition{ Row: 0, Col: 0, SizeX: 12, SizeY: 2, }, }, }, ColumnsPerRow: &columnsPerRow, }) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create dashboard: %v\n", err) os.Exit(1) } fmt.Printf("Created dashboard ID: %d\n", dashResp.DashboardID) fmt.Printf("URL: %s\n", dashResp.DashboardURL) fmt.Printf("Slug: %s\n", dashResp.Slug) // Get dashboard by ID dash, err := client.GetDashboard(int(dashResp.DashboardID)) if err != nil { fmt.Fprintf(os.Stderr, "Failed to get dashboard: %v\n", err) os.Exit(1) } fmt.Printf("Dashboard: %s\n", dash.Name) fmt.Printf("Visualizations: %d, Text widgets: %d\n", len(dash.VisualizationWidgets), len(dash.TextWidgets)) // Get dashboard by owner handle and slug dashBySlug, err := client.GetDashboardBySlug("duneanalytics", "defi-overview") if err != nil { fmt.Fprintf(os.Stderr, "Failed to get dashboard by slug: %v\n", err) } else { fmt.Printf("Found dashboard: %s (ID: %d)\n", dashBySlug.Name, dashBySlug.DashboardID) } // Update dashboard newName := "DeFi Analytics Dashboard v2" tags := []string{"defi", "analytics", "trading"} _, err = client.UpdateDashboard(int(dashResp.DashboardID), models.UpdateDashboardRequest{ Name: &newName, Tags: &tags, }) if err != nil { fmt.Fprintf(os.Stderr, "Failed to update dashboard: %v\n", err) } // Archive dashboard archiveResp, err := client.ArchiveDashboard(int(dashResp.DashboardID)) if err != nil { fmt.Fprintf(os.Stderr, "Failed to archive dashboard: %v\n", err) } else { fmt.Printf("Archived: %v (ID: %d)\n", archiveResp.OK, archiveResp.DashboardID) } } ``` -------------------------------- ### Build the Dune CLI Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/README.md Compile the CLI tool from the source code. ```bash go build -o dunecli cmd/main.go ``` -------------------------------- ### Manage Uploaded Tables Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/README.md Comprehensive operations for listing, creating, uploading, inserting, clearing, and deleting user-uploaded tables. ```go // List all uploaded tables tables, err := client.ListUploads(50, 0) if err != nil { // handle error } for _, table := range tables.Tables { fmt.Printf("Table: %s (size: %s bytes)\n", table.FullName, table.TableSizeBytes) } // Create a new table with defined schema createResp, err := client.CreateUpload(models.UploadsCreateRequest{ Namespace: "my_user", TableName: "interest_rates", Description: "10 year daily interest rates", IsPrivate: false, Schema: []models.UploadsColumn{ { Name: "date", Type: "timestamp", Nullable: false, }, { Name: "rate", Type: "double", Nullable: true, }, }, }) if err != nil { // handle error } fmt.Printf("Created table: %s\n", createResp.FullName) // Upload CSV data to create a new table csvResp, err := client.UploadCSV(models.UploadsCSVRequest{ TableName: "my_table", Data: "col1,col2\nval1,val2\nval3,val4", Description: "My test table", IsPrivate: false, }) if err != nil { // handle error } fmt.Printf("Uploaded CSV to: %s\n", csvResp.FullName) // Insert data into an existing table (CSV format) insertResp, err := client.InsertIntoUpload( "my_user", "interest_rates", "2024-01-01,3.5\n2024-01-02,3.6", "text/csv", ) if err != nil { // handle error } fmt.Printf("Inserted %d rows (%d bytes)\n", insertResp.RowsWritten, insertResp.BytesWritten) // Insert data in NDJSON format ndjsonData := `{"date":"2024-01-03","rate":3.7} {"date":"2024-01-04","rate":3.8}` insertResp, err = client.InsertIntoUpload( "my_user", "interest_rates", ndjsonData, "application/x-ndjson", ) // Clear all data from a table (preserves schema) clearResp, err := client.ClearUpload("my_user", "interest_rates") if err != nil { // handle error } // Delete a table permanently deleteResp, err := client.DeleteUpload("my_user", "interest_rates") if err != nil { // handle error } ``` -------------------------------- ### Run All E2E Tests Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/e2e/README.md Execute all end-to-end tests using the go test command with verbose output and a specified timeout. ```bash go test ./e2e/... -v -timeout 120s ``` -------------------------------- ### Execute Query Pipelines Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Manage multi-step query workflows by executing pipelines and polling for status updates. ```go package main import ( "fmt" "os" "time" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" "github.com/duneanalytics/duneapi-client-go/models" ) func main() { env := config.FromAPIKey("your_api_key") client := dune.NewDuneClient(env) // Start pipeline execution pipelineResp, err := client.QueryPipelineExecute(models.PipelineExecuteRequest{ QueryID: "pipeline_query_id", Performance: "large", }) if err != nil { fmt.Fprintf(os.Stderr, "Failed to start pipeline: %v\n", err) os.Exit(1) } fmt.Printf("Pipeline execution ID: %s\n", pipelineResp.PipelineExecutionID) // Poll pipeline status for { status, err := client.PipelineStatus(pipelineResp.PipelineExecutionID) if err != nil { fmt.Fprintf(os.Stderr, "Failed to get status: %v\n", err) os.Exit(1) } fmt.Printf("Pipeline status: %s\n", status.Status) for _, node := range status.NodeExecutions { fmt.Printf(" Node %d: %s (query: %d, execution: %s)\n", node.ID, node.QueryExecutionStatus.Status, node.QueryExecutionStatus.QueryID, node.QueryExecutionStatus.ExecutionID) } if status.Status == "COMPLETED" || status.Status == "FAILED" { break } time.Sleep(5 * time.Second) } } ``` -------------------------------- ### Upload and Insert Data with Dune API Go Client Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Shows how to create tables from CSV data, append CSV or NDJSON data to existing tables, and clear table contents. ```go package main import ( "fmt" "os" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" "github.com/duneanalytics/duneapi-client-go/models" ) func main() { env := config.FromAPIKey("your_api_key") client := dune.NewDuneClient(env) // Upload CSV to create a new table csvData := `date,symbol,price,volume 2024-01-01,ETH,2300.50,1500000 2024-01-02,ETH,2350.25,1800000 2024-01-03,ETH,2280.00,1200000` csvResp, err := client.UploadCSV(models.UploadsCSVRequest{ TableName: "token_prices", Data: csvData, Description: "Daily token prices", IsPrivate: false, }) if err != nil { fmt.Fprintf(os.Stderr, "CSV upload failed: %v\n", err) os.Exit(1) } fmt.Printf("Uploaded to: %s (success: %v)\n", csvResp.FullName, csvResp.Success) // Insert additional CSV data into existing table additionalCsv := `2024-01-04,ETH,2400.00,2000000 2024-01-05,ETH,2450.75,2200000` insertResp, err := client.InsertIntoUpload( "my_username", "token_prices", additionalCsv, "text/csv", ) if err != nil { fmt.Fprintf(os.Stderr, "Insert failed: %v\n", err) os.Exit(1) } fmt.Printf("Inserted %d rows (%d bytes)\n", insertResp.RowsWritten, insertResp.BytesWritten) // Insert NDJSON data ndjsonData := `{"date":"2024-01-06","symbol":"ETH","price":2500.00,"volume":2500000} {"date":"2024-01-07","symbol":"ETH","price":2550.25,"volume":2800000}` insertResp, err = client.InsertIntoUpload( "my_username", "token_prices", ndjsonData, "application/x-ndjson", ) if err != nil { fmt.Fprintf(os.Stderr, "NDJSON insert failed: %v\n", err) os.Exit(1) } fmt.Printf("Inserted %d rows via NDJSON\n", insertResp.RowsWritten) // Clear all data from table (preserves schema) clearResp, err := client.ClearUpload("my_username", "token_prices") if err != nil { fmt.Fprintf(os.Stderr, "Clear failed: %v\n", err) os.Exit(1) } fmt.Printf("Table cleared: %s\n", clearResp.Message) } ``` -------------------------------- ### Perform Query CRUD Operations in Go Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Demonstrates the full lifecycle of a saved query using the Dune API client. Requires a valid API key to initialize the client. ```go package main import ( "fmt" "os" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" "github.com/duneanalytics/duneapi-client-go/models" ) func main() { env := config.FromAPIKey("your_api_key") client := dune.NewDuneClient(env) // Create a new saved query createResp, err := client.CreateQuery(models.CreateQueryRequest{ Name: "Top DEX Traders", Description: "Find top traders by volume on DEX platforms", QuerySQL: ` SELECT taker as trader, COUNT(*) as trade_count, SUM(amount_usd) as total_volume FROM dex.trades WHERE block_date >= date '{{start_date}}' GROUP BY 1 ORDER BY 3 DESC LIMIT {{limit}} `, IsPrivate: false, Parameters: []models.QueryParameter{ {Key: "start_date", Type: "date", Value: "2024-01-01"}, {Key: "limit", Type: "number", Value: "100"}, }, }) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create query: %v\n", err) os.Exit(1) } fmt.Printf("Created query ID: %d\n", createResp.QueryID) // Get query details query, err := client.GetQuery(createResp.QueryID) if err != nil { fmt.Fprintf(os.Stderr, "Failed to get query: %v\n", err) os.Exit(1) } fmt.Printf("Query: %s (owner: %s, version: %d)\n", query.Name, query.Owner, query.Version) fmt.Printf("SQL:\n%s\n", query.QuerySQL) // Update the query newName := "Top DEX Traders - Updated" newSQL := query.QuerySQL + "\n-- Last updated via API" _, err = client.UpdateQuery(createResp.QueryID, models.UpdateQueryRequest{ Name: &newName, QuerySQL: &newSQL, Tags: []string{"dex", "trading", "analytics"}, }) if err != nil { fmt.Fprintf(os.Stderr, "Failed to update query: %v\n", err) os.Exit(1) } fmt.Println("Query updated successfully") // Archive the query _, err = client.ArchiveQuery(createResp.QueryID) if err != nil { fmt.Fprintf(os.Stderr, "Failed to archive query: %v\n", err) os.Exit(1) } fmt.Println("Query archived") } ``` -------------------------------- ### Execute Queries via CLI Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Commands for building and running the Dune CLI to execute queries, handle parameters, and poll for results. ```bash # Build the CLI go build -o dunecli cmd/main.go # Execute a query and wait for results DUNE_API_KEY=your_api_key ./dunecli -q 1234567 # Execute with parameters (JSON format) DUNE_API_KEY=your_api_key ./dunecli -q 1234567 -p '{"wallet_address": "0x123...", "min_value": 1000}' # Get results for an existing execution DUNE_API_KEY=your_api_key ./dunecli -e 01HXYZ123456789ABCDEFGHIJK # Custom polling interval (10 seconds) and retry limit (20) DUNE_API_KEY=your_api_key ./dunecli -q 1234567 -poll-interval 10s -max-retries 20 # Pipe output to jq for formatting DUNE_API_KEY=your_api_key ./dunecli -q 1234567 | jq '.result.rows[0]' ``` -------------------------------- ### Execute Raw SQL Queries Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Run SQL queries directly against the Dune engine without pre-saving them. Use the WaitGetResults method to poll for completion. ```go package main import ( "fmt" "os" "time" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" "github.com/duneanalytics/duneapi-client-go/models" ) func main() { env := config.FromAPIKey("your_api_key") client := dune.NewDuneClient(env) // Execute raw SQL execution, err := client.RunSQL(models.ExecuteSQLRequest{ SQL: ` SELECT block_date, SUM(amount_usd) as total_volume FROM dex.trades WHERE block_date >= date '2024-01-01' GROUP BY 1 ORDER BY 1 DESC LIMIT 30 `, Performance: "large", // Use large cluster for heavy queries QueryParameters: map[string]any{ "custom_param": "value", // Optional parameters }, }) if err != nil { fmt.Fprintf(os.Stderr, "SQL execution failed: %v\n", err) os.Exit(1) } // Wait for results results, err := execution.WaitGetResults(5*time.Second, 20) if err != nil { fmt.Fprintf(os.Stderr, "Failed to get results: %v\n", err) os.Exit(1) } for _, row := range results.Result.Rows { fmt.Printf("%s: $%.2f\n", row["block_date"], row["total_volume"]) } } ``` -------------------------------- ### Inline Environment Variables for E2E Tests Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/e2e/README.md Provide environment variables DUNE_API_KEY and DUNE_API_KEY_OWNER_HANDLE directly on the command line for running E2E tests. This is an alternative to exporting them globally. ```bash DUNE_API_KEY=your_key DUNE_API_KEY_OWNER_HANDLE=your_namespace go test ./e2e/... -v ``` -------------------------------- ### Execute Queries via CLI Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/README.md Trigger a query execution using the CLI. Use the -p flag to provide parameters as a JSON string. ```bash DUNE_API_KEY= ./dunecli -q ``` ```bash DUNE_API_KEY= ./dunecli -q -p '{"": ""}' ``` -------------------------------- ### Explore Datasets Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/README.md Methods for listing available datasets with filtering and retrieving detailed metadata for a specific dataset. ```go // List all datasets with optional filtering datasets, err := client.ListDatasets( 50, // limit 0, // offset "dune", // owner_handle (optional, use "" to skip) "spell", // dataset_type (optional, use "" to skip) ) if err != nil { // handle error } for _, dataset := range datasets.Datasets { fmt.Printf("Dataset: %s (%s.%s)\n", dataset.Slug, dataset.Namespace, dataset.TableName) fmt.Printf(" Owner: %s\n", dataset.Owner.Handle) fmt.Printf(" Columns: %d\n", len(dataset.Columns)) } // Get detailed information about a specific dataset dataset, err := client.GetDataset("dex.trades") if err != nil { // handle error } fmt.Printf("Dataset: %s\n", dataset.Name) fmt.Printf("Description: %s\n", dataset.Description) for _, col := range dataset.Columns { fmt.Printf(" - %s (%s, nullable: %v)\n", col.Name, col.Type, col.Nullable) } ``` -------------------------------- ### Search Datasets by Contract Address in Go Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Use this to find datasets related to a specific smart contract address on specified blockchains. Schema and metadata can be included in the response. ```go package main import ( "fmt" "os" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" "github.com/duneanalytics/duneapi-client-go/models" ) func main() { env := config.FromAPIKey("your_api_key") client := dune.NewDuneClient(env) query := "uniswap" limit := int32(20) includeSchema := true // Search datasets with filters results, err := client.SearchDatasets(models.SearchDatasetsRequest{ Query: &query, Categories: []string{"dex"}, Blockchains: []string{"ethereum", "polygon"}, DatasetTypes: []string{"spell", "decoded"}, Schemas: []string{}, IncludeSchema: &includeSchema, IncludeMetadata: &includeSchema, Limit: &limit, }) if err != nil { fmt.Fprintf(os.Stderr, "Search failed: %v\n", err) os.Exit(1) } fmt.Printf("Found %d results\n", results.Total) for _, result := range results.Results { fmt.Printf("- %s (category: %s)\n", result.FullName, result.Category) if result.Description != nil { fmt.Printf(" Description: %s\n", *result.Description) } if len(result.Blockchains) > 0 { fmt.Printf(" Blockchains: %v\n", result.Blockchains) } } // Search by smart contract address contractResults, err := client.SearchDatasetsByContractAddress( models.SearchDatasetsByContractAddressRequest{ ContractAddress: "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", Blockchains: []string{"ethereum"}, Limit: &limit, IncludeSchema: &includeSchema, }, ) if err != nil { fmt.Fprintf(os.Stderr, "Contract search failed: %v\n", err) os.Exit(1) } fmt.Printf("\nFound %d datasets for contract\n", contractResults.Total) for _, result := range contractResults.Results { fmt.Printf("- %s\n", result.FullName) } } ``` -------------------------------- ### Retrieve Query Results with Pagination Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Fetch query results using an execution ID or query ID. Supports auto-pagination or manual offset and limit configuration. ```go package main import ( "fmt" "os" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" "github.com/duneanalytics/duneapi-client-go/models" ) func main() { env := config.FromAPIKey("your_api_key") client := dune.NewDuneClient(env) executionID := "01HXYZ123456789ABCDEFGHIJK" // Get all results (auto-paginated) allResults, err := client.QueryResultsV2(executionID, models.ResultOptions{}) if err != nil { fmt.Fprintf(os.Stderr, "Failed to get results: %v\n", err) os.Exit(1) } fmt.Printf("Total rows fetched: %d\n", len(allResults.Result.Rows)) // Get specific page of results pageResults, err := client.QueryResultsV2(executionID, models.ResultOptions{ Page: &models.ResultPageOption{ Offset: 1000, // Skip first 1000 rows Limit: 500, // Fetch 500 rows }, }) if err != nil { fmt.Fprintf(os.Stderr, "Failed to get page: %v\n", err) os.Exit(1) } fmt.Printf("Page rows: %d, Next offset: %v\n", len(pageResults.Result.Rows), pageResults.NextOffset) // Get results by query ID (latest execution) latestResults, err := client.ResultsByQueryID("1234567", models.ResultOptions{}) if err != nil { fmt.Fprintf(os.Stderr, "Failed to get results by query ID: %v\n", err) os.Exit(1) } fmt.Printf("Latest execution rows: %d\n", latestResults.Result.Metadata.TotalRowCount) } ``` -------------------------------- ### Run Query Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/README.md Executes a query by ID with provided parameters and returns the result rows. ```APIDOC ## POST /query/{queryID}/execute ### Description Executes a specific query and returns the result rows. ### Method POST ### Endpoint /query/{queryID}/execute ### Parameters #### Path Parameters - **queryID** (int) - Required - The ID of the query to execute. #### Request Body - **queryParameters** (map[string]any) - Optional - Key-value pairs for query parameters. ### Response #### Success Response (200) - **rows** (array) - An array of result rows. ``` -------------------------------- ### Retrieve Execution Results via CLI Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/README.md Fetch results or status for a specific execution ID. ```bash DUNE_API_KEY= ./dunecli -e ``` -------------------------------- ### Skip E2E Tests in Short Mode Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/e2e/README.md Run tests while skipping any marked as 'short', useful for CI environments where full test suites are not required. ```bash go test ./e2e/... -short ``` -------------------------------- ### Extract specific fields via CLI Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Uses the Dune CLI to execute a query and pipe the output to jq for CSV formatting. ```bash DUNE_API_KEY=your_api_key ./dunecli -q 1234567 | jq -r '.result.rows[] | [.date, .volume] | @csv' ``` -------------------------------- ### Table Management Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/README.md Comprehensive methods for managing uploaded tables, including creation, data insertion, and deletion. ```APIDOC ## POST /uploads ### Description Creates a new table with a defined schema. ### Method POST ### Endpoint /uploads ### Request Body - **Namespace** (string) - Required - **TableName** (string) - Required - **Description** (string) - Optional - **IsPrivate** (bool) - Optional - **Schema** (array) - Required - List of column definitions. ## POST /uploads/{namespace}/{tableName}/insert ### Description Inserts data into an existing table using CSV or NDJSON format. ### Method POST ### Endpoint /uploads/{namespace}/{tableName}/insert ### Parameters #### Path Parameters - **namespace** (string) - Required - **tableName** (string) - Required ### Request Body - **Data** (string) - Required - The data to insert. - **ContentType** (string) - Required - 'text/csv' or 'application/x-ndjson'. ``` -------------------------------- ### Set Environment Variables for E2E Tests Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/e2e/README.md Export required environment variables DUNE_API_KEY and DUNE_API_KEY_OWNER_HANDLE before running E2E tests. These are necessary for authentication and namespace operations. ```bash export DUNE_API_KEY=your_api_key_here export DUNE_API_KEY_OWNER_HANDLE=your_namespace go test ./e2e/... -v ``` -------------------------------- ### Run Specific E2E Upload Tests Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/e2e/README.md Execute only the upload-related end-to-end tests, specifying the test function name and a shorter timeout. ```bash go test ./e2e/... -v -run TestUpload -timeout 60s ``` -------------------------------- ### Monitor API Usage with Go Source: https://context7.com/duneanalytics/duneapi-client-go/llms.txt Retrieves current billing period statistics and historical usage data for a specific date range. ```go package main import ( "fmt" "os" "github.com/duneanalytics/duneapi-client-go/config" "github.com/duneanalytics/duneapi-client-go/dune" ) func main() { env := config.FromAPIKey("your_api_key") client := dune.NewDuneClient(env) // Get current billing period usage usage, err := client.GetUsage() if err != nil { fmt.Fprintf(os.Stderr, "Failed to get usage: %v\n", err) os.Exit(1) } fmt.Printf("Private Queries: %d\n", usage.PrivateQueries) fmt.Printf("Private Dashboards: %d\n", usage.PrivateDashboards) fmt.Printf("Storage: %d / %d bytes\n", usage.BytesUsed, usage.BytesAllowed) for _, period := range usage.BillingPeriods { fmt.Printf("\nBilling Period: %s to %s\n", period.StartDate, period.EndDate) fmt.Printf(" Credits used: %.2f / %d\n", period.CreditsUsed, period.CreditsIncluded) } // Get usage for specific date range historicalUsage, err := client.GetUsageForDates("2024-01-01", "2024-03-31") if err != nil { fmt.Fprintf(os.Stderr, "Failed to get historical usage: %v\n", err) os.Exit(1) } fmt.Printf("\nHistorical usage (Q1 2024):\n") for _, period := range historicalUsage.BillingPeriods { fmt.Printf(" %s - %s: %.2f credits\n", period.StartDate, period.EndDate, period.CreditsUsed) } } ``` -------------------------------- ### Run Specific E2E Dataset Tests Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/e2e/README.md Execute only the dataset-related end-to-end tests, specifying the test function name and a shorter timeout. ```bash go test ./e2e/... -v -run TestDataset -timeout 60s ``` -------------------------------- ### Deprecated Table Endpoints in Go Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/README.md These methods are deprecated and scheduled for removal on March 1, 2026. Migrate to the corresponding ListUploads, CreateUpload, UploadCSV, DeleteUpload, ClearUpload, and InsertIntoUpload methods. ```go // DEPRECATED: Use ListUploads instead tables, err := client.ListTables(50, 0) // DEPRECATED: Use CreateUpload instead createResp, err := client.CreateTable(req) // DEPRECATED: Use UploadCSV instead csvResp, err := client.UploadCSVDeprecated(req) // DEPRECATED: Use DeleteUpload instead deleteResp, err := client.DeleteTable("my_user", "table_name") // DEPRECATED: Use ClearUpload instead clearResp, err := client.ClearTable("my_user", "table_name") // DEPRECATED: Use InsertIntoUpload instead insertResp, err := client.InsertTable("my_user", "table_name", data, contentType) ``` -------------------------------- ### Dataset Discovery Source: https://github.com/duneanalytics/duneapi-client-go/blob/main/README.md Methods to list and retrieve detailed information about datasets available on Dune. ```APIDOC ## GET /datasets ### Description Lists all datasets with optional filtering by owner and type. ### Method GET ### Endpoint /datasets ### Parameters #### Query Parameters - **limit** (int) - Optional - Number of results to return. - **offset** (int) - Optional - Number of results to skip. - **owner_handle** (string) - Optional - Filter by owner handle. - **dataset_type** (string) - Optional - Filter by dataset type. ## GET /datasets/{datasetName} ### Description Retrieves detailed information about a specific dataset. ### Method GET ### Endpoint /datasets/{datasetName} ### Parameters #### Path Parameters - **datasetName** (string) - Required - The name of the dataset. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.