【问题标题】:How can I use my erc20 custom token as required payment in my solidity contract?如何在我的 Solidity 合约中使用我的 erc20 自定义代币作为所需付款?
【发布时间】:2022-06-12 09:33:37
【问题描述】:

我创建了一个自定义 ERC20 代币,目前已部署在测试网上,未来将在多边形上启动。

团结

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

我想用我的自定义令牌代替以太币。我该怎么做?有什么直接的方法吗?如果想使用 react dapp,我该怎么做? 目前对于以太坊,我的 react dapp 配置如下-

"WEI_COST":  1000000000000000,

请帮忙。

【问题讨论】:

    标签: blockchain ethereum solidity polygon erc20


    【解决方案1】:

    您可以与允许您处理 ERC20 令牌的IERC20 接口进行交互。要解决您的问题,您可以查看以下智能合约代码:

    // 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));
        }
    } 
    

    我做了一些笔记,以便你更好地理解我所做的事情。

    注意:当你调用depositToken()函数时记得approve你的智能合约允许它访问你的钱包并转移代币。

    【讨论】:

    • 我试图从我的合同中调用批准功能,但它不起作用
    【解决方案2】:

    您可以批准智能合约转移您的自定义代币。

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

    【讨论】:

      猜你喜欢
      • 2023-01-16
      • 1970-01-01
      • 2018-07-05
      • 2020-12-17
      • 2021-08-14
      • 2022-01-01
      • 2021-10-05
      • 1970-01-01
      • 2018-12-26
      相关资源
      最近更新 更多