关于 wallet-monitoring-bot
wallet-monitoring-bot 是用于构建 Solana 钱包链上监控与告警系统的技能,面向开发者。内容涵盖数据源选择、交易解析、过滤、去重及运行维护。
主要功能
- 01Webhook 或轮询监控
- 02解析 SOL、代币和 NFT 转账
- 03按金额与代币筛选
- 04按交易签名去重
- 05告警分级与聚合
适用场景
- 01监控项目金库的转出交易
- 02跟踪多个大额持币钱包
- 03按阈值发送交易告警
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ sanctifiedops/ solana-skills --skill wallet-monitoring-bot安装后在 Claude Code 中输入/wallet-monitoring-bot确认已加载。
详细介绍
钱包监控机器人
角色定位:你是专精于链上监控的 Solana 机器人构建者。你的目标是构建可靠的钱包跟踪系统,在尊重速率限制和隐私的同时,对有意义的事件发出提醒。
初步评估
- 你要监控哪些钱包(财库、大户、特定地址)?
- 哪些事件比较重要:所有转账、特定代币、仅超过阈值的事件,还是 NFT 转移?
- 延迟要求:实时(几秒)还是批处理(几分钟)?
- 提醒渠道:Discord、Telegram、Slack、自定义 webhook?
- 数据源:Helius webhook、轮询、WebSocket?
- 隐私要求:公开提醒还是仅限内部?
- 预算:免费套餐限制,还是付费索引器?
核心原则
- Webhook 优于轮询:尽可能使用 Helius/Triton webhook。这样可以节省速率限制额度,并降低延迟。
- 按签名去重:每笔交易都有唯一签名。将其用作幂等键。
- 丰富数据,而非单纯转发:原始交易数据没有用。解析指令、解析代币名称并计算美元价值。
- 智能限流:汇总小额事件;大额事件立即提醒。
- 故障时保持安全:出错时,宁可漏掉提醒,也不要重复发送提醒。
- 尊重隐私:在公开渠道中隐去敏感信息;在内部记录完整数据。
工作流
1. 选择数据源
// Option A: Helius Webhooks (Recommended)
// - Real-time, low latency
// - No rate limit concerns for receiving
// - Requires Helius account
// Option B: Polling with getSignaturesForAddress
// - Works with any RPC
// - Higher latency (poll interval)
// - Rate limit sensitive
// Option C: WebSocket (accountSubscribe)
// - Real-time for account balance changes
// - Doesn't capture full tx details
// - Connection management complexity
const DATA_SOURCES = {
heliusWebhook: {
latency: '1-3 seconds',
rateLimit: 'None (receiving)',
setup: 'Medium',
cost: 'Free tier: 10 webhooks, Paid: unlimited',
},
polling: {
latency: 'Poll interval (5-60s typical)',
rateLimit: 'Subject to RPC limits',
setup: 'Easy',
cost: 'RPC costs',
},
websocket: {
latency: 'Sub-second',
rateLimit: 'Connection limits',
setup: 'Complex (reconnection logic)',
cost: 'RPC costs',
},
};
2. 设置 Helius Webhook
// Create webhook via Helius API
async function createHeliusWebhook(
apiKey: string,
walletAddresses: string[],
webhookUrl: string
): Promise<string> {
const response = await fetch('https://api.helius.xyz/v0/webhooks', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
webhookURL: webhookUrl,
transactionTypes: ['TRANSFER', 'SWAP', 'NFT_SALE'],
accountAddresses: walletAddresses,
webhookType: 'enhanced', // Parsed transaction data
authHeader: 'X-Webhook-Secret: your-secret', // Optional
}),
});
const { webhookID } = await response.json();
return webhookID;
}
// Webhook payload structure (enhanced mode)
interface HeliusWebhookPayload {
type: string;
fee: number;
feePayer: string;
signature: string;
slot: number;
timestamp: number;
nativeTransfers: NativeTransfer[];
tokenTransfers: TokenTransfer[];
description: string;
source: string;
}
3. 轮询实现(替代方案)
import { Connection, PublicKey } from '@solana/web3.js';
class WalletPoller {
private connection: Connection;
private lastSignatures: Map<string, string> = new Map();
private pollInterval: number;
constructor(rpcUrl: string, pollIntervalMs: number = 10000) {
this.connection = new Connection(rpcUrl);
this.pollInterval = pollIntervalMs;
}
async startPolling(
wallets: string[],
onTransaction: (wallet: string, tx: ParsedTransaction) => void
) {
// Initial fetch to set baseline
for (const wallet of wallets) {
const sigs = await this.connection.getSignaturesForAddress(
new PublicKey(wallet),
{ limit: 1 }
);
if (sigs.length > 0) {
this.lastSignatures.set(wallet, sigs[0].signature);
}
}
// Poll loop
setInterval(async () => {
for (const wallet of wallets) {
try {
await this.checkWallet(wallet, onTransaction);
} catch (error) {
console.error(`Error polling ${wallet}:`, error);
}
}
}, this.pollInterval);
}
private async checkWallet(
wallet: string,
onTransaction: (wallet: string, tx: ParsedTransaction) => void
) {
const lastSig = this.lastSignatures.get(wallet);
const sigs = await this.connection.getSignaturesForAddress(
new PublicKey(wallet),
{
until: lastSig,
limit: 20,
}
);
if (sigs.length === 0) return;
// Update last seen
this.lastSignatures.set(wallet, sigs[0].signature);
// Process new transactions (oldest first)
for (const sig of sigs.reverse()) {
const tx = await this.connection.getParsedTransaction(sig.signature, {
maxSupportedTransactionVersion: 0,
});
if (tx) {
onTransaction(wallet, tx);
}
}
}
}
4. 交易解析
interface ParsedTransfer {
signature: string;
timestamp: number;
type: 'SOL' | 'TOKEN' | 'NFT';
direction: 'IN' | 'OUT';
amount: number;
amountUsd?: number;
token?: {
mint: string;
symbol: string;
decimals: number;
};
from: string;
to: string;
fee: number;
}
function parseTransaction(
watchedWallet: string,
tx: ParsedTransactionWithMeta
): ParsedTransfer[] {
const transfers: ParsedTransfer[] = [];
// Parse native SOL transfers
const preBalances = tx.meta?.preBalances || [];
const postBalances = tx.meta?.postBalances || [];
const accounts = tx.transaction.message.accountKeys;
for (let i = 0; i < accounts.length; i++) {
const account = accounts[i].pubkey.toString();
const change = (postBalances[i] - preBalances[i]) / 1e9;
if (account === watchedWallet && Math.abs(change) > 0.0001) {
transfers.push({
signature: tx.transaction.signatures[0],
timestamp: tx.blockTime || 0,
type: 'SOL',
direction: change > 0 ? 'IN' : 'OUT',
amount: Math.abs(change),
from: change < 0 ? watchedWallet : 'unknown',
to: change > 0 ? watchedWallet : 'unknown',
fee: tx.meta?.fee || 0,
});
}
}
// Parse token transfers
const tokenTransfers = tx.meta?.postTokenBalances || [];
// ... additional parsing logic
return transfers;
}
5. 筛选与阈值
interface FilterConfig {
// Amount thresholds (in USD or native units)
minSolAmount?: number;
minUsdAmount?: number;
// Token filters
tokenWhitelist?: string[]; // Only these tokens
tokenBlacklist?: string[]; // Ignore these tokens
// Direction filters
directions?: ('IN' | 'OUT')[];
// Aggregation
aggregateWindow?: number; // ms to aggregate small transfers
aggregateThreshold?: number; // Below this, aggregate
// Cooldown
cooldownPerWallet?: number; // ms between alerts for same wallet
}
class TransferFilter {
private config: FilterConfig;
private lastAlert: Map<string, number> = new Map();
private pendingAggregates: Map<string, ParsedTransfer[]> = new Map();
constructor(config: FilterConfig) {
this.config = config;
}
shouldAlert(wallet: string, transfer: ParsedTransfer): boolean {
// Check cooldown
const lastTime = this.lastAlert.get(wallet) || 0;
if (Date.now() - lastTime < (this.config.cooldownPerWallet || 0)) {
return false;
}
// Check direction
if (this.config.directions && !this.config.directions.includes(transfer.direction)) {
return false;
}
// Check token filters
if (transfer.token) {
if (this.config.tokenWhitelist &&
!this.config.tokenWhitelist.includes(transfer.token.mint)) {
return false;
}
if (this.config.tokenBlacklist?.includes(transfer.token.mint)) {
return false;
}
}
// Check amount thresholds
if (transfer.type === 'SOL' && this.config.minSolAmount &&
transfer.amount < this.config.minSolAmount) {
return false;
}
if (this.config.minUsdAmount && transfer.amountUsd &&
transfer.amountUsd < this.config.minUsdAmount) {
return false;
}
return true;
}
}
6. 提醒格式
interface AlertMessage {
title: string;
description: string;
fields: { name: string; value: string; inline?: boolean }[];
color: number;
url?: string;
}
function formatDiscordAlert(
wallet: string,
transfer: ParsedTransfer,
walletLabel?: string
): AlertMessage {
const direction = transfer.direction === 'IN' ? '📥 Received' : '📤 Sent';
const emoji = transfer.direction === 'IN' ? '🟢' : '🔴';
const amount = transfer.type === 'SOL'
? `${transfer.amount.toFixed(4)} SOL`
: `${transfer.amount.toLocaleString()} ${transfer.token?.symbol || 'tokens'}`;
const usdValue = transfer.amountUsd
? ` (~$${transfer.amountUsd.toLocaleString()})`
: '';
return {
title: `${emoji} ${direction}${walletLabel ? ` - ${walletLabel}` : ''}`,
description: `${amount}${usdValue}`,
fields: [
{
name: 'Wallet',
value: `\`${wallet.slice(0, 4)}...${wallet.slice(-4)}\``,
inline: true,
},
{
name: transfer.direction === 'IN' ? 'From' : 'To',
value: `\`${(transfer.direction === 'IN' ? transfer.from : transfer.to).slice(0, 8)}...\``,
inline: true,
},
{
name: 'Time',
value: `<t:${transfer.timestamp}:R>`,
inline: true,
},
],
color: transfer.direction === 'IN' ? 0x00ff00 : 0xff6b6b,
url: `https://solscan.io/tx/${transfer.signature}`,
};
}
// Send to Discord
async function sendDiscordAlert(
webhookUrl: string,
alert: AlertMessage
): Promise<void> {
await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
embeds: [{
title: alert.title,
description: alert.description,
fields: alert.fields,
color: alert.color,
url: alert.url,
timestamp: new Date().toISOString(),
}],
}),
});
}
7. 去重
class SignatureDeduplicator {
private seen: Set<string> = new Set();
private maxSize: number;
private cleanupThreshold: number;
constructor(maxSize: number = 10000) {
this.maxSize = maxSize;
this.cleanupThreshold = maxSize * 0.8;
}
isDuplicate(signature: string): boolean {
if (this.seen.has(signature)) {
return true;
}
// Add to seen set
this.seen.add(signature);
// Cleanup if too large (simple approach: clear half)
if (this.seen.size > this.maxSize) {
const toKeep = Array.from(this.seen).slice(-this.cleanupThreshold);
this.seen = new Set(toKeep);
}
return false;
}
}
// For persistent deduplication, use Redis
import Redis from 'ioredis';
class RedisDeduplicator {
private redis: Redis;
private keyPrefix: string;
private ttlSeconds: number;
constructor(redisUrl: string, ttlSeconds: number = 86400) {
this.redis = new Redis(redisUrl);
this.keyPrefix = 'tx:seen:';
this.ttlSeconds = ttlSeconds;
}
async isDuplicate(signature: string): Promise<boolean> {
const key = `${this.keyPrefix}${signature}`;
const exists = await this.redis.exists(key);
if (exists) {
return true;
}
await this.redis.setex(key, this.ttlSeconds, '1');
return false;
}
}
模板 / 操作手册
机器人配置模板
interface BotConfig {
// Wallets to monitor
wallets: {
address: string;
label: string;
filters?: FilterConfig;
}[];
// Data source
dataSource: 'helius' | 'polling' | 'websocket';
heliusApiKey?: string;
rpcUrl?: string;
pollIntervalMs?: number;
// Alerting
alertChannels: {
type: 'discord' | 'telegram' | 'slack' | 'webhook';
url: string;
minSeverity?: 'info' | 'warning' | 'critical';
}[];
// Defaults
defaultFilters: FilterConfig;
// Operations
healthCheckInterval: number;
metricsEnabled: boolean;
}
const exampleConfig: BotConfig = {
wallets: [
{
address: 'Treasury...xyz',
label: 'Project Treasury',
filters: { minUsdAmount: 1000 },
},
{
address: 'Whale...abc',
label: 'Known Whale',
filters: { directions: ['OUT'] },
},
],
dataSource: 'helius',
heliusApiKey: process.env.HELIUS_API_KEY,
alertChannels: [
{
type: 'discord',
url: process.env.DISCORD_WEBHOOK,
},
],
defaultFilters: {
minSolAmount: 1,
minUsdAmount: 100,
cooldownPerWallet: 60000,
},
healthCheckInterval: 60000,
metricsEnabled: true,
};
提醒严重程度矩阵
| 事件 | 阈值 | 严重程度 | 提醒行为 |
|---|---|---|---|
| 大额 SOL 转出 | > 100 SOL | 严重 | 立即发送至所有渠道 |
| 中额 SOL 转出 | 10-100 SOL | 警告 | 立即发送至主要渠道 |
| 小额 SOL 转出 | 1-10 SOL | 信息 | 每 15 分钟批量发送 |
| 任意 SOL 转入 | > 1 SOL | 信息 | 每 15 分钟批量发送 |
| 代币转账 | > $1000 | 警告 | 立即发送 |
| NFT 转移 | 任意 | 信息 | 批量发送 |
常见故障模式 + 调试
“提醒重复”
- 原因:重试逻辑未进行去重
- 检测:同一笔交易多次出现
- 修复:按签名实现幂等性;使用 Redis 持久化
“交易遗漏”
- 原因:轮询间隔过长,或 webhook 未收到数据
- 检测:与区块浏览器对比
- 修复:确认 webhook 已启用;缩短轮询间隔;添加健康检查
“触发速率限制”
- 原因:轮询时 RPC 调用过多
- 检测:日志中出现 429 错误
- 修复:切换到 webhook;批量发送请求;添加指数退避
“代币金额错误”
- 原因:未考虑小数位数
- 检测:金额相差 10^X
- 修复:获取 mint 信息以确定小数位数;缓存代币元数据
“机器人崩溃但没有提醒”
- 原因:没有健康监控
- 检测:无声故障
- 修复:添加健康检查端点;在心跳缺失时发出提醒
质量标准 / 验证
满足以下条件时,实施即告完成:
- Webhook 或轮询运行可靠
- 去重可防止重复提醒
- 筛选器能正确应用阈值
- 提醒格式清晰并包含链接
- 遵守速率限制
- 已配置健康监控
- 错误处理不会导致提醒刷屏
- 已在 devnet 上使用真实交易进行测试
输出格式
请提供:
- 架构概览:数据流图
- 配置:钱包、筛选器、渠道
- 代码:核心监控与提醒逻辑
- 提醒示例:格式化后的提醒示例
- 运维手册:健康检查、调试步骤
示例
简单示例:财库监控
输入:“监控我们的财库,发现任何超过 10 SOL 的转出时发出提醒”
输出:
const treasuryMonitor = new WalletMonitor({
wallets: [{
address: 'TreasuryAddressHere',
label: 'Project Treasury',
}],
filters: {
directions: ['OUT'],
minSolAmount: 10,
},
alertChannel: {
type: 'discord',
url: process.env.DISCORD_TREASURY_WEBHOOK,
},
});
// Alert format:
// 🔴 Sent - Project Treasury
// 25.5 SOL (~$2,550)
// Wallet: Trea...xyz
// To: 7xK8...abc
// Time: 2 minutes ago
// [View on Solscan]
复杂示例:多钱包巨鲸追踪器
输入:“构建一个巨鲸追踪器,监控 $TOKEN 的前 10 名持有者,并为每个巨鲸设置不同的提醒规则”
输出:查看完整实现,其中包括:
- 每个钱包的自定义阈值
- 跨钱包关联分析(检测多个巨鲸是否同时行动)
- 每日汇总
- 针对大额同步卖出的关键提醒
- 集成价格数据源以进行美元换算
评论
支持 Markdown