React中Ethers.js调用ERC1155 mint函数地址参数报错的解决方法
问题:Ethers.js调用ERC1155合约mint函数时地址参数错误
问题场景
在React应用中使用Ethers.js编写handleMint()函数,调用基于ERC1155标准的智能合约mint方法时,传递参数出现错误。
React端代码
async function handleMint1() { console.log(props.accounts) if (window.ethereum) { const provider = new ethers.providers.Web3Provider(window.ethereum); const signer = provider.getSigner(); const contract = new ethers.Contract( charlesWhitsteenProjectAddress, charlesWhitsteenProjectNFT.abi, signer ); try { const response = await contract.mint(props.accounts, BigNumber.from('1'), BigNumber.from(mintAmount1), { value: ethers.utils.parseEther((0.01 * mintAmount1).toString()) }); console.log('response: ', response); } catch (err) { console.log('error: ', err) } } }
注:props.accounts为已连接的钱包地址,BigNumber.from('1')是token ID,BigNumber.from(mintAmount1)是铸造数量。
Solidity合约mint函数
function mint(address _recipient, uint256 _tokenId, uint256 _amount) public payable { if(whitelistedAddresses[msg.sender] == 0) { require(mintEnabled, "Minting has not been enabled."); require(msg.value == _amount * mintPrice, "Incorrect mint value."); } else { require(whitelistGiveaway, "Whitelist giveaway has not been enabled"); require(isValid(_tokenId) == true, "Whitelist giveaway is no longer valid."); whitelistedAddresses[msg.sender] -= _amount; } require(_amount >= 1, "please enter a valid number"); require(totalSupply[_tokenId] + _amount <= maxSupply, "Sorry, you have exceeded the supply."); require(tokenIdMints[msg.sender][_tokenId] + _amount <= maxPerTokenId, "Sorry, you have exceeded the alotted amount per token ID."); totalSupply[_tokenId] += _amount; tokenIdMints[msg.sender][_tokenId] += _amount; _mint(_recipient, _tokenId, _amount, ""); }
报错信息
error: Error: invalid address or ENS name (argument="name", value=["0x.."], code=INVALID_ARGUMENT, version=contracts/5.6.2)
解决方法
报错原因是props.accounts是数组类型(格式为["0x..."]),但合约mint函数第一个参数需要的是单个address类型的值。
修改步骤
- 直接取
props.accounts数组的第一个元素作为收款地址传入:
const response = await contract.mint( props.accounts[0], // 提取数组中第一个地址 BigNumber.from('1'), BigNumber.from(mintAmount1), { value: ethers.utils.parseEther((0.01 * mintAmount1).toString()) } );
- 可选:增加钱包连接状态判断,避免数组为空的情况:
if (!props.accounts || props.accounts.length === 0) { console.log("请先连接钱包"); return; }
内容的提问来源于stack exchange,提问作者Damon
相关产品推荐
相关产品推荐

