Buy Nft with erc20

Hello…! thanks for support ! here is my issue:
I have an erc721 collect with a function to create nft and get some pay in erc20

function createItem() public payable nonReentrant returns (uint256) {

    require(switchSale == true, "Closed");
    IERC20(address(0xe4671844Fcb3cA9A80A1224B6f9A0A6c2Ba2a7d5)).transfer(owner(), price);  

    _tokenIds.increment();
    uint256 newItemId = _tokenIds.current();


     nextToken();

    address tokenAddress = address(this);


    Items[newItemId] = Item(newItemId,  msg.sender, "https://ipfs.moralis.io:2053/ipfs/QmfUXxUrR3uvRMbN9g8RVU8ewxePNydauZm3cF7qxBDjS9");

    _safeMint(msg.sender, newItemId);
    emit itemAdded(newItemId, tokenAddress);
  
    return newItemId;
}

My problems comes in frotend when i want to send the transaction with the tokens but i get errors what u recommend me?:

    const cootiesContract = await new web3.eth.Contract(abi.specialNftAbi, contractAddress)

const options = {

  type: "erc20",

  receiver: "0x069dFfD8D5E00952D956aEF824D3E3DcDadeEA63",

  amount: Moralis.Units.ETH(result.toString()),

  contractAddress: "0xe4671844Fcb3cA9A80A1224B6f9A0A6c2Ba2a7d5",

};


 const tx = {

     from: user.get('ethAddress'),

     gas: 100000,

     data:  Moralis.transfer(options).toEncodeAbi()

 }


      await cootiesContract.methods.createItem().send(tx).on('receipt', async (receipt: any) => { ...}

usually you need to approve the smart contract to transfer those tokens and then call the mint function

you can use .approve to do that approval

1 Like

yeah i try several solutions but im stuck in this

Hello friend.

  • You declared createItem as payable, when it shouldn’t be
  • transfer is for BNB/ETH transfers. You need to encode or import the ERC20 pattern and use transferFrom.
  • I think there is no need to approve if the contract is not to carry out token sales.
  • Put the @param of the value of the ERC20 token to be paid in the created market of the NFT. Paste it into the createItem function.

Finally, don’t forget what you are going to do with the tokens, whether to withdraw to your external account (withdraw function) or to sell in the contract itself (call uniswapV2). Each of the options are a different approach.

Remember to mark this answer as the correct one if it answers your question. Please keep asking so we can help you.

Italo Honorato
Blockchain Analyst

1 Like