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

如何将用户输入的动态值传递给ERC20合约构造函数?

动态传递ERC20代币名称与符号的问题

我正在开发一个可根据用户输入自动生成ERC20代币的网站,核心需求是将用户提供的name和symbol动态传递给ERC20构造函数,而非硬编码到合约中。尝试三种方法均失败:

  • 覆盖OpenZeppelin ERC20的name和symbol变量,部署后代币无名称;
  • 向ERC20构造函数传递变量时出现语法错误:Expected ',' but got 'memory'solidity(2314);
  • 忽略ERC20构造函数仅实现自定义构造函数,收到错误:Contract "DamiKing" should be marked as abstract.

尝试一代码

Token.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract DamiKing is ERC20 {
address public admin;
string name;
string symbol;

event serverStatus(string serverMessage);
constructor() ERC20(name, symbol) 
payable {

    _name = name;
    _symbol = symbol;
    _mint(msg.sender, 10000 * 10 ** decimals());
    admin = msg.sender;
}

deploy.js

async function main() {
const [owner] = await hre.ethers.getSigners();
const DMKContractFactory = await hre.ethers.getContractFactory("DamiKing");
const DMKContract = await DMKContractFactory.deploy("damilare", "afo");
const x = await DMKContract.deployed();
console.log("Smart Contract Deployed with the address: ",DMKContract.address);
console.log("Total Suppy: ",await DMKContract.checkBalance(owner.address), await DMKContract.symbol());
console.log("owner address: ", owner.address);
console.log(x)
}

尝试二代码

Token.sol

constructor() ERC20(string memory name, string memory symbol) payable {
    _mint(msg.sender, 10000 * 10 ** decimals());
    admin = msg.sender;
}

尝试三代码

Token.sol

constructor(string memory name, string memory symbol) payable {
    _mint(msg.sender, 10000 * 10 ** decimals());
    admin = msg.sender;
}

正确解决方案

问题根源

  1. 尝试一:重复定义name和symbol变量,且调用ERC20构造时变量未赋值(默认空字符串),导致代币名称为空;OpenZeppelin的ERC20已封装_name和_symbol,无需重复声明。
  2. 尝试二:构造函数参数声明位置错误,需先在合约构造函数定义参数,再传递给父类ERC20构造。
  3. 尝试三:继承ERC20但未调用父类构造函数,Solidity要求必须显式调用父类构造,否则合约需标记为抽象,但我们需要可部署的合约,因此必须正确调用。

修正后的合约代码

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract DamiKing is ERC20 {
    address public admin;
    event serverStatus(string serverMessage);

    // 先声明构造参数,再传递给ERC20父类构造函数
    constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) payable {
        _mint(msg.sender, 10000 * 10 ** decimals());
        admin = msg.sender;
    }

    // 补充原部署代码中调用的checkBalance方法
    function checkBalance(address account) public view returns (uint256) {
        return balanceOf(account);
    }
}

部署代码说明

你的deploy.js代码无需修改,调用deploy("damilare", "afo")会将参数正确传递给合约构造函数,部署后即可通过name()和symbol()方法获取动态设置的代币名称与符号。


内容的提问来源于stack exchange,提问作者Dami Hahfo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:20:22