web3 第六章 (DAPP 连接测试合约并 mint)

631 阅读1分钟

读合约

使用 wagmi 的 useReadContract hook 读取合约的信息。比如读取 nft 的数量。 在 ERC-721 标准中,balanceOf 函数用于查询某个地址拥有的 NFT(非同质化代币)的数量。

const result = useReadContract({
    abi: [
      {
        type: "function",
        name: "balanceOf",
        stateMutability: "view",
        inputs: [{ name: "owner", type: "address" }],
        outputs: [{ type: "uint256" }],
      },
    ],
    address: contractInfo.find((item) => item.id === chain?.id)
      ?.contractAddress as `0x${string}`,
    functionName: "balanceOf",
    args: [account?.address as `0x${string}`],
  });

这个时候获取的值是 0,因为我们还没有任何 NFT。

写合约

这里使用 wagmi 的 useWriteContract 方法请求合约,把 abi 和 address 换成我们自己的

writeContract(
{
  abi: [
    {
      type: "function",
      name: "mint",
      stateMutability: "payable",
      inputs: [
        {
          internalType: "uint256",
          name: "quantity",
          type: "uint256",
        },
      ],
      outputs: [],
    },
  ],
  address: contractInfo.find((item) => item.id === chain?.id)
    ?.contractAddress as `0x${string}`,
  functionName: "mint",
  args: [BigInt(1)],
  value: parseEther("0.01"),
},
{
  onSuccess: () => {
    message.success("Mint Success");
  },
  onError: (err) => {
    message.error(err.message);
  },
}
);

连接上测试网,点击 mint 按钮,调用 mint 方法。授权 image.png

点击确认, mint 成功,再次调用 balanceOf 方法,显示结果为 1。表明 mint 成功。