Skip to content

Commit 4597261

Browse files
authored
Merge pull request #800 from ai16z/feat/trust-tg-client
fix: swap type error, create user trust on first message in telegram
2 parents d3ee3a1 + 6b8a9c4 commit 4597261

File tree

5 files changed

+101
-34
lines changed

5 files changed

+101
-34
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
export async function getOrCreateRecommenderInBe(
2+
recommenderId: string,
3+
username: string,
4+
backendToken: string,
5+
backend: string,
6+
retries = 3,
7+
delayMs = 2000
8+
) {
9+
for (let attempt = 1; attempt <= retries; attempt++) {
10+
try {
11+
const response = await fetch(
12+
`${backend}/api/updaters/getOrCreateRecommender`,
13+
{
14+
method: "POST",
15+
headers: {
16+
"Content-Type": "application/json",
17+
Authorization: `Bearer ${backendToken}`,
18+
},
19+
body: JSON.stringify({
20+
recommenderId: recommenderId,
21+
username: username,
22+
}),
23+
}
24+
);
25+
const data = await response.json();
26+
return data;
27+
} catch (error) {
28+
console.error(
29+
`Attempt ${attempt} failed: Error getting or creating recommender in backend`,
30+
error
31+
);
32+
if (attempt < retries) {
33+
console.log(`Retrying in ${delayMs} ms...`);
34+
await new Promise((resolve) => setTimeout(resolve, delayMs));
35+
} else {
36+
console.error("All attempts failed.");
37+
}
38+
}
39+
}
40+
}

packages/client-telegram/src/telegramClient.ts

+31
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,24 @@
11
import { Context, Telegraf } from "telegraf";
22
import { IAgentRuntime, elizaLogger } from "@ai16z/eliza";
33
import { MessageManager } from "./messageManager.ts";
4+
import { getOrCreateRecommenderInBe } from "./getOrCreateRecommenderInBe.ts";
45

