Skip to content

Commit

Permalink
allSettled
Browse files Browse the repository at this point in the history
  • Loading branch information
jongan69 committed Jan 13, 2025
1 parent 42f0ffc commit 724fb00
Show file tree
Hide file tree
Showing 8 changed files with 157 additions and 105 deletions.
11 changes: 9 additions & 2 deletions src/pages/api/analyze/generate-thesis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
// console.log("Tokens:", tokens);

// Process tokens and fetch missing information
const processedTopTokens = (await Promise.all(
const processedTopTokensSettled = await Promise.allSettled(
(tokens.summary?.slice(0, 10) || []).map(async (token: any) => {
let name = token.name;
let symbol = token.symbol;
Expand All @@ -43,7 +43,14 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}
return null;
})
)).filter((token): token is NonNullable<typeof token> => token !== null);
)

const processedTopTokens = processedTopTokensSettled
.filter((result): result is PromiseFulfilledResult<typeof tokens> =>
result.status === 'fulfilled' && result.value !== null
)
.map(result => result.value);


const summarizedTokens = {
totalTokens: tokens.totalTokens,
Expand Down
29 changes: 16 additions & 13 deletions src/pages/api/analyze/trends.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,23 +28,26 @@ export default async function handler(
}

try {
// Process keywords and resolve addresses
const processedKeywords = await Promise.all(
keywords.map(async (kw: string) => {
if (isSolanaAddress(kw)) {
const tokenInfo = await getTokenInfo(kw);
return tokenInfo?.symbol || kw;
}
return kw;
})
);
// Process keywords and resolve addresses using Promise.allSettled
const keywordPromises = keywords.map(async (kw: string) => {
if (isSolanaAddress(kw)) {
const tokenInfo = await getTokenInfo(kw);
return tokenInfo?.symbol || kw;
}
return kw;
});

const settledResults = await Promise.allSettled(keywordPromises);
const processedKeywords = settledResults
.filter((result): result is PromiseFulfilledResult<string> =>
result.status === 'fulfilled')
.map(result => result.value);

// Clean and filter keywords
const cleanedKeywords = processedKeywords
.filter((kw: string) => kw.length < 30) // Filter out long addresses
.map((kw: string) => kw.replace(/[^a-zA-Z0-9]/g, '')) // Remove special characters
.filter((kw: string) => kw.length < 30)
.map((kw: string) => kw.replace(/[^a-zA-Z0-9]/g, ''))
.filter((kw: string) => {
// Keep only uppercase alphanumeric strings (tickers)
const isUpperCase = kw === kw.toUpperCase();
const hasLetters = /[A-Z]/.test(kw);
return isUpperCase && hasLetters && kw.length >= 2;
Expand Down
134 changes: 69 additions & 65 deletions src/pages/api/historical/getTradeData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,77 +54,81 @@ export default async function handler(
const transactions = await response.json();
console.log(`Found ${transactions.length} total transactions`);

const tradeHistory = [];

// Process transactions to extract trade data
for (const txn of transactions) {
try {
// Focus on SWAP transactions
if (txn.type !== 'SWAP' || !txn.tokenTransfers?.length) continue;

// Get the input and output transfers
const transfers = txn.tokenTransfers.filter((transfer: TokenTransfer) =>
transfer.fromUserAccount === address || transfer.toUserAccount === address
);

if (transfers.length < 2) continue;

// Find the "out" and "in" transfers
const tokenOut = transfers.find((t: TokenTransfer) => t.fromUserAccount === address);
const tokenIn = transfers.find((t: TokenTransfer) => t.toUserAccount === address);

if (!tokenIn || !tokenOut) continue;

// Get token information
const [tokenInInfo, tokenOutInfo] = await Promise.all([
getTokenInfo(tokenIn.mint),
getTokenInfo(tokenOut.mint)
]);

// Skip if we couldn't get token info
if (!tokenInInfo || !tokenOutInfo) continue;

const trade = {
timestamp: txn.timestamp,
signature: txn.signature,
tokenIn: {
mint: tokenIn.mint,
amount: tokenIn.tokenAmount,
decimals: tokenInInfo.decimals || 9,
symbol: tokenInInfo.symbol || 'Unknown',
image: tokenInInfo.image || null,
website: tokenInInfo.website || null,
price: tokenInInfo.price,
priceNative: tokenInInfo.priceNative || 0
},
tokenOut: {
mint: tokenOut.mint,
amount: tokenOut.tokenAmount,
decimals: tokenOutInfo.decimals || 9,
symbol: tokenOutInfo.symbol || 'Unknown',
image: tokenOutInfo.image || null,
website: tokenOutInfo.website || null,
price: tokenOutInfo.price,
priceNative: tokenOutInfo.priceNative || 0
},
fee: txn.fee || 0,
success: true,
source: txn.source || 'Unknown DEX'
};

tradeHistory.push(trade);
// Create array of promises for processing each transaction
const tradePromises = transactions.map(async (txn: any) => {
// Skip non-SWAP transactions early
if (txn.type !== 'SWAP' || !txn.tokenTransfers?.length) return null;

// Get the input and output transfers
const transfers = txn.tokenTransfers.filter((transfer: TokenTransfer) =>
transfer.fromUserAccount === address || transfer.toUserAccount === address
);

if (transfers.length < 2) return null;

// Find the "out" and "in" transfers
const tokenOut = transfers.find((t: TokenTransfer) => t.fromUserAccount === address);
const tokenIn = transfers.find((t: TokenTransfer) => t.toUserAccount === address);

if (!tokenIn || !tokenOut) return null;

// Get token information
const [tokenInInfo, tokenOutInfo] = await Promise.allSettled([
getTokenInfo(tokenIn.mint),
getTokenInfo(tokenOut.mint)
]);

// Skip if either promise was rejected or returned null
if (tokenInInfo.status !== 'fulfilled' || tokenOutInfo.status !== 'fulfilled' ||
!tokenInInfo.value || !tokenOutInfo.value) return null;

return {
timestamp: txn.timestamp,
signature: txn.signature,
tokenIn: {
mint: tokenIn.mint,
amount: tokenIn.tokenAmount,
decimals: tokenInInfo.value.decimals || 9,
symbol: tokenInInfo.value.symbol || 'Unknown',
image: tokenInInfo.value.image || null,
website: tokenInInfo.value.website || null,
price: tokenInInfo.value.price,
priceNative: tokenInInfo.value.priceNative || 0
},
tokenOut: {
mint: tokenOut.mint,
amount: tokenOut.tokenAmount,
decimals: tokenOutInfo.value.decimals || 9,
symbol: tokenOutInfo.value.symbol || 'Unknown',
image: tokenOutInfo.value.image || null,
website: tokenOutInfo.value.website || null,
price: tokenOutInfo.value.price,
priceNative: tokenOutInfo.value.priceNative || 0
},
fee: txn.fee || 0,
success: true,
source: txn.source || 'Unknown DEX'
};
});

// Process all promises in parallel
const results = await Promise.allSettled(tradePromises);

// Filter successful results and remove nulls
const tradeHistory = results
.filter((result): result is PromiseFulfilledResult<any> =>
result.status === 'fulfilled' && result.value !== null
)
.map(result => {
const trade = result.value;
console.log('Processed trade:', {
tokenIn: trade.tokenIn.symbol,
tokenOut: trade.tokenOut.symbol,
amountIn: trade.tokenIn.amount,
amountOut: trade.tokenOut.amount
});

} catch (err) {
console.error('Error processing transaction:', err);
continue;
}
}
return trade;
});

console.log(`Successfully processed ${tradeHistory.length} trades`);

Expand Down
6 changes: 5 additions & 1 deletion src/pages/api/port/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export default async function handler(
console.log('Raw portfolios from DB:', portfolios);

// Fetch performance data for each portfolio
const portfoliosWithPerformance = await Promise.all(
const performanceResults = await Promise.allSettled(
portfolios.map(async (portfolio) => {
const performance = await getPortfolioPerformance(portfolio.portfolioId);
console.log(`Performance for portfolio ${portfolio.portfolioId}:`, performance);
Expand All @@ -72,6 +72,10 @@ export default async function handler(
})
);

const portfoliosWithPerformance = performanceResults
.filter((result): result is PromiseFulfilledResult<any> => result.status === 'fulfilled')
.map(result => result.value);

// Get top performers for each time frame
const getTopPerformers = (timeFrame: '30m' | '1h' | '6h' | '24h') => {
return portfoliosWithPerformance
Expand Down
9 changes: 8 additions & 1 deletion src/pages/api/premium/twitterTrending.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default async function handler(
await client.initialize();
}
// Fetch tweets from all tracked accounts
const allTweets = await Promise.all(
const results = await Promise.allSettled(
TRACKED_ACCOUNTS.map(async (username) => {
try {
const userTweets = await client.getUserTweets(username);
Expand All @@ -58,6 +58,13 @@ export default async function handler(
})
);

// Filter out rejected promises and get fulfilled values
const allTweets = results
.filter((result): result is PromiseFulfilledResult<{username: string, tweets: Tweet[]}> =>
result.status === 'fulfilled'
)
.map(result => result.value);

// Filter out empty results and sort by date
const flattenedTweets = allTweets
.flatMap(({ username, tweets }) =>
Expand Down
13 changes: 11 additions & 2 deletions src/utils/fetchSP500.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const fetchSP500MarketCap = async (): Promise<number> => {
// Calculate total market cap
let totalMarketCap = 0;

await Promise.all(
const results = await Promise.allSettled(
tickers.map(async (ticker) => {
try {
// Fetch market cap from Yahoo Finance
Expand All @@ -36,10 +36,12 @@ export const fetchSP500MarketCap = async (): Promise<number> => {
await collection.updateOne(
{ Symbol: ticker },
{ $set: { marketCap: quote.marketCap, lastUpdated: new Date() } },
{ upsert: true } // Insert if it doesn't exist
{ upsert: true }
);
return { status: 'success', ticker, marketCap: quote.marketCap };
} else {
console.warn(`Market cap missing for ${ticker}, skipping...`);
return { status: 'missing', ticker };
}
} catch (error: any) {
console.error(`Error fetching data for ${ticker}:`, error.message);
Expand All @@ -50,13 +52,20 @@ export const fetchSP500MarketCap = async (): Promise<number> => {
if (fallbackCompany?.marketCap) {
console.warn(`Using last saved market cap for ${ticker}: ${fallbackCompany.marketCap}`);
totalMarketCap += fallbackCompany.marketCap;
return { status: 'fallback', ticker, marketCap: fallbackCompany.marketCap };
} else {
console.warn(`No saved market cap found for ${ticker}, skipping...`);
return { status: 'error', ticker, error: error.message };
}
}
})
);

// Log summary of results
const succeeded = results.filter(r => r.status === 'fulfilled').length;
const failed = results.filter(r => r.status === 'rejected').length;
console.log(`Processed ${succeeded} successful and ${failed} failed requests`);

return totalMarketCap;
} catch (error: any) {
console.error('Error fetching data from MongoDB or Yahoo Finance:', error.message);
Expand Down
27 changes: 21 additions & 6 deletions src/utils/getSimilarCoins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,18 @@ interface TokenData {

export const getSimilarCoins = async (userTokens: Token[]): Promise<TokenComparison[]> => {
try {
// Fetch data from all three endpoints
const [latestTokenProfiles, latestTokenBoosts, topTokenBoosts] = await Promise.all([
// First change - initial API calls
const responses = await Promise.allSettled([
fetch('https://api.dexscreener.com/token-profiles/latest/v1').then(r => r.json()),
fetch('https://api.dexscreener.com/token-boosts/latest/v1').then(r => r.json()),
fetch('https://api.dexscreener.com/token-boosts/top/v1').then(r => r.json())
]);

// Extract values from fulfilled promises, use empty arrays for rejected ones
const [latestTokenProfiles, latestTokenBoosts, topTokenBoosts] = responses.map(result =>
result.status === 'fulfilled' ? result.value : []
);

console.log("API Responses:", {
profiles: latestTokenProfiles,
boosts: latestTokenBoosts,
Expand All @@ -46,10 +51,14 @@ export const getSimilarCoins = async (userTokens: Token[]): Promise<TokenCompari

const seen = new Set();
// First get token info for all tokens
const tokenInfos = await Promise.all(
const tokenInfoResults = await Promise.allSettled(
tokens.map(token => getTokenInfo(token.tokenAddress))
);

const tokenInfos = tokenInfoResults.map(result =>
result.status === 'fulfilled' ? result.value : null
);

const filteredTokens = tokens.filter((token, index) => {
if (!token || typeof token !== 'object') return false;
const symbol = tokenInfos[index]?.symbol;
Expand Down Expand Up @@ -121,12 +130,18 @@ export const getSimilarCoins = async (userTokens: Token[]): Promise<TokenCompari
}));
};

// Process and combine tokens from all sources
const combinedTokens = (await Promise.all([
// For the final combination of tokens
const combinedTokensResults = await Promise.allSettled([
processTokens(latestTokenProfiles || []),
processTokens(latestTokenBoosts || []),
processTokens(topTokenBoosts || [])
])).flat().slice(0, 20);
]);

const combinedTokens = combinedTokensResults
.filter(result => result.status === 'fulfilled')
.map(result => (result as PromiseFulfilledResult<TokenData[]>).value)
.flat()
.slice(0, 20);

console.log("Combined tokens count:", combinedTokens.length);
console.log("First few combined tokens:", combinedTokens.slice(0, 3));
Expand Down
Loading

0 comments on commit 724fb00

Please sign in to comment.