[英]Sending ERC20 tokens using the transfer function
I'm pretty new to programing in solidity and I'm currently trying to run a simple smart contract in Remix, seen bellow:我对 Solidity 编程很陌生,我目前正在尝试在 Remix 中运行一个简单的智能合约,如下所示:
pragma solidity ^0.8.0;
import "github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
contract Swap {
address public owner;
uint256 public balance;
event TransferReceived(address _from, uint _amount);
event TransferSent(address _from, address _destAddr, uint _amount);
constructor() {
owner = msg.sender;
}
receive() payable external {
balance += msg.value;
emit TransferReceived(msg.sender, msg.value);
}
function withdraw(uint amount, address payable destAddr) public {
require(msg.sender == owner, "Only owner can withdraw funds");
require(amount <= balance, "Insufficient funds");
destAddr.transfer(amount);
balance -= amount;
emit TransferSent(msg.sender, destAddr, amount);
}
function transferERC20(IERC20 token, address to, uint256 amount) public {
require(msg.sender == owner, "Only owner can withdraw funds");
uint256 erc20balance = token.balanceOf(address(this));
require(amount <= erc20balance, "balance is low");
token.transfer(to, amount);
emit TransferSent(msg.sender, to, amount);
}
}
While I can successfully send BNB and call the withdraw
function giving the value sent and my wallet address in the BSC testnet, I'm having issues when running the transferERC20
function.虽然我可以成功发送 BNB 并调用
withdraw
function 提供发送的值和我在 BSC 测试网中的钱包地址,但在运行transferERC20
function 时遇到问题。 The only output that I get when calling this method is the following message:我在调用此方法时得到的唯一 output 是以下消息:
Gas estimation errored with the following message (see below).
气体估计错误并显示以下消息(见下文)。 The transaction execution will likely fail.
事务执行可能会失败。 Do you want to force sending?
是否要强制发送? Internal JSON-RPC error.
内部 JSON-RPC 错误。 { "code": -32000, "message": "execution reverted" }
{“代码”:-32000,“消息”:“执行恢复”}
I've tried several different addresses that I found in the testnet.bscscan website for BNB while making sure that the contract had enough funds for transfering, but I had no success.我尝试了几个在 testnet.bscscan 网站上为 BNB 找到的不同地址,同时确保合约有足够的资金进行转账,但我没有成功。
Can someone suggest what might be going wrong in my contract/setup?有人可以建议我的合同/设置可能出了什么问题吗? Am I making this transfer properly?
我是否正确进行此转移?
fix constrcutor修复构造器
constructor() { // payable allows payment of ether with a call. owner = payable(msg.sender); }
make sure those require
statements are satisfied确保满足这些
require
语句
require(msg.sender == owner, "Only owner can withdraw funds"); require(amount <= balance, "Insufficient funds");
check that you are connected to correct network检查您是否连接到正确的网络
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.