Skip to content

Commit

Permalink
Merge pull request focai-acc#3 from chainbase-labs/add-chainbase-plugin
Browse files Browse the repository at this point in the history
feat: chainbase plugin for focEliza
  • Loading branch information
cpppppp7 authored Jan 12, 2025
2 parents 82607be + 05a63d8 commit 3c09a59
Show file tree
Hide file tree
Showing 17 changed files with 844 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -467,3 +467,6 @@ TAVILY_API_KEY=
# Verifiable Inference Configuration
VERIFIABLE_INFERENCE_ENABLED=false # Set to false to disable verifiable inference
VERIFIABLE_INFERENCE_PROVIDER=opacity # Options: opacity

# Chainbase Configuration
CHAINBASE_API_KEY=demo # demo is free tier
1 change: 1 addition & 0 deletions agent/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
"@elizaos/plugin-arthera": "workspace:*",
"@elizaos/plugin-allora": "workspace:*",
"@elizaos/plugin-opacity": "workspace:*",
"@elizaos/plugin-chainbase": "workspace:*",
"readline": "1.3.0",
"ws": "8.18.0",
"yargs": "17.7.2"
Expand Down
2 changes: 2 additions & 0 deletions agent/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ import { zksyncEraPlugin } from "@elizaos/plugin-zksync-era";
import { OpacityAdapter } from "@elizaos/plugin-opacity";
import { openWeatherPlugin } from "@elizaos/plugin-open-weather";
import { stargazePlugin } from "@elizaos/plugin-stargaze";
import { chainbasePlugin } from "@elizaos/plugin-chainbase";
import Database from "better-sqlite3";
import fs from "fs";
import net from "net";
Expand Down Expand Up @@ -729,6 +730,7 @@ export async function createAgent(
? artheraPlugin
: null,
getSecret(character, "ALLORA_API_KEY") ? alloraPlugin : null,
getSecret(character, "CHAINBASE_API_KEY") ? chainbasePlugin : null,
].filter(Boolean),
providers: [],
actions: [],
Expand Down
66 changes: 66 additions & 0 deletions packages/plugin-chainbase/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Chainbase Plugin for Eliza

The Chainbase Plugin for Eliza bridges the gap between on-chain data and AI agents, enabling natural language interactions with blockchain data across multiple networks. This plugin leverages Chainbase's comprehensive blockchain data infrastructure to provide real-time insights and analytics.

## Description

This plugin serves as a powerful interface between Eliza AI agents and blockchain data, allowing users to query and analyze on-chain information using natural language. It transforms complex blockchain queries into actionable insights without requiring deep technical knowledge.

## Key Features

- **Multi-chain Data Access**: Access comprehensive data across multiple blockchain networks
- **Natural Language Processing**: Convert natural language queries into blockchain data analytics and insights
- **Real-time Data**: Get up-to-date blockchain information and analytics

## Supported Networks

- Ethereum
- Polygon
- BNB Smart Chain (BSC)
- Avalanche
- Arbitrum One
- Optimism
- Base
- zkSync
- Merlin

## Usage Examples

### On-chain Data Queries

```plaintext
Query: "query onchain data: This address 0x8308964da9ed5d2e8012023d7c7ef02f9e6438c7 which tokens on Ethereum are held"
```

This query will return the token holdings for the specified Ethereum address.

```plaintext
Query: "query onchain data: List the top 10 Ethereum blocks by total gas used in the last 24 hours"
```

This query will analyze and return gas usage statistics for recent Ethereum blocks.

```plaintext
Query: "query onchain data: The address 0x8308964da9ed5d2e8012023d7c7ef02f9e6438c7 last 10 Ethereum token transfer"
```

This query will fetch the most recent 10 token transfer events for the specified Ethereum address, including both incoming and outgoing transfers.

## Components

- **Actions**: Pre-configured blockchain data retrieval and analysis actions
- **Providers**: Data providers for different blockchain networks
- **Evaluators**: Analysis tools for blockchain data interpretation
- **Services**: Specialized services for data processing and transformation

## Getting Started

To use this plugin, you'll need a Chainbase API key:

