简体   繁体   中英

How can I use my erc20 custom token as required payment in my solidity contract?

I have created a custom ERC20 token and that is currently deployed on testnet and will launch it on polygon in future.

Solidity

 uint256 public cost = 0.001 ether;
 function test(uint256 _mintAmount) public payable {
               require(msg.value >= cost * _mintAmount);
               //some code
    }

I want to use my custom token in place of ether. How do I do it? Is there any straight forward way for it? And if want to use a react dapp how may I do that? Currently for Ethereum, my react dapp is configured as follow-

"WEI_COST":  1000000000000000,

Please help.

You can interact with IERC20 interface that allows you to handle ERC20 token. To solve your issue you can see this smart contract code:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract MintWithERC20 {
    IERC20 token;
    uint256 public cost = 1 * 10**18;

    // NOTE: Pass it the token address that your contract must accept like deposit 
    constructor(address _addressToken) {
        token = IERC20(_addressToken);
    }

    // NOTE: Deposit token that you specificied into smart contract constructor 
    function depositToken(uint _amount, uint _mintAmount) public {
        require(_amount >= cost * _mintAmount);
        token.transferFrom(msg.sender, address(this), _amount);
    }

    // NOTE: You can check how many tokens have your smart contract balance   
    function getSmartContractBalance() external view returns(uint) {
        return token.balanceOf(address(this));
    }
} 

I put some notes for understand to you better what I done.

Attention: When you'll call depositToken() function remember to approve your smart contract for give it permission to access in your wallet and transfer the tokens.

You can approve the smart contract to transfer your custom token.

//approving smart contract to transfer token token.approve(address(this), _amount);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM