Nft Minter Dapp – 无法铸造NFT

huangapple go评论64阅读模式
英文:

Nft Minter Dapp - Unable to mint the nft

问题

I hard coded a NFT-minter dApp. I tried minting it on the Polygon Mumbai Testnet, but it seems like the NFT is not minting. Although the transaction was successful and I have the transaction hash, the NFT doesn't show up in the wallet.

Can anyone help me troubleshoot this issue?

我的智能合约代码 ->

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.1;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract MyNFTCollection is ERC721, Ownable {
    uint256 public constant MAX_NFTS = 10;
    uint256 public constant PRICE = 0.01 ether;
    uint256 public nextTokenId = 1;

    constructor() ERC721("MyNFTCollection", "MYNFT") {}

    function mint() public payable {
        require(nextTokenId < MAX_NFTS, "Maximum number of NFTs minted");
        require(msg.value >= PRICE, "Not enough Ether sent");

        _safeMint(msg.sender, nextTokenId);
        nextTokenId++;
    }

    function withdraw() public onlyOwner {
        uint256 balance = address(this).balance;
        payable(msg.sender).transfer(balance);
    }

}

App.js 文件代码 ->

import React, { useState } from 'react';
import Web3 from 'web3';
import { Container, Row, Col, Button, Navbar } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.css';
import MyNFTCollection from './contract/MyNFTCollection.json';
import img1 from './images/1.png';
import './App.css';

function App() {

  const [web3, setWeb3] = useState(null);
  const [contract, setContract] = useState(null);
  const [account, setAccount] = useState("");
  const [tokenOwned, setTokenOwned] = useState([]);
  const [error, setError] = useState("");

  const connectWeb3 = async () => {
    try{
      if(window.ethereum){
        const web3 = new Web3(window.ethereum);
        //await window.ethereum.enable();
        await window.ethereum.request({ method: 'eth_requestAccounts' });
        setWeb3(web3);
        const contract = new web3.eth.Contract(
          MyNFTCollection.abi, "0xD5C6ba7fD9AB133d8CfCE96bF144B152C218B107"
        );
        setContract(contract);
        const accounts = await web3.eth.getAccounts();
        setAccount(accounts[0]);
        const tokenOwned = await contract.methods
          .tokenOfOwner(accounts[0])
          .call();
        setTokenOwned(tokenOwned);
      }else{
        setError("Please install Metamask!");
      }
    }catch(err) {
      console.error(err);
      setError("Failed to connect to Ethereum network!");
    }
  };

  const buyToken = async() => {
    try{
      const result = await contract.methods.mint().send({
        from: account,
        value: web3.utils.toWei("0.01", "ether"),
      });
      console.log(result);
      setTokenOwned([...tokenOwned, result]);
    }catch(err){
      console.error(err);
    }
  };

  if(!web3){
    return(
      <div className="connect-web3">
        <Button variant="primary" onClick={connectWeb3}>Connect to Ethereum Network</Button>
        {error && <p>{error}</p>}
      </div>
    );
  }

  return (
    <>
      <Navbar bg="dark" varient="dark">
        <Navbar .Brand>&nbsp; Moon Monkey NFT </Navbar .Brand>
        <Navbar .Text>{account}</Navbar .Text>
      </Navbar>
      <br/>
      <Container className="my-nft">
        <Row className="justify-content-center">
          <Col xs={12} md={8} lg={6}>
            <Row className="justify-content-center">
              {[1,2,3,4,5,6,7,8,9].map((tokenId) => (
                <Col xs={12} md={6} lg={4} key={tokenId}>
                  <div className="nft-card">
                    <img
                      src={img1}
                      alt={`NFT #${tokenId}.png`}
                      width={200}
                      style={{marginBottom: "10px"}}
                    />
                  </div>
                </Col>
              ))}
            </Row>
            <br/>
            <div className="text-center">
              <Button variant="success" onClick={buyToken}>Buy NFT</Button>
              <p className="mt-2">
                Cost: 0.01 MATIC
              </p>
              <p>
                You own {tokenOwned.length}/{10} NFTs.{' '}
              </p>
            </div>
          </Col>
        </Row>
      </Container>
    </>
  );
}

export default App;
英文:

I hard coded a NFT-minter dApp. I tried minting it on the Polygon Mumbai Testnet, but it seems like the NFT is not minting. Although the transaction was successful and I have the transaction hash, the NFT doesn't show up in the wallet.

Can anyone help me troubleshoot this issue?

