简体   繁体   English

如何将我们的 ERC20 代币作为我们产品的费用?

[英]how to take a our ERC20 token as fee to our products?

I have one product if the consumer want to buy my product he needs to pay 50 ERC20 Tokens.我有一种产品,如果消费者想购买我的产品,他需要支付 50 个 ERC20 代币。 how to write this smart contract and how to know that he payed my tokens only ?如何编写这个智能合约以及如何知道他只支付了我的代币?

First, the user needs to manually approve your contract to spend their tokens by executing the approve() function on the token contract.首先,用户需要通过对代币合约执行approve()函数来手动批准您的合约以使用他们的代币。 This is a security measure, and you can read more about the reasoning behind it in this answer or this other answer .这是一项安全措施,您可以在此答案此其他答案中阅读有关其背后推理的更多信息。

Then, your contract can call the token contract's transferFrom() function, passing it arguments stating that you want to transfer tokens from the user, to your contract address.然后,您的合约可以调用代币合约的transferFrom()函数,向其传递参数,说明您希望将代币从用户转移到您的合约地址。

If the transfer not successful (the user has not approved your contract to spend their tokens or didn't have enough tokens to perform the transfer), the token contract should return false from the transferFrom() function, so you can validate the return value in a require() condition for example.如果转账不成功(用户没有批准你的合约花费他们的代币或者没有足够的代币来执行转账),代币合约应该从transferFrom()函数返回false ,这样你就可以验证返回值例如在require()条件下。

pragma solidity ^0.8;

interface IERC20 { // defining an interface of the (external) token contract that you're going to be interacting with
    function decimals() external view returns (uint8);
    function transferFrom(address _from, address _to, uint256 _amount) external returns (bool);
}

contract MyContract {
    function buy() external {
        IERC20 tokenContract = IERC20(address(0x123)); // the token contract address

        // reverts if the transfer wasn't successful
        require(
            tokenContract.transferFrom(
                msg.sender, // from the user
                address(this), // to this contract
                50 * (10 ** tokenContract.decimals()) // 50 tokens, incl. decimals of the token contract
            ) == true,
            'Could not transfer tokens from your address to this contract' // error message in case the transfer was not successful
        );
        
        // transfer was successful, rest of your code
    }
}

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

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