# 快人一步！使用nodejs + ethers.js实现自动mint NFT

By [dapaopao](https://paragraph.com/@dapaopao) · 2022-11-05

---

一、准备工作
------

1.环境需要 安装node js [下载地址](https://nodejs.org/)

2.申请一个RPC地址，我这里用的是alchemy提供的节点：[注册地址](https://www.alchemy.com/)

![](https://storage.googleapis.com/papyrus_images/93a445208945abba3100054360ba05a860387350aff953826ec24190eccdbe34.png)

注册成功后会有一个dashboard界面，点击view key

注意你的network 我这里用的是以太坊的测试链 Goerli,如果要用主网需要换成主网的network

![](https://storage.googleapis.com/papyrus_images/fb42d6da192f63b334dbc4155175181f4d4924eded82cedbc865559aebfe1b4f.png)

点击copy复制HTTPS的链接

![](https://storage.googleapis.com/papyrus_images/ca6bda58decc2f35e49bc88831131c8028a118299829973c89da3589dd67b40e.png)

二、代码实现
------

1.初始化项目

    npm init
    

安装ethers.js

    npm install --save ethers
    

2.当前目录创建index.js文件，配置参数，其中一些参数根据mint的合约需要手动调整

    const ethers = require("ethers");
    //第一步中申请的https链接
    const rpc = new ethers.providers.JsonRpcProvider("https://eth-goerli.g.alchemy.com/v2/<填写你的key>");
    //合约地址 我的测试合约0xbECEE4aa0Ba59285E82Ec8f4B70BBb9F63B0482d
    const address = "<填写你要mint合约的地址>";
    //钱包私钥
    const privateKey = "<填写你的钱包私钥>";
    //下面配置只是针对我的测试合约配置
    //mint数量
    const mintCount = 1;
    //最大mint数量
    const maxCount = 10;
    //每个数量单价 单位 eth 
    const mintPrice = "0.005";
    //mint 开始时间 时间戳
    const startingTimestamp = 1667623198;
    //对应需要调用方法的abi
    const abi = [{
            inputs: [{
                internalType: "uint256",
                name: "tokenQuantity",
                type: "uint256"
            }],
            name: "mintPublic",
            outputs: [],
            stateMutability: "payable",
            type: "function"
        },
        {
            inputs: [{
                internalType: "address",
                name: "owner",
                type: "address"
            }],
            name: "balanceOf",
            outputs: [{
                internalType: "uint256",
                name: "",
                type: "uint256"
            }],
            stateMutability: "view",
            type: "function",
        },
        {
            inputs: [],
            name: "symbol",
            outputs: [{
    
                internalType: "string",
                name: "",
                type: "string"
            }],
            stateMutability: "view",
            type: "function"
        },
    ];
    

abi可与去已验证合约的最下方找到，只需要你用到的方法即可，当然也可以全部复制。

![](https://storage.googleapis.com/papyrus_images/b5b7c50c857e6297e28b99c11f55ef6bc0b98efc9dccc39b3b49b22f2e3d075a.png)

我写的这个合约地址用到的mint方法是mintPublic每个地址最多mint10个每次最多mint1个，你也可以自己写一个合约调用自己的地址。

3.连接钱包

    // 用私钥创建钱包对象
    const wallet = new ethers.Wallet(privateKey,rpc);
    // 构造 nft 的合约对象
    const nftObject = new ethers.Contract(address, abi, wallet);
    

4.监听区块

    (async () => {
      // 监控区块产生的事件
      rpc.on("block", async (blockNumber) => {
        // 获取最新产生区块的时间戳
        const { timestamp } = await rpc.getBlock(blockNumber);
        // 查询地址拥有NFT的数量 balanceOf需要在abi中声明
        const numOwned = (await nftObject.balanceOf(wallet.address)).toNumber();
        // 打印信息
        console.log(`Block #${blockNumber} balance: ${numOwned} times tokens.`);
        // 判断时间戳，提前发起请求
        if (timestamp + 15 >= startingTimestamp && numOwned != maxCount) {
          // 记录发送交易的日志
          console.log(`Sending transaction in ${blockNumber}.`);
          
          // 第二、三个参数是矿工费，在 eip-1559 之后，发送交易需要设置 maxFeePerGas 基础费用（会被燃烧掉）和 maxPriorityFeePerGas 小费（给旷工的奖励）
          // 可以看到这里通过设置很高 gas 的费用去贿赂旷工尽快打包交易
          await nftObject.mintPublic(mintCount, {
            value: ethers.utils.parseEther(mintPrice),
            maxFeePerGas: ethers.utils.parseUnits("200", "gwei"),
            maxPriorityFeePerGas: ethers.utils.parseUnits("200", "gwei"),
          });
        }
    
        // 当查询到 nft 的余额数量是maxCount个时候退出
        if (numOwned == maxCount) {
          console.log("Successfully exiting");
          process.exit(1);
        }
      });
    })();
    

代码部分完成运行

    node index.js
    

![](https://storage.googleapis.com/papyrus_images/c1746b493666bdca60cfb7b2be052c284ff2175178df12116dfd894e9efc142e.png)

![](https://storage.googleapis.com/papyrus_images/c42ab45d22b5a0360beb478d749cc8d6df29ac1b6e08c4c18e7b1c078aa241af.png)

![](https://storage.googleapis.com/papyrus_images/bad7873bea5dc9e13d78219adf4c36df5dd613b27dd041c59ee7cbefe35a373e.png)

上述交易链接：[测试网区块浏览器链接](https://goerli.etherscan.io/tx/0x988ecf4f896ad234d851ccffae6c0650642de76b8bc302bc84397982c759345b)

因为测试网fee太高我只mint了3个就没eth了。但是可以看出代码是完全没问题的。

三、总结
----

当然这只是最简单的自动mint方式，还有很多可以优化。

如果有好的建议或者意见非常欢迎沟通，可以关注推特分享一些感兴趣的东西。

[https://twitter.com/dapaopao\_eth](https://twitter.com/dapaopao_eth)

---

*Originally published on [dapaopao](https://paragraph.com/@dapaopao/nodejs-ethers-js-mint-nft)*
