forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwallet.ts
249 lines (216 loc) · 7.93 KB
/
wallet.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
import {
IAgentRuntime,
Memory,
Provider,
State,
elizaLogger,
} from "@elizaos/core";
import { KeyPair, keyStores, connect, Account, utils } from "near-api-js";
import BigNumber from "bignumber.js";
import { KeyPairString } from "near-api-js/lib/utils";
import NodeCache from "node-cache";
const PROVIDER_CONFIG = {
networkId: process.env.NEAR_NETWORK || "testnet",
nodeUrl:
process.env.RPC_URL ||
`https://rpc.${process.env.NEAR_NETWORK || "testnet"}.near.org`,
walletUrl: `https://${process.env.NEAR_NETWORK || "testnet"}.mynearwallet.com/`,
helperUrl: `https://helper.${process.env.NEAR_NETWORK || "testnet"}.near.org`,
explorerUrl: `https://${process.env.NEAR_NETWORK || "testnet"}.nearblocks.io`,
MAX_RETRIES: 3,
RETRY_DELAY: 2000,
SLIPPAGE: process.env.SLIPPAGE ? parseInt(process.env.SLIPPAGE) : 1,
};
export interface NearToken {
name: string;
symbol: string;
decimals: number;
balance: string;
uiAmount: string;
priceUsd: string;
valueUsd: string;
valueNear?: string;
}
interface WalletPortfolio {
totalUsd: string;
totalNear?: string;
tokens: Array<NearToken>;
}
export class WalletProvider implements Provider {
private cache: NodeCache;
private account: Account | null = null;
private keyStore: keyStores.InMemoryKeyStore;
constructor(private accountId: string) {
this.cache = new NodeCache({ stdTTL: 300 }); // Cache TTL set to 5 minutes
this.keyStore = new keyStores.InMemoryKeyStore();
}
async get(
runtime: IAgentRuntime,
_message: Memory,
_state?: State
): Promise<string | null> {
try {
return await this.getFormattedPortfolio(runtime);
} catch (error) {
elizaLogger.error("Error in wallet provider:", error);
return null;
}
}
public async connect(runtime: IAgentRuntime) {
if (this.account) return this.account;
const secretKey = runtime.getSetting("NEAR_WALLET_SECRET_KEY");
const publicKey = runtime.getSetting("NEAR_WALLET_PUBLIC_KEY");
if (!secretKey || !publicKey) {
throw new Error("NEAR wallet credentials not configured");
}
// Create KeyPair from secret key
const keyPair = KeyPair.fromString(secretKey as KeyPairString);
// Set the key in the keystore
await this.keyStore.setKey(
PROVIDER_CONFIG.networkId,
this.accountId,
keyPair
);
const nearConnection = await connect({
networkId: PROVIDER_CONFIG.networkId,
keyStore: this.keyStore,
nodeUrl: PROVIDER_CONFIG.nodeUrl,
walletUrl: PROVIDER_CONFIG.walletUrl,
helperUrl: PROVIDER_CONFIG.helperUrl,
});
this.account = await nearConnection.account(this.accountId);
return this.account;
}
private async fetchWithRetry(
url: string,
options: RequestInit = {}
): Promise<any> {
let lastError: Error;
for (let i = 0; i < PROVIDER_CONFIG.MAX_RETRIES; i++) {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
elizaLogger.error(`Attempt ${i + 1} failed:`, error);
lastError = error as Error;
if (i < PROVIDER_CONFIG.MAX_RETRIES - 1) {
await new Promise((resolve) =>
setTimeout(
resolve,
PROVIDER_CONFIG.RETRY_DELAY * Math.pow(2, i)
)
);
}
}
}
throw lastError!;
}
async fetchPortfolioValue(
runtime: IAgentRuntime
): Promise<WalletPortfolio> {
try {
const cacheKey = `portfolio-${this.accountId}`;
const cachedValue = this.cache.get<WalletPortfolio>(cacheKey);
if (cachedValue) {
elizaLogger.log("Cache hit for fetchPortfolioValue");
return cachedValue;
}
const account = await this.connect(runtime);
const balance = await account.getAccountBalance();
// Convert yoctoNEAR to NEAR
const nearBalance = utils.format.formatNearAmount(
balance.available
);
// Fetch NEAR price in USD
const nearPrice = await this.fetchNearPrice();
const valueUsd = new BigNumber(nearBalance).times(nearPrice);
const portfolio: WalletPortfolio = {
totalUsd: valueUsd.toString(),
totalNear: nearBalance,
tokens: [
{
name: "NEAR Protocol",
symbol: "NEAR",
decimals: 24,
balance: balance.available,
uiAmount: nearBalance,
priceUsd: nearPrice.toString(),
valueUsd: valueUsd.toString(),
},
],
};
this.cache.set(cacheKey, portfolio);
return portfolio;
} catch (error) {
elizaLogger.error("Error fetching portfolio:", error);
throw error;
}
}
private async fetchNearPrice(): Promise<number> {
const cacheKey = "near-price";
const cachedPrice = this.cache.get<number>(cacheKey);
if (cachedPrice) {
return cachedPrice;
}
try {
const response = await this.fetchWithRetry(
"https://api.coingecko.com/api/v3/simple/price?ids=near&vs_currencies=usd"
);
const price = response.near.usd;
this.cache.set(cacheKey, price);
return price;
} catch (error) {
elizaLogger.error("Error fetching NEAR price:", error);
return 0;
}
}
formatPortfolio(
runtime: IAgentRuntime,
portfolio: WalletPortfolio
): string {
let output = `${runtime.character.system}\n`;
output += `Account ID: ${this.accountId}\n\n`;
const totalUsdFormatted = new BigNumber(portfolio.totalUsd).toFixed(2);
const totalNearFormatted = portfolio.totalNear;
output += `Total Value: $${totalUsdFormatted} (${totalNearFormatted} NEAR)\n\n`;
output += "Token Balances:\n";
for (const token of portfolio.tokens) {
output += `${token.name} (${token.symbol}): ${token.uiAmount} ($${new BigNumber(token.valueUsd).toFixed(2)})\n`;
}
output += "\nMarket Prices:\n";
output += `NEAR: $${new BigNumber(portfolio.tokens[0].priceUsd).toFixed(2)}\n`;
return output;
}
async getFormattedPortfolio(runtime: IAgentRuntime): Promise<string> {
try {
const portfolio = await this.fetchPortfolioValue(runtime);
return this.formatPortfolio(runtime, portfolio);
} catch (error) {
elizaLogger.error("Error generating portfolio report:", error);
return "Unable to fetch wallet information. Please try again later.";
}
}
}
const walletProvider: Provider = {
get: async (
runtime: IAgentRuntime,
_message: Memory,
_state?: State
): Promise<string | null> => {
try {
const accountId = runtime.getSetting("NEAR_ADDRESS");
if (!accountId) {
throw new Error("NEAR_ADDRESS not configured");
}
const provider = new WalletProvider(accountId);
return await provider.getFormattedPortfolio(runtime);
} catch (error) {
elizaLogger.error("Error in wallet provider:", error);
return null;
}
},
};
export { walletProvider };