How to mint an NFT by paying token?

Hi everyone.
I am new in solidity. I just want to create a ERC721 contract to mint by ERC20 token. I written the contract like this:

    function creatCard() public payable returns (uint) {
        require(msg.value == 0.01 ether);
        uint _newCardId = cardId.current();
        _safeMint(msg.sender, _newCardId);
        idToOwner[_newCardId] = msg.sender;
        idToCard[_newCardId] = Cards(_newCardId,_getRandom(_newCardId, 100) + 1,_getRandom(_newCardId, 9),1,0);
        return _newCardId;

on the front end, I written by javascript like this:

async function mint() {
    var data = await myContract.methods.creatCard().send({
        gas: 2500000
    .on("transactionHash", function () {
    .on("receipt", function () {
    .on("confirmation", function () {
    .on("error", async function () {

I does work by paying 0.01 ether to mint a new card.

But I want to pay other token instead, such as BUSD or ERC20 I create, not ETH,
so, how can I update my code?

you need to use an interface

interface IERC20 {
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);


then do something like this in your code

IERC20 token;
function a(address _add) public onlyOwner {
token = IERC20(_add);

to transfer tokens you can use TransferFrom


do not forget to let the user approve tokens first

Thanks a lot, Team_X. I have solved the problem by your suggestion.

1 Like