Ward AI SDK Documentation
Complete guide to integrating Ward AI's security monitoring and threat detection into your Solana applications.
Quick Start
Get up and running with Ward AI in minutes. The SDK is already included in this project - just import and use it.
Step 1: Setup Environment
Add your Ward AI API key to your environment variables:
# .env.local WARD_AI_API_KEY=your_api_key_here
Step 2: Import the SDK
Import the Ward AI client in your code:
import { WardAIClient } from '@/lib/ward-ai';
const ward = new WardAIClient({
apiKey: process.env.WARD_AI_API_KEY
});Step 3: Run Your First Analysis
Analyze a Solana token for security threats:
// Phase 1: Analyze token security
const analysis = await ward.analyzeToken(
'solana-contract-address'
);
console.log('Risk Score:', analysis.riskScore);
console.log('Threats:', analysis.threats.length);Step 4: Use Advanced Features
Access Phase 2 AI-powered analytics:
// Phase 2: Get AI trading signals
const signals = await ward.getTradingSignals(
'solana-contract-address'
);
signals.forEach(signal => {
console.log(`${signal.signalType}: ${signal.confidence}%`);
});What's Next?
- → Explore Phase 1 Features for security monitoring
- → Try Phase 2 Features for advanced AI analytics
- → Use React Hooks for seamless integration
Installation
Option 1: Install from npm (Coming Soon)
Install the Ward AI SDK package using your preferred package manager:
npm install ward-ai-sdk
# or
pnpm add ward-ai-sdk
# or
yarn add ward-ai-sdkOption 2: Use in Ward AI Projects
If you're working within a Ward AI project, the SDK is already included:
import { WardAIClient } from '@/lib/ward-ai';Environment Variables
Set your WARD_AI_API_KEY in your environment variables to authenticate requests (optional for public endpoints).
API endpoint: https://ward-ai.com/api
Authentication
The Ward AI SDK uses API keys for authentication. Ensure your API key is securely stored and accessible via environment variables.
import { WardAIClient } from '@/lib/ward-ai';
const client = new WardAIClient({
apiKey: process.env.WARD_AI_API_KEY,
});Getting Started
Ward AI provides a comprehensive SDK for real-time security monitoring of Solana token launches. Detect insider selling, liquidity drains, deployer LP withdrawals, and sniper volume attacks.
Two-Phase Architecture
Phase 1 provides core monitoring and threat detection. Phase 2 unlocks advanced AI analytics, portfolio protection, smart contract auditing, and social sentiment analysis.
Phase 1: Core Security
Phase 1 provides essential security monitoring capabilities including token analysis, threat detection, and real-time alerts.
analyzeToken()
Analyze a Solana token for security risks and potential threats.
const analysis = await ward.analyzeToken('token-address');Parameters
tokenAddressstring - The Solana token contract address
Returns
{
tokenAddress: string;
riskScore: number; // 0-100
threatLevel: 'low' | 'medium' | 'high' | 'critical';
threats: Array<{
type: string;
severity: string;
description: string;
detectedAt: string;
}>;
analysis: {
liquidityScore: number;
holderDistribution: number;
tradingVolume: number;
};
}Live Alerts
Receive real-time alerts for detected threats and suspicious activities.
// Subscribe to receive live alerts
await ward.subscribeToAlerts((alert) => {
console.log(`New Alert: ${alert.type} - ${alert.message}`);
// Handle alert (e.g., display notification, trigger action)
});
// Unsubscribe when no longer needed
// ward.unsubscribeFromAlerts();Real-time Notifications
Configurable alert thresholds and delivery mechanisms ensure you're always informed about critical security events.
Monitoring Stats
Access real-time monitoring statistics to understand token activity and security posture.
// Get overall monitoring statistics
const stats = await ward.getMonitoringStats();
console.log('Total Tokens Monitored:', stats.totalTokens);
console.log('Active Threats Detected:', stats.activeThreats);
console.log('Average Risk Score:', stats.averageRiskScore);Threat Detection
Access historical threat data and configure custom security guards for your specific needs.
// Get threat history for a specific token
const threats = await ward.getTokenThreats('token-address');
// Configure custom guards for enhanced security
await ward.configureGuards('token-address', {
insiderSelling: { enabled: true, threshold: 5 },
liquidityDrain: { enabled: true, threshold: 20 },
deployerLpWithdrawal: { enabled: true },
sniperVolume: { enabled: true, threshold: 50 }
});Detects when team wallets or insiders dump tokens
Alerts when liquidity is being removed from pools
Monitors deployer wallet for LP token withdrawals
Identifies suspicious trading patterns from bots
Phase 2: Advanced Analytics & AI
Phase 2 introduces powerful AI-driven features for comprehensive portfolio protection and threat prediction.
Portfolio Protection Mode
Automatically monitor your entire wallet holdings with real-time threat detection across all tokens.
// Enable portfolio protection
await ward.enablePortfolioProtection('your-wallet-address');
// Get portfolio status
const portfolio = await ward.getPortfolioProtection('your-wallet-address');
console.log('Total Value:', portfolio.totalValue);
console.log('Tokens Monitored:', portfolio.tokensMonitored);
console.log('Active Threats:', portfolio.activeThreats);
// View holdings with risk scores
portfolio.holdings.forEach(holding => {
console.log(`${holding.tokenName}: Risk ${holding.riskScore}/100`);
if (holding.threats.length > 0) {
console.log('Threats:', holding.threats);
}
});Portfolio Protection monitors all holdings 24/7 and sends alerts for any suspicious activity across your entire wallet.
Smart Contract Audit Scanner
Automated vulnerability detection for smart contracts with comprehensive safety checks.
// Run smart contract audit
const audit = await ward.auditSmartContract('token-address');
console.log('Audit Score:', audit.securityScore + '/100');
console.log('Vulnerabilities Found:', audit.vulnerabilities.length);
// Check safety features
console.log('Safety Checks:');
console.log(' Ownership:', audit.safetyChecks.ownership);
console.log(' Mintable:', audit.safetyChecks.mintable);
console.log(' Pausable:', audit.safetyChecks.pausable);
console.log(' Blacklist:', audit.safetyChecks.blacklist);
console.log(' Proxy:', audit.safetyChecks.proxy);
// View vulnerabilities
audit.vulnerabilities.forEach(vuln => {
console.log(`[${vuln.severity}] ${vuln.type}`);
console.log('Description:', vuln.description);
console.log('Recommendation:', vuln.recommendation);
});Machine Learning Models
Custom ML models trained on historical manipulation patterns for predictive threat detection.
// Get ML prediction
const prediction = await ward.getMLPrediction('token-address');
console.log('Manipulation Risk:', prediction.manipulationRisk + '%');
console.log('Predicted Pattern:', prediction.predictedPattern);
console.log('Confidence:', prediction.confidence + '%');
// View key indicators
prediction.indicators.forEach(indicator => {
console.log(`${indicator.name}: ${indicator.value}`);
console.log(`Signal: ${indicator.signal}, Weight: ${indicator.weight}`);
});
// Compare with historical patterns
prediction.historicalComparisons.forEach(comp => {
console.log(`Similar to ${comp.tokenAddress}`);
console.log(`Similarity: ${comp.similarity}%, Outcome: ${comp.outcome}`);
});
// Get recommendations
prediction.recommendations.forEach(rec => {
console.log('Recommendation:', rec);
});Pattern Types
- pump_and_dump - Coordinated price manipulation
- rug_pull - Liquidity removal pattern
- insider_trading - Pre-announcement accumulation
- organic_growth - Healthy trading patterns
ML models are trained on thousands of historical manipulation events and continuously updated with new patterns.
Custom Model Training
Train custom ML models with your own historical data for specialized detection patterns.
// Train custom model
const result = await ward.trainCustomModel({
name: 'my-custom-detector',
trainingData: [
{
tokenAddress: 'token-1',
outcome: 'scam',
features: { volume: 1000000, liquidity: 50000, holders: 100 }
},
{
tokenAddress: 'token-2',
outcome: 'legitimate',
features: { volume: 500000, liquidity: 200000, holders: 5000 }
}
]
});
console.log('Model ID:', result.modelId);
// Use custom model for prediction
const customPrediction = await ward.predictWithCustomModel(
result.modelId,
'new-token-address'
);React Hooks
Pre-built React hooks for seamless integration with automatic polling, loading states, and error handling.
Phase 1 Hooks
import { useTokenAnalysis } from '@/lib/ward-ai';
function TokenDashboard({ tokenAddress }) {
const { data, loading, error, refetch } = useTokenAnalysis(tokenAddress);
if (loading) return <div>Analyzing token...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h2>Risk Score: {data.riskScore}/100</h2>
<button onClick={refetch}>Refresh Analysis</button>
</div>
);
}import { useLiveAlerts } from '@/lib/ward-ai';
function AlertsFeed() {
const { alerts, loading, error } = useLiveAlerts(5000); // Poll every 5s
return (
<div>
{alerts.map(alert => (
<div key={alert.id} className={alert.severity}>
{alert.message}
</div>
))}
</div>
);
}Phase 2 Hooks
import { usePortfolioProtection } from '@/lib/ward-ai';
function PortfolioDashboard({ walletAddress }) {
const { data, loading, error } = usePortfolioProtection(walletAddress);
return (
<div>
<h2>Total Value: ${data.totalValue}</h2>
<p>Tokens Monitored: {data.tokensMonitored}</p>
<p>Active Threats: {data.activeThreats}</p>
</div>
);
}import { useSmartContractAudit } from '@/lib/ward-ai';
function AuditResults({ tokenAddress }) {
const { audit, loading, error, refetch } = useSmartContractAudit(tokenAddress);
return (
<div>
<h2>Audit Score: {audit.auditScore}/100</h2>
<p>Vulnerabilities: {audit.vulnerabilities.length}</p>
<button onClick={refetch}>Re-scan Contract</button>
</div>
);
}import { useSocialSentiment } from '@/lib/ward-ai';
function SentimentWidget({ tokenAddress }) {
const { sentiment, loading, error } = useSocialSentiment(tokenAddress);
return (
<div>
<h2>Sentiment: {sentiment.sentiment}</h2>
<p>Score: {sentiment.overallScore}/100</p>
<p>Twitter Mentions: {sentiment.twitter.mentions}</p>
</div>
);
}import { useMLPrediction } from '@/lib/ward-ai';
function MLInsights({ tokenAddress }) {
const { prediction, loading, error } = useMLPrediction(tokenAddress);
return (
<div>
<h2>Manipulation Risk: {prediction.manipulationRisk}%</h2>
<p>Pattern: {prediction.predictedPattern}</p>
<p>Confidence: {prediction.confidence}%</p>
</div>
);
}Error Handling
The SDK provides comprehensive error handling with detailed error codes and messages.
import { WardAIClient, WardAIError } from '@/lib/ward-ai';
try {
const analysis = await ward.analyzeToken('invalid-address');
} catch (error) {
if (error instanceof WardAIError) {
console.error('Status:', error.statusCode);
console.error('Code:', error.code);
console.error('Message:', error.message);
// Handle specific errors
if (error.code === 'TIMEOUT') {
// Retry logic
} else if (error.statusCode === 401) {
// Authentication error
}
}
}Need help? Visit our official website or check the GitHub repository.
Built with love for the Solana ecosystem
Social Sentiment Analysis
Track Twitter/X and Reddit sentiment for tokens with real-time community activity monitoring.
API Requirements
This feature requires X (Twitter) API access, which is a paid service. You'll need to obtain API credentials from the X Developer Portal to access Twitter/X sentiment data and metrics.
const sentiment = await ward.getSocialSentiment('token-address'); console.log('Overall Score:', sentiment.overallScore); console.log('Sentiment:', sentiment.sentiment); // 'bullish' | 'bearish' | 'neutral' // Twitter/X metrics console.log('Twitter Mentions:', sentiment.twitter.mentions); console.log('Twitter Sentiment:', sentiment.twitter.sentiment); console.log('Influencer Mentions:', sentiment.twitter.influencerMentions); console.log('Trending Score:', sentiment.twitter.trendingScore); // Reddit metrics console.log('Reddit Posts:', sentiment.reddit.posts); console.log('Reddit Comments:', sentiment.reddit.comments); console.log('Reddit Sentiment:', sentiment.reddit.sentiment); console.log('Subreddits:', sentiment.reddit.subreddits); // Community activity console.log('Active Users:', sentiment.communityActivity.activeUsers); console.log('Engagement Rate:', sentiment.communityActivity.engagement); console.log('Growth Rate:', sentiment.communityActivity.growthRate);Bullish
Positive sentiment
Neutral
Mixed signals
Bearish
Negative sentiment