How to batch mint 400 ERC-721 NFT's using a loop

Hi everyone! I managed to mint 40 NFT’s using the Ropsten Truffle console, but I can’t seem to get it to work on a sol file using Truffle. Here is some of my code for context.

pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";

contract MyNft is ERC721 {
  constructor() ERC721("MyNFT", "NFT") public {}

  mapping(uint256 => string) private _CIDS;

  function CID(uint256 tokenId) public view returns (string memory) {
    require(_exists(tokenId), "ERC721Metadata: CID query for nonexistent token");
    string memory _CID = _CIDS[tokenId];
    return _CID;

  function _setTokenCID(uint256 tokenId, string memory _CID) internal virtual {
    require(_exists(tokenId), "ERC721Metadata: CID set of nonexistent token");
    _CIDS[tokenId] = _CID;

  function mint(string memory _CID) public {
      uint256 _newId = totalSupply();

     for(uint i = 0; i<=400; i++){
      _safeMint(msg.sender, (_newId + i));
      _setTokenCID((_newId + i), _CID);

My Network is ropsten and im using Infura

  networks: {
    ropsten: {
      provider: () => { 
        return new HDWalletProvider(mnemonic,`wss://${infuraAccessKey}`);
      network_id: "3",
      gas: 5500000,        // Ropsten has a lower block limit than mainnet
      confirmations: 2,    // # of confs to wait between deployments. (default: 0)
      timeoutBlocks: 200,  // # of blocks before a deployment times out  (minimum/default: 50)
      skipDryRun: true,    

When I run the migrations it gives me a nonce too low error or it runs out of gas.
I know gas it not an issue because I got it to work on the console.

The code I used on the console:


This is the token I batch minted on the console, but I want to do this on a sol file.

Any help would really help me, thank you!

It says x >= 40 which looks wrong. On your solidity code it says x <= 400 which is a lot more.

That said, by running that on the console you’re sending many separate transactions and it’s not necessarily an indication that you’ll be able to fit it all in a single transaction because it could hit the gas limit. Try starting with a lower amount and see if it works.

That one was a typo, meant to do >= for both

That doesn’t make sense to me. for (x = 0; x >= 40; x++) won’t do any iterations.

for(x=0;x<=40;x++) {code} My bad

But that’s not the issue


To clear up confusion, post your updated code in a code box again.

It’s easier to launch the contract and use a web3 script to loop through a function IMO

Hello! What solution did you choise? WEB3 JS or in contract loop?

I tried going with web 3 and running a loop on the mint function but I have to pay for each mint that way. I'm getting a contract error when looping , so i must be doing something wrong.

1 Like