ERC20支付处理
ERC20 Payment processing
我的智能合约出了什么问题,因为我收到“错误:无法估计气体;交易可能失败或可能需要手动气体限制”。在前端,我先调用 approveTokens() 然后再调用 acceptPayment()
pragma solidity ^0.8.11;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
contract PaymentProcessor {
address public owner;
IERC20 public token;
constructor(address _owner, address _token) {
owner = _owner;
token = IERC20(_token);
}
event PaymentCompleted(
address payer,
uint256 amount,
uint paymentId,
uint timestamp
);
function approveTokens(uint256 amount) public returns(bool){
token.approve(owner, amount);
return true;
}
function getAllowance() public view returns(uint256){
return token.allowance(msg.sender, owner);
}
function acceptPayment(uint256 amount, uint paymentId) payable public {
require(amount > getAllowance(), "Please approve tokens before transferring");
token.transfer(owner, amount);
emit PaymentCompleted(msg.sender, amount, paymentId, block.timestamp);
}
}
用户需要直接在 token
地址上调用 approve()
,而不是通过您的合约。
您当前的实施批准 owner
花费 PaymentProcessor
的代币,因为 PaymentProcessor
是 token
合同上下文中的 msg.sender
。
我的智能合约出了什么问题,因为我收到“错误:无法估计气体;交易可能失败或可能需要手动气体限制”。在前端,我先调用 approveTokens() 然后再调用 acceptPayment()
pragma solidity ^0.8.11;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
contract PaymentProcessor {
address public owner;
IERC20 public token;
constructor(address _owner, address _token) {
owner = _owner;
token = IERC20(_token);
}
event PaymentCompleted(
address payer,
uint256 amount,
uint paymentId,
uint timestamp
);
function approveTokens(uint256 amount) public returns(bool){
token.approve(owner, amount);
return true;
}
function getAllowance() public view returns(uint256){
return token.allowance(msg.sender, owner);
}
function acceptPayment(uint256 amount, uint paymentId) payable public {
require(amount > getAllowance(), "Please approve tokens before transferring");
token.transfer(owner, amount);
emit PaymentCompleted(msg.sender, amount, paymentId, block.timestamp);
}
}
用户需要直接在 token
地址上调用 approve()
,而不是通过您的合约。
您当前的实施批准 owner
花费 PaymentProcessor
的代币,因为 PaymentProcessor
是 token
合同上下文中的 msg.sender
。