简体   繁体   English

如何在我的 Solidity 合约中使用我的 erc20 自定义代币作为所需付款?

[英]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.我创建了一个自定义 ERC20 代币,目前已部署在测试网上,未来将在多边形上启动。

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?如果想使用 react dapp,我该怎么做? Currently for Ethereum, my react dapp is configured as follow-目前对于以太坊,我的 react dapp 配置如下-

"WEI_COST":  1000000000000000,

Please help.请帮忙。

You can interact with IERC20 interface that allows you to handle ERC20 token.您可以与允许您处理 ERC20 令牌的IERC20接口进行交互。 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.注意:当您调用depositToken()函数时,请记住approve您的智能合约,以允许其访问您的钱包并转移代币。

You can approve the smart contract to transfer your custom token.您可以批准智能合约来转移您的自定义代币。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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