My Smart Contract Code ->

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
import &quot;@openzeppelin/contracts/token/ERC721/ERC721.sol&quot;;
import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;
contract MyNFTCollection is ERC721, Ownable {
uint256 public constant MAX_NFTS = 10;
uint256 public constant PRICE = 0.01 ether;
uint256 public nextTokenId = 1;
constructor() ERC721(&quot;MyNFTCollection&quot;, &quot;MYNFT&quot;) {}
function mint() public payable {
require(nextTokenId &lt; MAX_NFTS, &quot;Maximum number of NFTs minted&quot;);
require(msg.value &gt;= PRICE, &quot;Not enough Ether sent&quot;);
_safeMint(msg.sender, nextTokenId);
nextTokenId++;
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
}

App.js file code ->

import React, { useState } from &#39;react&#39;;
import Web3 from &#39;web3&#39;;
import { Container, Row, Col, Button, Navbar } from &#39;react-bootstrap&#39;;
import &#39;bootstrap/dist/css/bootstrap.css&#39;;
import MyNFTCollection from &#39;./contract/MyNFTCollection.json&#39;;
import img1 from &#39;./images/1.png&#39;
import &#39;./App.css&#39;;
function App() {
const [web3, setWeb3] = useState(null);
const [contract, setContract] = useState(null);
const [account, setAccount] = useState(&quot;&quot;);
const [tokenOwned, setTokenOwned] = useState([]);
const [error, setError] = useState(&quot;&quot;);
const connectWeb3 = async () =&gt; {
try{
if(window.ethereum){
const web3 = new Web3(window.ethereum);
//await window.ethereum.enable();
await window.ethereum.request({ method: &#39;eth_requestAccounts&#39; });
setWeb3(web3);
const contract = new web3.eth.Contract(
MyNFTCollection.abi, &quot;0xD5C6ba7fD9AB133d8CfCE96bF144B152C218B107&quot;
);
setContract(contract);
const accounts = await web3.eth.getAccounts();
setAccount(accounts[0]);
const tokenOwned = await contract.methods
.tokenOfOwner(accounts[0])
.call();
setTokenOwned(tokenOwned);
}else{
setError(&quot;Please install Metamask!&quot;);
}
}catch(err) {
console.error(err);
setError(&quot;Failed to connect to Ethereum network!&quot;);
}
};
const buyToken = async() =&gt; {
try{
const result = await contract.methods.mint().send({
from: account,
value: web3.utils.toWei(&quot;0.01&quot;, &quot;ether&quot;),
});
console.log(result);
setTokenOwned([...tokenOwned, result]);
}catch(err){
console.error(err);
}
};
if(!web3){
return(
&lt;div className=&quot;connect-web3&quot;&gt;
&lt;Button variant=&quot;primary&quot; onClick={connectWeb3}&gt;Connect to Ethereum Network&lt;/Button&gt;
{error &amp;&amp; &lt;p&gt;{error}&lt;/p&gt;}
&lt;/div&gt;
);
}
return (
&lt;&gt;
&lt;Navbar bg=&quot;dark&quot; varient=&quot;dark&quot;&gt;
&lt;Navbar .Brand&gt;&amp;nbsp; Moon Monkey NFT &lt;/Navbar .Brand&gt;
&lt;Navbar .Text&gt;{account}&lt;/Navbar .Text&gt;
&lt;/Navbar&gt;
&lt;br/&gt;
&lt;Container className=&quot;my-nft&quot;&gt;
&lt;Row className=&quot;justify-content-center&quot;&gt;
&lt;Col xs={12} md={8} lg={6}&gt;
&lt;Row className=&quot;justify-content-center&quot;&gt;
{[1,2,3,4,5,6,7,8,9].map((tokenId) =&gt; (
&lt;Col xs={12} md={6} lg={4} key={tokenId}&gt;
&lt;div className=&quot;nft-card&quot;&gt;
&lt;img
src={img1}
alt={`NFT #${tokenId}.png`}
width={200}
style={{marginBottom: &quot;10px&quot;}}
/&gt;
&lt;/div&gt;
&lt;/Col&gt;
))}
&lt;/Row&gt;
&lt;br/&gt;
&lt;div className=&quot;text-center&quot;&gt;
&lt;Button variant=&quot;success&quot; onClick={buyToken}&gt;Buy NFT&lt;/Button&gt;
&lt;p className=&quot;mt-2&quot;&gt;
Cost: 0.01 MATIC
&lt;/p&gt;
&lt;p&gt;
You own {tokenOwned.length}/{10} NFTs.{&quot; &quot;}
&lt;/p&gt;
&lt;/div&gt;
&lt;/Col&gt;
&lt;/Row&gt;
&lt;/Container&gt;
&lt;/&gt;
);
}
export default App;

答案1

得分: 1

虽然交易成功并且我有交易哈希,

如果您成功调用了 mint() 交易,
并且该交易已完成,
那么您已成功铸造了这个NFT
NFT的数据已存储在链上。

但NFT在钱包中不显示。

这是与铸造交易是否成功无关的问题。
这是因为与EVM兼容的钱包无法
(也不可能)
知道您感兴趣的每个代币的地址。
它可能知道一些非常流行/默认已建立的常见代币,
但不会知道任何全新的代币,
尤其是您刚部署的代币。

如果您使用MetaMask浏览器扩展程序,
请查看这篇文章

(选择“扩展”,然后选择“手动添加NFT”)

然后,您将看到如何导入您的NFT的逐步说明
通过使用您新智能合约的部署地址。
其他钱包遵循类似的模式。

英文:

> Although the transaction was successful and I have the transaction hash,

If you were able to invoke a mint() transaction,
and that has completed,
then you have minted this NFT successfully.
The data for the NFT is on chain.

> the NFT doesn't show up in the wallet.

This is a separate issue from whether or not the mint transaction was successful.
It is because EVM-compatible wallets do not
(and cannot possibly)
know the addresses of every single token that you are interested in.
It may know of a few common ones that are very popular/ established by default,
but not any brand new ones,
especially ones that you have just deployed.

If you are using the MetaMask browser extension,
check out this article

(select "Extension", then select "Adding NFTs manually")

And then you'll see step by steps instructions on how to import you NFT
by using the deployed address of your new smart contract.
Other wallets follow a similar pattern.

huangapple
  • 本文由 发表于 2023年5月22日 03:05:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76301477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定