[英]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.