2

could someone please elaborate on: fromBlock: the starting time range we want to fetch NFT mints over (defaults to latest)

I tried to pass a block but its not working... I have also seen fromBlock": "0x0" but not sure what 0x0 stands for...

I would like to fetch the last 10 blocks or so.

I am referring to: https://docs.alchemy.com/alchemy/enhanced-apis/transfers-api#alchemy_getassettransfers=

1 Answer 1

3

Alchemist here 💙

To fetch all NFT mint events within the last 10 blocks, you can use:

  1. ethers.js to fetch block num, and then
  2. 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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.