<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by devDwarf on Medium]]></title>
        <description><![CDATA[Stories by devDwarf on Medium]]></description>
        <link>https://medium.com/@devdwarf?source=rss-1dcd0a4757e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hpw4bzmTNicBir9AyuYE_w.jpeg</url>
            <title>Stories by devDwarf on Medium</title>
            <link>https://medium.com/@devdwarf?source=rss-1dcd0a4757e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:10:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devdwarf/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Fetching Token Holders at Warp Speed with Alchemy ’s Supercharged APIs]]></title>
            <link>https://medium.com/@devdwarf/fetching-token-holders-at-warp-speed-with-alchemy-s-supercharged-apis-c5ea12f5c371?source=rss-1dcd0a4757e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5ea12f5c371</guid>
            <dc:creator><![CDATA[devDwarf]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 20:54:55 GMT</pubDate>
            <atom:updated>2025-08-07T14:02:13.833Z</atom:updated>
            <content:encoded><![CDATA[<p>When building dashboards, planning airdrops, or analyzing communities, getting the list of <strong>NFT or token holders</strong> is crucial. Alchemy offers two solid paths for this, one supercharged and one old school. Let’s explore both.</p><p><strong>Method 1: The Fast Lane — Alchemy NFT &amp; Token API</strong></p><p>Did you know you can fetch the entire list of <strong>NFT or ERC-20 token holders</strong> along with their balances in milliseconds using Alchemy?</p><p>With <strong>Alchemy’s Token and NFT APIs</strong>, you don’t need to loop through token IDs or scan the entire blockchain. A single API call gives you a complete snapshot of all current holders of a contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F4EuJ50pECFf2oHa.jpg" /></figure><p>Here’s the endpoint (for NFTs):</p><pre>GET https://eth-mainnet.g.alchemy.com/nft/v3/YOUR_API_KEY/getOwnersForContract</pre><p>And for ERC-20 tokens, Alchemy offers similar capabilities via their <a href="https://docs.alchemy.com/reference/token-api-overview">Token API</a>.</p><p>Query parameters for NFTs:</p><pre>?contractAddress=0xYourNFTContract<br>&amp;withTokenBalances=true</pre><p>This returns:</p><ul><li>A list of all wallet addresses currently holding NFTs or tokens from the specified contract</li><li>If withTokenBalances=true, it includes which token IDs (for NFTs) or balance amounts (for tokens) each address holds</li></ul><p><strong>Example (API key omitted):</strong></p><pre>GET https://eth-mainnet.g.alchemy.com/nft/v3/YOUR_API_KEY/getOwnersForContract?contractAddress=0x6e4b3bb131bd85682a2d3ddd5661d2816f186e81&amp;withTokenBalances=true</pre><p>The result is fast, reliable, and indexed, perfect for building leaderboards, running airdrops, or analyzing holder distribution.</p><p>This method works the same for <strong>ERC-20 tokens</strong> too. Simply switch over to the Token API and enjoy the same speed and simplicity.</p><blockquote><em>Note: This method requires </em><strong><em>full platform support</em></strong><em> on Alchemy. If your contract or network isn’t yet supported, you’ll need to go manual.</em></blockquote><p><strong>Method 2: The Manual Route — Scanning Transfer Events with Ethers.js</strong></p><p>If the NFT or Token API isn’t supported on your network (e.g., Base, Scroll) or for your specific contract, you can fall back to the good old way: scan Transfer events manually with ethers.js.</p><p>This method works both for <strong>ERC-721/1155 NFTs</strong> and <strong>ERC-20 tokens</strong>. Just make sure your ABI includes the correct Transfer event.</p><p>Here’s a Node.js script tailored for NFTs, but easily adaptable to ERC-20 tokens:</p><pre>const { ethers } = require(&quot;ethers&quot;);<br>const fs = require(&quot;fs/promises&quot;);<br>const dotenv = require(&quot;dotenv&quot;);<br><br>// Load environment variables from .env file<br>// env file should have : RPC_URL=&quot;https://eth-mainnet.g.alchemy.com/v2/yourApiKey&quot;<br>dotenv.config();<br><br>// --- Configuration ---<br>const RPC_URL = process.env.RPC_URL;<br>const NFT_CONTRACT_ADDRESS = &quot;0x6e4b3bb131bd85682a2d3ddd5661d2816f186e81&quot;;<br>const START_BLOCK = 22638129;<br>const OUTPUT_FILE = &quot;nft-snapshot-holders.json&quot;;<br>const BATCH_SIZE = 10000; // Number of blocks to query at once<br>const CONCURRENT_BATCHES = 10; // Number of concurrent batches to process<br>const RETRY_ATTEMPTS = 3; // Number of retry attempts on error<br>const BURN_ADDRESS = &quot;0x0000000000000000000000000000000000000000&quot;;<br><br>const NFT_ABI = [<br>  &quot;event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)&quot;<br>];<br><br>// --- Helper Functions ---<br><br>/**<br> * Fetches Transfer events for a given block range with retry logic.<br> */<br>async function getTransferEvents(contract, fromBlock, toBlock) {<br>  for (let attempt = 1; attempt &lt;= RETRY_ATTEMPTS; attempt++) {<br>    try {<br>      console.log(`Querying: Block ${fromBlock} - ${toBlock}`);<br>      return await contract.queryFilter(&quot;Transfer&quot;, fromBlock, toBlock);<br>    } catch (err) {<br>      console.error(`Error (Block ${fromBlock}-${toBlock}, Attempt ${attempt}/${RETRY_ATTEMPTS}): ${err.message}`);<br>      if (attempt === RETRY_ATTEMPTS) {<br>        throw new Error(`Failed to fetch events for block range ${fromBlock}-${toBlock}.`);<br>      }<br>      // Wait a bit before the next attempt<br>      await new Promise(resolve =&gt; setTimeout(resolve, 1000 * attempt));<br>    }<br>  }<br>}<br><br>// --- Main Function ---<br><br>async function main() {<br>  if (!RPC_URL) {<br>    throw new Error(&quot;RPC_URL is not defined in the .env file. Please copy .env.example to .env and fill it out.&quot;);<br>  }<br><br>  const provider = new ethers.providers.StaticJsonRpcProvider(RPC_URL);<br>  const contract = new ethers.Contract(NFT_CONTRACT_ADDRESS, NFT_ABI, provider);<br>  const latestBlock = await provider.getBlockNumber();<br>  console.log(`Current block: ${latestBlock}`);<br><br>  const ownerMap = new Map(); // tokenId -&gt; current owner<br><br>  const blockRanges = [];<br>  for (let fromBlock = START_BLOCK; fromBlock &lt;= latestBlock; fromBlock += BATCH_SIZE) {<br>    const toBlock = Math.min(fromBlock + BATCH_SIZE - 1, latestBlock);<br>    blockRanges.push({ fromBlock, toBlock });<br>  }<br><br>  console.log(`Processing ${blockRanges.length} block ranges in batches of ${CONCURRENT_BATCHES}.`);<br><br>  for (let i = 0; i &lt; blockRanges.length; i += CONCURRENT_BATCHES) {<br>    const batch = blockRanges.slice(i, i + CONCURRENT_BATCHES);<br>    const eventPromises = batch.map(range =&gt; getTransferEvents(contract, range.fromBlock, range.toBlock));<br>    <br>    const eventArrays = await Promise.all(eventPromises);<br><br>    for (const events of eventArrays) {<br>        if (!events) continue; // Can be null after an error<br>        for (const event of events) {<br>            if (event.args?.tokenId &amp;&amp; event.args?.to) {<br>                const tokenId = event.args.tokenId.toString();<br>                const toAddress = event.args.to.toLowerCase();<br><br>                if (toAddress === BURN_ADDRESS) {<br>                    ownerMap.delete(tokenId); // Remove burned token from the map<br>                } else {<br>                    ownerMap.set(tokenId, toAddress);<br>                }<br>            }<br>        }<br>    }<br>    console.log(`Processed batches: ${Math.min(i + CONCURRENT_BATCHES, blockRanges.length)}/${blockRanges.length}`);<br>  }<br><br>  console.log(&quot;All events processed. Grouping owners...&quot;);<br><br>  // Group token IDs by owner<br>  const holders = {};<br>  for (const [tokenId, owner] of ownerMap.entries()) {<br>    if (!holders[owner]) {<br>      holders[owner] = [];<br>    }<br>    holders[owner].push(tokenId);<br>  }<br><br>  await fs.writeFile(OUTPUT_FILE, JSON.stringify(holders, null, 2));<br><br>  console.log(`Done. Found ${Object.keys(holders).length} unique holders. Snapshot saved to &#39;${OUTPUT_FILE}&#39;.`);<br>}<br><br>main().catch(err =&gt; {<br>  console.error(&quot;An unexpected error occurred:&quot;, err);<br>  process.exit(1);<br>});</pre><h3>When to Use This Script</h3><p>If your contract is deployed on a new EVM network (e.g., Base)<br> If Alchemy API doesn’t support your contract yet<br> If you want full control over how data is collected and stored</p><blockquote><em>Reminder: This method applies to both NFTs and tokens. For ERC-20, just update the ABI and token contract address accordingly.</em></blockquote><blockquote>Bonus: Using Alchemy’s Cortex Engine under the hood gives this manual method a serious speed boost. Event scanning has never felt smoother.</blockquote><p><strong>Conclusion</strong></p><p>If your project is on a supported network with full Alchemy support, fetching holder data becomes incredibly easy. One API call. That’s it.</p><p>Whether you’re building NFT projects or ERC-20 token apps, <strong>Alchemy’s APIs give you superpowers</strong>.</p><p>If you’re on a new EVM network or prefer more control, ethers.js gives you everything you need.</p><p>But seriously, on supported chains?</p><p>It’s fast. It’s clean. It’s beautiful.</p><p><strong>I love Alchemy.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5ea12f5c371" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an NFT Portfolio Viewer with Alchemy NFT API and Next.js]]></title>
            <link>https://medium.com/@devdwarf/building-an-nft-portfolio-viewer-with-alchemy-nft-api-and-next-js-d5be9b429022?source=rss-1dcd0a4757e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5be9b429022</guid>
            <dc:creator><![CDATA[devDwarf]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 19:36:45 GMT</pubDate>
            <atom:updated>2025-07-17T19:36:45.360Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s say you’re building an NFT marketplace or a wallet app. Displaying the NFTs a user owns is not as simple as it sounds. You’d have to deal with large data indexes, support various protocols, and on top of that, crawl and process metadata accurately. In short, it’s both complex and resource-intensive.</p><p>Alchemy’s NFT API simplifies this entire process with just a few API calls. By providing a wallet address, you can easily retrieve all the NFTs owned by that address, complete with images and metadata details.</p><p>Today, we’re going to build a Personal NFT Portfolio Viewer using Next.js and Alchemy NFT API. By the end, you’ll have a sleek web app where you can enter any wallet address and instantly visualize all associated NFTs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FmAC_RhzqPRrEwdzGIdh1A.png" /></figure><h3>Step 1: Setting Up an Alchemy Account</h3><p>First, we need access to the Alchemy API.Visit alchemy.com and sign up for a free account.Once inside the dashboard, click Create App.<br>Fill in:<br>App Name: NFT Portfolio Viewer<br>Chain: Ethereum<br>Network: Mainnet<br>Once created, grab your API Key from the app’s settings.</p><h3>Step 2: Initializing the Next.js Project</h3><p>Let’s start coding!</p><pre>npx create-next-app nft-portfolio-viewer<br>cd nft-portfolio-viewer<br>npm install axios</pre><p>Create a .env.local file to store your Alchemy API key:<br>ALCHEMY_API_KEY=your_alchemy_api_key_here</p><h3>Step 3: Building the Backend API Route</h3><p>We’ll create an API route in Next.js to handle requests to Alchemy’s NFT API.</p><p>Create a new file at:<br>/pages/api/nfts.js</p><pre><br>import { NextApiRequest, NextApiResponse } from &#39;next&#39;;<br>import axios from &#39;axios&#39;;<br><br>export default async function handler(req, res) {<br>  if (req.method !== &#39;GET&#39;) {<br>    return res.status(405).json({ message: &#39;Method not allowed&#39; });<br>  }<br><br>  const { address } = req.query;<br><br>  if (!address || typeof address !== &#39;string&#39;) {<br>    return res.status(400).json({ message: &#39;Address is required&#39; });<br>  }<br><br>  try {<br>    const alchemyApiKey = process.env.ALCHEMY_API_KEY;<br>    const url = `https://eth-mainnet.g.alchemy.com/nft/v3/${alchemyApiKey}/getNFTsForOwner?owner=${address}`;<br><br>    const { data } = await axios.get(url);<br><br>    return res.status(200).json(data);<br>  } catch (error) {<br>    console.error(error);<br>    return res.status(500).json({ message: &#39;Internal server error&#39; });<br>  }<br>}</pre><p>Now, you have a backend endpoint at:<br>/api/nfts?address=0xWalletAddressHere</p><h3>Step 4: Building the Frontend UI</h3><p>Next, we’ll create a simple frontend where users can enter their wallet address and visualize their NFTs.</p><p>First, open the index page:<br>/pages/index.js</p><pre>&#39;use client&#39;;<br><br>import { useState } from &#39;react&#39;;<br><br>interface NFT {<br>  tokenId: string;<br>  name: string;<br>  image?: {<br>    cachedUrl: string;<br>  };<br>}<br><br>export default function Home() {<br>  const [address, setAddress] = useState(&#39;&#39;);<br>  const [nfts, setNfts] = useState&lt;NFT[]&gt;([]);<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState&lt;string | null&gt;(null);<br><br>  const fetchNFTs = async () =&gt; {<br>    setLoading(true);<br>    setError(null);<br>    try {<br>      const response = await fetch(`/api/nfts?address=${address}`);<br>      if (!response.ok) {<br>        throw new Error(&#39;Failed to fetch NFTs&#39;);<br>      }<br>      const data = await response.json();<br>      setNfts(data.ownedNfts);<br>    } catch (err) {<br>      if (err instanceof Error) {<br>        setError(err.message);<br>      } else {<br>        setError(&#39;An unknown error occurred&#39;);<br>      }<br>    } finally {<br>      setLoading(false);<br>    }<br>  };<br><br>  const handleSubmit = (e: React.FormEvent) =&gt; {<br>    e.preventDefault();<br>    fetchNFTs();<br>  };<br><br>  return (<br>    &lt;div className=&quot;font-sans grid grid-rows-[auto_1fr_auto] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20&quot;&gt;<br>      &lt;header className=&quot;text-center&quot;&gt;<br>        &lt;h1 className=&quot;text-4xl font-bold mb-4&quot;&gt;NFT Portfolio&lt;/h1&gt;<br>        &lt;p className=&quot;text-lg text-gray-600&quot;&gt;<br>          Enter a wallet address to view its NFTs<br>        &lt;/p&gt;<br>      &lt;/header&gt;<br><br>      &lt;main className=&quot;flex flex-col gap-8 row-start-2 items-center w-full max-w-4xl&quot;&gt;<br>        &lt;form onSubmit={handleSubmit} className=&quot;flex gap-4 items-center w-full max-w-lg&quot;&gt;<br>          &lt;input<br>            type=&quot;text&quot;<br>            value={address}<br>            onChange={(e) =&gt; setAddress(e.target.value)}<br>            placeholder=&quot;Enter wallet address&quot;<br>            className=&quot;flex-grow p-2 border rounded&quot;<br>          /&gt;<br>          &lt;button<br>            type=&quot;submit&quot;<br>            disabled={loading}<br>            className=&quot;p-2 bg-blue-500 text-white rounded disabled:bg-gray-400&quot;<br>          &gt;<br>            {loading ? &#39;Loading...&#39; : &#39;Fetch NFTs&#39;}<br>          &lt;/button&gt;<br>        &lt;/form&gt;<br><br>        {error &amp;&amp; &lt;p className=&quot;text-red-500&quot;&gt;{error}&lt;/p&gt;}<br><br>        &lt;div className=&quot;grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 w-full&quot;&gt;<br>          {nfts.map((nft) =&gt; (<br>            &lt;div key={nft.tokenId} className=&quot;border rounded p-4&quot;&gt;<br>              &lt;img<br>                src={nft.image?.cachedUrl ?? &#39;https://via.placeholder.com/150&#39;}<br>                alt={nft.name}<br>                width={150}<br>                height={150}<br>                className=&quot;w-full h-auto rounded&quot;<br>              /&gt;<br>              &lt;h3 className=&quot;font-bold mt-2&quot;&gt;{nft.name}&lt;/h3&gt;<br>            &lt;/div&gt;<br>          ))}<br>        &lt;/div&gt;<br>      &lt;/main&gt;<br><br>      &lt;footer className=&quot;row-start-3 flex gap-4 items-center justify-center&quot;&gt;<br>        &lt;a<br>          href=&quot;https://alchemy.com/?a=create-web3-dapp&quot;<br>          target=&quot;_blank&quot;<br>          rel=&quot;noopener noreferrer&quot;<br>          className=&quot;flex items-center gap-2 hover:underline&quot;<br>        &gt;<br>          &lt;img<br>            src=&quot;/vercel.svg&quot;<br>            alt=&quot;Vercel Logo&quot;<br>            width={20}<br>            height={20}<br>          /&gt;<br>          Powered by Alchemy<br>        &lt;/a&gt;<br>      &lt;/footer&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>This will display an input field for the wallet address, a button to fetch NFTs, and a grid of cards showing each NFT’s image, title, and contract address.</p><p>Now you have a working NFT Portfolio Viewer! You can style it further using CSS or libraries like Tailwind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DtkUGpvkCLdXmiBx1Q8xKg.png" /></figure><p>If you want to see the complete example or clone it directly, check out the GitHub repository here:<br><a href="https://github.com/thedevdwarf/nft-portfolio">https://github.com/thedevdwarf/nft-portfolio</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5be9b429022" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>