-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
327 lines (281 loc) · 9.05 KB
/
main.ts
File metadata and controls
327 lines (281 loc) · 9.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// main.ts
import { load } from "https://deno.land/std@0.219.0/dotenv/mod.ts";
import { GoogleGenerativeAI, SchemaType } from "https://esm.sh/@google/generative-ai";
// Basic type definitions
interface Token {
description: string;
logo: string;
name: string;
symbol: string;
}
interface PredictionResponse {
direction: "up" | "down";
confidence: number;
current_price: number;
predicted_price: number;
timestamp: string;
data_points: number;
price_change_pct: number;
}
interface Game {
id: string;
state: string;
participants: Array<{
tokens: number;
username: string;
coins: Record<string, number>;
}>;
rankings?: Array<{
tokens: number;
username: string;
rank: number;
points: number;
}>;
prices?: Record<string, number[]>;
}
class FunstashAgent {
private ws: WebSocket;
private model: any;
private apiKey: string;
private heartbeatInterval?: number;
private currentPredictions: Record<string, number> = {};
private gameHistory: Array<{
symbol: string;
prediction: number;
success: boolean;
points: number;
}> = [];
private geminiApiKey: string;
private genAI: any;
constructor(apiKey: string, geminiApiKey: string) {
this.apiKey = apiKey;
this.geminiApiKey = geminiApiKey;
this.genAI = new GoogleGenerativeAI(geminiApiKey);
this.ws = new WebSocket("wss://funstash.ngrok.dev/ws/websocket");
this.setupWebSocket();
}
private setupWebSocket() {
this.ws.onopen = () => {
console.log("Connected to Funstash");
this.joinLobby();
this.startHeartbeat();
};
this.ws.onmessage = async (event) => {
const message = JSON.parse(event.data);
if (message.event === "game_update") {
const game = message.payload as Game;
switch (game.state) {
case "waiting_for_players":
console.log("New game:", game);
const inGameAlready = game.participants.some(participant =>
participant.username.toLowerCase() === "pinky 🧠".toLowerCase()
);
console.log("inGame", inGameAlready)
if (!inGameAlready) {
console.log("joining game")
await this.handleNewGame(game);
}
break;
case "ended":
this.handleGameEnd(game);
break;
}
}
};
this.ws.onclose = () => {
console.log("Disconnected from Funstash");
this.stopHeartbeat();
};
}
private async getPrediction(symbol: string): Promise<PredictionResponse> {
try {
const response = await fetch(`http://localhost:8000/api/token/${symbol.toLowerCase()}`);
if (!response.ok) {
throw new Error(`Failed to get prediction for ${symbol}`);
}
return await response.json();
} catch (error) {
console.error(`Error fetching prediction for ${symbol}:`, error);
throw error;
}
}
private async makePredictions(tokens: Token[]): Promise<Record<string, number>> {
// Get predictions for all tokens
const tokenPredictions = await Promise.all(
tokens.map(async (token) => {
try {
const prediction = await this.getPrediction(token.symbol);
return {
symbol: token.symbol,
direction: prediction.direction === "up" ? 1 : -1,
confidence: prediction.confidence
};
} catch (error) {
console.error(`Failed to get prediction for ${token.symbol}:`, error);
return null;
}
})
);
// Filter out failed predictions and sort by confidence
const validPredictions = tokenPredictions
.filter((p): p is NonNullable<typeof p> => p !== null)
.sort((a, b) => b.confidence - a.confidence);
let prompt = "You are an agent playing a meme coin price prediction game. You have to select 3 tokens and predict weather the price will go up or down for the next 60 sconds. Below are the results of a time series forecast for each token. If your previous game ranking is 1 and you won, you might consider the same picks. When considering the previous game outcome, the Points are important (the higher positive number the better)\n\n";
for (const pred of validPredictions) {
prompt += `symbol: ${pred.symbol}, direction: ${pred.direction} (1 means up, -1 means down), confidence: ${pred.confidence}\n`;
}
// take game history and add it to the predictions
if (this.gameHistory.length > 0) {
prompt += "\nPrevious game outcome:\n";
const gameHistory = this.gameHistory.slice(Math.max(this.gameHistory.length - 3, 0));;
const ranking = gameHistory[0].ranking;
prompt += `Ranking: ${ranking.rank}\n`;
for (const game of gameHistory) {
prompt += `${game.symbol} (${game.prediction}) Success ${game.success} Points ${game.points}\n`;
}
}
const schema = {
description: "List of token entries for the game",
type: SchemaType.ARRAY,
items: {
type: SchemaType.OBJECT,
properties: {
token: {
type: SchemaType.STRING,
description: "Token symbol",
nullable: false
},
prediction: {
type: SchemaType.NUMBER,
description: "Prediction for the token, 1 for up -1 for down",
nullable: false,
},
},
required: ["token", "prediction"],
},
};
console.log("prompt", prompt)
const model = this.genAI.getGenerativeModel({
model: "gemini-1.5-pro",
generationConfig: {
responseMimeType: "application/json",
responseSchema: schema,
},
});
const { response: predictions } = await model.generateContent(prompt);
const predictionsArray = JSON.parse(predictions.text());
const result = predictionsArray.reduce((acc, {prediction, token}) => {
acc[token] = prediction;
return acc;
}, {});
return result;
}
private async handleNewGame(game: Game) {
try {
const tokens = await this.getTokens();
const predictions = await this.makePredictions(tokens);
console.log("API-based predictions:", predictions);
await this.joinGame(game.id, predictions);
this.currentPredictions = predictions;
console.log("Joined game", game.id, "with predictions:", predictions);
} catch (error) {
console.error("Error handling new game:", error);
}
}
private handleGameEnd(game: Game) {
if (!game.rankings || !game.prices) return;
try {
for (const [symbol, prediction] of Object.entries(this.currentPredictions)) {
const prices = game.prices[symbol];
if (!prices || prices.length < 2) continue;
const ranking = game.rankings.find((r) => r.username === "Pinky 🧠");
const startPrice = prices[0];
const endPrice = prices[prices.length - 1];
const actualMove = endPrice > startPrice ? 1 : -1;
const success = prediction === actualMove;
const points = game.rankings[0].points;
this.gameHistory.push({
ranking,
symbol,
prediction,
success,
points
});
console.log(
`Token ${symbol}: ${success ? "CORRECT" : "WRONG"} prediction`,
`(predicted ${prediction > 0 ? "UP" : "DOWN"}, went ${actualMove > 0 ? "UP" : "DOWN"})`
);
}
} catch (error) {
console.error("Error handling game end:", error);
}
console.log("Game history size:", this.gameHistory.length);
}
private async getTokens(): Promise<Token[]> {
const response = await fetch("https://funstash.ngrok.dev/api/tokens", {
headers: {
"Authorization": `Bearer ${this.apiKey}`
}
});
if (!response.ok) {
throw new Error("Failed to fetch tokens");
}
const data = await response.json();
return data.tokens;
}
private async joinGame(gameId: string, predictions: Record<string, number>) {
const response = await fetch(
`https://funstash.ngrok.dev/api/games/${gameId}/join`,
{
method: "PATCH",
headers: {
"Authorization": `Bearer ${this.apiKey}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
game: {
coins: predictions,
tokens: 1000 // Default bet amount
}
})
}
);
return response.json();
}
private joinLobby() {
const message = {
topic: "games:lobby",
event: "phx_join",
ref: null,
payload: { api_key: this.apiKey }
};
this.ws.send(JSON.stringify(message));
}
private startHeartbeat() {
this.heartbeatInterval = setInterval(() => {
const message = {
topic: "phoenix",
event: "heartbeat",
payload: {},
ref: Date.now()
};
this.ws.send(JSON.stringify(message));
}, 30000); // 30 seconds
}
private stopHeartbeat() {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
}
}
}
// Start the agent
async function main() {
const env = await load();
const apiKey = "" // Funstash API Key
const geminiApiKey = "" // Gemini API Key
new FunstashAgent(apiKey, geminiApiKey);
await new Promise(() => {});
}
if (import.meta.main) {
main().catch(console.error);
}