AI Image Generation
Create stunning visuals with DALL-E 3
Tarex Documentation
Comprehensive Technical Documentation for BNB Chain AI Intelligence Platform
Overview
Tarex is an advanced AI-powered intelligence platform specifically designed for the BNB Chain ecosystem. Built on cutting-edge artificial intelligence and blockchain technology, Tarex provides real-time market analysis, token insights, and comprehensive blockchain data aggregation.
Key Features
- Real-Time Token Analysis: Instant access to token metrics, price movements, and liquidity data
- AI-Powered Chat Interface: Natural language processing for intuitive blockchain queries
- Smart Contract Interaction: Direct integration with BNB Chain smart contracts
- Image Generation: DALL-E 3 integration for creating crypto-themed visuals
- x402 Network Integration: Advanced agent orchestration and cross-chain capabilities
Technology Stack
{
"frontend": {
"language": "JavaScript (ES6+)",
"styling": "CSS3 with Custom Properties",
"apis": ["OpenAI GPT-4", "DALL-E 3", "DexScreener API"]
},
"backend": {
"runtime": "Node.js",
"framework": "Express.js",
"ai": "OpenAI API Integration"
},
"blockchain": {
"network": "BNB Smart Chain (BSC)",
"rpc": "https://bsc-dataseed.binance.org",
"explorer": "BscScan API Integration"
}
}
System Architecture
Tarex employs a modern, scalable architecture designed for high-performance blockchain data processing and AI inference.
Core Components
1. Frontend Layer
The client-side application is built with vanilla JavaScript for optimal performance and minimal dependencies.
// State Management System
let currentMessages = [];
let currentUser = null;
let chatHistory = [];
// WebSocket Connection for Real-Time Updates
const wsConnection = {
endpoint: 'wss://tarex.network/stream',
reconnect: true,
heartbeat: 30000
};
// API Client Configuration
const apiClient = {
baseURL: '/api',
timeout: 30000,
headers: {
'Content-Type': 'application/json',
'X-Client-Version': '1.0.0'
}
};
2. Backend Services
Express.js server handling API requests, AI processing, and blockchain interactions.
// Server Configuration
const express = require('express');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const app = express();
const PORT = process.env.PORT || 3000;
// Rate Limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP'
});
app.use('/api/', limiter);
// Routes
app.post('/api/chat', handleChatRequest);
app.post('/api/analyze-token', analyzeToken);
app.get('/api/trending', getTrendingTokens);
app.get('/api/network-stats', getNetworkStats);
app.post('/api/generate-image', generateImage);
3. AI Integration Layer
// OpenAI Configuration
const { OpenAI } = require('openai');
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
// Chat Completion Handler
async function processChatMessage(messages) {
const response = await openai.chat.completions.create({
model: 'gpt-4-turbo-preview',
messages: [
{
role: 'system',
content: `You are Tarex, an expert AI assistant specializing in
BNB Chain, cryptocurrency analysis, and blockchain technology.
Provide accurate, insightful responses about tokens, DeFi,
smart contracts, and market trends.`
},
...messages
],
temperature: 0.7,
max_tokens: 2000
});
return response.choices[0].message.content;
}
x402 Network Integration
Tarex is integrated with the x402 agent network, enabling advanced cross-chain capabilities and decentralized AI orchestration.
What is x402?
x402 is a next-generation decentralized agent network that enables AI agents to communicate, collaborate, and execute complex multi-step tasks across different blockchain networks.
Agent Capabilities
- Cross-Chain Analysis: Analyze tokens and transactions across multiple blockchain networks
- Automated Trading Signals: Generate real-time trading insights based on on-chain data
- Smart Contract Auditing: Automated security analysis of deployed contracts
- Portfolio Management: Track and optimize multi-chain crypto portfolios
Integration Code
// x402 Agent Configuration
const x402Config = {
agentId: 'e098fb48-21dd-4c56-b8b6-5a62fc96674b',
network: 'x402-mainnet',
endpoint: 'https://api.x402scan.com/v1',
capabilities: [
'token-analysis',
'cross-chain-bridge',
'smart-contract-interaction',
'defi-protocol-integration'
]
};
// Initialize x402 Connection
async function initializeX402Agent() {
const agent = await x402.Agent.connect({
id: x402Config.agentId,
credentials: process.env.X402_API_KEY
});
// Register event listeners
agent.on('task-request', handleTaskRequest);
agent.on('cross-chain-event', handleCrossChainEvent);
return agent;
}
API Reference
Chat Endpoint
/api/chat
Send messages to the AI assistant and receive intelligent responses.
// Request
POST /api/chat
Content-Type: application/json
{
"messages": [
{
"role": "user",
"content": "What are the current trends on BNB Chain?"
}
]
}
// Response
{
"success": true,
"message": "Based on current data, BNB Chain is experiencing...",
"timestamp": "2024-01-15T10:30:00Z"
}
Token Analysis Endpoint
/api/analyze-token
Analyze a specific token by contract address.
// Request
POST /api/analyze-token
Content-Type: application/json
{
"contractAddress": "0x..."
}
// Response
{
"success": true,
"data": {
"baseToken": {
"name": "Token Name",
"symbol": "TKN",
"address": "0x..."
},
"priceUsd": "1.25",
"volume": {
"h24": "1250000"
},
"liquidity": {
"usd": "5000000"
},
"priceChange": {
"h24": "+15.5"
}
}
}
Trending Tokens Endpoint
/api/trending
Get the current trending tokens on BNB Chain.
Network Statistics Endpoint
/api/network-stats
Retrieve real-time BNB Chain network statistics.
Image Generation Endpoint
/api/generate-image
// Request
POST /api/generate-image
Content-Type: application/json
{
"prompt": "A futuristic BNB coin in cyberspace"
}
// Response
{
"success": true,
"imageUrl": "https://..."
}
Smart Contract Integration
Tarex interacts with various smart contracts on BNB Chain for token analysis and DeFi protocol integration.
BEP-20 Token Interface
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IBEP20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external returns (bool);
function allowance(address owner, address spender)
external view returns (uint256);
function approve(address spender, uint256 amount)
external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount)
external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
Web3 Integration
// Web3 Provider Setup
const Web3 = require('web3');
const web3 = new Web3('https://bsc-dataseed.binance.org');
// Contract Interaction
async function getTokenInfo(contractAddress) {
const contract = new web3.eth.Contract(BEP20_ABI, contractAddress);
const [name, symbol, decimals, totalSupply] = await Promise.all([
contract.methods.name().call(),
contract.methods.symbol().call(),
contract.methods.decimals().call(),
contract.methods.totalSupply().call()
]);
return { name, symbol, decimals, totalSupply };
}
// PancakeSwap Router Integration
const PANCAKE_ROUTER = '0x10ED43C718714eb63d5aA57B78B54704E256024E';
const routerContract = new web3.eth.Contract(ROUTER_ABI, PANCAKE_ROUTER);
async function getTokenPrice(tokenAddress) {
const path = [tokenAddress, WBNB_ADDRESS];
const amounts = await routerContract.methods
.getAmountsOut(web3.utils.toWei('1', 'ether'), path)
.call();
return amounts[1];
}
Deployment Guide
Prerequisites
- Node.js v18 or higher
- npm or yarn package manager
- OpenAI API key
- BscScan API key (optional)
Installation Steps
# 1. Clone the repository
git clone https://github.com/tarex/tarex-platform.git
cd tarex-platform
# 2. Install dependencies
npm install
# 3. Configure environment variables
cp .env.example .env
# Edit .env file with your credentials:
# OPENAI_API_KEY=sk-...
# PORT=3000
# NODE_ENV=production
# 4. Start the server
npm start
# For development with auto-reload:
npm run dev
Environment Variables
# .env Configuration
OPENAI_API_KEY=sk-proj-your-key-here
PORT=3000
NODE_ENV=production
# Optional
BSCSCAN_API_KEY=your-bscscan-key
X402_API_KEY=your-x402-key
RATE_LIMIT_MAX=100
RATE_LIMIT_WINDOW_MS=900000
Production Deployment
# Using PM2 for process management
npm install -g pm2
# Start application
pm2 start server.js --name tarex
# Configure auto-restart on crashes
pm2 startup
pm2 save
# Monitor logs
pm2 logs tarex
# Nginx reverse proxy configuration
server {
listen 80;
server_name tarex.io;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Docker Deployment
# Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
# docker-compose.yml
version: '3.8'
services:
tarex:
build: .
ports:
- "3000:3000"
environment:
- OPENAI_API_KEY=${OPENAI_API_KEY}
- NODE_ENV=production
restart: unless-stopped