如何使用 JavaScript 创建 NFT

2025-05-27

如何使用 JavaScript 创建 NFT

这篇博文基于 V1 版本,已过时。请使用 thirdweb V2 版本进行您即将开展的项目。

在我之前的文章中,我解释了如何使用 Solidity 创建 NFT。但是如果你不想学习 Solidity 怎么办?

没人有时间理会那个婊子。

如果你想继续使用你的老朋友 JavaScript,那就让我来告诉你,有一种方法可以做到。我向你介绍thirdweb——一个开发者可以在其应用中使用的智能合约、SDK 和 UI 组件库。

如果你只需调用一个函数,将代币的元数据作为参数,它就能为你铸造一个 NFT,那该有多酷啊mint!而且,你甚至不需要写一行 Solidity 代码。让我们看看这是否可行。

thirdweb简介

projects您首先需要了解的是和 的概念modules。简而言之,项目是充当模块容器的智能合约。另一方面,模块是包含智能合约和其他功能的包。前往此链接了解更多信息。

我们需要采取的所有步骤

以下是我们铸造 NFT 所需采取的步骤:

  1. 使用 thirdweb 创建项目
  2. 在我们的项目中部署 NFT 模块
  3. 铸造我们的 NFT

所有这些步骤都只用 JavaScript 完成。我会将这些步骤分成 3 个不同的.js文件。

设置

在开始编写代码之前,我们需要创建一个MetaMask钱包。由于我们将在网络上部署合约Rinkeby,因此我们还需要一些测试网 ETH 来批准交易。以下是有关如何创建 MetaMask 钱包并获取测试网 ETH 的指南

现在,前往你的 thirdweb 仪表板并创建一个项目。输入项目名称和描述。确保已将网络切换到 Rinkeby。

创建项目 - thirdweb 仪表板

我们将使用代码完成其他所有工作。

代码

继续创建一个空项目并安装所有必要的包:

  • @3rdweb/sdk - 使用 thirdweb 提供的智能合约
  • 以太币——用于连接我们的 MetaMask 钱包
  • dotenv——.env从文件中获取敏感数据
npm init -y
npm install @3rdweb/sdk ethers dotenv
Enter fullscreen mode Exit fullscreen mode

让我们创建 3 个单独的文件来编写我上面提到的所有步骤。

touch 1-init-sdk.js 2-deploy-collection.js 3-mint-nft.js
Enter fullscreen mode Exit fullscreen mode

1.初始化SDK

我喜欢先展示完整的代码,然后再进行解释。因此,在进一步讨论之前,这里是第一个文件的代码,即1-init-sdk.js

import { ThirdwebSDK } from '@3rdweb/sdk';
import ethers from 'ethers';

import dotenv from 'dotenv';
dotenv.config();

const sdk = new ThirdwebSDK(
  new ethers.Wallet(
    // Your wallet private key. ALWAYS KEEP THIS PRIVATE, DO NOT SHARE IT WITH ANYONE.
    // Add it to your .env file and do not commit that file to github!
    process.env.PRIVATE_KEY,
    // RPC URL, we'll use our Alchemy API URL from our .env file.
    ethers.getDefaultProvider('https://rinkeby-light.eth.linkpool.io/')
  )
);

(async () => {
  try {
    const apps = await sdk.getApps();
    console.log('Your app address is:', apps[0].address);
  } catch (err) {
    console.error('Failed to get apps from the sdk', err);
    process.exit(1);
  }
})();

// We are exporting the initialised thirdweb SDK so that we can use it in our other scripts
export default sdk;
Enter fullscreen mode Exit fullscreen mode

代码非常简单。我们导入 thirdweb,然后初始化 SDK。最后将其导出,以便在下一个脚本中重复使用。

我们也在运行这个:

