【发布时间】:2021-10-05 02:51:18
【问题描述】:
如果消费者想要购买我的产品,我有一个产品,他需要支付 50 ERC20 代币。这个智能合约怎么写,怎么知道他只支付了我的代币?
【问题讨论】:
标签: blockchain ethereum solidity erc20
如果消费者想要购买我的产品,我有一个产品,他需要支付 50 ERC20 代币。这个智能合约怎么写,怎么知道他只支付了我的代币?
【问题讨论】:
标签: blockchain ethereum solidity erc20
首先,用户需要通过在代币合约上执行approve() 函数来手动批准您的合约以使用他们的代币。这是一项安全措施,您可以在this answer 或this other answer 中阅读更多有关其背后原因的信息。
然后,您的合约可以调用代币合约的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
}
}
【讨论】: