Skip to content
The Chat Archive
o4-mini-2025-04-16· OpenAI LMArena Human Preference 140K

make an script to find what specific solana token that top 100 wallet hold or what…

  1. User

    make an script to find what specific solana token that top 100 wallet hold or what tokens is hold by many whale wallet. in python so i give a list of top solana wallets and you dig into it i give you csv file and your code must python

  2. Assistant

    Here’s a self-contained Python script that:

    1. Reads a CSV of Solana wallet addresses
    2. Fetches each wallet’s SPL-token accounts via the Solana RPC (parsed JSON)
    3. Aggregates which tokens appear across your wallet list
    4. Prints out, for each token mint, how many wallets hold it—and the top held mints

    You can run it like:

    pip install solana pandas aiohttp tqdm
    python find_whale_tokens.py wallets.csv
    
    #!/usr/bin/env python3
    import sys
    import csv
    import asyncio
    from collections import Counter, defaultdict
    
    import pandas as pd
    from solana.rpc.async_api import AsyncClient
    from solana.publickey import PublicKey
    from tqdm.asyncio import tqdm
    
    RPC_ENDPOINT = "https://api.mainnet-beta.solana.com"
    TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
    
    
    async def fetch_tokens(client: AsyncClient, owner: str):
        """
        Query getTokenAccountsByOwner for a given wallet (parsed JSON).
        Return a dict mint -> uiAmount.
        """
        resp = await client.get_token_accounts_by_owner(
            PublicKey(owner),
            program_id=TOKEN_PROGRAM_ID,
            encoding="jsonParsed",
        )
        result = {}
        if resp["result"] and resp["result"]["value"]:
            for acct in resp["result"]["value"]:
                info = acct["account"]["data"]["parsed"]["info"]
                amt = info["tokenAmount"]["uiAmount"]
                mint = info["mint"]
                if amt and amt > 0:
                    result[mint] = amt
        return result
    
    
    async def main(csv_path: str):
        # 1) Read CSV of addresses
        df = pd.read_csv(csv_path, header=None, names=["wallet"])
        wallets = df["wallet"].astype(str).tolist()
    
        client = AsyncClient(RPC_ENDPOINT)
        # 2) Fetch each wallet’s tokens in parallel
        wallet_to_tokens = {}
        async for owner, tokens in tqdm(
            asyncio.as_completed([fetch_tokens(client, w) for w in wallets]),
            total=len(wallets),
            desc="Fetching wallets",
        ):
            # to preserve mapping we have to match tasks back to wallets;
            # simpler: reorder tasks to (wallet,task) pairs:
            break  # we’ll rewrite below
    
        # Better: pair each wallet with the task
        tasks = {asyncio.create_task(fetch_tokens(client, w)): w for w in wallets}
        token_counts = Counter()
        for task in tqdm(asyncio.as_completed(tasks), total=len(tasks), desc="Processing"):
            tokens = await task
            owner = tasks[task]
            wallet_to_tokens[owner] = tokens
            # count each mint once per wallet
            for mint in tokens.keys():
                token_counts[mint] += 1
    
        await client.close()
    
        # 3) Prepare final report
        # Sort tokens by number of wallets holding them (descending)
        top_tokens = token_counts.most_common()
    
        print(f"\nTotal wallets processed: {len(wallets)}\n")
        print("Top tokens by number of whale wallets holding them:")
        print(f"{'Rank':>4}  {'Mint':44}  {'Wallet Count':>12}")
        print("-" * 66)
        for rank, (mint, cnt) in enumerate(top_tokens[:20], start=1):
            print(f"{rank:>4}. {mint:44}  {cnt:12}")
    
        # 4) (Optional) dump full token_counts to CSV
        out_df = pd.DataFrame(top_tokens, columns=["mint", "wallet_count"])
        out_df.to_csv("token_whale_counts.csv", index=False)
        print("\nFull token counts saved to token_whale_counts.csv")
    
    
    if __name__ == "__main__":
        if len(sys.argv) != 2:
            print("Usage: python find_whale_tokens.py <wallets.csv>")
            sys.exit(1)
        asyncio.run(main(sys.argv[1]))
    

    Explanation of key parts:

    • Uses the official solana-py async RPC client
    • get_token_accounts_by_owner(..., encoding="jsonParsed") returns you mint & human-readable uiAmount directly
    • Aggregates with a Python Counter so you know “how many wallets hold mint X”
    • Prints top 20 mints, and writes a full CSV for further analysis

    Feel free to tweak concurrency, RPC endpoints, or output formatting as needed! 🚀

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.