Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions adifi/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ANTHROPIC_API_KEY=your_anthropic_api_key_here
GRAPH_API_KEY=your_graph_api_key_here
18 changes: 18 additions & 0 deletions adifi/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Environment files
.env
.env.*
!.env.example

# Dependencies
node_modules/

# Build outputs
dist/
build/

# Logs
*.log

# IDE files
.vscode/
.idea/
123 changes: 123 additions & 0 deletions adifi/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# Adifi - AI-Powered Uniswap Trading Assistant

Adifi is an intelligent trading assistant that provides real-time analysis and recommendations for Uniswap pools. Built with AI technology powered by Claude 3 Sonnet, it helps traders make informed decisions by analyzing pool metrics and market conditions.

## Features

- 🤖 AI-powered trading analysis
- 📊 Real-time Uniswap pool metrics
- 💡 Smart trading recommendations
- ⚠️ Risk assessment and warnings
- 🎯 Entry, exit, and stop-loss suggestions

## Tech Stack

- Frontend: React + Vite + TypeScript
- Backend: Express.js + Node.js
- AI: Anthropic's Claude 3 + LangChain
- DeFi: Uniswap + The Graph Protocol
- Infrastructure: Vercel

## Prerequisites

- Node.js 18.x
- npm 8.x or higher
- An Anthropic API key
- A Graph Protocol API key

## Installation

1. Clone the repository:
```bash
git clone <repository-url>
cd examples/typescript/cli-agent
```

2. Install dependencies:
```bash
npm install
```

3. Create a `.env` file in the project root:
```bash
ANTHROPIC_API_KEY=your_anthropic_api_key
GRAPH_API_KEY=your_graph_api_key
```

## Running Locally

1. Start the development server:
```bash
npm run dev
```
This will start both the frontend and backend servers concurrently.

Or start them separately:
```bash
# Terminal 1 - Start API server
npm run dev:server

# Terminal 2 - Start frontend
npm run dev:web
```

2. Open your browser and navigate to:
- Frontend: http://localhost:5173
- API: http://localhost:3001

## Usage Guide

1. **Basic Query**
- Enter a Uniswap pool address in the chat
- Example: "Analyze the trading setup for the ETH/USDC pool at 0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8"

2. **Understanding Responses**
The AI will provide:
- Market Analysis
- Trading Recommendation (Buy/Sell/Hold)
- Entry Price
- Stop Loss Level
- Take Profit Target
- Confidence Level
- Risk Warning

3. **Example Queries**
- "Should I enter a position in the ETH/USDC pool now?"
- "What's the current market condition for the USDC/ETH pool?"
- "Analyze the trading setup for [pool address]"

## Production Build

To create a production build:
```bash
npm run build
npm run preview
```

## Environment Variables

- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude 3
- `GRAPH_API_KEY`: Your Graph Protocol API key
- `VITE_API_URL`: API URL for production (set automatically)

## Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## Disclaimer

This tool provides trading analysis and suggestions based on AI interpretations of market data. All trading decisions should be made with careful consideration of your own research and risk tolerance. This is not financial advice.

## License

This project is licensed under the Apache-2.0 License - see the LICENSE file for details.

## Support

From Latam to the world 🌎

For support, please open an issue in the repository or contact the development team.
152 changes: 152 additions & 0 deletions adifi/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import express from 'express';
import cors from 'cors';
import { ChatAnthropic } from "@langchain/anthropic";
import { HumanMessage } from "@langchain/core/messages";
import { UniswapTool } from '../src/tools/uniswapTool';
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { MemorySaver } from "@langchain/langgraph";
import { WardenAgentKit } from "@wardenprotocol/warden-agent-kit-core";
import { WardenToolkit } from "@wardenprotocol/warden-langchain";
import * as dotenv from 'dotenv';

// Load environment variables
dotenv.config();

const app = express();

// CORS setup as per Vercel docs
app.use(
cors({
origin: [
"http://localhost:3000",
"http://localhost:5173",
"http://localhost:5174",
"https://agentaiblockchainadifi-juls95-juls95s-projects.vercel.app"
],
})
);

app.use(express.json());

// Initialize agent
let agent: any = null;
let isInitializing = false;

async function initializeAgent() {
if (isInitializing) return;
isInitializing = true;

try {
const llm = new ChatAnthropic({
modelName: "claude-3-sonnet-20240229",
anthropicApiKey: process.env.ANTHROPIC_API_KEY,
});

const config = {
privateKeyOrAccount: process.env.PRIVATE_KEY as `0x${string}` || undefined,
};

const agentkit = new WardenAgentKit(config);
const uniswapTool = new UniswapTool();
const wardenToolkit = new WardenToolkit(agentkit as any);
const tools = [...wardenToolkit.getTools(), uniswapTool];

const memory = new MemorySaver();

agent = await createReactAgent({
llm,
tools,
checkpointSaver: memory,
messageModifier: `
You're a specialized Uniswap trading analyst. When users ask about Uniswap pools:
1. ALWAYS use the get_uniswap_metrics tool with the exact pool address first
2. Analyze the metrics and provide:
- Current market conditions
- Trading recommendation (Buy/Sell/Hold)
- Suggested entry price
- Recommended stop-loss level (usually 2-5% below entry for buys)
- Target price for taking profits
3. Include a confidence level (Low/Medium/High) based on:
- Volume trends
- Price stability
- Liquidity depth
4. Add risk warnings and remind users this is not financial advice

Format your response like this:
Market Analysis: [your analysis of current metrics]
Trading Setup:
- Recommendation: [Buy/Sell/Hold]
- Entry Price: [price]
- Stop Loss: [price]
- Take Profit: [price]
Confidence Level: [Low/Medium/High]
Risk Warning: [your risk warning]
`
});

console.log('Trading analysis agent initialized successfully');
return agent;
} catch (error) {
console.error('Failed to initialize agent:', error);
throw error;
} finally {
isInitializing = false;
}
}

// Health check endpoint
app.get('/', (req, res) => {
res.json({ status: 'API is running' });
});

// Chat endpoint
app.post('/chat', async (req, res) => {
try {
const { message } = req.body;
if (!message) {
return res.status(400).json({ error: 'Message is required' });
}

if (!agent) {
await initializeAgent();
}

if (!agent) {
return res.status(503).json({ error: 'Agent not initialized' });
}

const stream = await agent.stream(
{ messages: [new HumanMessage(message)] },
{ configurable: { thread_id: "Warden Agent Kit API!" } }
);

let response = '';
for await (const chunk of stream) {
if ("agent" in chunk) {
response = chunk.agent.messages[0].content;
} else if ("tools" in chunk) {
response = chunk.tools.messages[0].content;
}
}

res.json({ response });
} catch (error: unknown) {
console.error('Chat error:', error);
if (error instanceof Error) {
res.status(500).json({ error: error.message });
} else {
res.status(500).json({ error: 'An unknown error occurred' });
}
}
});

// Only start the server if we're running locally
if (process.env.NODE_ENV !== 'production') {
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log('Environment:', process.env.NODE_ENV || 'development');
});
}

export default app;
Loading