PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 28, 2022

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

 July 28, 2022     blockchain, erc20, ethereum, polygon, solidity     No comments   

Issue

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.


Solution

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.



Answered By - Kerry99
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing