Alchemist here 💙
To fetch all NFT mint events within the last 10 blocks, you can use:
- ethers.js to fetch block num, and then
- use the Alchemy
getAssetTransfers
request to search "erc721" and "erc1155" transfers that have a fromAddress
set to the null address, to filter for "mint events"
Here's an example script, you just need to swap out "your-api-key"
with your Alchemy API key (sign up here if you don't have one).
import fetch, {Headers} from 'node-fetch';
import {ethers} from 'ethers';
// TODO: replace with your Alchemy API key
const API_KEY = "your-api-key";
const alchemy = new ethers.providers.AlchemyProvider("homestead", API_KEY);
// Get block range
const currentBlock = await alchemy.getBlockNumber();
const tenBlocksAgo = currentBlock - 10;
console.log("currentBlock:", currentBlock);
console.log("currentBlock (hex):", ethers.utils.hexlify(currentBlock));
console.log("10 blocks ago:", tenBlocksAgo);
console.log("10 blocks ago (hex):", ethers.utils.hexlify(tenBlocksAgo));
// Create alchemy getAssetTransfers request body
var requestBody = JSON.stringify({
"jsonrpc": "2.0",
"id": 0,
"method": "alchemy_getAssetTransfers",
"params": [
{
"fromBlock": ethers.utils.hexlify(tenBlocksAgo),
"excludeZeroValue": true,
"category": ["external", "erc721", "erc1155"],
"fromAddress": "0x0000000000000000000000000000000000000000"
}
]
});
// Construct the fetch request
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: requestBody,
redirect: 'follow'
};
// Fetch and print
fetch(`https://eth-mainnet.alchemyapi.io/v2/${API_KEY}`, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Hope that helps!