我创建ERC20令牌,并希望将令牌传输到另一个地址。
我在元帐户中有两个帐户。(帐户A/B)
我的ERC20代码在这里(我在帐户A中部署并保存令牌)
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol";
contract MyToken is ERC20 {
constructor(string memory name, string memory symbol) ERC20(name,symbol) {
// mint 1000 token
_mint(msg.sender, 1000*10**uint(decimals()));
}
}
问题:如何将ERC20令牌从当前地址传输到另一个地址?(A->B)
我在帐户A中使用了这段代码,但不起作用。
pragma solidity ^0.8.7;
// SPDX-License-Identifier: MIT
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";
contract TokenTransfer {
IERC20 _token;
// token = MyToken's contract address
constructor(address token) public {
_token = IERC20(token);
}
// to = Account B's address
function stake(address to, uint amount) public {
_token.approve(address(this), amount);
require(_token.allowance(address(this), address(this)) >= amount);
_token.transferFrom(msg.sender, to, amount);
}
}
错误信息
transact to TokenTransfer.stake errored: Internal JSON-RPC error.
{
"code": 3,
"message": "execution reverted: ERC20: insufficient allowance",
"data": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001d45524332303a20696e73756666696369656e7420616c6c6f77616e6365000000"
}
怎么修呢?
发布于 2022-04-20 08:30:13
你的逻辑是错的!如果您想在不传递智能契约的情况下将令牌从帐户A发送到帐户B,则可以使用Metamask和其他钱包中的“send”选项。如果您想要使用智能契约,那么您的逻辑就会改变。在智能合同代码中,有一些错误:
当您编写此语句时,您正在批准智能契约本身移动您的令牌,但它没有任何令牌!关于approve()
函数的另一件事。这一操作必须从用户做起,在细节上,一个人必须给予智能合同许可才能访问他的钱包;
_token.transferFrom(msg.sender, to, amount);
,(msg.sender
是智能契约),您不能将任何金额转移到接收方地址,因为智能契约没有令牌的数量。
transfer()
函数而不是transferFrom()
时,因为最后一个函数需要批准+传输,而智能合同本身不能批准。而transfer()
只使用转帐资金。要解决此问题,您可以看到以下智能契约代码:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";
contract TokenTransfer {
IERC20 _token;
// token = MyToken's contract address
constructor(address token) {
_token = IERC20(token);
}
// Modifier to check token allowance
modifier checkAllowance(uint amount) {
require(_token.allowance(msg.sender, address(this)) >= amount, "Error");
_;
}
// In your case, Account A must to call this function and then deposit an amount of tokens
function depositTokens(uint _amount) public checkAllowance(_amount) {
_token.transferFrom(msg.sender, address(this), _amount);
}
// to = Account B's address
function stake(address to, uint amount) public {
_token.transfer(to, amount);
}
// Allow you to show how many tokens owns this smart contract
function getSmartContractBalance() external view returns(uint) {
return _token.balanceOf(address(this));
}
}
https://stackoverflow.com/questions/71941928
复制