1. Visit [Chainbase Platform](https://console.chainbase.com) to create an account
2. Once logged in, you can obtain a free API key from your dashboard
3. Set your API key as the `CHAINBASE_API_KEY` environment variable

For development and testing purposes, you can use the API key "demo" to test the basic functionality.

For more detailed information about the available APIs and endpoints, please refer to the [Chainbase API Documentation](https://docs.chainbase.com/api-reference/overview).
3 changes: 3 additions & 0 deletions packages/plugin-chainbase/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import eslintGlobalConfig from "../../eslint.config.mjs";

export default [...eslintGlobalConfig];
Empty file.
14 changes: 14 additions & 0 deletions packages/plugin-chainbase/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "@elizaos/plugin-chainbase",
"version": "0.1.7-alpha.1",
"main": "dist/index.js",
"type": "module",
"types": "dist/index.d.ts",
"dependencies": {
"@elizaos/core": "workspace:*"
},
"scripts": {
"build": "tsup --format esm --dts",
"dev": "tsup --format esm --dts --watch"
}
}
228 changes: 228 additions & 0 deletions packages/plugin-chainbase/src/actions/queryData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
import {
Action,
IAgentRuntime,
Memory,
State,
HandlerCallback,
elizaLogger,
generateText,
ModelClass,
} from "@elizaos/core";
import { generateSQL, executeQuery } from "../libs/chainbase";
import { responsePrompt } from "../templates";

const QUERY_PREFIX = "query onchain data:";

export const queryBlockChainData: Action = {
name: "QUERY_BLOCKCHAIN_DATA",
similes: ["ANALYZE_BLOCKCHAIN", "GET_CHAIN_DATA", "QUERY_ONCHAIN_DATA"],
description:
"Query blockchain data using natural language starting with 'query onchain data:'",

validate: async (runtime: IAgentRuntime, message: Memory) => {
elizaLogger.log("Validating runtime for QUERY_BLOCKCHAIN_DATA...");
return !!(
runtime.character.settings.secrets?.CHAINBASE_API_KEY ||
process.env.CHAINBASE_API_KEY
);
},

handler: async (
runtime: IAgentRuntime,
message: Memory,
state?: State,
options?: { [key: string]: unknown },
callback?: HandlerCallback
) => {
try {
const messageText = message.content.text.toLowerCase();

if (!messageText.includes(QUERY_PREFIX)) {
callback({
text: `Please use the format: ${QUERY_PREFIX} <your natural language query>`,
});
return;
}

const queryText = message.content.text
.slice(
message.content.text.toLowerCase().indexOf(QUERY_PREFIX) +
QUERY_PREFIX.length
)
.trim();

if (!queryText) {
callback({
text: `Please provide a specific query after '${QUERY_PREFIX}'`,
});
return;
}

// Generate SQL from natural language
const sql = await generateSQL(queryText);

// Execute query on Chainbase
const result = await executeQuery(sql);

// Use generateText to format the response
const formattedResponse = await generateText({
runtime,
context: responsePrompt(
{
sql,
columns: result.columns,
data: result.data,
totalRows: result.totalRows,
},
queryText
),
modelClass: ModelClass.SMALL,
});

callback({
text: formattedResponse,
});
} catch (error) {
elizaLogger.error("Error in queryChainbase action:", error);
return "error";
}
},

examples: [
[
{
user: "user",
content: {
text: "query onchain data: Calculate the average gas used per block on Ethereum in the last 100 blocks",
action: "QUERY_BLOCKCHAIN_DATA",
},
},
{
user: "assistant",
content: {
text: "📊 Query Results...",
},
},
],
[
{
user: "user",
content: {
text: "query onchain data: Show me the top 10 active Ethereum addresses by transaction count in the last 1000 blocks",
action: "QUERY_BLOCKCHAIN_DATA",
},
},
{
user: "assistant",
content: {
text: "📊 Query Results...",
},
},
],
[
{
user: "user",
content: {
text: "query onchain data: List Ethereum transactions with value greater than 1 ETH in the last 1000 blocks",
action: "QUERY_BLOCKCHAIN_DATA",
},
},
{
user: "assistant",
content: {
text: "📊 Query Results...",
},
},
],
[
{
user: "user",
content: {
text: "query onchain data: Calculate the total ETH transaction fees collected in the last 100 Ethereum blocks",
action: "QUERY_BLOCKCHAIN_DATA",
},
},
{
user: "assistant",
content: {
text: "📊 Query Results...",
},
},
],
[
{
user: "user",
content: {
text: "query onchain data: Show me the distribution of ETH transaction values in the last 1000 Ethereum transactions",
action: "QUERY_BLOCKCHAIN_DATA",
},
},
{
user: "assistant",
content: {
text: "📊 Query Results...",
},
},
],
[
{
user: "user",
content: {
text: "query onchain data: Find Ethereum blocks that have more than 200 transactions in the last 24 hours",
action: "QUERY_BLOCKCHAIN_DATA",
},
},
{
user: "assistant",
content: {
text: "📊 Query Results...",
},
},
],
[
{
user: "user",
content: {
text: "query onchain data: What's the average gas price trend on Ethereum mainnet in the last 1000 blocks",
action: "QUERY_BLOCKCHAIN_DATA",
},
},
{
user: "assistant",
content: {
text: "📊 Query Results...",
},
},
],
[
{
user: "user",
content: {
text: "query onchain data: Show me Ethereum addresses that have both sent and received ETH in the last 100 blocks",
action: "QUERY_BLOCKCHAIN_DATA",
},
},
{
user: "assistant",
content: {
text: "📊 Query Results...",
},
},
],
[
{
user: "user",
content: {
text: "query onchain data: List the top 10 Ethereum blocks by total gas used in the last 24 hours",
action: "QUERY_BLOCKCHAIN_DATA",
},
},
{
user: "assistant",
content: {
text: "📊 Query Results...",
},
},
],
],
};
Loading

0 comments on commit 3c09a59

Please sign in to comment.