forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrustScoreProvider.ts
594 lines (537 loc) · 21.8 KB
/
trustScoreProvider.ts
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import {
ProcessedTokenData,
TokenSecurityData,
// TokenTradeData,
// DexScreenerData,
// DexScreenerPair,
// HolderData,
} from "../types/token.ts";
import { Connection, PublicKey } from "@solana/web3.js";
import { getAssociatedTokenAddress } from "@solana/spl-token";
import { TokenProvider } from "./token.ts";
import { WalletProvider } from "./wallet.ts";
import {
TrustScoreDatabase,
RecommenderMetrics,
TokenPerformance,
TradePerformance,
TokenRecommendation,
} from "../adapters/trustScoreDatabase.ts";
import settings from "@ai16z/eliza/src/settings.ts";
import {
IAgentRuntime,
Memory,
Provider,
State,
} from "@ai16z/eliza/src/types.ts";
const Wallet = settings.MAIN_WALLET_ADDRESS;
interface TradeData {
buy_amount: number;
is_simulation: boolean;
}
interface sellDetails {
sell_amount: number;
sell_recommender_id: string | null;
}
interface RecommendationGroup {
recommendation: any;
trustScore: number;
}
interface RecommenderData {
recommenderId: string;
trustScore: number;
riskScore: number;
consistencyScore: number;
recommenderMetrics: RecommenderMetrics;
}
interface TokenRecommendationSummary {
tokenAddress: string;
averageTrustScore: number;
averageRiskScore: number;
averageConsistencyScore: number;
recommenders: RecommenderData[];
}
export class TrustScoreManager {
private tokenProvider: TokenProvider;
private trustScoreDb: TrustScoreDatabase;
private connection: Connection = new Connection(settings.RPC_URL!);
private baseMint: PublicKey = new PublicKey(settings.BASE_MINT!);
private DECAY_RATE = 0.95;
private MAX_DECAY_DAYS = 30;
constructor(
tokenProvider: TokenProvider,
trustScoreDb: TrustScoreDatabase
) {
this.tokenProvider = tokenProvider;
this.trustScoreDb = trustScoreDb;
}
//getRecommenederBalance
async getRecommenederBalance(recommenderWallet: string): Promise<number> {
try {
const tokenAta = await getAssociatedTokenAddress(
new PublicKey(recommenderWallet),
this.baseMint
);
const tokenBalInfo =
await this.connection.getTokenAccountBalance(tokenAta);
const tokenBalance = tokenBalInfo.value.amount;
const balance = parseFloat(tokenBalance);
return balance;
} catch (error) {
console.error("Error fetching balance", error);
return 0;
}
}
/**
* Generates and saves trust score based on processed token data and user recommendations.
* @param tokenAddress The address of the token to analyze.
* @param recommenderId The UUID of the recommender.
* @returns An object containing TokenPerformance and RecommenderMetrics.
*/
async generateTrustScore(
tokenAddress: string,
recommenderId: string,
recommenderWallet: string
): Promise<{
tokenPerformance: TokenPerformance;
recommenderMetrics: RecommenderMetrics;
}> {
const processedData: ProcessedTokenData =
await this.tokenProvider.getProcessedTokenData();
console.log(`Fetched processed token data for token: ${tokenAddress}`);
const recommenderMetrics =
await this.trustScoreDb.getRecommenderMetrics(recommenderId);
const isRapidDump = await this.isRapidDump(tokenAddress);
const sustainedGrowth = await this.sustainedGrowth(tokenAddress);
const suspiciousVolume = await this.suspiciousVolume(tokenAddress);
const balance = await this.getRecommenederBalance(recommenderWallet);
const virtualConfidence = balance / 1000000; // TODO: create formula to calculate virtual confidence based on user balance
const lastActive = recommenderMetrics.lastActiveDate;
const now = new Date();
const inactiveDays = Math.floor(
(now.getTime() - lastActive.getTime()) / (1000 * 60 * 60 * 24)
);
const decayFactor = Math.pow(
this.DECAY_RATE,
Math.min(inactiveDays, this.MAX_DECAY_DAYS)
);
const decayedScore = recommenderMetrics.trustScore * decayFactor;
const validationTrustScore =
this.trustScoreDb.calculateValidationTrust(tokenAddress);
return {
tokenPerformance: {
tokenAddress:
processedData.dexScreenerData.pairs[0]?.baseToken.address ||
"",
priceChange24h:
processedData.tradeData.price_change_24h_percent,
volumeChange24h: processedData.tradeData.volume_24h,
trade_24h_change:
processedData.tradeData.trade_24h_change_percent,
liquidity:
processedData.dexScreenerData.pairs[0]?.liquidity.usd || 0,
liquidityChange24h: 0,
holderChange24h:
processedData.tradeData.unique_wallet_24h_change_percent,
rugPull: false, // TODO: Implement rug pull detection
isScam: false, // TODO: Implement scam detection
marketCapChange24h: 0, // TODO: Implement market cap change
sustainedGrowth: sustainedGrowth,
rapidDump: isRapidDump,
suspiciousVolume: suspiciousVolume,
validationTrust: validationTrustScore,
lastUpdated: new Date(),
},
recommenderMetrics: {
recommenderId: recommenderId,
trustScore: recommenderMetrics.trustScore,
totalRecommendations: recommenderMetrics.totalRecommendations,
successfulRecs: recommenderMetrics.successfulRecs,
avgTokenPerformance: recommenderMetrics.avgTokenPerformance,
riskScore: recommenderMetrics.riskScore,
consistencyScore: recommenderMetrics.consistencyScore,
virtualConfidence: virtualConfidence,
lastActiveDate: now,
trustDecay: decayedScore,
lastUpdated: new Date(),
},
};
}
async updateRecommenderMetrics(
recommenderId: string,
tokenPerformance: TokenPerformance,
recommenderWallet: string
): Promise<void> {
const recommenderMetrics =
await this.trustScoreDb.getRecommenderMetrics(recommenderId);
const totalRecommendations =
recommenderMetrics.totalRecommendations + 1;
const successfulRecs = tokenPerformance.rugPull
? recommenderMetrics.successfulRecs
: recommenderMetrics.successfulRecs + 1;
const avgTokenPerformance =
(recommenderMetrics.avgTokenPerformance *
recommenderMetrics.totalRecommendations +
tokenPerformance.priceChange24h) /
totalRecommendations;
const overallTrustScore = this.calculateTrustScore(
tokenPerformance,
recommenderMetrics
);
const riskScore = this.calculateOverallRiskScore(
tokenPerformance,
recommenderMetrics
);
const consistencyScore = this.calculateConsistencyScore(
tokenPerformance,
recommenderMetrics
);
const balance = await this.getRecommenederBalance(recommenderWallet);
const virtualConfidence = balance / 1000000; // TODO: create formula to calculate virtual confidence based on user balance
const lastActive = recommenderMetrics.lastActiveDate;
const now = new Date();
const inactiveDays = Math.floor(
(now.getTime() - lastActive.getTime()) / (1000 * 60 * 60 * 24)
);
const decayFactor = Math.pow(
this.DECAY_RATE,
Math.min(inactiveDays, this.MAX_DECAY_DAYS)
);
const decayedScore = recommenderMetrics.trustScore * decayFactor;
const newRecommenderMetrics: RecommenderMetrics = {
recommenderId: recommenderId,
trustScore: overallTrustScore,
totalRecommendations: totalRecommendations,
successfulRecs: successfulRecs,
avgTokenPerformance: avgTokenPerformance,
riskScore: riskScore,
consistencyScore: consistencyScore,
virtualConfidence: virtualConfidence,
lastActiveDate: new Date(),
trustDecay: decayedScore,
lastUpdated: new Date(),
};
await this.trustScoreDb.updateRecommenderMetrics(newRecommenderMetrics);
}
calculateTrustScore(
tokenPerformance: TokenPerformance,
recommenderMetrics: RecommenderMetrics
): number {
const riskScore = this.calculateRiskScore(tokenPerformance);
const consistencyScore = this.calculateConsistencyScore(
tokenPerformance,
recommenderMetrics
);
return (riskScore + consistencyScore) / 2;
}
calculateOverallRiskScore(
tokenPerformance: TokenPerformance,
recommenderMetrics: RecommenderMetrics
) {
const riskScore = this.calculateRiskScore(tokenPerformance);
const consistencyScore = this.calculateConsistencyScore(
tokenPerformance,
recommenderMetrics
);
return (riskScore + consistencyScore) / 2;
}
calculateRiskScore(tokenPerformance: TokenPerformance): number {
let riskScore = 0;
if (tokenPerformance.rugPull) {
riskScore += 10;
}
if (tokenPerformance.isScam) {
riskScore += 10;
}
if (tokenPerformance.rapidDump) {
riskScore += 5;
}
if (tokenPerformance.suspiciousVolume) {
riskScore += 5;
}
return riskScore;
}
calculateConsistencyScore(
tokenPerformance: TokenPerformance,
recommenderMetrics: RecommenderMetrics
): number {
const avgTokenPerformance = recommenderMetrics.avgTokenPerformance;
const priceChange24h = tokenPerformance.priceChange24h;
return Math.abs(priceChange24h - avgTokenPerformance);
}
async suspiciousVolume(tokenAddress: string): Promise<boolean> {
const processedData: ProcessedTokenData =
await this.tokenProvider.getProcessedTokenData();
const unique_wallet_24h = processedData.tradeData.unique_wallet_24h;
const volume_24h = processedData.tradeData.volume_24h;
const suspiciousVolume = unique_wallet_24h / volume_24h > 0.5;
console.log(`Fetched processed token data for token: ${tokenAddress}`);
return suspiciousVolume;
}
async sustainedGrowth(tokenAddress: string): Promise<boolean> {
const processedData: ProcessedTokenData =
await this.tokenProvider.getProcessedTokenData();
console.log(`Fetched processed token data for token: ${tokenAddress}`);
return processedData.tradeData.volume_24h_change_percent > 50;
}
async isRapidDump(tokenAddress: string): Promise<boolean> {
const processedData: ProcessedTokenData =
await this.tokenProvider.getProcessedTokenData();
console.log(`Fetched processed token data for token: ${tokenAddress}`);
return processedData.tradeData.trade_24h_change_percent < -50;
}
async checkTrustScore(tokenAddress: string): Promise<TokenSecurityData> {
const processedData: ProcessedTokenData =
await this.tokenProvider.getProcessedTokenData();
console.log(`Fetched processed token data for token: ${tokenAddress}`);
return {
ownerBalance: processedData.security.ownerBalance,
creatorBalance: processedData.security.creatorBalance,
ownerPercentage: processedData.security.ownerPercentage,
creatorPercentage: processedData.security.creatorPercentage,
top10HolderBalance: processedData.security.top10HolderBalance,
top10HolderPercent: processedData.security.top10HolderPercent,
};
}
/**
* Creates a TradePerformance object based on token data and recommender.
* @param tokenAddress The address of the token.
* @param recommenderId The UUID of the recommender.
* @param data ProcessedTokenData.
* @returns TradePerformance object.
*/
async createTradePerformance(
runtime: IAgentRuntime,
tokenAddress: string,
recommenderId: string,
data: TradeData
): Promise<TradePerformance> {
const recommender =
await this.trustScoreDb.getOrCreateRecommenderWithDiscordId(
recommenderId
);
const processedData: ProcessedTokenData =
await this.tokenProvider.getProcessedTokenData();
const wallet = new WalletProvider(
new Connection("https://api.mainnet-beta.solana.com"),
new PublicKey(Wallet!)
);
const prices = await wallet.fetchPrices(runtime);
const solPrice = prices.solana.usd;
const buySol = data.buy_amount / parseFloat(solPrice);
const buy_value_usd = data.buy_amount * processedData.tradeData.price;
const creationData = {
token_address: tokenAddress,
recommender_id: recommender.id,
buy_price: processedData.tradeData.price,
sell_price: 0,
buy_timeStamp: new Date().toISOString(),
sell_timeStamp: "",
buy_amount: data.buy_amount,
sell_amount: 0,
buy_sol: buySol,
received_sol: 0,
buy_value_usd: buy_value_usd,
sell_value_usd: 0,
profit_usd: 0,
profit_percent: 0,
buy_market_cap:
processedData.dexScreenerData.pairs[0]?.marketCap || 0,
sell_market_cap: 0,
market_cap_change: 0,
buy_liquidity:
processedData.dexScreenerData.pairs[0]?.liquidity.usd || 0,
sell_liquidity: 0,
liquidity_change: 0,
last_updated: new Date().toISOString(),
rapidDump: false,
};
this.trustScoreDb.addTradePerformance(creationData, data.is_simulation);
return creationData;
}
/**
* Updates a trade with sell details.
* @param tokenAddress The address of the token.
* @param recommenderId The UUID of the recommender.
* @param buyTimeStamp The timestamp when the buy occurred.
* @param sellDetails An object containing sell-related details.
* @param isSimulation Whether the trade is a simulation. If true, updates in simulation_trade; otherwise, in trade.
* @returns boolean indicating success.
*/
async updateSellDetails(
runtime: IAgentRuntime,
tokenAddress: string,
recommenderId: string,
sellTimeStamp: string,
sellDetails: sellDetails,
isSimulation: boolean
) {
const recommender =
await this.trustScoreDb.getOrCreateRecommenderWithDiscordId(
recommenderId
);
const processedData: ProcessedTokenData =
await this.tokenProvider.getProcessedTokenData();
const wallet = new WalletProvider(
new Connection("https://api.mainnet-beta.solana.com"),
new PublicKey(Wallet!)
);
const prices = await wallet.fetchPrices(runtime);
const solPrice = prices.solana.usd;
const sellSol = sellDetails.sell_amount / parseFloat(solPrice);
const sell_value_usd =
sellDetails.sell_amount * processedData.tradeData.price;
const trade = await this.trustScoreDb.getLatestTradePerformance(
tokenAddress,
recommender.id,
isSimulation
);
const buyTimeStamp = trade.buy_timeStamp;
const marketCap =
processedData.dexScreenerData.pairs[0]?.marketCap || 0;
const liquidity =
processedData.dexScreenerData.pairs[0]?.liquidity.usd || 0;
const sell_price = processedData.tradeData.price;
const profit_usd = sell_value_usd - trade.buy_value_usd;
const profit_percent = (profit_usd / trade.buy_value_usd) * 100;
const market_cap_change = marketCap - trade.buy_market_cap;
const liquidity_change = liquidity - trade.buy_liquidity;
const isRapidDump = await this.isRapidDump(tokenAddress);
const sellDetailsData = {
sell_price: sell_price,
sell_timeStamp: sellTimeStamp,
sell_amount: sellDetails.sell_amount,
received_sol: sellSol,
sell_value_usd: sell_value_usd,
profit_usd: profit_usd,
profit_percent: profit_percent,
sell_market_cap: marketCap,
market_cap_change: market_cap_change,
sell_liquidity: liquidity,
liquidity_change: liquidity_change,
rapidDump: isRapidDump,
sell_recommender_id: sellDetails.sell_recommender_id || null,
};
this.trustScoreDb.updateTradePerformanceOnSell(
tokenAddress,
recommender.id,
buyTimeStamp,
sellDetailsData,
isSimulation
);
return sellDetailsData;
}
// get all recommendations
async getRecommendations(
startDate: Date,
endDate: Date
): Promise<Array<TokenRecommendationSummary>> {
const recommendations = this.trustScoreDb.getRecommendationsByDateRange(
startDate,
endDate
);
// Group recommendations by tokenAddress
const groupedRecommendations = recommendations.reduce(
(acc, recommendation) => {
const { tokenAddress } = recommendation;
if (!acc[tokenAddress]) acc[tokenAddress] = [];
acc[tokenAddress].push(recommendation);
return acc;
},
{} as Record<string, Array<TokenRecommendation>>
);
const result = Object.keys(groupedRecommendations).map(
(tokenAddress) => {
const tokenRecommendations =
groupedRecommendations[tokenAddress];
// Initialize variables to compute averages
let totalTrustScore = 0;
let totalRiskScore = 0;
let totalConsistencyScore = 0;
const recommenderData = [];
tokenRecommendations.forEach((recommendation) => {
const tokenPerformance =
this.trustScoreDb.getTokenPerformance(
recommendation.tokenAddress
);
const recommenderMetrics =
this.trustScoreDb.getRecommenderMetrics(
recommendation.recommenderId
);
const trustScore = this.calculateTrustScore(
tokenPerformance,
recommenderMetrics
);
const consistencyScore = this.calculateConsistencyScore(
tokenPerformance,
recommenderMetrics
);
const riskScore = this.calculateRiskScore(tokenPerformance);
// Accumulate scores for averaging
totalTrustScore += trustScore;
totalRiskScore += riskScore;
totalConsistencyScore += consistencyScore;
recommenderData.push({
recommenderId: recommendation.recommenderId,
trustScore,
riskScore,
consistencyScore,
recommenderMetrics,
});
});
// Calculate averages for this token
const averageTrustScore =
totalTrustScore / tokenRecommendations.length;
const averageRiskScore =
totalRiskScore / tokenRecommendations.length;
const averageConsistencyScore =
totalConsistencyScore / tokenRecommendations.length;
return {
tokenAddress,
averageTrustScore,
averageRiskScore,
averageConsistencyScore,
recommenders: recommenderData,
};
}
);
// Sort recommendations by the highest average trust score
result.sort((a, b) => b.averageTrustScore - a.averageTrustScore);
return result;
}
}
export const trustScoreProvider: Provider = {
async get(
runtime: IAgentRuntime,
message: Memory,
state?: State
): Promise<string> {
try {
const trustScoreDb = new TrustScoreDatabase(
runtime.databaseAdapter.db
);
// Get the user ID from the message
const userId = message.userId;
if (!userId) {
console.error("User ID is missing from the message");
return "";
}
// Get the recommender metrics for the user
const recommenderMetrics =
await trustScoreDb.getRecommenderMetrics(userId);
if (!recommenderMetrics) {
console.error("No recommender metrics found for user:", userId);
return "";
}
// Compute the trust score
const trustScore = recommenderMetrics.trustScore;
const user = await runtime.databaseAdapter.getAccountById(userId);
// Format the trust score string
const trustScoreString = `${user.name}'s trust score: ${trustScore.toFixed(2)}`;
return trustScoreString;
} catch (error) {
console.error("Error in trust score provider:", error.message);
return `Failed to fetch trust score: ${error instanceof Error ? error.message : "Unknown error"}`;
}
},
};