Skip to content

Instantly share code, notes, and snippets.

@cordt-sei
Last active December 9, 2024 01:29
Show Gist options
  • Save cordt-sei/e6d2d5be440f981dc5a8abd6ddaced09 to your computer and use it in GitHub Desktop.
Save cordt-sei/e6d2d5be440f981dc5a8abd6ddaced09 to your computer and use it in GitHub Desktop.
Find all tokens and owners for ERC721 collection [pointer]
// pipe output to file if your collection has a large number of tokens
// [node index.js > tokens.json]
import { ethers } from "ethers";
// Use your provided RPC and contract address
const provider = new ethers.JsonRpcProvider("http://localhost:8545");
const contractAddress = "0x[contract_address]";
const abi = [
"function totalSupply() public view returns (uint256)",
"function ownerOf(uint256 tokenId) public view returns (address)"
];
const contract = new ethers.Contract(contractAddress, abi, provider);
async function fetchAllTokensParallel() {
try {
// Query the total number of tokens from the contract
const totalTokens = await contract.totalSupply();
console.log(`Total Tokens: ${totalTokens.toString()}`);
// Convert BigInt to Number (safe for reasonably sized collections)
const totalTokensNumber = Number(totalTokens);
// Create an array of promises for token IDs
const tokenPromises = Array.from({ length: totalTokensNumber }, (_, i) =>
contract.ownerOf(i)
.then(owner => ({ tokenId: i + 1, owner })) // Resolve with tokenId and owner
.catch(() => null) // Catch errors for non-existent tokens
);
// Wait for all promises to resolve
const results = await Promise.all(tokenPromises);
// Filter out null results (invalid tokens)
return results.filter(token => token !== null);
} catch (error) {
console.error("Error fetching tokens:", error);
return [];
}
}
// Fetch and log all tokens
fetchAllTokensParallel()
.then(tokens => {
console.log(`Total Tokens Retrieved: ${tokens.length}`);
console.log("All Tokens:", JSON.stringify(tokens, null, 2)); // Pretty print the entire output
})
.catch(console.error);
{
"name": "ercnft",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"license": "MIT",
"dependencies": {
"ethers": "^6.13.4"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment