1
1
import { IAgentRuntime , Memory , Provider , State } from "@ai16z/eliza" ;
2
2
import { Connection , PublicKey } from "@solana/web3.js" ;
3
3
import BigNumber from "bignumber.js" ;
4
-
4
+ import NodeCache from "node-cache" ;
5
5
// Provider configuration
6
6
const PROVIDER_CONFIG = {
7
7
BIRDEYE_API : "https://public-api.birdeye.so" ,
@@ -49,10 +49,14 @@ interface Prices {
49
49
}
50
50
51
51
export class WalletProvider {
52
+ private cache : NodeCache ;
53
+
52
54
constructor (
53
55
private connection : Connection ,
54
56
private walletPublicKey : PublicKey
55
- ) { }
57
+ ) {
58
+ this . cache = new NodeCache ( { stdTTL : 300 } ) ; // Cache TTL set to 5 minutes
59
+ }
56
60
57
61
private async fetchWithRetry (
58
62
runtime ,
@@ -103,6 +107,15 @@ export class WalletProvider {
103
107
104
108
async fetchPortfolioValue ( runtime ) : Promise < WalletPortfolio > {
105
109
try {
110
+ const cacheKey = `portfolio-${ this . walletPublicKey . toBase58 ( ) } ` ;
111
+ const cachedValue = this . cache . get < WalletPortfolio > ( cacheKey ) ;
112
+
113
+ if ( cachedValue ) {
114
+ console . log ( "Cache hit for fetchPortfolioValue" ) ;
115
+ return cachedValue ;
116
+ }
117
+ console . log ( "Cache miss for fetchPortfolioValue" ) ;
118
+
106
119
const walletData = await this . fetchWithRetry (
107
120
runtime ,
108
121
`${ PROVIDER_CONFIG . BIRDEYE_API } /v1/wallet/token_list?wallet=${ this . walletPublicKey . toBase58 ( ) } `
@@ -130,8 +143,7 @@ export class WalletProvider {
130
143
} ) ) ;
131
144
132
145
const totalSol = totalUsd . div ( solPriceInUSD ) ;
133
-
134
- return {
146
+ const portfolio = {
135
147
totalUsd : totalUsd . toString ( ) ,
136
148
totalSol : totalSol . toFixed ( 6 ) ,
137
149
items : items . sort ( ( a , b ) =>
@@ -140,6 +152,8 @@ export class WalletProvider {
140
152
. toNumber ( )
141
153
) ,
142
154
} ;
155
+ this . cache . set ( cacheKey , portfolio ) ;
156
+ return portfolio ;
143
157
} catch ( error ) {
144
158
console . error ( "Error fetching portfolio:" , error ) ;
145
159
throw error ;
@@ -148,6 +162,15 @@ export class WalletProvider {
148
162
149
163
async fetchPrices ( runtime ) : Promise < Prices > {
150
164
try {
165
+ const cacheKey = "prices" ;
166
+ const cachedValue = this . cache . get < Prices > ( cacheKey ) ;
167
+
168
+ if ( cachedValue ) {
169
+ console . log ( "Cache hit for fetchPrices" ) ;
170
+ return cachedValue ;
171
+ }
172
+ console . log ( "Cache miss for fetchPrices" ) ;
173
+
151
174
const { SOL , BTC , ETH } = PROVIDER_CONFIG . TOKEN_ADDRESSES ;
152
175
const tokens = [ SOL , BTC , ETH ] ;
153
176
const prices : Prices = {
@@ -181,6 +204,7 @@ export class WalletProvider {
181
204
}
182
205
}
183
206
207
+ this . cache . set ( cacheKey , prices ) ;
184
208
return prices ;
185
209
} catch ( error ) {
186
210
console . error ( "Error fetching prices:" , error ) ;
0 commit comments