llm-trading-agent-security — скилл Claude Code: защита
Скилл проверяет защиту автономного трейдинг-агента с доступом к кошельку или транзакциям. Нужен при аудите лимитов, симуляции и работы с ключами.
npx skills add affaan-m/ECC --skill llm-trading-agent-security -a claude-codeЧто делает llm-trading-agent-security
Скилл раскладывает защиту агента по независимым слоям: фильтрация prompt injection во внешних данных, лимиты одной транзакции и дневных расходов, симуляция перед отправкой и обязательный min_amount_out. В наборе есть примеры на Python с Decimal, асинхронным вызовом self.w3.eth.call и проверкой проскальзывания.
Отдельные блоки описывают circuit breaker при последовательных убытках или просадке, изоляцию кошелька, хранение ключа в TRADING_WALLET_PRIVATE_KEY, private RPC, дедлайны и MEV-защиту. Для работы с примером кошелька нужен Python и библиотека eth_account; для отправки транзакций используется объект w3. Ставьте скилл, если агент подписывает сделки, свопы или операции с treasury. Для агента без доступа к активам он избыточен.
Какие задачи решает
- отфильтровать prompt injection в данных блокчейна и лентах
- ограничить сумму одной транзакции и дневные расходы
- проверить транзакцию симуляцией до отправки
- остановить торговлю после убытков или просадки
- изолировать ключи и кошелёк агента
Примеры запросов агенту
- Проверь защиту этого агента перед выдачей ему права подписывать транзакции.
- Добавь лимит одной сделки, дневной лимит и проверку `min_amount_out` перед отправкой.
- Проведи аудит хранения `TRADING_WALLET_PRIVATE_KEY` и правил circuit breaker.
Как установить llm-trading-agent-security
1Через Skills CLI (Vercel)
npx skills add affaan-m/ECC --skill llm-trading-agent-security -a claude-code2Вручную: положить файлы
~/.claude/skills/llm-trading-agent-security/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/llm-trading-agent-security/
1Через Skills CLI (Vercel)
npx skills add affaan-m/ECC --skill llm-trading-agent-security -a codex2Вручную: положить файлы
.agents/skills/llm-trading-agent-security/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add affaan-m/ECC --skill llm-trading-agent-security -a cursor2Вручную: положить файлы
.cursor/skills/llm-trading-agent-security/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install affaan-m/ECC llm-trading-agent-security2Вручную: положить файлы
.github/skills/llm-trading-agent-security/SKILL.md1Через Skills CLI (Vercel)
npx skills add affaan-m/ECC --skill llm-trading-agent-security -a gemini-cli2Командой платформы
gemini skills install https://github.com/affaan-m/ECC --path skills/llm-trading-agent-securityВручную: положить файлы
.devin/skills/llm-trading-agent-security/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add affaan-m/ECC --skill llm-trading-agent-security -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
Из того же набора146
Весь набор →Похожие
Вопросы о llm-trading-agent-security
Как установить llm-trading-agent-security в Claude Code?
Выполните npx skills add affaan-m/ECC --skill llm-trading-agent-security -a claude-code. Файл скилла появится в ~/.claude/skills/llm-trading-agent-security/SKILL.md.
Что делает llm-trading-agent-security?
Скилл помогает проверить prompt injection, лимиты расходов, симуляцию транзакций, circuit breaker, изоляцию кошелька и защиту от MEV. Он рассчитан на агента с правом подписывать или отправлять транзакции.
Что нужно для работы с ключом кошелька?
Ключ должен приходить из переменной TRADING_WALLET_PRIVATE_KEY или secret manager. Для примера загрузки ключа используется библиотека eth_account, а агенту рекомендуется выделенный hot wallet с нужными средствами.
Исходный текст
SKILL.md · MIT
---
name: llm-trading-agent-security
description: Security patterns for autonomous trading agents with wallet or transaction authority. Covers prompt injection, spend limits, pre-send simulation, circuit breakers, MEV protection, and key handling. Use when an autonomous agent holds wallet or transaction authority and its limits, simulation, or key handling need review.
metadata:
version: "1.0.0"
origin: ECC direct-port adaptation
---
# LLM Trading Agent Security
Autonomous trading agents have a harsher threat model than normal LLM apps: an injection or bad tool path can turn directly into asset loss.
## When to Use
- Building an AI agent that signs and sends transactions
- Auditing a trading bot or on-chain execution assistant
- Designing wallet key management for an agent
- Giving an LLM access to order placement, swaps, or treasury operations
## How It Works
Layer the defenses. No single check is enough. Treat prompt hygiene, spend policy, simulation, execution limits, and wallet isolation as independent controls.
## Examples
### Treat prompt injection as a financial attack
```python
import re
INJECTION_PATTERNS = [
r'ignore (previous|all) instructions',
r'new (task|directive|instruction)',
r'system prompt',
r'send .{0,50} to 0x[0-9a-fA-F]{40}',
r'transfer .{0,50} to',
r'approve .{0,50} for',
]
def sanitize_onchain_data(text: str) -> str:
for pattern in INJECTION_PATTERNS:
if re.search(pattern, text, re.IGNORECASE):
raise ValueError(f"Potential prompt injection: {text[:100]}")
return text
```
Do not blindly inject token names, pair labels, webhooks, or social feeds into an execution-capable prompt.
### Hard spend limits
```python
from decimal import Decimal
MAX_SINGLE_TX_USD = Decimal("500")
MAX_DAILY_SPEND_USD = Decimal("2000")
class SpendLimitError(Exception):
pass
class SpendLimitGuard:
def check_and_record(self, usd_amount: Decimal) -> None:
if usd_amount > MAX_SINGLE_TX_USD:
raise SpendLimitError(f"Single tx ${usd_amount} exceeds max ${MAX_SINGLE_TX_USD}")
daily = self._get_24h_spend()
if daily + usd_amount > MAX_DAILY_SPEND_USD:
raise SpendLimitError(f"Daily limit: ${daily} + ${usd_amount} > ${MAX_DAILY_SPEND_USD}")
self._record_spend(usd_amount)
```
### Simulate before sending
```python
class SlippageError(Exception):
pass
async def safe_execute(self, tx: dict, expected_min_out: int | None = None) -> str:
sim_result = await self.w3.eth.call(tx)
if expected_min_out is None:
raise ValueError("min_amount_out is required before send")
actual_out = decode_uint256(sim_result)
if actual_out < expected_min_out:
raise SlippageError(f"Simulation: {actual_out} < {expected_min_out}")
signed = self.account.sign_transaction(tx)
return await self.w3.eth.send_raw_transaction(signed.raw_transaction)
```
### Circuit breaker
```python
class TradingCircuitBreaker:
MAX_CONSECUTIVE_LOSSES = 3
MAX_HOURLY_LOSS_PCT = 0.05
def check(self, portfolio_value: float) -> None:
if self.consecutive_losses >= self.MAX_CONSECUTIVE_LOSSES:
self.halt("Too many consecutive losses")
if self.hour_start_value <= 0:
self.halt("Invalid hour_start_value")
return
hourly_pnl = (portfolio_value - self.hour_start_value) / self.hour_start_value
if hourly_pnl < -self.MAX_HOURLY_LOSS_PCT:
self.halt(f"Hourly PnL {hourly_pnl:.1%} below threshold")
```
### Wallet isolation
```python
import os
from eth_account import Account
private_key = os.environ.get("TRADING_WALLET_PRIVATE_KEY")
if not private_key:
raise EnvironmentError("TRADING_WALLET_PRIVATE_KEY not set")
account = Account.from_key(private_key)
```
Use a dedicated hot wallet with only the required session funds. Never point the agent at a primary treasury wallet.
### MEV and deadline protection
```python
import time
PRIVATE_RPC = "https://rpc.flashbots.net"
MAX_SLIPPAGE_BPS = {"stable": 10, "volatile": 50}
deadline = int(time.time()) + 60
```
## Pre-Deploy Checklist
- External data is sanitized before entering the LLM context
- Spend limits are enforced independently from model output
- Transactions are simulated before send
- `min_amount_out` is mandatory
- Circuit breakers halt on drawdown or invalid state
- Keys come from env or a secret manager, never code or logs
- Private mempool or protected routing is used when appropriate
- Slippage and deadlines are set per strategy
- All agent decisions are audit-logged, not just successful sends
© affaan-m · MIT · affaan-m/ECC