For Agents & LLMs
Insight is a powerful tool that can be used to power AI agents and LLMs with blockchain data. To use the API in your AI agent you can use the llms.txt file bellow.
- llms.txt file
- For developers who prefer working with OpenAPI specifications, our complete API documentation is available in OpenAPI format here.
If you prefer to use the API in an LLM prompt, the schema below can be copied and pasted into the AI assistant of your choice. Feed this to your assistant, then ask your assistant to construct Insight queries on your behalf, asking it for certain onchain information.
# ATTENTION LLMs - API Usage Instructions## API URL```typescriptconst baseUrl = `https://{{chainId}}.insight.thirdweb.com`;```## AuthenticationThe API supports three authentication methods:```typescript// 1. Header Authenticationconst headers = {"x-client-id": "{{clientId}}", // thirdweb Client ID};// 2. Query Parameterconst url = "https://{{chainId}}.insight.thirdweb.com/v1/events?clientId={{clientId}}";// 3. Bearer Tokenconst headers = {Authorization: "Bearer {{jwtToken}}",};// Example using fetch with header authasync function getEvents() {const response = await fetch("https://{{chainId}}.insight.thirdweb.com/v1/events", {headers: {"x-client-id": "{{clientId}}",},});return await response.json();}```## Core Concepts### Chain IDs- As a subdomain:```typescript// Exampleconst baseUrl = `https://{{chainId}}.insight.thirdweb.com`;```- As a query parameter (this is useful if you want to query multiple chains):```typescript// Example for a single chainconst url = `https://insight.thirdweb.com/v1/events?chain={{chainId}}`;// Example for multiple chainsconst url = `https://insight.thirdweb.com/v1/events?chain=1&chain=137`;```We won't duplicate multichain examples for each endpoint, but you can pass multiple chains in the query parameters pretty much everywhere!### Base Response Structure```typescriptinterface BaseResponse<T> {data: T[];meta: {chain_id: number; // Requiredpage: number; // Requiredlimit: number; // Requiredtotal_items: number; // Requiredtotal_pages: number; // Requiredaddress?: string; // Optionalsignature?: string; // Optional}}// Example response from getting events{"data": [{"chain_id": 1,"block_number": "{{blockNumber}}","transaction_hash": "{{transactionHash}}","address": "{{contractAddress}}","data": "{{data}}","topics": ["{{topic}}"]}],"meta": {"chain_id": 1,"page": 0,"limit": 20,"total_items": 150,"total_pages": 8}}```## API Examples### Events API```typescript// 1. Get All Eventsasync function getAllEvents() {const response = await fetch("https://{{chainId}}.insight.thirdweb.com/v1/events", {headers: { "x-client-id": "{{clientId}}" },});return await response.json();}// 2. Get Contract Events with Filteringasync function getContractEvents(contractAddress: string) {const params = new URLSearchParams({filter_block_number_gte: blockNumber,sort_by: "block_timestamp",sort_order: "desc",limit: "{{limit}}",});const url = `https://{{chainId}}.insight.thirdweb.com/v1/events/{{contractAddress}}?${params}`;const response = await fetch(url, {headers: { "x-client-id": "{{clientId}}" },});return await response.json();}```### Token Balance API```typescript// 1. Get ERC20 Balancesasync function getERC20Balances(ownerAddress: string) {const response = await fetch(`https://{{chainId}}.insight.thirdweb.com/v1/tokens/erc20/${ownerAddress}`,{ headers: { "x-client-id": "{{clientId}}" } },);const data = await response.json();// Example response:// {// "data": [// {// "tokenAddress": "0x123...",// "balance": "1000000000000000000"// }// ]// }return data;}// 2. Get NFT Balancesasync function getNFTBalances(ownerAddress: string) {const response = await fetch(`https://{{chainId}}.insight.thirdweb.com/v1/tokens/erc721/${ownerAddress}`,{ headers: { "x-client-id": "{{clientId}}" } },);const data = await response.json();// Example response:// {// "data": [// {// "collectionAddress": "0x456...",// "tokenId": "1",// "balance": "1"// }// ]// }return data;}```### AggregationsInsight supports powerful aggregation functions that can be used to analyze blockchain data. Here's how to use them:```typescript// Basic aggregation structureconst response = await fetch('https://{{chainId}}.insight.thirdweb.com/v1/endpoint?aggregate=function(field) AS alias',{ headers: { 'x-client-id': '{{clientId}}' } });// Multiple aggregations in one requestconst response = await fetch('https://{{chainId}}.insight.thirdweb.com/v1/endpoint?aggregate=count() AS total&aggregate=sum(value) AS total_value',{ headers: { 'x-client-id': '{{clientId}}' } });// With filtersconst response = await fetch('https://{{chainId}}.insight.thirdweb.com/v1/transactions?aggregate=count() AS tx_count&filter_timestamp_gte=2024-01-01',{ headers: { 'x-client-id': '{{clientId}}' } });```#### Aggregation Presets available in the playground as examples1. **Default Aggregations**- `count() AS count_all` - Count all items- `sum(gas_used) AS total_gas_used` - Total gas used- `avg(gas_used) AS avg_gas_used` - Average gas used- `min(gas_used) AS min_gas_used` - Minimum gas used- `max(gas_used) AS max_gas_used` - Maximum gas used- `countDistinct(column_name) AS unique_count` - Count distinct values2. **Events Specific**- `count() AS event_count` - Count events- `countDistinct(address) AS unique_addresses` - Unique addresses- `min(block_number) AS min_block` - Minimum block number- `max(block_number) AS max_block` - Maximum block number3. **Transactions Specific**- `count() AS transaction_count` - Count transactions- `sum(value) AS total_value_wei` - Total value transferred- `sum(gas_used) AS total_gas_used` - Total gas used- `avg(value) AS avg_value_wei` - Average value- `avg(gas_used) AS avg_gas_used` - Average gas used- `countDistinct(from_address) AS unique_senders` - Unique senders- `countDistinct(to_address) AS unique_receivers` - Unique receivers4. **Wallet Transactions**- `count() AS transaction_count` - Transaction count- `sum(value) AS total_value_wei` - Total value- `avg(value) AS avg_value_wei` - Average value- `sum(gas_used * gas_price) AS total_fees_wei` - Total fees5. **Blocks Specific**- `sum(transaction_count) AS total_transactions` - Total transactions- `avg(transaction_count) AS avg_transactions_per_block` - Avg tx/block- `sum(gas_used) AS total_gas_used` - Total gas used- `min(number) AS min_block_number` - Min block number- `max(number) AS max_block_number` - Max block number#### Common Aggregation Examples```typescript// 1. Get transaction statisticsconst txStats = await fetch('https://{{chainId}}.insight.thirdweb.com/v1/transactions?aggregate=count() AS transaction_count&aggregate=sum(value) AS total_value_wei&aggregate=avg(gas_used) AS avg_gas_used',{ headers: { 'x-client-id': '{{clientId}}' } });// 2. Get wallet transaction statsconst walletStats = await fetch('https://{{chainId}}.insight.thirdweb.com/v1/wallets/0x123.../transactions?aggregate=count() AS transaction_count&aggregate=sum(value) AS total_value_wei&aggregate=sum(gas_used * gas_price) AS total_fees_wei',{ headers: { 'x-client-id': '{{clientId}}' } });```#### Filtering with Aggregations```typescript// Get transaction stats for a specific time periodconst txStats = await fetch('https://{{chainId}}.insight.thirdweb.com/v1/transactions?aggregate=count() AS transaction_count&aggregate=sum(value) AS total_value_wei&filter_timestamp_gte=2024-01-01&filter_timestamp_lte=2024-01-31',{ headers: { 'x-client-id': '{{clientId}}' } });// Get block metrics for recent blocksconst blockStats = await fetch('https://{{chainId}}.insight.thirdweb.com/v1/blocks?aggregate=sum(transaction_count) AS total_transactions&aggregate=avg(transaction_count) AS avg_transactions_per_block&filter_number_gte=18000000',{ headers: { 'x-client-id': '{{clientId}}' } });```### Using Filters```typescript// Example: Get events with complex filteringasync function getFilteredEvents() {const params = new URLSearchParams({// Block filtersfilter_block_number_gte: blockNumberStart,filter_block_number_lte: blockNumberEnd,// Time filtersfilter_block_timestamp_gte: "{{timestamp}}",// Transaction filtersfilter_from_address: "{{fromAddress}}",filter_value_gte: "{{value}}", // 1 ETH// Paginationpage: "{{page}}",limit: "{{limit}}",// Sortingsort_by: "{{sortBy}}",sort_order: "{{sortOrder}}",});const response = await fetch(`https://{{chainId}}.insight.thirdweb.com/v1/events?${params}`,{ headers: { "x-client-id": "{{clientId}}" } },);return await response.json();}```### Error Handling```typescriptasync function safeApiCall() {try {const response = await fetch("https://{{chainId}}.insight.thirdweb.com/v1/events", {headers: { "x-client-id": "{{clientId}}" },});if (!response.ok) {const errorData = await response.json();// Example error response:// { "error": "Invalid client ID" }throw new Error(errorData.error);}return await response.json();} catch (error) {console.error("API Error:", error.message);throw error;}}```## WebhooksWebhooks are a powerful tool for building event-driven AI agents that can react to on-chain activity in real-time. By subscribing to specific blockchain events or transactions, your agent can receive notifications and trigger automated workflows.### Use Cases for AI Agents- **Real-time Monitoring**: An agent can monitor for specific events (e.g., a large transfer to a whale wallet) and trigger alerts or other actions.- **Automated Workflows**: When a specific on-chain action occurs (e.g., a new NFT is minted), an agent can automatically kick off a downstream process, like updating a database or sending a notification.- **Data Aggregation**: Use webhooks to feed on-chain data into a vector database or other data store for later analysis by an LLM.### Getting Started with WebhooksTo get started, you can create and manage webhooks through the Insight API. For detailed instructions, refer to the [Managing Webhooks documentation](/insight/webhooks/managing-webhooks).### Filtering EventsInsight's webhooks feature a powerful filtering system that lets you subscribe to only the events and transactions you care about. For example, you can create a single webhook that notifies your agent of both ERC-20 and ERC-721 `Transfer` events by providing multiple ABIs in the filter.```typescript{"v1.events": {"chain_ids": ["1"],"signatures": [{"sig_hash": "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef","abi": "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"}]"}]}}```For more advanced filtering options, see the [Filtering documentation](/insight/webhooks/filtering).### Understanding the PayloadWhen a webhook is triggered, it sends a payload to your specified endpoint. This payload contains the event or transaction data that your agent will need to process. To learn more about the structure of this payload, see the [Payload documentation](/insight/webhooks/payload).## API Reference### Events API1. **Get All Events**```typescriptGET /v1/eventsinterface EventsResponse {data: Event[];meta: MetaData;}```2. **Get Contract Events**```typescriptGET /v1/events/:contractAddress```3. **Get Specific Event Type**```typescriptGET /v1/events/:contractAddress/:signature```### Transactions API1. **Get All Transactions**```typescriptGET /v1/transactions```2. **Get Contract Transactions**```typescriptGET /v1/transactions/:contractAddress```3. **Get Specific Transaction Type**```typescriptGET /v1/transactions/:contractAddress/:signature```### Token Balance API1. **ERC20 Balances**```typescriptGET /v1/tokens/erc20/:ownerAddressinterface ERC20Response {data: {tokenAddress: string; // Requiredbalance: string; // Required}[];}```2. **ERC721 & ERC1155 Balances**```typescriptGET /v1/tokens/erc721/:ownerAddressGET /v1/tokens/erc1155/:ownerAddressinterface TokenBalanceResponse {data: {collectionAddress: string; // RequiredtokenId: string; // Requiredbalance: string; // Required}[];}```## Query Parameters### Common Parameters```typescriptinterface CommonQueryParams {page?: number; // Default: 0limit?: number; // Default: 20, must be > 0sort_by?: "block_number" | "block_timestamp" | "transaction_index";sort_order?: "asc" | "desc";group_by?: string; // Group results by a specific fieldaggregate?: string[]; // Apply aggregate functions (count, sum, avg, etc.) to grouped results}```### Filter Types1. **Block Filters**```typescriptinterface BlockFilters {filter_block_number?: number; // Example: 1000000filter_block_number_gte?: number; // Example: 1000000filter_block_number_gt?: number; // Example: 1000000filter_block_number_lte?: number; // Example: 1000000filter_block_number_lt?: number; // Example: 1000000filter_block_hash?: string; // Example: "0x3a1fba5..."}```2. **Time Filters**```typescriptinterface TimeFilters {filter_block_timestamp?: number; // Example: 1715222400filter_block_timestamp_gte?: number; // Example: 1715222400filter_block_timestamp_gt?: number; // Example: 1715222400filter_block_timestamp_lte?: number; // Example: 1715222400filter_block_timestamp_lt?: number; // Example: 1715222400}```3. **Transaction Filters**```typescriptinterface TransactionFilters {filter_transaction_index?: number;filter_transaction_hash?: string;filter_from_address?: string;filter_value?: string; // Value in wei (e.g., "1000000000000000000" for 1 ETH)filter_value_gte?: string;filter_value_gt?: string;filter_value_lte?: string;filter_value_lt?: string;filter_gas_price?: number;filter_gas?: number;// Additional gte, gt, lte, lt variants for numeric fields}```## Error HandlingAll endpoints return standard error responses for 400 and 500 status codes:```typescript// 400 Bad Request// 500 Internal Server Errorinterface ErrorResponse {error: string; // Required}```