56
export class TelegramClient {
67
private bot: Telegraf<Context>;
78
private runtime: IAgentRuntime;
89
private messageManager: MessageManager;
10+
private backend;
11+
private backendToken;
12+
private tgTrader;
913

1014
constructor(runtime: IAgentRuntime, botToken: string) {
1115
elizaLogger.log("📱 Constructing new TelegramClient...");
1216
this.runtime = runtime;
1317
this.bot = new Telegraf(botToken);
1418
this.messageManager = new MessageManager(this.bot, this.runtime);
19+
this.backend = runtime.getSetting("BACKEND_URL");
20+
this.backendToken = runtime.getSetting("BACKEND_TOKEN");
21+
this.tgTrader = runtime.getSetting("TG_TRADER"); // boolean To Be added to the settings
1522
elizaLogger.log("✅ TelegramClient constructor completed");
1623
}
1724

@@ -45,6 +52,30 @@ export class TelegramClient {
4552

4653
this.bot.on("message", async (ctx) => {
4754
try {
55+
if (this.tgTrader) {
56+
const userId = ctx.from?.id.toString();
57+
const username =
58+
ctx.from?.username || ctx.from?.first_name || "Unknown";
59+
if (!userId) {
60+
elizaLogger.warn(
61+
"Received message from a user without an ID."
62+
);
63+
return;
64+
}
65+
try {
66+
await getOrCreateRecommenderInBe(
67+
userId,
68+
username,
69+
this.backendToken,
70+
this.backend
71+
);
72+
} catch (error) {
73+
elizaLogger.error(
74+
"Error getting or creating recommender in backend",
75+
error
76+
);
77+
}
78+
}
4879
await this.messageManager.handleMessage(ctx);
4980
} catch (error) {
5081
elizaLogger.error("❌ Error handling message:", error);

packages/plugin-solana/src/evaluators/trust.ts

+28-29
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,9 @@ These are an examples of the expected output of this task:
5353
Extract any new recommendations from the conversation that are not already present in the list of known recommendations below:
5454
{{recentRecommendations}}
5555
56-
- Include the recommender's username
56+
- Include the recommender's username
5757
- Try not to include already-known recommendations. If you think a recommendation is already known, but you're not sure, respond with alreadyKnown: true.
58-
- Set the conviction to 'none', 'low', 'medium' or 'high'
58+
- Set the conviction to 'none', 'low', 'medium' or 'high'
5959
- Set the recommendation type to 'buy', 'dont_buy', 'sell', or 'dont_sell'
6060
- Include the contract address and/or ticker if available
6161
@@ -67,13 +67,13 @@ Response should be a JSON object array inside a JSON markdown block. Correct res
6767
[
6868
{
6969
"recommender": string,
70-
"ticker": string | null,
70+
"ticker": string | null,
7171
"contractAddress": string | null,
7272
"type": enum<buy|dont_buy|sell|dont_sell>,
7373
"conviction": enum<none|low|medium|high>,
7474
"alreadyKnown": boolean
7575
},
76-
...
76+
...
7777
]
7878
\`\`\``;
7979

@@ -259,7 +259,6 @@ async function handler(runtime: IAgentRuntime, message: Memory) {
259259
runtime,
260260
rec.contractAddress,
261261
userId,
262-
account.username, // we need this to create the recommender account in the BE
263262
{
264263
buy_amount: rec.buyAmount,
265264
is_simulation: true,
@@ -301,7 +300,7 @@ export const trustEvaluator: Evaluator = {
301300
examples: [
302301
{
303302
context: `Actors in the scene:
304-
{{user1}}: Experienced DeFi degen. Constantly chasing high yield farms.
303+
{{user1}}: Experienced DeFi degen. Constantly chasing high yield farms.
305304
{{user2}}: New to DeFi, learning the ropes.
306305
307306
Recommendations about the actors:
@@ -332,7 +331,7 @@ None`,
332331
"recommender": "{{user1}}",
333332
"ticker": "SOLARUG",
334333
"contractAddress": "FCweoTfJ128jGgNEXgdfTXdEZVk58Bz9trCemr6sXNx9",
335-
"type": "buy",
334+
"type": "buy",
336335
"conviction": "medium",
337336
"alreadyKnown": false
338337
}
@@ -341,7 +340,7 @@ None`,
341340
},
342341

343342
{
344-
context: `Actors in the scene:
343+
context: `Actors in the scene:
345344
{{user1}}: Solana maximalist. Believes Solana will flip Ethereum.
346345
{{user2}}: Multichain proponent. Holds both SOL and ETH.
347346
@@ -370,25 +369,25 @@ Recommendations about the actors:
370369
outcome: `\`\`\`json
371370
[
372371
{
373-
"recommender": "{{user1}}",
372+
"recommender": "{{user1}}",
374373
"ticker": "COPETOKEN",
375374
"contractAddress": null,
376375
"type": "sell",
377-
"conviction": "low",
376+
"conviction": "low",
378377
"alreadyKnown": true
379378
},
380379
{
381-
"recommender": "{{user1}}",
380+
"recommender": "{{user1}}",
382381
"ticker": "SOYLENT",
383382
"contractAddress": null,
384383
"type": "sell",
385-
"conviction": "low",
384+
"conviction": "low",
386385
"alreadyKnown": true
387386
},
388387
{
389388
"recommender": "{{user1}}",
390389
"ticker": "SOLVAULT",
391-
"contractAddress": "7tRzKud6FBVFEhYqZS3CuQ2orLRM21bdisGykL5Sr4Dx",
390+
"contractAddress": "7tRzKud6FBVFEhYqZS3CuQ2orLRM21bdisGykL5Sr4Dx",
392391
"type": "buy",
393392
"conviction": "high",
394393
"alreadyKnown": false
@@ -399,7 +398,7 @@ Recommendations about the actors:
399398

400399
{
401400
context: `Actors in the scene:
402-
{{user1}}: Self-proclaimed Solana alpha caller. Allegedly has insider info.
401+
{{user1}}: Self-proclaimed Solana alpha caller. Allegedly has insider info.
403402
{{user2}}: Degen gambler. Will ape into any hyped token.
404403
405404
Recommendations about the actors:
@@ -419,25 +418,25 @@ None`,
419418
},
420419
] as ActionExample[],
421420
outcome: `\`\`\`json
422-
[
421+
[
423422
{
424423
"recommender": "{{user1}}",
425424
"ticker": "ROULETTE",
426-
"contractAddress": "48vV5y4DRH1Adr1bpvSgFWYCjLLPtHYBqUSwNc2cmCK2",
425+
"contractAddress": "48vV5y4DRH1Adr1bpvSgFWYCjLLPtHYBqUSwNc2cmCK2",
427426
"type": "buy",
428427
"conviction": "high",
429-
"alreadyKnown": false
428+
"alreadyKnown": false
430429
}
431-
]
430+
]
432431
\`\`\``,
433432
},
434433

435434
{
436435
context: `Actors in the scene:
437-
{{user1}}: NFT collector and trader. Bullish on Solana NFTs.
436+
{{user1}}: NFT collector and trader. Bullish on Solana NFTs.
438437
{{user2}}: Only invests based on fundamentals. Sees all NFTs as worthless JPEGs.
439438
440-
Recommendations about the actors:
439+
Recommendations about the actors:
441440
None
442441
`,
443442
messages: [
@@ -473,22 +472,22 @@ None
473472
},
474473
],
475474
outcome: `\`\`\`json
476-
[
475+
[
477476
{
478-
"recommender": "{{user1}}",
477+
"recommender": "{{user1}}",
479478
"ticker": "PIXELAPE",
480479
"contractAddress": "3hAKKmR6XyBooQBPezCbUMhrmcyTkt38sRJm2thKytWc",
481480
"type": "buy",
482-
"conviction": "high",
481+
"conviction": "high",
483482
"alreadyKnown": false
484-
}
483+
}
485484
]
486485
\`\`\``,
487486
},
488487

489488
{
490489
context: `Actors in the scene:
491-
{{user1}}: Contrarian investor. Bets against hyped projects.
490+
{{user1}}: Contrarian investor. Bets against hyped projects.
492491
{{user2}}: Trend follower. Buys tokens that are currently popular.
493492
494493
Recommendations about the actors:
@@ -519,24 +518,24 @@ None`,
519518
},
520519
},
521520
],
522-
outcome: `\`\`\`json
521+
outcome: `\`\`\`json
523522
[
524523
{
525524
"recommender": "{{user2}}",
526525
"ticker": "SAMOYED",
527526
"contractAddress": "5TQwHyZbedaH4Pcthj1Hxf5GqcigL6qWuB7YEsBtqvhr",
528-
"type": "buy",
527+
"type": "buy",
529528
"conviction": "medium",
530529
"alreadyKnown": false
531530
},
532531
{
533532
"recommender": "{{user1}}",
534533
"ticker": "SAMOYED",
535534
"contractAddress": "5TQwHyZbedaH4Pcthj1Hxf5GqcigL6qWuB7YEsBtqvhr",
536-
"type": "dont_buy",
535+
"type": "dont_buy",
537536
"conviction": "high",
538537
"alreadyKnown": false
539-
}
538+
}
540539
]
541540
\`\`\``,
542541
},

packages/plugin-solana/src/providers/simulationSellingService.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -407,7 +407,7 @@ export class SimulationSellingService {
407407
const hash = Math.random().toString(36).substring(7);
408408
const transaction = {
409409
tokenAddress: tokenAddress,
410-
type: "sell",
410+
type: "sell" as "buy" | "sell",
411411
transactionHash: hash,
412412
amount: sellDetails.sell_amount,
413413
price: processedData.tradeData.price,

packages/plugin-solana/src/providers/trustScoreProvider.ts

+1-4
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,6 @@ export class TrustScoreManager {
349349
runtime: IAgentRuntime,
350350
tokenAddress: string,
351351
recommenderId: string,
352-
username: string,
353352
data: TradeData
354353
): Promise<TradePerformance> {
355354
const recommender =
@@ -460,7 +459,7 @@ export class TrustScoreManager {
460459
recommenderId
461460
);
462461
// api call to update trade performance
463-
this.createTradeInBe(tokenAddress, recommenderId, username, data);
462+
this.createTradeInBe(tokenAddress, recommenderId, data);
464463
return creationData;
465464
}
466465

@@ -471,7 +470,6 @@ export class TrustScoreManager {
471470
async createTradeInBe(
472471
tokenAddress: string,
473472
recommenderId: string,
474-
username: string,
475473
data: TradeData,
476474
retries = 3,
477475
delayMs = 2000
@@ -490,7 +488,6 @@ export class TrustScoreManager {
490488
tokenAddress: tokenAddress,
491489
tradeData: data,
492490
recommenderId: recommenderId,
493-
username: username,
494491
}),
495492
}
496493
);

0 commit comments

Comments
 (0)