[英]How to modify a transfer function of an ERC20 token so that it takes a fee equal to 0.0004 ether for every token transfer
[英]how to take a our ERC20 token as fee to our products?
我有一种产品,如果消费者想购买我的产品,他需要支付 50 个 ERC20 代币。 如何编写这个智能合约以及如何知道他只支付了我的代币?
首先,用户需要通过对代币合约执行approve()
函数来手动批准您的合约以使用他们的代币。 这是一项安全措施,您可以在此答案或此其他答案中阅读有关其背后推理的更多信息。
然后,您的合约可以调用代币合约的transferFrom()
函数,向其传递参数,说明您希望将代币从用户转移到您的合约地址。
如果转账不成功(用户没有批准你的合约花费他们的代币或者没有足够的代币来执行转账),代币合约应该从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.