Skip to content

feat(example): add discord wallet tracker bot #82

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
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
11 changes: 11 additions & 0 deletions python/bsc-smart-contract-risk-assessment/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Python
venv/
__pycache__/

# Node
node_modules/
dist/
.env

# Others
*.log
140 changes: 140 additions & 0 deletions python/bsc-smart-contract-risk-assessment/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
# BSC Smart Contract Risk Agent

This project is an AI-powered agent that analyzes smart contract ABIs for potential risks using:

- **Python** (OpenAI + BscScan API)
- **Node.js + TypeScript** (to interact with the agent)

---

## 📁 Project Structure

```plaintext
evm_agent/
├── agent.py # Python AI agent
├── testAgent.ts # TypeScript script to call the agent
├── testAgent.js # Transpiled JavaScript output
├── .env # API keys
├── package.json
├── tsconfig.json
├── venv/ # Python virtual environment
└── node_modules/ # Node.js dependencies
```

---

## ⚙️ Step 1: Python Setup

Create a virtual environment and install the required libraries:

```bash
cd evm_agent
python -m venv venv
```

Activate the virtual environment:

- On **Windows**:

```bash
venv\Scripts\activate
```

- On **macOS/Linux**:

```bash
source venv/bin/activate
```

Install Python dependencies:

```bash
pip install openai python-dotenv langdetect requests
```

---

## 🔐 Step 2: Create the `.env` File

Create a `.env` file in the root directory and insert your API keys:

```env
BSCSCAN_API_KEY=your_bscscan_api_key_here
OPENAI_API_KEY=your_openai_api_key_here
```

---

## ⚙️ Step 3: TypeScript Setup

Install Node.js dependencies and compile the TypeScript file:

```bash
npm install
npx tsc
```

This will generate `testAgent.js` from `testAgent.ts`.

---

## ▶️ Step 4: Running the Agent

### Option 1: Run the Python script directly

```bash
python agent.py
```

Example input:

```
0x4E83362442f8e5e6cFd4081C2A2dA47F52A49089 đánh giá bằng tiếng việt
```

### Option 2: Run using Node.js

```bash
node testAgent.js
```

---

## 🧠 Features

- Extracts EVM contract address from user message
- Fetches contract ABI from BscScan
- Uses OpenAI (GPT-4 or GPT-3.5) to analyze:
- Use of `delegatecall`, `selfdestruct`, or `onlyOwner`
- Suspicious token withdrawals without approval
- Potential backdoors or unauthorized fund access
- Detects language (English or Vietnamese) and replies accordingly

---

## ⚠️ Windows Unicode Output Fix

### In `agent.py`

Add the following at the top of the file to ensure UTF-8 output in Windows terminals:

```python
import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
```

### In `testAgent.ts`

Ensure output is decoded as UTF-8:

```ts
python.stdout.on("data", (data) => {
console.log("Output:", data.toString("utf8"));
});
```

---

## ✅ Completed

You now have a working AI agent to analyze smart contract risks.
107 changes: 107 additions & 0 deletions python/bsc-smart-contract-risk-assessment/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import re
import requests
import os
from dotenv import load_dotenv
from openai import OpenAI
from langdetect import detect
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')


# Load environment variables from .env file
load_dotenv()
BSCSCAN_API_KEY = os.getenv("BSCSCAN_API_KEY")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")

# Initialize OpenAI client
client = OpenAI(api_key=OPENAI_API_KEY)


def extract_evm_address(text):
"""Extract the first EVM address found in the user input."""
match = re.search(r"0x[a-fA-F0-9]{40}", text)
return match.group(0) if match else None


def get_abi_from_bscscan(address):
"""Fetch contract ABI from BscScan API."""
url = "https://api.bscscan.com/api"
params = {
"module": "contract",
"action": "getabi",
"address": address,
"apikey": BSCSCAN_API_KEY,
}
try:
response = requests.get(url, params=params)
result = response.json()
if result.get("status") != "1":
return None
return result["result"]
except Exception as e:
print(f"Error while fetching ABI: {e}")
return None


def analyze_abi_with_ai(abi_json, user_input):
# Phát hiện ngôn ngữ đầu vào
lang = detect(user_input)
if lang.startswith("vi"):
reply_language = "Trả lời bằng tiếng Việt."
else:
reply_language = "Respond in English."

prompt = f"""You are a smart contract security expert.
Analyze the following smart contract ABI and identify any potential risks or malicious patterns.

Specifically, check for:
- Dangerous operations such as `delegatecall`, `selfdestruct`, or centralized access via `onlyOwner`.
- Any suspicious functions that may transfer or withdraw tokens or assets *without the explicit consent of the wallet owner* (e.g. `transferFrom` or hidden withdrawal logic).
- Potential backdoors or privilege escalation that allow unauthorized access to funds.

{reply_language}

Summarize your findings clearly and concisely.

ABI:
{abi_json}
"""

try:
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a smart contract auditor."},
{"role": "user", "content": prompt}
],
temperature=0.2
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"Failed to analyze ABI with AI: {str(e)}"


def main():
print("Enter user message (containing EVM contract address):")
user_input = input("> ")

address = extract_evm_address(user_input)
if not address:
print("No EVM address found in input.")
return

print(f"Found address: {address}")
abi = get_abi_from_bscscan(address)
if not abi:
print("Could not fetch ABI from BscScan.")
return

print("ABI fetched. Analyzing with AI...")
result = analyze_abi_with_ai(abi, user_input)
print("\n AI Risk Assessment:")
print(result)


if __name__ == "__main__":
main()
48 changes: 48 additions & 0 deletions python/bsc-smart-contract-risk-assessment/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions python/bsc-smart-contract-risk-assessment/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "evm_agent",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"@types/node": "^24.0.3",
"typescript": "^5.8.3"
}
}
19 changes: 19 additions & 0 deletions python/bsc-smart-contract-risk-assessment/testAgent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var child_process_1 = require("child_process");
// Nhập câu chat (có thể thay đổi)
var userInput = "0xb0C22098741B3E4EF88eEb7d8b56c6E3945C0603 đánh giá bằng tiếng việt";
// Gọi Python script
var python = (0, child_process_1.spawn)("python", ["agent.py"]);
python.stdin.write(userInput + "\n");
python.stdin.end();
// Lắng nghe output từ Python
python.stdout.on("data", function (data) {
console.log("Output:", data.toString("utf8"));
});
python.stderr.on("data", function (data) {
console.error("Error: ".concat(data));
});
python.on("close", function (code) {
console.log("Python process exited with code ".concat(code));
});
24 changes: 24 additions & 0 deletions python/bsc-smart-contract-risk-assessment/testAgent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { spawn } from "child_process";

// Nhập câu chat (có thể thay đổi)
const userInput =
"0xb0C22098741B3E4EF88eEb7d8b56c6E3945C0603 đánh giá bằng tiếng việt";

// Gọi Python script
const python = spawn("python", ["agent.py"]);

python.stdin.write(userInput + "\n");
python.stdin.end();

// Lắng nghe output từ Python
python.stdout.on("data", (data) => {
console.log("Output:", data.toString("utf8"));
});

python.stderr.on("data", (data) => {
console.error(`Error: ${data}`);
});

python.on("close", (code) => {
console.log(`Python process exited with code ${code}`);
});
Loading