You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ethers.js中调用键为枚举、值为结构体的Solidity映射?

解决Ethers.js调用Solidity映射验证初始化值的问题

Solidity中声明为public的映射会自动生成对应的getter函数,你可以通过Ethers.js调用这个函数来获取映射的值,具体操作如下:

1. 理解自动生成的Getter函数

你的feature是mapping(MintingFeature => NftSpec) public,Solidity会自动生成一个名为feature的getter函数,签名为:

function feature(MintingFeature key) external view returns (uint256 supplyLimit, uint256 cost, uint256 maxMintAmountPerTx, uint256 alreadyMinted, bool toggle);

由于枚举MintingFeature在ABI中会被解析为uint256类型,调用时直接传入枚举对应的索引值即可:

  • publicMinting对应0
  • whitelistMinting对应1
  • giftMinting对应2

2. Ethers.js + Chai测试代码示例

假设你已经完成合约部署并获取了contractInstance,测试代码可以这样写:

const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("YourNFTContract", function () {
  let contract;

  beforeEach(async function () {
    // 部署合约
    const YourNFT = await ethers.getContractFactory("YourNFT");
    contract = await YourNFT.deploy();
    await contract.deployed();
  });

  it("初始化publicMinting参数正确", async function () {
    // 调用getter获取publicMinting对应的NftSpec
    const publicMintingSpec = await contract.feature(0); // 0对应publicMinting

    // 断言每个字段与构造函数初始化值一致
    expect(publicMintingSpec.supplyLimit).to.equal(2000);
    expect(publicMintingSpec.cost).to.equal(ethers.utils.parseEther("0.02"));
    expect(publicMintingSpec.maxMintAmountPerTx).to.equal(3);
    expect(publicMintingSpec.alreadyMinted).to.equal(0);
    expect(publicMintingSpec.toggle).to.equal(false);
  });

  it("初始化whitelistMinting参数正确", async function () {
    const whitelistMintingSpec = await contract.feature(1); // 1对应whitelistMinting

    expect(whitelistMintingSpec.supplyLimit).to.equal(1000);
    expect(whitelistMintingSpec.cost).to.equal(ethers.utils.parseEther("0.015"));
    expect(whitelistMintingSpec.maxMintAmountPerTx).to.equal(1);
    expect(whitelistMintingSpec.alreadyMinted).to.equal(0);
    expect(whitelistMintingSpec.toggle).to.equal(false);
  });
});

3. 注意事项

  • 新版本Ethers.js返回的struct是对象,可直接通过字段名访问;旧版本可能返回数组,需通过索引访问(比如publicMintingSpec[0]对应supplyLimit,publicMintingSpec[4]对应toggle)。
  • 处理以太币数值时,要用ethers.utils.parseEther()将字符串转换为wei单位,和Solidity中的0.02 ether对应。

内容的提问来源于stack exchange,提问作者Angga Danar Prasetyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 14:06:55