9

When creating the contract for minting NFTs using the erc-721 standard, I want to be able to accept payment from my own erc-20 token instead of 'ETH'.

How can this be accomplished?

1

2 Answers 2

11

You can edit the mint function require the user to transfer certain ERC-20 tokens in your mint function. You can define a price for the ERC-721 tokens in terms of the ERC-20 token, and perform a transferFrom on the ERC-20 contract.

Of course, the user should have to approve the ERC-721 contract as a spender. The code could look something like this.

contract MyNFT is ERC721 {
    address tokenAddress;
    uint256 price;

    constructor(address _tokenAddress, uint256 _price) ERC721("MyNFT", "NFT") {
        tokenAddress = _tokenAddress;
        price = _price;
    }

    function safeMint(address to, uint256 tokenId) public {
        ERC20(tokenAddress).transferFrom(msg.sender, address(this), price);
        _safeMint(to, tokenId);
    }
}

1

I would just add to the accepted answer that the approve function has to be called from outside the contract (from the frontend for example). It took my a couple of days to figure this out, so just adding it in case someone is also struggling with it.

1
  • can u share that code? Commented Feb 13, 2023 at 8:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.