(async () => {
  try {
    const apps = await sdk.getApps();
    // Get the address of the most recently created project
    console.log("Your app address is:", apps[0].address);
  } catch (err) {
    console.error("Failed to get apps from the sdk", err);
    process.exit(1);
  }
})(
Enter fullscreen mode Exit fullscreen mode

这段代码返回的是你的应用或项目的地址。它是用来存放所有模块的容器的地址。还记得我们一开始用仪表盘创建了一个项目吗?这段代码会返回它的地址。

继续在终端中运行以下命令:

node 1-init-sdk.js
Enter fullscreen mode Exit fullscreen mode

以下是我运行脚本时得到的结果:

lilcoderman % node scripts/1-init-sdk.js
Your app address is: 0x25320e23DCd1813D11787aD836865a64CC69897A
Enter fullscreen mode Exit fullscreen mode

2.部署NFT模块

现在我们有了项目/应用,让我们使用deployNftModulethirdweb 提供的方法来部署我们的集合。这是我们在第一步中初始化的 SDK 可用的方法之一。

我们目前还不会在这里创建 NFT。此模块仅帮助我们创建并部署一个 ERC-721 集合到 Rinkeby 测试网。我们只是设置集合本身的元数据。您知道,例如名称(例如 Bored Ape Yacht Club)、描述以及与整个集合相关的图像。

继续将以下代码复制到2-deploy-collection.js文件中:

import sdk from './1-init-sdk.js';
import { readFileSync } from 'fs';

import dotenv from 'dotenv';
dotenv.config();

const app = sdk.getAppModule('YOUR_APP_ADDRESS');

(async () => {
  try {
    const nftModule = await app.deployNftModule({
      // The collection's name, ex. CryptoPunks
      name: 'JavaScript NFTS',
      // A description for the collection.
      description:
        'How to mint an NFT using Javascript - a tutorial by @lilcoderman',
      // The image for the collection that will show up on OpenSea.
      image: readFileSync('assets/collection.png'),
      // The amount of royalty collected on all royalties represented as basis points. The default is 0 (no royalties).
      // 1 basis point = 0.01%
      // For example: if this value is 100, then the royalty is 1% of the total sales.
      sellerFeeBasisPoints: 0,
      // The address of the royalty recipient. All royalties will be sent to this address.
      feeRecipient: process.env.WALLET_ADDRESS,
      // The symbol for the NFT Collection
      symbol: 'JS',
    });

    console.log(
      '✅ Successfully deployed nft module, address:',
      nftModule.address
    );
  } catch (error) {
    console.log('failed to deploy nft module', error);
  }
})();
Enter fullscreen mode Exit fullscreen mode

这段代码非常直观易懂。我们从上一个文件中导入了 SDK,并调用了它的一个方法。该方法将为我们部署一个 NFT 模块(即集合)。我们还提供了必要的元数据作为函数的参数deployNftModule

运行此脚本后,它将返回集合的地址。以下是我得到的:

lilcoderman % node scripts/2-deploy-collection.js
✅ Successfully deployed nft module, address: 0x1C267DC8841999de9B9C4F33D63a8d6bC81b8e2D
Enter fullscreen mode Exit fullscreen mode

3. 是时候铸造我们的 NFT 了

我们快完成了!是时候铸造我们的 NFT 了,我们甚至还没有写一行 Solidity 代码。这可能是我们迄今为止编写的最简单的代码。将以下代码复制到最终文件中3-mint-nft.js

import sdk from './1-init-sdk.js';
import { readFileSync } from 'fs';

const nft = sdk.getNFTModule('YOUR_NFT_MODULE_ADDRESS');

(async () => {
  try {
    await nft.mint({
      name: 'LCM',
      description: 'Follow me on twitter @lilcoderman',
      image: readFileSync('assets/nft.png'),
      properties: {},
    });
    console.log('✅ Successfully created a new NFT in the collection!');
  } catch (error) {
    console.error('failed to create the new NFT', error);
  }
})();
Enter fullscreen mode Exit fullscreen mode

getNFTModule和之前一样,我们从第一个文件导入 SDK。不过,这次我们使用的是模块。该模块返回的是我们的 ERC-721 合约。

然后,我们可以从合约中调用该mint函数来创建真正的 NFT!mint 函数需要一个包含代币元数据的对象。我已将 NFT 的名称、描述和图像作为参数传入。您也可以根据需要设置其属性。

现在,让我们运行它:

lilcoderman % node scripts/3-mint-nft.js
✅ Successfully created a new NFT in the collection!
Enter fullscreen mode Exit fullscreen mode

您现在可以在 thirdweb仪表板上查看 NFT

NFT 收藏 - thirdweb 仪表板

我们也可以通过OpenSea上的地址找到我们的 NFT。点击此链接查看我的 NFT。

就这样!现在你只用 JavaScript 就铸造了一个 NFT。是不是很酷炫?

无论如何,这里是包含所有代码的 Github repo:https://github.com/abdulrauf11/tutorial-thirdweb-nft

接下来是什么...

thirdweb 的功能远不止铸造 NFT 集合。它拥有创建自定义代币的模块、NFT 市场,甚至 DAO!未来,他们还计划支持 Solana 和 Flow 等其他区块链。

我们使用 JavaScript 完成所有步骤,但这不是必需的。您可以使用仪表板手动完成所有操作。我认为,使用代码执行操作会更加灵活。

请记住,如果您要在生产中使用 ThirdWeb,他们会从您的版税中抽取 5% 的小额佣金。考虑到他们的产品让我们的生活更加便捷,我觉得这很公平。


别离开我,带我一起走

喜欢这篇文章吗?关注我的社交媒体账号,了解更多关于 NFT、Web 开发和垃圾帖的信息。

推特:@lilcoderman

Instagram:@lilcoderman

文章来源:https://dev.to/lilcoderman/how-to-create-a-motherfcking-nft-using-javascript-2foj
PREV
2024 年备忘单集
NEXT
面向对象 (POO) 和 JavaScript 的复杂程序