# Build with AI Source: https://docs.sim.dune.com/build-with-ai Build faster with Sim APIs using LLMs. We provide several resources to help you use LLMs and AI coding assistants to build much faster with Sim APIs. ## AI Search First, **AI Search** is built directly into this documentation site. The search bar, powered by Mintlify, can understand natural language queries. Ask questions about endpoints, authentication, or specific data points, and it will answer you with the most relevant, accurate information. ## Use with LLMs ### Complete Documentation for LLMs For LLM applications such as custom agents, RAG systems, or any scenario requiring our complete documentation, we provide an optimized text file at [`https://docs.sim.dune.com/llms-full.txt`](https://docs.sim.dune.com/llms-full.txt). ### Per-Page Access Each page on this documentation site offers several ways to access its content in LLM-friendly formats: * **Copy Page:** Copies the fully rendered content of the current page. * **View Markdown:** Provides a URL with the raw Markdown source. This is ideal for direct input into LLMs. * **Open with ChatGPT:** Instantly loads the page's content into a new session with ChatGPT. Ask questions, summarize, or generate code based on the page's content. You can retrieve the Markdown version of any documentation page by appending `.md` to its URL. For example, `/evm/activity` becomes [`https://docs.sim.dune.com/evm/activity.md`](https://docs.sim.dune.com/evm/activity.md). You can also type `⌘C` or `Ctrl+C` to copy any page's Markdown content. Try it now. ## Cursor Integration To integrate our documentation directly into Cursor: 1. Go to Cursor Settings -> Features -> Docs -> Add new doc. 2. Enter "docs.sim.dune.com" in the URL field. 3. Provide a name (e.g., "@simdocs"). 4. Hit confirm. The documentation will sync automatically. 5. Reference Sim APIs documentation by typing `@simdocs` (or your chosen name) in your Cursor chat window. ## OpenAPI Specifications For a more compact format, we provide OpenAPI specifications for each of our endpoints. These files detail available parameters, request bodies, and response schemas. This format is particularly useful for LLMs and AI code generation tools to understand our API structure. You can find our OpenAPI specifications in the following directories: * EVM API specifications: [`/evm/openapi/`](https://github.com/duneanalytics/sim-docs/tree/main/evm/openapi) * SVM API specifications: [`/svm/openapi/`](https://github.com/duneanalytics/sim-docs/tree/main/svm/openapi) # Error Handling Source: https://docs.sim.dune.com/error-handling How to handle errors when using Sim APIs This guide explains how to handle errors when using Sim APIs, including common error codes, troubleshooting steps, and code examples for proper error handling. ## Error Response Format When an error occurs, Sim APIs return a standard error response format: ```json { "error": { "message": "Description of what went wrong", "code": "ERROR_CODE" } } ``` ## Common Error Codes | HTTP Status | Error Code | Description | Troubleshooting | | ----------- | ----------------------- | -------------------------- | -------------------------------------------------------------------------------------------- | | 401 | UNAUTHORIZED | Invalid or missing API key | Check that you're including the correct API key in the `X-Sim-Api-Key` header | | 400 | BAD\_REQUEST | Malformed request | Verify the address format and other parameters in your request | | 404 | NOT\_FOUND | Resource not found | Verify the endpoint URL and resource identifiers | | 429 | RATE\_LIMIT\_EXCEEDED | Too many requests | Implement backoff strategies and consider upgrading your plan if you consistently hit limits | | 500 | INTERNAL\_SERVER\_ERROR | Server-side error | Retry the request after a short delay; if persistent, contact support | ## Handling Errors in Code Here are examples of how to properly handle errors in different programming languages: ### JavaScript ```javascript fetch('https://api.sim.dune.com/v1/evm/balances/0xd8da6bf26964af9d7eed9e03e53415d37aa96045', { method: 'GET', headers: {'X-Sim-Api-Key': 'YOUR_API_KEY'} }) .then(response => { if (!response.ok) { return response.json().then(err => { throw new Error(`API error: ${err.error?.message || response.statusText}`); }); } return response.json(); }) .then(data => { console.log('Success:', data); // Process your data here }) .catch(err => { console.error('Error fetching balances:', err); // Handle error appropriately in your application // e.g., show user-friendly message, retry, or fallback behavior }); ``` ### Python ```python import requests import time def get_balances(address, api_key, max_retries=3): url = f"https://api.sim.dune.com/v1/evm/balances/{address}" headers = {"X-Sim-Api-Key": api_key} for attempt in range(max_retries): try: response = requests.get(url, headers=headers) response.raise_for_status() # Raises an exception for 4XX/5XX responses return response.json() except requests.exceptions.HTTPError as err: status_code = err.response.status_code error_data = {} try: error_data = err.response.json() except: pass error_message = error_data.get('error', {}).get('message', 'Unknown error') print(f"HTTP Error {status_code}: {error_message}") # Handle specific error codes if status_code == 429: # Rate limit exceeded wait_time = min(2 ** attempt, 60) # Exponential backoff print(f"Rate limit exceeded. Retrying in {wait_time} seconds...") time.sleep(wait_time) continue elif status_code == 500: # Server error if attempt < max_retries - 1: wait_time = 2 ** attempt print(f"Server error. Retrying in {wait_time} seconds...") time.sleep(wait_time) continue # For other errors or if we've exhausted retries return {"error": error_message, "status_code": status_code} except requests.exceptions.RequestException as err: print(f"Request error: {err}") return {"error": "Network or connection error", "details": str(err)} return {"error": "Max retries exceeded"} # Usage result = get_balances("0xd8da6bf26964af9d7eed9e03e53415d37aa96045", "YOUR_API_KEY") if "error" in result: print(f"Failed to get balances: {result['error']}") else: print(f"Found {len(result['balances'])} token balances") ``` ## Best Practices for Error Handling 1. **Always check for errors**: Don't assume API calls will succeed. 2. **Implement retry logic with backoff**: For transient errors (like rate limits or server errors), implement exponential backoff: ```javascript async function fetchWithRetry(url, options, maxRetries = 3) { let retries = 0; while (retries < maxRetries) { try { const response = await fetch(url, options); if (response.ok) return response.json(); const error = await response.json(); // Don't retry for client errors (except rate limiting) if (response.status < 500 && response.status !== 429) { throw new Error(error.error?.message || response.statusText); } // For rate limiting or server errors, retry with backoff retries++; const delay = Math.min(1000 * 2 ** retries, 10000); await new Promise(resolve => setTimeout(resolve, delay)); } catch (err) { if (retries === maxRetries - 1) throw err; retries++; } } } ``` 3. **Provide meaningful error messages**: Transform API error responses into user-friendly messages. 4. **Log errors for debugging**: Maintain detailed logs of API errors for troubleshooting. 5. **Implement fallbacks**: When possible, have fallback behavior when API calls fail. ## Debugging Tips If you're experiencing persistent errors: 1. **Verify your API key**: Ensure it's valid and has the necessary permissions. 2. **Check request format**: Validate that your request parameters match the API specifications. 3. **Inspect full error responses**: The error message often contains specific details about what went wrong. 4. **Monitor your usage**: Check if you're approaching or exceeding rate limits. 5. **Test with cURL**: Isolate issues by testing the API directly with cURL: ```bash curl -v -X GET "https://api.sim.dune.com/v1/evm/balances/0xd8da6bf26964af9d7eed9e03e53415d37aa96045" \ -H "X-Sim-Api-Key: YOUR_API_KEY" ``` ## Need More Help? If you're still experiencing issues after following these guidelines, please reach out through our [support channels](/support). # Activity Source: https://docs.sim.dune.com/evm/activity evm/openapi/activity.json get /v1/evm/activity/{uri} View chronologically ordered transactions including native transfers, ERC20 movements, NFT transfers, and decoded contract interactions. export const SupportedChains = ({endpoint}) => { const [data, setData] = useState(null); useEffect(() => { fetch("https://api.sim.dune.com/v1/evm/supported-chains", { method: "GET", headers: { "X-Sim-Api-Key": "sim_qfIvSWu7c8WBXzfCQ0SeLBGJts204uyT" } }).then(response => response.json()).then(setData); }, []); if (data === null) { return null; } const chains = endpoint !== undefined ? data.chains.filter(chain => chain[endpoint]?.supported) : data.chains; console.log("data", data); return {chains.map(chain => )}
name chain_id tags
{chain.name} {chain.chain_id} {chain.tags.join(", ")}
; }; ![Activity Sv](https://mintlify.s3.us-west-1.amazonaws.com/sim-dune/images/activity.svg) The Activity API provides a realtime feed of onchain activity for any EVM address. The newest activity is returned first and includes: * Native token transfers * ERC20 token transfers with metadata (symbol, decimals) * ERC721 (NFT) transfers with token IDs * Contract interactions with decoded function calls ## Spam Tokens The Activity API supports filtering out activities related to spam tokens using the `?exclude_spam_tokens` parameter. When specified, this parameter will exclude transactions and transfers involving tokens that meet spam criteria, providing a cleaner activity feed. We include all the data needed for custom filtering in the responses, allowing you to implement your own filtering logic. For a detailed explanation of our spam filtering approach, see our [Spam Token Filtering](/spam-filtering) guide. # Add Account Activity Source: https://docs.sim.dune.com/evm/add-account-activity Expand your realtime crypto wallet by integrating a dynamic feed of onchain activity. Now that you have a wallet capable of showing realtime token balances and total portfolio value, let's enhance it by adding an *Activity* tab. A key feature for any wallet is the ability to view past transaction activity. This includes native currency transfers, ERC20 token movements, NFT transfers, and decoded interactions with smart contracts. The [Activity API](/evm/activity) provides a comprehensive, realtime feed of this onchain activity, letting you implement this functionality with a single API request across 60+ EVM chains. Access the complete source code for this wallet on GitHub Interact with the finished wallet app This guide assumes you've completed the first guide, [Build a Realtime Wallet](/evm/build-a-realtime-wallet). Your project should already be set up to fetch and display token balances. ## See It in Action You can see the activity feed in action by trying the live demo below. Click on the "Activity" tab to explore transaction history for the sample wallet: