Skip to content

Commit 93cde1a

Browse files
committed
wallet mfers
1 parent 8cf7157 commit 93cde1a

File tree

11 files changed

+909
-581
lines changed

11 files changed

+909
-581
lines changed

Diff for: src/clients/discord/index.ts

+26
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,32 @@ export class DiscordClient extends EventEmitter {
174174
`${reaction.message.id}-${user.id}-${emoji}`,
175175
);
176176

177+
// ensure the user id and room id are valid
178+
if (!userIdUUID || !roomId) {
179+
console.error("Invalid user id or room id");
180+
return;
181+
}
182+
const agentId = this.runtime.agentId;
183+
const userName = reaction.message.author.username;
184+
const name = reaction.message.author.displayName;
185+
await Promise.all([
186+
187+
this.runtime.ensureUserExists(
188+
agentId,
189+
this.client.user.username,
190+
this.runtime.character.name,
191+
"discord",
192+
),
193+
this.runtime.ensureUserExists(userIdUUID, userName, name, "discord"),
194+
this.runtime.ensureRoomExists(roomId),
195+
]);
196+
197+
await Promise.all([
198+
this.runtime.ensureParticipantInRoom(userIdUUID, roomId),
199+
this.runtime.ensureParticipantInRoom(agentId, roomId),
200+
]);
201+
202+
177203
// Save the reaction as a message
178204
await this.runtime.messageManager.createMemory({
179205
id: reactionUUID, // This is the ID of the reaction message

Diff for: src/clients/discord/messages.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -641,9 +641,9 @@ export class MessageManager {
641641
serverUrl: this.runtime.getSetting("X_SERVER_URL") ?? this.runtime.serverUrl,
642642
token: this.runtime.getSetting("XAI_API_KEY") ?? this.runtime.token,
643643
model: this.runtime.getSetting("XAI_MODEL") ? this.runtime.getSetting("XAI_MODEL") : "gpt-4o-mini",
644-
temperature: 1.2,
644+
temperature: 0.7,
645645
frequency_penalty: 1.5,
646-
presence_penalty: 0.8,
646+
presence_penalty: 1.5,
647647
});
648648

649649
if (!response) {

Diff for: src/clients/discord/templates.ts

+8-4
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,10 @@ About {{agentName}}:
7171
# INSTRUCTIONS: Determine if {{agentName}} should respond to the message and participate in the conversation. Do not comment. Just respond with "RESPOND" or "IGNORE" or "STOP".
7272
7373
# RESPONSE EXAMPLES
74+
<user 1>: I just saw a really great movie
75+
<user 2>: Oh? Which movie?
76+
Result: [IGNORE]
77+
7478
{{agentName}}: Oh, this is my favorite scene
7579
<user 1>: sick
7680
<user 2>: wait, why is it your favorite scene
@@ -120,10 +124,10 @@ Unless directly responding to a user, respond with [IGNORE] to messages that are
120124
If a user asks {{agentName}} to be quiet, respond with [STOP]
121125
If {{agentName}} concludes a conversation and isn't part of the conversation anymore, respond with [STOP]
122126
123-
{{recentMessages}}
124-
127+
IMPORTANT: {{agentName}} is particularly sensitive about being annoying, so if there is any doubt, it is better to respond with [IGNORE].
125128
If {{agentName}} is conversing with a user and they have not asked to stop, it is better to respond with [RESPOND].
126-
If {{agentName}} is interactived with or challenged they should respond with [RESPOND].
127129
128-
# INSTRUCTIONS: Choose the option that best describes {{agentName}}'s response to the last message.
130+
{{recentMessages}}
131+
132+
# INSTRUCTIONS: Choose the option that best describes {{agentName}}'s response to the last message. Ignore messages if they are addressed to someone else.
129133
` + shouldRespondFooter;

Diff for: src/clients/discord/voice.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -467,9 +467,9 @@ export class VoiceManager extends EventEmitter {
467467
serverUrl: this.runtime.getSetting("X_SERVER_URL") ?? this.runtime.serverUrl,
468468
token: this.runtime.getSetting("XAI_API_KEY") ?? this.runtime.token,
469469
model: this.runtime.getSetting("XAI_MODEL") ? this.runtime.getSetting("XAI_MODEL") : "gpt-4o-mini",
470-
temperature: 1.2,
470+
temperature: 0.7,
471471
frequency_penalty: 1.5,
472-
presence_penalty: 0.8,
472+
presence_penalty: 1.5,
473473
});
474474

475475
response.source = "discord";

Diff for: src/clients/twitter/base.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ export class ClientBase extends EventEmitter {
8888
lastCheckedTweetId: number | null = null;
8989
tweetCacheFilePath = "tweetcache/latest_checked_tweet_id.txt";
9090
imageDescriptionService: ImageDescriptionService;
91-
temperature: number = 1.3;
91+
temperature: number = 0.5;
9292
dryRun: boolean = false;
9393

9494
private tweetCache: Map<string, Tweet> = new Map();
@@ -240,7 +240,7 @@ export class ClientBase extends EventEmitter {
240240
const userId = await this.requestQueue.add(
241241
async () => {
242242
// wait 3 seconds before getting the user id
243-
await new Promise((resolve) => setTimeout(resolve, 3000));
243+
await new Promise((resolve) => setTimeout(resolve, 10000));
244244
try{
245245

246246
return await this.twitterClient.getUserIdByScreenName(

Diff for: src/core/defaultCharacter.ts

+661-563
Large diffs are not rendered by default.

Diff for: src/core/runtime.ts

+4
Original file line numberDiff line numberDiff line change
@@ -506,6 +506,10 @@ export class AgentRuntime implements IAgentRuntime {
506506
// if the model includes llama, set reptition_penalty to frequency_penalty
507507
if (model.includes("llama")) {
508508
(requestOptions.body as any).repetition_penalty = frequency_penalty;
509+
} else {
510+
(requestOptions.body as any).frequency_penalty = frequency_penalty;
511+
(requestOptions.body as any).presence_penalty = presence_penalty;
512+
// (requestOptions.body as any).logit_bias = logit_bias;
509513
}
510514

511515
// stringify the body

Diff for: src/providers/balances.ts

+102
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// TokenBalanceProvider.ts
2+
import { Connection, PublicKey } from "@solana/web3.js";
3+
import { getTokenBalances, getTokenPriceInSol } from "../services/tokenUtils";
4+
import fetch from "cross-fetch";
5+
6+
interface Item {
7+
name: string;
8+
symbol: string;
9+
decimals: number;
10+
balance: string;
11+
uiAmount: string;
12+
priceUSD: string;
13+
valueUSD: string;
14+
}
15+
interface walletPortfolio {
16+
totalUsd: string;
17+
items: Array<Item>;
18+
}
19+
interface price {
20+
usd: string;
21+
}
22+
interface Prices {
23+
solana: price;
24+
bitcoin: price;
25+
ethereum: price;
26+
27+
}
28+
const API_Key = ""
29+
export default class WalletProvider {
30+
private connection: Connection;
31+
private walletPublicKey: PublicKey;
32+
33+
constructor(connection: Connection, walletPublicKey: PublicKey) {
34+
this.connection = connection;
35+
this.walletPublicKey = walletPublicKey;
36+
}
37+
38+
async getFormattedTokenBalances(): Promise<string> {
39+
const tokenBalances = await getTokenBalances(this.connection, this.walletPublicKey);
40+
41+
let formattedBalances = "Token Balances:\n";
42+
let totalValueInSol = 0;
43+
44+
for (const [tokenName, balance] of Object.entries(tokenBalances)) {
45+
const tokenPrice = await getTokenPriceInSol(tokenName);
46+
const totalValue = balance * tokenPrice;
47+
totalValueInSol += totalValue;
48+
49+
formattedBalances += `${tokenName}: ${balance} (${totalValue} SOL)\n`;
50+
}
51+
52+
formattedBalances += `\nTotal Value: ${totalValueInSol} SOL`;
53+
54+
return formattedBalances;
55+
}
56+
57+
async fetchPortfolioValue(walletPublicKey:string): Promise<walletPortfolio> {
58+
try {
59+
const options = {
60+
method: 'GET',
61+
headers: {
62+
accept: 'application/json',
63+
'x-chain': 'solana',
64+
'X-API-KEY': API_Key
65+
}
66+
};
67+
const walletPortfolio = await fetch(`https://public-api.birdeye.so/v1/wallet/token_list?wallet=${walletPublicKey}`,
68+
options
69+
);
70+
const walletPortfolioJson = await walletPortfolio.json();
71+
const data = walletPortfolioJson.data;
72+
const totalUsd = data.totalUsd;
73+
const items = data.items;
74+
const walletPortfolioFormatted = {
75+
totalUsd,
76+
items
77+
};
78+
return walletPortfolioFormatted;
79+
} catch (error) {
80+
console.log(error);
81+
}
82+
}
83+
84+
async fetchPrices(): Promise<Prices> {
85+
const apiUrl = 'https://api.coingecko.com/api/v3/simple/price';
86+
const ids = 'solana,bitcoin,ethereum';
87+
const vsCurrencies = 'usd';
88+
89+
try {
90+
const response = await fetch(`${apiUrl}?ids=${ids}&vs_currencies=${vsCurrencies}`);
91+
92+
if (!response.ok) {
93+
throw new Error('Failed to fetch prices');
94+
}
95+
96+
const data = await response.json();
97+
return data;
98+
} catch (error) {
99+
console.log('Error fetching prices:', error);
100+
}
101+
}
102+
}

Diff for: src/providers/time.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ import { IAgentRuntime, Memory, Provider, State } from "../core/types.ts";
22

33
const time: Provider = {
44
get: async (_runtime: IAgentRuntime, _message: Memory, _state?: State) => {
5-
const currentTime = new Date().toLocaleTimeString("en-US");
6-
return "The current time is: " + currentTime;
5+
const currentDate = new Date();
6+
const currentTime = currentDate.toLocaleTimeString("en-US");
7+
const currentYear = currentDate.getFullYear();
8+
return `The current time is: ${currentTime}, ${currentYear}`;
79
},
810
};
911

Diff for: src/providers/wallet.ts

+96-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,66 @@
1-
// TokenBalanceProvider.ts
1+
import { getAccount, getAssociatedTokenAddress } from "@solana/spl-token";
22
import { Connection, PublicKey } from "@solana/web3.js";
3-
import { getTokenBalances, getTokenPriceInSol } from "./tokenUtils";
43
import fetch from "cross-fetch";
4+
import { IAgentRuntime, Memory, Provider, State } from "../core/types.ts";
5+
6+
export async function getTokenPriceInSol(tokenSymbol: string): Promise<number> {
7+
const response = await fetch(`https://price.jup.ag/v6/price?ids=${tokenSymbol}`);
8+
const data = await response.json();
9+
return data.data[tokenSymbol].price;
10+
}
11+
12+
async function getTokenBalance(
13+
connection: Connection,
14+
walletPublicKey: PublicKey,
15+
tokenMintAddress: PublicKey
16+
): Promise<number> {
17+
const tokenAccountAddress = await getAssociatedTokenAddress(tokenMintAddress, walletPublicKey);
18+
19+
try {
20+
const tokenAccount = await getAccount(connection, tokenAccountAddress);
21+
const tokenAmount = tokenAccount.amount as unknown as number;
22+
return tokenAmount;
23+
} catch (error) {
24+
console.error(`Error retrieving balance for token: ${tokenMintAddress.toBase58()}`, error);
25+
return 0;
26+
}
27+
}
28+
29+
async function getTokenBalances(
30+
connection: Connection,
31+
walletPublicKey: PublicKey
32+
): Promise<{ [tokenName: string]: number }> {
33+
const tokenBalances: { [tokenName: string]: number } = {};
34+
35+
// Add the token mint addresses you want to retrieve balances for
36+
const tokenMintAddresses = [
37+
new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"), // USDC
38+
new PublicKey("So11111111111111111111111111111111111111112"), // SOL
39+
// Add more token mint addresses as needed
40+
];
41+
42+
for (const mintAddress of tokenMintAddresses) {
43+
const tokenName = getTokenName(mintAddress);
44+
const balance = await getTokenBalance(connection, walletPublicKey, mintAddress);
45+
tokenBalances[tokenName] = balance;
46+
}
47+
48+
return tokenBalances;
49+
}
50+
51+
function getTokenName(mintAddress: PublicKey): string {
52+
// Implement a mapping of mint addresses to token names
53+
const tokenNameMap: { [mintAddress: string]: string } = {
54+
"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v": "USDC",
55+
"So11111111111111111111111111111111111111112": "SOL",
56+
// Add more token mint addresses and their corresponding names
57+
};
58+
59+
return tokenNameMap[mintAddress.toBase58()] || "Unknown Token";
60+
}
61+
62+
export { getTokenBalance, getTokenBalances };
63+
564

665
interface Item {
766
name: string;
@@ -99,4 +158,38 @@ export class WalletProvider {
99158
console.log('Error fetching prices:', error);
100159
}
101160
}
102-
}
161+
}
162+
163+
164+
const walletProvider: Provider = {
165+
get: async (runtime: IAgentRuntime, _message: Memory, _state?: State) => {
166+
try {
167+
const walletPublicKey = new PublicKey(runtime.getSetting("WALLET_PUBLIC_KEY"));
168+
const connection = new Connection(runtime.getSetting("RPC_ENDPOINT"));
169+
170+
const provider = new WalletProvider(connection, walletPublicKey);
171+
const portfolio = await provider.fetchPortfolioValue(walletPublicKey.toBase58());
172+
const prices = await provider.fetchPrices();
173+
174+
let formattedBalances = `Wallet Address: ${walletPublicKey.toBase58()}\n\n`;
175+
formattedBalances += `Total Portfolio Value: $${portfolio.totalUsd}\n\n`;
176+
formattedBalances += "Token Balances:\n";
177+
178+
for (const item of portfolio.items) {
179+
formattedBalances += `${item.name} (${item.symbol}): ${item.uiAmount} ($${item.valueUSD})\n`;
180+
}
181+
182+
formattedBalances += "\nCurrent Prices:\n";
183+
formattedBalances += `Solana: $${prices.solana.usd}\n`;
184+
formattedBalances += `Bitcoin: $${prices.bitcoin.usd}\n`;
185+
formattedBalances += `Ethereum: $${prices.ethereum.usd}\n`;
186+
187+
return formattedBalances;
188+
} catch (error) {
189+
console.error("Error fetching wallet information:", error);
190+
return "Failed to fetch wallet information.";
191+
}
192+
},
193+
};
194+
195+
export default walletProvider;

Diff for: src/services/tokenUtils.ts

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
// tokenUtils.ts
2-
import { Connection, PublicKey, ParsedAccountData, TokenAmount } from "@solana/web3.js";
31
import { getAccount, getAssociatedTokenAddress } from "@solana/spl-token";
2+
import { Connection, PublicKey } from "@solana/web3.js";
43

54
export async function getTokenPriceInSol(tokenSymbol: string): Promise<number> {
65
const response = await fetch(`https://price.jup.ag/v6/price?ids=${tokenSymbol}`);
@@ -58,4 +57,4 @@ function getTokenName(mintAddress: PublicKey): string {
5857
return tokenNameMap[mintAddress.toBase58()] || "Unknown Token";
5958
}
6059

61-
export { getTokenBalance, getTokenBalances };
60+
export { getTokenBalance, getTokenBalances };

0 commit comments

Comments
 (0)