-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.ts
1622 lines (1411 loc) · 52 KB
/
index.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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import dotenv from 'dotenv';
import { TwitterApi } from 'twitter-api-v2';
import { Client as DiscordClient, Message } from 'discord.js';
import Groq from "groq-sdk";
import { Annotation, MemorySaver, StateGraphArgs } from "@langchain/langgraph";
// Import services
import { SocialService } from './services/social/index.js';
import { Content } from './utils/content.js';
import { Parser } from './utils/parser.js';
import { TradingService } from './services/blockchain/trading.js';
// Types
import { TokenInfo, MarketAnalysis, TradeResult, AgentCommand, CommandContext, MarketMetrics } from './services/blockchain/types.js';
import { SocialMetrics } from './services/social/index.js';
import { StateGraph } from "@langchain/langgraph";
import { SolanaAgentState, solanaAgentState } from "./utils/state.js";
import { generalistNode } from "./agents/generalAgent.js";
import { transferSwapNode } from "./agents/transferOrSwap.js";
import { managerNode } from "./agents/manager.js";
import { readNode } from "./agents/readAgent.js";
import { START, END } from "@langchain/langgraph";
import { managerRouter } from "./utils/route.js";
import { BaseMessage, HumanMessage } from "@langchain/core/messages";
import {
IAgentRuntime,
elizaLogger} from "@ai16z/eliza";
// Import mainCharacter from local file
import { mainCharacter } from './mainCharacter.js';
declare module "@langchain/langgraph" {
interface MemorySaver {
save(data: { role: string; content: string }): Promise<void>;
}
}
dotenv.config();
loadConfig();
interface ServiceConfig {
dataProcessor: any;
aiService: AIService;
twitterService: any;
tradingService?: TradingService;
jupiterPriceService?: JupiterPriceV2Service;
jupiterPriceV2Service?: JupiterPriceV2Service;
chatService?: any;
}
async function fetchTokenAddresses(): Promise<string[]> {
try {
const response = await axios.get('https://tokens.jup.ag/tokens?tags=verified');
return response.data.map((token: any) => token.address);
} catch (error) {
elizaLogger.error('Failed to fetch token addresses:', error);
throw error;
}
}
async function initializeServices() {
try {
// Fetch token addresses dynamically
const tokenAddresses = await fetchTokenAddresses();
// Initialize data processor
const dataProcessor = new MarketDataProcessor(
process.env.HELIUS_API_KEY!,
'https://tokens.jup.ag/tokens?tags=verified',
CONFIG.SOLANA.PUBLIC_KEY
);
// Initialize AI service
const aiService: AIService = new AIService({
groqApiKey: process.env.GROQ_API_KEY!,
defaultModel: CONFIG.AI.GROQ.MODEL,
maxTokens: CONFIG.AI.GROQ.MAX_TOKENS,
temperature: CONFIG.AI.GROQ.DEFAULT_TEMPERATURE
});
// Initialize Twitter service
const twitterService = new TwitterService(
{
apiKey: process.env.TWITTER_API_KEY!,
apiSecret: process.env.TWITTER_API_SECRET!,
accessToken: process.env.TWITTER_ACCESS_TOKEN!,
accessSecret: process.env.TWITTER_ACCESS_SECRET!,
bearerToken: process.env.TWITTER_BEARER_TOKEN!,
oauthClientId: process.env.OAUTH_CLIENT_ID!,
oauthClientSecret: process.env.OAUTH_CLIENT_SECRET!,
mockMode: process.env.TWITTER_MOCK_MODE === 'true',
maxRetries: Number(process.env.TWITTER_MAX_RETRIES) || 3,
retryDelay: Number(process.env.TWITTER_RETRY_DELAY) || 5000,
contentRules: {
maxEmojis: Number(process.env.TWITTER_MAX_EMOJIS) || 0,
maxHashtags: Number(process.env.TWITTER_MAX_HASHTAGS) || 0,
minInterval: Number(process.env.TWITTER_MIN_INTERVAL) || 300000
},
marketDataConfig: {
heliusApiKey: process.env.HELIUS_API_KEY!,
updateInterval: 1800000,
volatilityThreshold: 0.05
},
tokenAddresses: tokenAddresses, // Pass the fetched token addresses
baseUrl: 'https://api.twitter.com'
},
aiService,
dataProcessor
);
// Initialize WalletProvider
const walletProviderInstance = new WalletProvider(
new Connection(CONFIG.SOLANA.RPC_URL),
new PublicKey(CONFIG.SOLANA.PUBLIC_KEY)
);
// Initialize TokenProvider
// Create cache adapter that implements ICacheManager
const cacheAdapter = {
async get<T>(key: string): Promise<T | undefined> {
return cache.get(key);
},
async set<T>(key: string, value: T, options?: any): Promise<void> {
cache.set(key, value, options?.ttl);
},
async delete(key: string): Promise<void> {
cache.del(key);
}
};
const cache = new NodeCache();
const tokenProviderInstance = new TokenProvider(
tokenAddresses[0],
walletProviderInstance,
cacheAdapter, // Use the adapter instead of raw cache
{ apiKey: CONFIG.SOLANA.RPC_URL } // Pass the correct configuration object
);
// Initialize JupiterService
const jupiterService = new JupiterService();
// Initialize JupiterPriceV2Service with all required arguments
const jupiterPriceV2Service = new JupiterPriceV2Service({
redis: {
host: process.env.REDIS_HOST!,
//port: redisPort,
//password: redisPassword, // Add missing password argument
keyPrefix: 'jupiter-price:',
enableCircuitBreaker: true
},
rpcConnection: {
url: CONFIG.SOLANA.RPC_URL,
walletPublicKey: PublicKey.toString()
},
rateLimitConfig: {
requestsPerMinute: 600,
windowMs: 60000
}
}, tokenProviderInstance, redisService as unknown as RedisService); // Remove the extra cache argument
// Initialize ChatService
const chatService = new ChatService(
aiService,
twitterService,
jupiterPriceV2Service!,
// Add this argument
);
return {
dataProcessor,
aiService,
twitterService,
jupiterPriceV2Service,
chatService
};
} catch (error) {
elizaLogger.error('Failed to initialize services:', error);
throw error;
}
}
function validateEnvironment() {
const requiredEnvVars = [
'GROQ_API_KEY',
'HELIUS_API_KEY',
'TWITTER_API_KEY',
'TWITTER_API_SECRET',
'TWITTER_ACCESS_TOKEN',
'TWITTER_ACCESS_SECRET',
'TWITTER_BEARER_TOKEN',
'OAUTH_CLIENT_ID',
'OAUTH_CLIENT_SECRET'
];
const missing = requiredEnvVars.filter(key => !process.env[key]);
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}
}
function logConfiguration() {
elizaLogger.info('Configuration loaded:', {
network: CONFIG.SOLANA.NETWORK,
rpcUrl: CONFIG.SOLANA.RPC_URL,
pubkey: CONFIG.SOLANA.PUBLIC_KEY
});
// Log environment variables (redacted)
const envVars = [
'TWITTER_API_KEY',
'TWITTER_API_SECRET',
'TWITTER_ACCESS_TOKEN',
'TWITTER_ACCESS_SECRET',
'TWITTER_BEARER_TOKEN',
'OAUTH_CLIENT_ID',
'OAUTH_CLIENT_SECRET'
];
envVars.forEach(key => {
const value = process.env[key];
elizaLogger.info(`${key}: ${value ? '****' + value.slice(-4) : 'Not set'}`);
});
}
// Extend IAgentRuntime to include llm
interface ExtendedAgentRuntime extends IAgentRuntime {
llm: Groq;
}
class MemeAgentInfluencer {
private connection!: Connection;
private groq!: Groq;
private twitter!: TwitterApi;
private discord!: DiscordClient;
private aiService!: AIService;
private socialService!: SocialService;
private tradingService!: TradingService;
private twitterService!: TwitterService;
public tokenAddress: string;
public getTokenAddress(): string {
return this.tokenAddress;
}
private isInitialized: boolean;
private twitterClient!: TwitterApi; // Add separate client for app-only auth
private appOnlyClient!: TwitterApi;
private runtime!: ExtendedAgentRuntime;
constructor() {
// Minimal initialization in constructor
this.isInitialized = false;
this.tokenAddress = '';
}
async initialize(): Promise<void> {
try {
console.log('Initializing JENNA...');
// 1. Initialize LLM
await this.initializeLLM();
// 2. Initialize Twitter
await this.verifyAndInitialize();
// 3. Initialize Solana
await this.initializeSolana();
// 4. Initialize Services
await this.initializeServices();
// 5. Start automation
await this.startAutomation();
this.isInitialized = true;
console.log('JENNA initialization complete');
} catch (error) {
console.error('Failed to initialize JENNA:', error);
await this.cleanup();
throw error;
}
}
private async initializeLLM(): Promise<void> {
try {
const groqApiKey = process.env.GROQ_API_KEY;
if (!groqApiKey) {
throw new Error('GROQ API key not found');
}
this.groq = new Groq({ apiKey: groqApiKey });
this.runtime = {
llm: this.groq,
// Add other runtime properties as needed
} as ExtendedAgentRuntime;
this.aiService = new AIService({
groqApiKey,
defaultModel: CONFIG.AI.GROQ.MODEL,
maxTokens: CONFIG.AI.GROQ.MAX_TOKENS,
temperature: CONFIG.AI.GROQ.DEFAULT_TEMPERATURE
});
console.log('LLM initialized successfully');
} catch (error) {
throw new Error(`Failed to initialize LLM: ${(error as Error).message}`);
}
}
private async initializeSolana(): Promise<void> {
try {
this.connection = new Connection(CONFIG.SOLANA.RPC_URL, {
commitment: 'confirmed',
disableRetryOnRateLimit: false
});
const version = await this.connection.getVersion();
console.log('Solana connection established:', version);
const publicKey = new PublicKey(CONFIG.SOLANA.PUBLIC_KEY);
const balance = await this.connection.getBalance(publicKey);
console.log('Wallet balance:', balance / 1e9, 'SOL');
// Initialize trading service
this.tradingService = new TradingService(
CONFIG.SOLANA.RPC_URL,
process.env.HELIUS_API_KEY!,
`https://price.jup.ag/v4/price?ids=${this.tokenAddress}`,
'https://tokens.jup.ag/tokens?tags=verified'
);
console.log('Solana connection initialized');
} catch (error) {
throw new Error(`Failed to initialize Solana: ${(error as Error).message}`);
}
}
async startAgent(): Promise<void> {
try {
// Initialize first
if (!this.isInitialized) {
await this.initialize();
}
// Then start either chat or autonomous mode
const mode = await selectMode();
const agentExecutor = await this.initializeAgent();
if (mode === "chat") {
await this.runChatMode(agentExecutor, {});
} else if (mode === "auto") {
await this.runAutonomousMode(agentExecutor, {});
}
} catch (error) {
console.error('Failed to start agent:', error);
await this.cleanup();
throw error;
}
}
public async verifyAndInitialize(): Promise<void> {
try {
const twitterConfig = {
username: process.env.TWITTER_USERNAME!,
password: process.env.TWITTER_PASSWORD!,
email: process.env.TWITTER_EMAIL!,
apiKey: process.env.TWITTER_API_KEY!,
apiSecret: process.env.TWITTER_API_SECRET!,
accessToken: process.env.TWITTER_ACCESS_TOKEN!,
accessSecret: process.env.TWITTER_ACCESS_SECRET!,
bearerToken: process.env.TWITTER_BEARER_TOKEN!,
oauthClientId: process.env.OAUTH_CLIENT_ID!,
oauthClientSecret: process.env.OAUTH_CLIENT_SECRET!,
mockMode: process.env.TWITTER_MOCK_MODE === 'true',
maxRetries: Number(process.env.TWITTER_MAX_RETRIES) || 3,
retryDelay: Number(process.env.TWITTER_RETRY_DELAY) || 5000,
contentRules: {
maxEmojis: Number(process.env.TWITTER_MAX_EMOJIS) || 0,
maxHashtags: Number(process.env.TWITTER_MAX_HASHTAGS) || 0,
minInterval: Number(process.env.TWITTER_MIN_INTERVAL) || 300000
}
};
// Validate all required credentials
const requiredCredentials = [
'username', 'password', 'email',
'apiKey', 'apiSecret',
'accessToken', 'accessSecret',
'bearerToken'
];
(requiredCredentials as Array<keyof typeof twitterConfig>).forEach((key) => {
if (!twitterConfig[key]) {
throw new Error(`Missing required Twitter credential: ${key}`);
}
});
// Initialize Twitter clients with credentials
this.twitter = new TwitterApi({
appKey: twitterConfig.apiKey,
appSecret: twitterConfig.apiSecret,
accessToken: twitterConfig.accessToken,
accessSecret: twitterConfig.accessSecret
});
// Initialize app-only client for streams
this.appOnlyClient = new TwitterApi(twitterConfig.bearerToken);
this.twitterClient = this.twitter;
// Verify credentials
await this.verifyTwitterCredentials();
elizaLogger.success('Twitter authentication successful');
} catch (error) {
elizaLogger.error('Twitter authentication error:', error);
throw new Error('Failed to initialize Twitter: ' + (error as Error).message);
}
}
private async setupTwitterStream(): Promise<void> {
try {
if (!this.appOnlyClient) {
throw new Error('App-only client not initialized');
}
// Set up stream using app-only client
const stream = await this.appOnlyClient.v2.searchStream({
'tweet.fields': ['referenced_tweets', 'author_id'],
expansions: ['referenced_tweets.id']
});
stream.autoReconnect = true;
stream.on('data', async (tweet) => {
try {
// Use regular client for replies
const sentiment = await this.aiService.analyzeSentiment(tweet.data.text);
if (sentiment > 0.5) {
const response = await this.aiService.generateResponse({
content: tweet.data.text,
platform: 'twitter',
author: tweet.data.author_id || 'unknown',
});
// Use user context client for posting replies
await this.twitter.v2.reply(response, tweet.data.id);
}
} catch (error) {
elizaLogger.error('Error handling tweet:', error);
}
});
elizaLogger.success('Twitter stream setup completed');
} catch (error) {
elizaLogger.error('Error setting up Twitter stream:', error);
throw error;
}
}
private async cleanup(): Promise<void> {
try {
if (this.appOnlyClient) {
// Use appOnlyClient for cleaning up stream rules
await this.appOnlyClient.v2.updateStreamRules({ delete: { ids: ['*'] } });
}
if (this.discord) {
this.discord.destroy();
}
this.isInitialized = false;
console.log('Cleanup completed successfully');
} catch (error) {
console.error('Error during cleanup:', error);
throw error;
}
}
private async initializeServices(): Promise<void> {
try {
await this.socialService.initialize();
elizaLogger.success('Social service initialized');
await this.setupMessageHandling();
elizaLogger.success('Message handling initialized');
await this.setupTwitterRules();
elizaLogger.success('Twitter rules initialized');
await this.setupTwitterStream();
elizaLogger.success('Twitter stream initialized');
} catch (error) {
elizaLogger.error('Service initialization failed:', error);
throw error;
}
}
private async verifyTwitterCredentials(): Promise<void> {
try {
const me = await this.twitter.v2.me();
elizaLogger.success(`Twitter credentials verified for @${me.data.username}`);
} catch (error) {
elizaLogger.error('Twitter credentials verification failed:', error);
throw new Error('Failed to verify Twitter credentials');
}
}
async postTweet(content: string, options: { mediaUrls?: string[] } = {}): Promise<void> {
try {
elizaLogger.info('Preparing to post tweet...');
let mediaIds: string[] = [];
if (options.mediaUrls?.length) {
mediaIds = await Promise.all(
options.mediaUrls.map(url => this.twitter.v1.uploadMedia(url))
);
}
const tweet = await this.twitter.v2.tweet({
text: content,
...(mediaIds.length && { media: { media_ids: mediaIds.slice(0, 4) as [string] | [string, string] | [string, string, string] | [string, string, string, string] } })
});
elizaLogger.success('Tweet posted successfully:', tweet.data.id);
} catch (error) {
elizaLogger.error('Failed to post tweet:', error);
throw error;
}
}
// Add postTweetWithRetry method
async postTweetWithRetry(content: string, retries = 3): Promise<void> {
const baseWaitTime = 5000; // Start with 5 seconds
let lastError: any;
for (let i = 0; i < retries; i++) {
try {
await this.twitter.v2.tweet({ text: content });
elizaLogger.success('Tweet posted successfully');
return;
} catch (error: any) {
lastError = error;
elizaLogger.error(`Failed to post tweet (attempt ${i + 1}):`, error);
await new Promise(resolve => setTimeout(resolve, baseWaitTime * (i + 1)));
}
}
elizaLogger.error('Failed to post tweet after multiple attempts:', lastError);
throw lastError;
}
private async setupTwitterRules(): Promise<void> {
try {
// Ensure we have a valid bearer token
if (!process.env.TWITTER_BEARER_TOKEN) {
throw new Error('Twitter Bearer Token is required for stream rules');
}
// Use app client for stream rules (same as user client in direct auth)
if (!this.appOnlyClient) {
this.appOnlyClient = this.twitter;
}
const rules = await this.appOnlyClient.v2.streamRules();
// Delete existing rules if any
if (rules.data?.length) {
await this.appOnlyClient.v2.updateStreamRules({
delete: { ids: rules.data.map(rule => rule.id) }
});
}
// Add new rules using app-only client
await this.appOnlyClient.v2.updateStreamRules({
add: [
// { value: `@${CONFIG.SOCIAL.TWITTER.USERNAME}`, tag: 'mentions' },
{ value: CONFIG.SOLANA.TOKEN_SETTINGS.SYMBOL, tag: 'token_mentions' }
]
});
elizaLogger.success('Twitter rules setup completed');
} catch (error: any) {
// More specific error handling
if (error.code === 403) {
elizaLogger.error('Authentication error: Make sure you have the correct Bearer Token with appropriate permissions');
} else {
elizaLogger.error('Error setting up Twitter rules:', error);
}
throw error;
}
}
private scheduleTwitterContent(tokenAddresses: string[]): void {
setInterval(async () => {
try {
const price = await this.getCurrentPrice();
const content = await this.aiService.generateResponse({
content: `Current ${CONFIG.SOLANA.TOKEN_SETTINGS.SYMBOL} price: ${price} SOL`,
platform: 'twitter',
author: '',
});
await this.postTweet(content);
} catch (error) {
elizaLogger.error('Error in scheduled Twitter content:', error);
}
}, CONFIG.AUTOMATION.CONTENT_GENERATION_INTERVAL);
}
private async setupMessageHandling(): Promise<void> {
this.discord.on('messageCreate', async (message: Message) => {
if (message.author.bot) return;
try {
const parsedCommand = Parser.parseCommand(message.content);
if (!parsedCommand) return;
const command: AgentCommand = {
...parsedCommand,
type: parsedCommand.type,
raw: message.content,
command: ''
};
await this.handleCommand(command, {
platform: 'discord',
channelId: message.channel.id,
messageId: message.id,
author: message.author.tag
});
} catch (error) {
elizaLogger.error('Error handling Discord command:', error);
await message.reply('Sorry, there was an error processing your command.');
}
});
await this.setupTwitterStream();
}
// Fix the startAutomation method
private async startAutomation(): Promise<void> {
await Promise.all([
this.startContentGeneration(),
this.startMarketMonitoring(),
this.startCommunityEngagement()
]);
// Add type check for mainCharacter.settings
if (!mainCharacter.settings?.chains) {
elizaLogger.warn('No tweet chains configured, using default interval');
const defaultInterval = 1800000; // 30 minutes
this.scheduleTweets(defaultInterval);
return;
}
const tweetChain = Array.isArray(mainCharacter.settings.chains)
? mainCharacter.settings.chains.find(chain => chain.type === 'tweet' && chain.enabled)
: mainCharacter.settings.chains.twitter?.[0];
const tweetInterval = tweetChain?.interval ?? 1800000;
this.scheduleTweets(tweetInterval);
}
// Add helper method for tweet scheduling
private scheduleTweets(interval: number): void {
setInterval(async () => {
try {
const marketData = await this.tradingService.getMarketData(this.tokenAddress);
await this.postAITweet({
topic: CONFIG.SOLANA.TOKEN_SETTINGS.SYMBOL,
price: marketData.price.toString(), // Convert to string
volume: marketData.volume24h.toString() // Convert to string
});
} catch (error) {
elizaLogger.error('Error in automated tweet generation:', error);
}
}, interval);
}
private async startContentGeneration(): Promise<void> {
const generateAndPost = async () => {
try {
const content = await Content.generateContent({
type: 'market_update',
variables: {
tokenName: CONFIG.SOLANA.TOKEN_SETTINGS.NAME,
tokenAddress: this.tokenAddress,
price: await this.getCurrentPrice()
}
});
// Post to Twitter instead of using socialService
await this.postTweet(content);
} catch (error) {
elizaLogger.error('Content generation error:', error);
}
};
await generateAndPost();
setInterval(generateAndPost, CONFIG.AUTOMATION.CONTENT_GENERATION_INTERVAL);
}
private async startMarketMonitoring(): Promise<void> {
const monitorMarket = async () => {
try {
const analysis = await this.analyzeMarket();
const tradingConfig = CONFIG.SOLANA.TRADING;
if (analysis.shouldTrade && analysis.confidence > tradingConfig.MIN_CONFIDENCE) {
await this.executeTrade(analysis);
}
} catch (error) {
elizaLogger.error('Market monitoring error:', error);
}
};
await monitorMarket();
setInterval(monitorMarket, CONFIG.AUTOMATION.MARKET_MONITORING_INTERVAL);
}
private async startCommunityEngagement(): Promise<void> {
const engage = async () => {
try {
const metrics: SocialMetrics = await this.socialService.getCommunityMetrics();
const content = await Content.generateContent({
type: 'community',
variables: {
followers: metrics.followers.toString(),
engagement: metrics.engagement.toString(),
activity: metrics.activity
}
});
await this.socialService.send(content);
} catch (error) {
elizaLogger.error('Community engagement error:', error);
}
};
await engage();
setInterval(engage, CONFIG.AUTOMATION.COMMUNITY_ENGAGEMENT_INTERVAL);
}
private async analyzeMarket(): Promise<MarketAnalysis> {
try {
const marketData = await this.tradingService.getMarketData(this.tokenAddress);
if (!marketData) {
throw new Error('Failed to fetch market data');
}
const aiAnalysis = await this.aiService.analyzeMarket(marketData);
const metrics: MarketMetrics = {
price: marketData.price || 0,
volume24h: marketData.volume24h || 0,
marketCap: marketData.marketCap || 0,
confidence: aiAnalysis.confidence || 0,
onChainData: marketData.onChainActivity || {},
volatility: marketData.volatility?.currentVolatility || 0,
momentum: marketData.volatility?.adjustmentFactor || 0,
strength: marketData.volatility?.averageVolatility || 0
};
return {
summary: aiAnalysis.summary || '',
sentiment: aiAnalysis.sentiment || 'NEUTRAL',
keyPoints: aiAnalysis.keyPoints || [],
recommendation: aiAnalysis.recommendation || null,
shouldTrade: aiAnalysis.shouldTrade || false,
confidence: aiAnalysis.confidence || 0,
action: aiAnalysis.action || 'HOLD',
reasons: aiAnalysis.reasons || [],
riskLevel: (aiAnalysis.riskLevel === 'LOW' || aiAnalysis.riskLevel === 'HIGH' ?
aiAnalysis.riskLevel : 'MEDIUM') as 'LOW' | 'MEDIUM' | 'HIGH',
metrics: metrics // Now includes all required properties
};
} catch (error) {
console.error('Error in market analysis:', error);
// Return fallback object with complete metrics
return {
summary: 'Error analyzing market',
sentiment: 'NEUTRAL',
keyPoints: [],
recommendation: null,
shouldTrade: false,
confidence: 0,
action: 'HOLD',
reasons: ['Error analyzing market'],
riskLevel: 'MEDIUM',
metrics: {
price: 0,
volume24h: 0,
marketCap: 0,
confidence: 0,
onChainData: {},
volatility: 0,
momentum: 0,
strength: 0
}
};
}
}
private async executeTrade(analysis: MarketAnalysis): Promise<TradeResult> {
return await this.tradingService.executeTrade(
analysis.action === 'BUY' ? 'SOL' : this.tokenAddress,
analysis.action === 'BUY' ? this.tokenAddress : 'SOL',
this.calculateTradeAmount(analysis),
CONFIG.SOLANA.TRADING.SLIPPAGE
);
}
private async getCurrentPrice(): Promise<number> {
return await this.tradingService.getTokenPrice(this.tokenAddress);
}
private calculateTradeAmount(analysis: MarketAnalysis): number {
return CONFIG.SOLANA.TRADING.BASE_AMOUNT * analysis.confidence;
}
private async handleCommand(
command: AgentCommand,
context: CommandContext
): Promise<void> {
try {
const response = await this.generateCommandResponse(command, context);
await this.socialService.sendMessage(context.platform, context.messageId, response);
} catch (error) {
elizaLogger.error('Command handling error:', error);
await this.socialService.sendMessage(
context.platform,
context.messageId,
'Sorry, there was an error processing your command.'
);
}
}
private async generateCommandResponse(
command: AgentCommand,
context: CommandContext
): Promise<string> {
switch (command.type) {
case 'price':
const price = await this.getCurrentPrice();
return `Current price: ${price} SOL`;
case 'stats':
const metrics = await this.tradingService.getMarketData(this.tokenAddress);
return `24h Volume: ${metrics.volume24h}\nMarket Cap: ${metrics.marketCap}`;
default:
const response = await this.aiService.generateResponse({
content: command.raw,
platform: context.platform,
author: context.author,
});
return response;
}
}
async replyToTweet(tweetId: string, content: string): Promise<void> {
try {
await this.twitter.v2.reply(content, tweetId);
elizaLogger.success('Reply posted successfully');
} catch (error) {
elizaLogger.error('Failed to reply to tweet:', error);
throw error;
}
}
private async initializeAgent(): Promise<void> {
// Initialize LLM
const groqApiKey = process.env.GROQ_API_KEY;
const llm = new Groq({ apiKey: groqApiKey });
// Load Bearer Token
const twitterBearerToken = process.env.TWITTER_BEARER_TOKEN;
const twitterAccessToken = process.env.TWITTER_ACCESS_TOKEN;
const twitterAccessTokenSecret = process.env.TWITTER_ACCESS_SECRET;
if (!twitterBearerToken || !twitterAccessToken || !twitterAccessTokenSecret) {
throw new Error("Twitter Bearer Token, access token, or access token secret is missing. Please check your .env file.");
}
// Load OAuth 2.0 Client ID and Client Secret
const oauthClientId = process.env.OAUTH_CLIENT_ID;
const oauthClientSecret = process.env.OAUTH_CLIENT_SECRET;
if (!oauthClientId || !oauthClientSecret) {
throw new Error("OAuth Client ID or Client Secret is missing. Please check your .env file.");
}
// Store buffered conversation history in memory
const memory = new MemorySaver();
// Create and configure the agent with default system prompt
const defaultSystemPrompt = "You are an AI agent specialized in cryptocurrency and blockchain interactions. Help users understand and interact with blockchain technology.";
const agent = await createReActAgent(
llm,
[], // Add tools as needed
memory,
defaultSystemPrompt // Use default prompt instead of mainCharacter.settings.systemPrompt
);
return agent;
}
private async runAutonomousMode(agentExecutor: any, config: any, interval = 10): Promise<void> {
console.log("Starting autonomous mode...");
while (true) {
try {
// Provide instructions autonomously
const thought = "Be creative and do something interesting on the blockchain. Choose an action or set of actions and execute it that highlights your abilities.";
// Run agent in autonomous mode
for await (const chunk of agentExecutor.stream({ messages: [{ content: thought }] }, config)) {
if (chunk.agent) {
console.log(chunk.agent.messages[0].content);
} else if (chunk.tools) {
console.log(chunk.tools.messages[0].content);
}
console.log("-------------------");
}
// Wait before the next action
await new Promise(resolve => setTimeout(resolve, interval * 1000));
} catch (error) {
console.log("Goodbye Agent!");
process.exit(0);
}
}
}
private async runChatMode(agentExecutor: any, config: any): Promise<void> {
console.log("Starting chat mode... Type 'exit' to end.");
while (true) {
try {
const userInput = await new Promise<string>(resolve => {
process.stdout.write("\nPrompt: ");
process.stdin.once('data', data => resolve(data.toString().trim()));
});
if (userInput.toLowerCase() === "exit") {
break;
}
// Run agent with the user's input in chat mode
for await (const chunk of agentExecutor.stream({ messages: [{ content: userInput }] }, config)) {
if (chunk.agent) {
console.log(chunk.agent.messages[0].content);
} else if (chunk.tools) {
console.log(chunk.tools.messages[0].content);
}
console.log("-------------------");
}
} catch (error) {
console.log("Goodbye Agent!");
process.exit(0);
}
}
}
// Add new method for AI tweet generation
private async generateTweetContent(context: any = {}): Promise<string> {
try {
const prompt = `Generate an engaging tweet about ${context.topic || 'cryptocurrency'}
that is informative and entertaining. Include relevant market metrics
if available. Max length: 280 characters.`;
const response = await this.runtime.llm.chat.completions.create({
messages: [{ role: 'user', content: prompt }],
model: 'mixtral-8x7b-32768',
max_tokens: 100,
temperature: 0.7
});
const message = response.choices[0]?.message?.content;
if (!message) {
throw new Error('Failed to generate tweet content');
}
return message.trim();
} catch (error) {
elizaLogger.error('Error generating tweet content:', error);
throw error;
}
}
// Add new method for AI-powered Twitter posting
async postAITweet(context: any = {}): Promise<void> {
try {
elizaLogger.info('Generating AI tweet...');
// Generate tweet content
const content = await this.generateTweetContent(context);
// Post tweet with retry logic
await this.postTweetWithRetry(content);