agentlaunch-templates 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/generator.d.ts +43 -0
- package/dist/generator.d.ts.map +1 -0
- package/dist/generator.js +213 -0
- package/dist/generator.js.map +1 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +39 -0
- package/dist/index.js.map +1 -0
- package/dist/registry.d.ts +49 -0
- package/dist/registry.d.ts.map +1 -0
- package/dist/registry.js +47 -0
- package/dist/registry.js.map +1 -0
- package/dist/templates/custom.d.ts +11 -0
- package/dist/templates/custom.d.ts.map +1 -0
- package/dist/templates/custom.js +458 -0
- package/dist/templates/custom.js.map +1 -0
- package/dist/templates/data-analyzer.d.ts +11 -0
- package/dist/templates/data-analyzer.d.ts.map +1 -0
- package/dist/templates/data-analyzer.js +565 -0
- package/dist/templates/data-analyzer.js.map +1 -0
- package/dist/templates/gifter.d.ts +15 -0
- package/dist/templates/gifter.d.ts.map +1 -0
- package/dist/templates/gifter.js +717 -0
- package/dist/templates/gifter.js.map +1 -0
- package/dist/templates/price-monitor.d.ts +11 -0
- package/dist/templates/price-monitor.d.ts.map +1 -0
- package/dist/templates/price-monitor.js +577 -0
- package/dist/templates/price-monitor.js.map +1 -0
- package/dist/templates/research.d.ts +11 -0
- package/dist/templates/research.d.ts.map +1 -0
- package/dist/templates/research.js +593 -0
- package/dist/templates/research.js.map +1 -0
- package/dist/templates/trading-bot.d.ts +11 -0
- package/dist/templates/trading-bot.d.ts.map +1 -0
- package/dist/templates/trading-bot.js +559 -0
- package/dist/templates/trading-bot.js.map +1 -0
- package/package.json +24 -0
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* trading-bot.ts — Generates buy/sell signals based on price momentum
|
|
3
|
+
*
|
|
4
|
+
* Platform constants (source of truth: deployed smart contracts):
|
|
5
|
+
* - Deploy fee: 120 FET (read dynamically, can change via multi-sig)
|
|
6
|
+
* - Graduation target: 30,000 FET -> auto DEX listing
|
|
7
|
+
* - Trading fee: 2% -> 100% to protocol treasury (NO creator fee)
|
|
8
|
+
*/
|
|
9
|
+
export const template = {
|
|
10
|
+
name: "trading-bot",
|
|
11
|
+
description: "Generates buy/sell signals for tokens based on price momentum and moving averages",
|
|
12
|
+
category: "Finance",
|
|
13
|
+
variables: [
|
|
14
|
+
{ name: "agent_name", required: true, description: "Name of the agent" },
|
|
15
|
+
{
|
|
16
|
+
name: "description",
|
|
17
|
+
default: "Generates buy/sell signals based on price momentum and moving averages",
|
|
18
|
+
description: "Short description of what this agent does",
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
name: "signal_window",
|
|
22
|
+
default: "10",
|
|
23
|
+
description: "Number of price data points used to compute moving average",
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
name: "buy_threshold",
|
|
27
|
+
default: "3",
|
|
28
|
+
description: "Percentage above moving average to trigger a BUY signal",
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
name: "sell_threshold",
|
|
32
|
+
default: "3",
|
|
33
|
+
description: "Percentage below moving average to trigger a SELL signal",
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
name: "rate_limit_per_minute",
|
|
37
|
+
default: "20",
|
|
38
|
+
description: "Max requests per user per minute",
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
name: "free_requests_per_day",
|
|
42
|
+
default: "10",
|
|
43
|
+
description: "Free tier daily request quota",
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
name: "premium_token_threshold",
|
|
47
|
+
default: "1000",
|
|
48
|
+
description: "Token balance required for premium tier",
|
|
49
|
+
},
|
|
50
|
+
],
|
|
51
|
+
dependencies: ["requests"],
|
|
52
|
+
secrets: ["AGENTVERSE_API_KEY", "AGENTLAUNCH_API_KEY", "AGENT_ADDRESS", "AGENT_OWNER_ADDRESS"],
|
|
53
|
+
code: `#!/usr/bin/env python3
|
|
54
|
+
"""
|
|
55
|
+
{{agent_name}} — AgentLaunch Trading Signal Agent
|
|
56
|
+
Generated by: agentlaunch scaffold {{agent_name}} --type trading-bot
|
|
57
|
+
|
|
58
|
+
Generates buy/sell signals using a simple moving-average crossover strategy.
|
|
59
|
+
Signals are advisory only — this agent does NOT execute trades.
|
|
60
|
+
|
|
61
|
+
Platform constants (source of truth: deployed smart contracts):
|
|
62
|
+
- Deploy fee: 120 FET (read dynamically, can change via multi-sig)
|
|
63
|
+
- Graduation target: 30,000 FET -> auto DEX listing
|
|
64
|
+
- Trading fee: 2% -> 100% to protocol treasury (NO creator fee)
|
|
65
|
+
|
|
66
|
+
DISCLAIMER: This agent provides informational signals only, not financial advice.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
from uagents import Agent, Context, Protocol
|
|
70
|
+
from uagents_core.contrib.protocols.chat import (
|
|
71
|
+
ChatAcknowledgement,
|
|
72
|
+
ChatMessage,
|
|
73
|
+
EndSessionContent,
|
|
74
|
+
TextContent,
|
|
75
|
+
chat_protocol_spec,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
import json
|
|
79
|
+
import os
|
|
80
|
+
import time
|
|
81
|
+
from collections import defaultdict
|
|
82
|
+
from datetime import datetime
|
|
83
|
+
from typing import Any, Dict, List, Optional
|
|
84
|
+
from uuid import uuid4
|
|
85
|
+
|
|
86
|
+
import requests
|
|
87
|
+
|
|
88
|
+
# ==============================================================================
|
|
89
|
+
# API CONFIG — Override via environment variables, never hardcode
|
|
90
|
+
# ==============================================================================
|
|
91
|
+
|
|
92
|
+
AGENTLAUNCH_API = os.environ.get("AGENTLAUNCH_API", "https://agent-launch.ai/api")
|
|
93
|
+
|
|
94
|
+
# ==============================================================================
|
|
95
|
+
# BUSINESS CONFIG
|
|
96
|
+
# ==============================================================================
|
|
97
|
+
|
|
98
|
+
OWNER_ADDRESS = os.environ.get("AGENT_OWNER_ADDRESS", "")
|
|
99
|
+
|
|
100
|
+
BUSINESS = {
|
|
101
|
+
"name": "{{agent_name}}",
|
|
102
|
+
"description": "{{description}}",
|
|
103
|
+
"version": "1.0.0",
|
|
104
|
+
"signal_window": int("{{signal_window}}"),
|
|
105
|
+
"buy_threshold_pct": float("{{buy_threshold}}"),
|
|
106
|
+
"sell_threshold_pct": float("{{sell_threshold}}"),
|
|
107
|
+
"free_requests_per_day": {{free_requests_per_day}},
|
|
108
|
+
"premium_token_threshold": {{premium_token_threshold}},
|
|
109
|
+
"rate_limit_per_minute": {{rate_limit_per_minute}},
|
|
110
|
+
"max_input_length": 5000,
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# ==============================================================================
|
|
115
|
+
# LAYER 1: FOUNDATION
|
|
116
|
+
# ==============================================================================
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class Logger:
|
|
120
|
+
"""Structured logging with audit trail."""
|
|
121
|
+
|
|
122
|
+
@staticmethod
|
|
123
|
+
def info(ctx: Context, event: str, data: Optional[Dict] = None) -> None:
|
|
124
|
+
ctx.logger.info(f"[{event}] {json.dumps(data or {})}")
|
|
125
|
+
|
|
126
|
+
@staticmethod
|
|
127
|
+
def audit(ctx: Context, user: str, action: str) -> None:
|
|
128
|
+
ctx.logger.info(
|
|
129
|
+
f"[AUDIT] user={user[:20]} action={action} "
|
|
130
|
+
f"ts={datetime.utcnow().isoformat()}"
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
@staticmethod
|
|
134
|
+
def error(ctx: Context, event: str, error: str) -> None:
|
|
135
|
+
ctx.logger.error(f"[{event}] {error}")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# ==============================================================================
|
|
139
|
+
# LAYER 2: SECURITY
|
|
140
|
+
# ==============================================================================
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class Security:
|
|
144
|
+
"""Rate limiting and input validation."""
|
|
145
|
+
|
|
146
|
+
def __init__(self) -> None:
|
|
147
|
+
self._requests: Dict[str, List[float]] = defaultdict(list)
|
|
148
|
+
self._check_count: int = 0
|
|
149
|
+
|
|
150
|
+
def check(self, ctx: Context, user_id: str, message: str) -> tuple:
|
|
151
|
+
now = time.time()
|
|
152
|
+
|
|
153
|
+
self._requests[user_id] = [
|
|
154
|
+
t for t in self._requests[user_id] if now - t < 60
|
|
155
|
+
]
|
|
156
|
+
if len(self._requests[user_id]) >= BUSINESS["rate_limit_per_minute"]:
|
|
157
|
+
return None, "Rate limit exceeded. Please wait a moment."
|
|
158
|
+
self._requests[user_id].append(now)
|
|
159
|
+
|
|
160
|
+
self._check_count += 1
|
|
161
|
+
if self._check_count % 100 == 0:
|
|
162
|
+
stale = [
|
|
163
|
+
k
|
|
164
|
+
for k, v in self._requests.items()
|
|
165
|
+
if not v or (now - max(v)) > 300
|
|
166
|
+
]
|
|
167
|
+
for k in stale:
|
|
168
|
+
del self._requests[k]
|
|
169
|
+
|
|
170
|
+
if not message or not message.strip():
|
|
171
|
+
return None, "Empty message."
|
|
172
|
+
if len(message) > BUSINESS["max_input_length"]:
|
|
173
|
+
return None, f"Message too long (max {BUSINESS['max_input_length']} chars)."
|
|
174
|
+
|
|
175
|
+
return message.strip(), None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# ==============================================================================
|
|
179
|
+
# LAYER 3: STABILITY
|
|
180
|
+
# ==============================================================================
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class Health:
|
|
184
|
+
"""Track uptime and error rate."""
|
|
185
|
+
|
|
186
|
+
def __init__(self) -> None:
|
|
187
|
+
self._start: datetime = datetime.utcnow()
|
|
188
|
+
self._requests: int = 0
|
|
189
|
+
self._errors: int = 0
|
|
190
|
+
|
|
191
|
+
def record(self, success: bool) -> None:
|
|
192
|
+
self._requests += 1
|
|
193
|
+
if not success:
|
|
194
|
+
self._errors += 1
|
|
195
|
+
|
|
196
|
+
def status(self) -> Dict[str, Any]:
|
|
197
|
+
uptime = (datetime.utcnow() - self._start).total_seconds()
|
|
198
|
+
error_rate = (self._errors / self._requests * 100) if self._requests else 0
|
|
199
|
+
return {
|
|
200
|
+
"status": "healthy" if error_rate < 10 else "degraded",
|
|
201
|
+
"uptime_seconds": int(uptime),
|
|
202
|
+
"requests": self._requests,
|
|
203
|
+
"error_rate": f"{error_rate:.1f}%",
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# ==============================================================================
|
|
208
|
+
# LAYER 4: SPEED
|
|
209
|
+
# ==============================================================================
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class Cache:
|
|
213
|
+
"""In-memory TTL cache."""
|
|
214
|
+
|
|
215
|
+
def __init__(self, max_size: int = 1000) -> None:
|
|
216
|
+
self._data: Dict[str, tuple] = {}
|
|
217
|
+
self._max_size: int = max_size
|
|
218
|
+
|
|
219
|
+
def get(self, key: str) -> Any:
|
|
220
|
+
if key in self._data:
|
|
221
|
+
value, expires = self._data[key]
|
|
222
|
+
if expires > time.time():
|
|
223
|
+
return value
|
|
224
|
+
del self._data[key]
|
|
225
|
+
return None
|
|
226
|
+
|
|
227
|
+
def set(self, key: str, value: Any, ttl: int = 300) -> None:
|
|
228
|
+
if len(self._data) >= self._max_size:
|
|
229
|
+
now = time.time()
|
|
230
|
+
expired = [k for k, (_, exp) in self._data.items() if exp <= now]
|
|
231
|
+
for k in expired:
|
|
232
|
+
del self._data[k]
|
|
233
|
+
if len(self._data) >= self._max_size:
|
|
234
|
+
to_drop = sorted(self._data.items(), key=lambda x: x[1][1])[
|
|
235
|
+
: self._max_size // 10
|
|
236
|
+
]
|
|
237
|
+
for k, _ in to_drop:
|
|
238
|
+
del self._data[k]
|
|
239
|
+
self._data[key] = (value, time.time() + ttl)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
# ==============================================================================
|
|
243
|
+
# LAYER 5: REVENUE
|
|
244
|
+
# ==============================================================================
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
class Revenue:
|
|
248
|
+
"""Token-gated access and daily usage quotas."""
|
|
249
|
+
|
|
250
|
+
def __init__(self, cache: Cache) -> None:
|
|
251
|
+
self._cache = cache
|
|
252
|
+
self._usage: Dict[str, List[str]] = defaultdict(list)
|
|
253
|
+
|
|
254
|
+
def get_tier(self, user_address: str) -> str:
|
|
255
|
+
cached = self._cache.get(f"tier:{user_address}")
|
|
256
|
+
if cached is not None:
|
|
257
|
+
return cached
|
|
258
|
+
try:
|
|
259
|
+
r = requests.get(
|
|
260
|
+
f"{AGENTLAUNCH_API}/agents/token/{user_address}", timeout=5
|
|
261
|
+
)
|
|
262
|
+
if r.status_code == 200:
|
|
263
|
+
data = r.json()
|
|
264
|
+
balance = data.get("balance", 0)
|
|
265
|
+
tier = (
|
|
266
|
+
"premium"
|
|
267
|
+
if balance >= BUSINESS["premium_token_threshold"]
|
|
268
|
+
else "free"
|
|
269
|
+
)
|
|
270
|
+
self._cache.set(f"tier:{user_address}", tier, ttl=300)
|
|
271
|
+
return tier
|
|
272
|
+
except Exception:
|
|
273
|
+
pass
|
|
274
|
+
return "free"
|
|
275
|
+
|
|
276
|
+
def check_quota(self, user_id: str, tier: str) -> tuple:
|
|
277
|
+
today = datetime.utcnow().date().isoformat()
|
|
278
|
+
self._usage[user_id] = [
|
|
279
|
+
t for t in self._usage[user_id] if t.startswith(today)
|
|
280
|
+
]
|
|
281
|
+
today_usage = len(self._usage[user_id])
|
|
282
|
+
limit = 1000 if tier == "premium" else BUSINESS["free_requests_per_day"]
|
|
283
|
+
if today_usage >= limit:
|
|
284
|
+
if tier == "free":
|
|
285
|
+
return False, (
|
|
286
|
+
f"Free limit reached ({limit}/day). "
|
|
287
|
+
f"Hold {BUSINESS['premium_token_threshold']} tokens for premium!"
|
|
288
|
+
)
|
|
289
|
+
return False, f"Daily limit reached ({limit}/day)."
|
|
290
|
+
self._usage[user_id].append(datetime.utcnow().isoformat())
|
|
291
|
+
return True, None
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
# ==============================================================================
|
|
295
|
+
# AGENTLAUNCH INTEGRATION
|
|
296
|
+
# ==============================================================================
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class AgentLaunch:
|
|
300
|
+
"""Create and manage tokens on AgentLaunch."""
|
|
301
|
+
|
|
302
|
+
@staticmethod
|
|
303
|
+
def tokenize() -> Dict:
|
|
304
|
+
agent_address = os.environ.get("AGENT_ADDRESS")
|
|
305
|
+
if not agent_address:
|
|
306
|
+
return {"error": "AGENT_ADDRESS env var not set."}
|
|
307
|
+
try:
|
|
308
|
+
r = requests.post(
|
|
309
|
+
f"{AGENTLAUNCH_API}/agents/tokenize",
|
|
310
|
+
headers={
|
|
311
|
+
"X-API-Key": os.environ.get("AGENTLAUNCH_API_KEY", ""),
|
|
312
|
+
"Content-Type": "application/json",
|
|
313
|
+
},
|
|
314
|
+
json={
|
|
315
|
+
"agentAddress": agent_address,
|
|
316
|
+
"name": BUSINESS["name"],
|
|
317
|
+
"description": BUSINESS["description"],
|
|
318
|
+
},
|
|
319
|
+
timeout=30,
|
|
320
|
+
)
|
|
321
|
+
return r.json() if r.status_code in [200, 201] else {"error": r.text}
|
|
322
|
+
except Exception as e:
|
|
323
|
+
return {"error": str(e)}
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
# ==============================================================================
|
|
327
|
+
# TRADING SIGNAL BUSINESS LOGIC
|
|
328
|
+
# ==============================================================================
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
class TradingBotBusiness:
|
|
332
|
+
"""
|
|
333
|
+
Moving-average crossover signal generator.
|
|
334
|
+
|
|
335
|
+
Collects price data points for each tracked token, computes a simple
|
|
336
|
+
moving average over BUSINESS['signal_window'] samples, then emits
|
|
337
|
+
BUY / SELL / HOLD signals based on the configured thresholds.
|
|
338
|
+
|
|
339
|
+
Note: Trading fee is 2% -> 100% to protocol treasury (no creator fee).
|
|
340
|
+
DISCLAIMER: Signals are informational only, not financial advice.
|
|
341
|
+
"""
|
|
342
|
+
|
|
343
|
+
def __init__(self) -> None:
|
|
344
|
+
self._prices: Dict[str, List[float]] = defaultdict(list)
|
|
345
|
+
|
|
346
|
+
def fetch_price(self, token_address: str) -> Optional[float]:
|
|
347
|
+
try:
|
|
348
|
+
r = requests.get(
|
|
349
|
+
f"{AGENTLAUNCH_API}/agents/token/{token_address}", timeout=10
|
|
350
|
+
)
|
|
351
|
+
if r.status_code == 200:
|
|
352
|
+
data = r.json()
|
|
353
|
+
price = (
|
|
354
|
+
data.get("price")
|
|
355
|
+
or (data.get("data") or {}).get("price")
|
|
356
|
+
)
|
|
357
|
+
return float(price) if price is not None else None
|
|
358
|
+
except Exception:
|
|
359
|
+
pass
|
|
360
|
+
return None
|
|
361
|
+
|
|
362
|
+
def moving_average(self, token_address: str) -> Optional[float]:
|
|
363
|
+
prices = self._prices[token_address]
|
|
364
|
+
window = BUSINESS["signal_window"]
|
|
365
|
+
if len(prices) < 2:
|
|
366
|
+
return None
|
|
367
|
+
sample = prices[-window:]
|
|
368
|
+
return sum(sample) / len(sample)
|
|
369
|
+
|
|
370
|
+
def compute_signal(self, token_address: str, current_price: float) -> str:
|
|
371
|
+
ma = self.moving_average(token_address)
|
|
372
|
+
if ma is None:
|
|
373
|
+
n = len(self._prices[token_address])
|
|
374
|
+
needed = max(0, BUSINESS["signal_window"] - n)
|
|
375
|
+
return f"ACCUMULATING DATA ({n} samples, need {needed} more for signal)"
|
|
376
|
+
|
|
377
|
+
deviation_pct = ((current_price - ma) / ma) * 100
|
|
378
|
+
|
|
379
|
+
if deviation_pct >= BUSINESS["buy_threshold_pct"]:
|
|
380
|
+
return (
|
|
381
|
+
f"BUY SIGNAL — price {deviation_pct:+.2f}% above MA{BUSINESS['signal_window']} "
|
|
382
|
+
f"({current_price:.6f} FET vs MA {ma:.6f} FET)"
|
|
383
|
+
)
|
|
384
|
+
elif deviation_pct <= -BUSINESS["sell_threshold_pct"]:
|
|
385
|
+
return (
|
|
386
|
+
f"SELL SIGNAL — price {deviation_pct:+.2f}% below MA{BUSINESS['signal_window']} "
|
|
387
|
+
f"({current_price:.6f} FET vs MA {ma:.6f} FET)"
|
|
388
|
+
)
|
|
389
|
+
else:
|
|
390
|
+
return (
|
|
391
|
+
f"HOLD — price {deviation_pct:+.2f}% from MA{BUSINESS['signal_window']} "
|
|
392
|
+
f"(threshold: ±{BUSINESS['buy_threshold_pct']}%)"
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
async def handle(self, ctx: Context, user_id: str, message: str, tier: str) -> str:
|
|
396
|
+
lower = message.lower()
|
|
397
|
+
|
|
398
|
+
# "signal <address>" — compute signal
|
|
399
|
+
if lower.startswith("signal ") or lower.startswith("analyse ") or lower.startswith("analyze "):
|
|
400
|
+
parts = message.split()
|
|
401
|
+
if len(parts) >= 2:
|
|
402
|
+
token_address = parts[1].strip()
|
|
403
|
+
price = self.fetch_price(token_address)
|
|
404
|
+
if price is None:
|
|
405
|
+
return f"Could not fetch price for {token_address}."
|
|
406
|
+
self._prices[token_address].append(price)
|
|
407
|
+
# Cap history
|
|
408
|
+
if len(self._prices[token_address]) > 200:
|
|
409
|
+
self._prices[token_address] = self._prices[token_address][-200:]
|
|
410
|
+
signal = self.compute_signal(token_address, price)
|
|
411
|
+
return (
|
|
412
|
+
f"Token: {token_address[:12]}...\\n"
|
|
413
|
+
f"Price: {price:.6f} FET\\n"
|
|
414
|
+
f"Signal: {signal}\\n\\n"
|
|
415
|
+
f"DISCLAIMER: Informational only, not financial advice."
|
|
416
|
+
)
|
|
417
|
+
|
|
418
|
+
return (
|
|
419
|
+
f"Welcome to {BUSINESS['name']}!\\n\\n"
|
|
420
|
+
f"Commands:\\n"
|
|
421
|
+
f" signal <token_address> — compute buy/sell/hold signal\\n"
|
|
422
|
+
f" analyse <token_address> — alias for signal\\n\\n"
|
|
423
|
+
f"Strategy: MA{BUSINESS['signal_window']} crossover\\n"
|
|
424
|
+
f"Buy threshold: +{BUSINESS['buy_threshold_pct']}% above MA\\n"
|
|
425
|
+
f"Sell threshold: -{BUSINESS['sell_threshold_pct']}% below MA\\n\\n"
|
|
426
|
+
f"DISCLAIMER: Informational only, not financial advice."
|
|
427
|
+
)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
# ==============================================================================
|
|
431
|
+
# REPLY HELPER
|
|
432
|
+
# ==============================================================================
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
async def reply(ctx: Context, sender: str, text: str, end: bool = False) -> None:
|
|
436
|
+
content = [TextContent(type="text", text=text)]
|
|
437
|
+
if end:
|
|
438
|
+
content.append(EndSessionContent(type="end-session"))
|
|
439
|
+
try:
|
|
440
|
+
await ctx.send(
|
|
441
|
+
sender,
|
|
442
|
+
ChatMessage(timestamp=datetime.utcnow(), msg_id=uuid4(), content=content),
|
|
443
|
+
)
|
|
444
|
+
except Exception as e:
|
|
445
|
+
ctx.logger.error(f"Failed to send reply to {sender[:20]}: {e}")
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
# ==============================================================================
|
|
449
|
+
# MAIN AGENT
|
|
450
|
+
# ==============================================================================
|
|
451
|
+
|
|
452
|
+
cache = Cache(max_size=1000)
|
|
453
|
+
security = Security()
|
|
454
|
+
health = Health()
|
|
455
|
+
revenue = Revenue(cache)
|
|
456
|
+
business = TradingBotBusiness()
|
|
457
|
+
|
|
458
|
+
agent = Agent()
|
|
459
|
+
chat_proto = Protocol(spec=chat_protocol_spec)
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
@chat_proto.on_message(ChatMessage)
|
|
463
|
+
async def handle_chat(ctx: Context, sender: str, msg: ChatMessage) -> None:
|
|
464
|
+
try:
|
|
465
|
+
await ctx.send(
|
|
466
|
+
sender,
|
|
467
|
+
ChatAcknowledgement(
|
|
468
|
+
timestamp=datetime.utcnow(), acknowledged_msg_id=msg.msg_id
|
|
469
|
+
),
|
|
470
|
+
)
|
|
471
|
+
except Exception as e:
|
|
472
|
+
ctx.logger.error(f"Failed to send ack to {sender[:20]}: {e}")
|
|
473
|
+
|
|
474
|
+
text = " ".join(
|
|
475
|
+
item.text for item in msg.content if isinstance(item, TextContent)
|
|
476
|
+
).strip()
|
|
477
|
+
text = text[: BUSINESS["max_input_length"]]
|
|
478
|
+
|
|
479
|
+
clean, error = security.check(ctx, sender, text)
|
|
480
|
+
if error:
|
|
481
|
+
health.record(False)
|
|
482
|
+
await reply(ctx, sender, error, end=True)
|
|
483
|
+
return
|
|
484
|
+
|
|
485
|
+
Logger.audit(ctx, sender, "request")
|
|
486
|
+
|
|
487
|
+
lower = clean.lower()
|
|
488
|
+
|
|
489
|
+
if lower in ("help", "?"):
|
|
490
|
+
tier = revenue.get_tier(sender)
|
|
491
|
+
await reply(
|
|
492
|
+
ctx,
|
|
493
|
+
sender,
|
|
494
|
+
f"**{BUSINESS['name']}** v{BUSINESS['version']}\\n\\n"
|
|
495
|
+
f"{BUSINESS['description']}\\n\\n"
|
|
496
|
+
f"Your tier: {tier.upper()}\\n\\n"
|
|
497
|
+
f"Commands: help, status, tokenize, signal <addr>",
|
|
498
|
+
)
|
|
499
|
+
return
|
|
500
|
+
|
|
501
|
+
if lower == "status":
|
|
502
|
+
s = health.status()
|
|
503
|
+
await reply(
|
|
504
|
+
ctx,
|
|
505
|
+
sender,
|
|
506
|
+
f"Status: {s['status']} | Uptime: {s['uptime_seconds']}s | "
|
|
507
|
+
f"Requests: {s['requests']} | Error rate: {s['error_rate']}",
|
|
508
|
+
)
|
|
509
|
+
return
|
|
510
|
+
|
|
511
|
+
if "tokenize" in lower:
|
|
512
|
+
if OWNER_ADDRESS and sender != OWNER_ADDRESS:
|
|
513
|
+
await reply(ctx, sender, "Only the agent owner can trigger tokenization.", end=True)
|
|
514
|
+
return
|
|
515
|
+
result = AgentLaunch.tokenize()
|
|
516
|
+
link = result.get("data", {}).get("handoff_link") or result.get("handoff_link")
|
|
517
|
+
await reply(
|
|
518
|
+
ctx,
|
|
519
|
+
sender,
|
|
520
|
+
f"Token created! Deploy here: {link}" if link else f"Result: {json.dumps(result)}",
|
|
521
|
+
end=True,
|
|
522
|
+
)
|
|
523
|
+
return
|
|
524
|
+
|
|
525
|
+
tier = revenue.get_tier(sender)
|
|
526
|
+
allowed, quota_error = revenue.check_quota(sender, tier)
|
|
527
|
+
if not allowed:
|
|
528
|
+
health.record(False)
|
|
529
|
+
await reply(ctx, sender, quota_error, end=True)
|
|
530
|
+
return
|
|
531
|
+
|
|
532
|
+
try:
|
|
533
|
+
response = await business.handle(ctx, sender, clean, tier)
|
|
534
|
+
health.record(True)
|
|
535
|
+
except Exception as e:
|
|
536
|
+
health.record(False)
|
|
537
|
+
Logger.error(ctx, "business_handle", str(e))
|
|
538
|
+
response = "Something went wrong. Please try again."
|
|
539
|
+
|
|
540
|
+
await reply(ctx, sender, response, end=True)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
@chat_proto.on_message(ChatAcknowledgement)
|
|
544
|
+
async def handle_ack(ctx: Context, sender: str, msg: ChatAcknowledgement) -> None:
|
|
545
|
+
ctx.logger.debug(f"Ack from {sender[:20]} for msg {msg.acknowledged_msg_id}")
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
@agent.on_interval(period=3600)
|
|
549
|
+
async def periodic_health(ctx: Context) -> None:
|
|
550
|
+
ctx.logger.info(f"[HEALTH] {json.dumps(health.status())}")
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
agent.include(chat_proto, publish_manifest=True)
|
|
554
|
+
|
|
555
|
+
if __name__ == "__main__":
|
|
556
|
+
agent.run()
|
|
557
|
+
`,
|
|
558
|
+
};
|
|
559
|
+
//# sourceMappingURL=trading-bot.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trading-bot.js","sourceRoot":"","sources":["../../src/templates/trading-bot.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,MAAM,CAAC,MAAM,QAAQ,GAAkB;IACrC,IAAI,EAAE,aAAa;IACnB,WAAW,EACT,mFAAmF;IACrF,QAAQ,EAAE,SAAS;IACnB,SAAS,EAAE;QACT,EAAE,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,mBAAmB,EAAE;QACxE;YACE,IAAI,EAAE,aAAa;YACnB,OAAO,EAAE,wEAAwE;YACjF,WAAW,EAAE,2CAA2C;SACzD;QACD;YACE,IAAI,EAAE,eAAe;YACrB,OAAO,EAAE,IAAI;YACb,WAAW,EAAE,4DAA4D;SAC1E;QACD;YACE,IAAI,EAAE,eAAe;YACrB,OAAO,EAAE,GAAG;YACZ,WAAW,EAAE,yDAAyD;SACvE;QACD;YACE,IAAI,EAAE,gBAAgB;YACtB,OAAO,EAAE,GAAG;YACZ,WAAW,EAAE,0DAA0D;SACxE;QACD;YACE,IAAI,EAAE,uBAAuB;YAC7B,OAAO,EAAE,IAAI;YACb,WAAW,EAAE,kCAAkC;SAChD;QACD;YACE,IAAI,EAAE,uBAAuB;YAC7B,OAAO,EAAE,IAAI;YACb,WAAW,EAAE,+BAA+B;SAC7C;QACD;YACE,IAAI,EAAE,yBAAyB;YAC/B,OAAO,EAAE,MAAM;YACf,WAAW,EAAE,yCAAyC;SACvD;KACF;IACD,YAAY,EAAE,CAAC,UAAU,CAAC;IAC1B,OAAO,EAAE,CAAC,oBAAoB,EAAE,qBAAqB,EAAE,eAAe,EAAE,qBAAqB,CAAC;IAC9F,IAAI,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwfP;CACA,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "agentlaunch-templates",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Agent code templates for the AgentLaunch platform",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": ["dist"],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "tsc",
|
|
17
|
+
"clean": "rm -rf dist"
|
|
18
|
+
},
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"typescript": "^5.3.0"
|
|
22
|
+
},
|
|
23
|
+
"engines": { "node": ">=18.0.0" }
|
|
24
|
+
}
|