Skip to content

Commit 70aa846

Browse files
committed
update pools methods
1 parent 9500950 commit 70aa846

File tree

2 files changed

+233
-91
lines changed

2 files changed

+233
-91
lines changed

packages/sui-agent/src/tools/aftermath/PoolTool.ts

Lines changed: 70 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -7,21 +7,30 @@ const af = new Aftermath('MAINNET');
77
const pools = af.Pools();
88

99
/**
10-
* Processes raw pool data into standardized format
11-
* @param pool - Raw pool data from Aftermath
12-
* @param poolId - Unique identifier for the pool
13-
* @returns Standardized pool information
10+
* Processes raw pool data into standardized format.
11+
* @param poolInstance - A Pool instance returned from Aftermath containing the pool data.
12+
* @param poolId - Unique identifier for the pool.
13+
* @returns Standardized pool information.
1414
*/
15-
async function processPool(pool: Pool, poolId: string): Promise<PoolInfo> {
15+
async function processPool(
16+
poolInstance: Pool,
17+
poolId: string,
18+
): Promise<PoolInfo> {
1619
try {
20+
// Fetch pool metrics using the poolId
1721
const metrics = await pools.getPoolsStats({ poolIds: [poolId] });
1822
const poolMetrics = metrics[0];
1923

20-
// Extract token information
21-
const tokens = Object.keys(pool.pool.coins || {});
24+
// Extract tokens (coin types) from the pool object.
25+
// Here we assume that the underlying pool data is stored in the `pool` property.
26+
const poolData = poolInstance.pool;
27+
const tokens = Object.keys(poolData.coins || {});
28+
29+
// For each token, extract its normalized balance.
2230
const reserves = tokens.map((token) => {
23-
const coinData = pool.pool.coins[token];
24-
return BigInt(coinData.normalizedBalance || 0);
31+
// Use optional chaining to guard against missing data.
32+
const coinData = poolData.coins[token];
33+
return BigInt(coinData?.normalizedBalance || 0);
2534
});
2635

2736
return {
@@ -30,7 +39,7 @@ async function processPool(pool: Pool, poolId: string): Promise<PoolInfo> {
3039
reserves,
3140
fee: poolMetrics?.fees || 0,
3241
tvl: poolMetrics?.tvl || 0,
33-
apr: (poolMetrics?.apr || 0) * 100,
42+
apr: (poolMetrics?.apr || 0) * 100, // Convert to percentage if needed
3443
};
3544
} catch (error: unknown) {
3645
console.error(`Error processing pool ${poolId}:`, error);
@@ -46,25 +55,25 @@ async function processPool(pool: Pool, poolId: string): Promise<PoolInfo> {
4655
}
4756

4857
/**
49-
* Gets detailed information about a specific pool
50-
* @param poolId - Unique identifier for the pool
51-
* @returns JSON string containing pool details or error information
58+
* Gets detailed information about a specific pool.
59+
* @param poolId - Unique identifier for the pool.
60+
* @returns JSON string containing pool details or error information.
5261
*/
5362
export async function getPool(
5463
...args: (string | number | bigint | boolean)[]
5564
): Promise<string> {
5665
const poolId = args[0] as string;
5766
try {
58-
const pool = await pools.getPool({ objectId: poolId });
59-
if (!pool) {
67+
const poolInstance = await pools.getPool({ objectId: poolId });
68+
if (!poolInstance) {
6069
return JSON.stringify([
6170
handleError('Pool not found', {
6271
reasoning: 'Pool not found with the specified ID.',
6372
query: `Attempted to fetch pool with ID: ${poolId}`,
6473
}),
6574
]);
6675
}
67-
const processedPool = await processPool(pool, poolId);
76+
const processedPool = await processPool(poolInstance, poolId);
6877
return JSON.stringify([
6978
{
7079
reasoning:
@@ -86,19 +95,21 @@ export async function getPool(
8695
}
8796

8897
/**
89-
* Retrieves information about all available pools
90-
* @returns JSON string containing all pool information
98+
* Retrieves information about all available pools.
99+
* @returns JSON string containing all pool information.
91100
*/
92101
export async function getAllPools(): Promise<string> {
93102
try {
94103
const allPools = await pools.getAllPools();
95104
const processedPools = await Promise.all(
96-
allPools.map(async (pool) => {
97-
if (!pool.pool?.objectId) return null;
98-
return processPool(pool, pool.pool.objectId);
105+
allPools.map(async (poolInstance) => {
106+
// Ensure the pool instance has an objectId defined.
107+
if (!poolInstance.pool?.objectId) return null;
108+
return processPool(poolInstance, poolInstance.pool.objectId);
99109
}),
100110
);
101111

112+
// Filter out any null or empty pools.
102113
const validPools = processedPools.filter(
103114
(pool): pool is PoolInfo => pool !== null && pool.tokens.length > 0,
104115
);
@@ -124,19 +135,19 @@ export async function getAllPools(): Promise<string> {
124135
}
125136

126137
/**
127-
* Gets deposit or withdrawal events for a specific pool
128-
* @param poolId - Unique identifier for the pool
129-
* @param eventType - Type of events to fetch ("deposit" or "withdraw")
130-
* @param limit - Maximum number of events to return
131-
* @returns JSON string containing event information
138+
* Gets deposit or withdrawal events for a specific pool.
139+
* @param poolId - Unique identifier for the pool.
140+
* @param eventType - Type of events to fetch ("deposit" or "withdraw").
141+
* @param limit - Maximum number of events to return.
142+
* @returns JSON string containing event information.
132143
*/
133144
export async function getPoolEvents(
134145
...args: (string | number | bigint | boolean)[]
135146
): Promise<string> {
136147
const [poolId, eventType, limit] = args as [string, string, number];
137148
try {
138-
const pool = await pools.getPool({ objectId: poolId });
139-
if (!pool) {
149+
const poolInstance = await pools.getPool({ objectId: poolId });
150+
if (!poolInstance) {
140151
return JSON.stringify([
141152
handleError('Pool not found', {
142153
reasoning: 'Pool not found with the specified ID.',
@@ -145,10 +156,11 @@ export async function getPoolEvents(
145156
]);
146157
}
147158

159+
// Depending on the event type, fetch the appropriate events.
148160
const eventData =
149161
eventType === 'deposit'
150-
? await pool.getDepositEvents({ limit })
151-
: await pool.getWithdrawEvents({ limit });
162+
? await poolInstance.getDepositEvents({ limit })
163+
: await poolInstance.getWithdrawEvents({ limit });
152164

153165
return JSON.stringify([
154166
{
@@ -170,31 +182,31 @@ export async function getPoolEvents(
170182
}
171183

172184
/**
173-
* Gets ranked pools by specified metric
174-
* @param metric - Metric to rank by (apr, tvl, fees, volume)
175-
* @param limit - Maximum number of pools to return
176-
* @param order - Sort order (ascending or descending)
177-
* @returns JSON string containing ranked pool information
185+
* Gets ranked pools by specified metric.
186+
* @param metric - Metric to rank by (apr, tvl, fees, volume).
187+
* @param limit - Maximum number of pools to return.
188+
* @param order - Sort order (ascending or descending).
189+
* @returns JSON string containing ranked pool information.
178190
*/
179191
export async function getRankedPools(
180192
...args: (string | number | bigint | boolean)[]
181193
): Promise<string> {
182194
const [metric, limit, order] = args as [string, number, string];
183195
try {
184-
// Fetch and process all pools
196+
// Fetch and process all pools.
185197
const allPools = await pools.getAllPools();
186198
const processedPools = await Promise.all(
187-
allPools.map(async (pool) => {
188-
if (!pool.pool?.objectId) return null;
189-
return processPool(pool, pool.pool.objectId);
199+
allPools.map(async (poolInstance) => {
200+
if (!poolInstance.pool?.objectId) return null;
201+
return processPool(poolInstance, poolInstance.pool.objectId);
190202
}),
191203
);
192204

193205
const validPools = processedPools.filter(
194206
(pool): pool is PoolInfo => pool !== null && pool.tokens.length > 0,
195207
);
196208

197-
// Sort pools based on the specified metric
209+
// Sort pools based on the specified metric.
198210
const sortedPools = validPools.sort((a, b) => {
199211
let valueA: number, valueB: number;
200212

@@ -223,10 +235,10 @@ export async function getRankedPools(
223235
return order === 'desc' ? valueB - valueA : valueA - valueB;
224236
});
225237

226-
// Take only the requested number of pools
238+
// Take only the requested number of pools.
227239
const topPools = sortedPools.slice(0, limit);
228240

229-
// Format the response with ranking information
241+
// Format the response with ranking information.
230242
const rankedPools = topPools.map((pool, index) => ({
231243
rank: index + 1,
232244
...pool,
@@ -266,38 +278,38 @@ export async function getRankedPools(
266278
}
267279

268280
/**
269-
* Gets pools filtered by specific criteria
270-
* @param minTvl - Minimum Total Value Locked requirement
271-
* @param minApr - Minimum Annual Percentage Rate requirement
272-
* @param tokens - Array of token symbols that must be in the pool
273-
* @returns JSON string containing filtered pool information
281+
* Gets pools filtered by specific criteria.
282+
* @param minTvl - Minimum Total Value Locked requirement.
283+
* @param minApr - Minimum Annual Percentage Rate requirement.
284+
* @param tokens - Array of token symbols that must be in the pool.
285+
* @returns JSON string containing filtered pool information.
274286
*/
275287
export async function getFilteredPools(
276288
...args: (string | number | bigint | boolean)[]
277289
): Promise<string> {
278290
const [minTvl, minApr, tokens] = args as [number, number, string[]];
279291
try {
280-
// Fetch and process all pools
292+
// Fetch and process all pools.
281293
const allPools = await pools.getAllPools();
282294
const processedPools = await Promise.all(
283-
allPools.map(async (pool) => {
284-
if (!pool.pool?.objectId) return null;
285-
return processPool(pool, pool.pool.objectId);
295+
allPools.map(async (poolInstance) => {
296+
if (!poolInstance.pool?.objectId) return null;
297+
return processPool(poolInstance, poolInstance.pool.objectId);
286298
}),
287299
);
288300

289-
// Apply filters
301+
// Apply filters.
290302
const filteredPools = processedPools.filter((pool): pool is PoolInfo => {
291303
if (!pool || pool.tokens.length === 0) return false;
292304

293-
// Apply TVL filter
305+
// Apply TVL filter.
294306
if (minTvl && pool.tvl < minTvl) return false;
295307

296-
// Apply APR filter
308+
// Apply APR filter.
297309
if (minApr && pool.apr < minApr) return false;
298310

299-
// Apply token filter
300-
if (tokens) {
311+
// Apply token filter.
312+
if (tokens && tokens.length > 0) {
301313
const poolTokens = pool.tokens.map((t) => t.toLowerCase());
302314
const hasRequiredTokens = tokens.every((token) =>
303315
poolTokens.some((poolToken) =>
@@ -310,7 +322,7 @@ export async function getFilteredPools(
310322
return true;
311323
});
312324

313-
// Format the response with detailed metrics
325+
// Format the response with detailed metrics.
314326
const formattedPools = filteredPools.map((pool) => ({
315327
...pool,
316328
metrics: {
@@ -341,7 +353,7 @@ export async function getFilteredPools(
341353
status: 'success',
342354
query: `Retrieved pools with${minTvl ? ` min TVL $${minTvl}` : ''}${
343355
minApr ? ` min APR ${minApr}%` : ''
344-
}${tokens ? ` containing tokens ${tokens.join(', ')}` : ''}`,
356+
}${tokens && tokens.length > 0 ? ` containing tokens ${tokens.join(', ')}` : ''}`,
345357
errors: [],
346358
},
347359
]);

0 commit comments

Comments
 (0)