[英]How to transfer ether to smart contract by msg.value?
I want to transfer some ether form my address to the smart contract, I have tried the code below but it doesn't work.我想将一些以太币从我的地址转移到智能合约,我尝试了下面的代码,但它不起作用。 How to transfer ether through msg.sender?
如何通过 msg.sender 转移以太币?
pragma solidity >=0.7.0 <0.9.0;
contract Test {
function testTransfer() external payable {
bool sent = payable(address(this)).send(msg.value);
require(sent, "invalid balance");
}
}
Once I trigger the function with the value of 1 ether, the error output is as below:一旦我用 1 ether 的值触发函数,错误输出如下:
I'm sure that I have enough Ether in my address.我确定我的地址中有足够的以太币。 What should I do to transfer the Ether?
我应该怎么做才能转移以太币? Thanks!
谢谢!
The transaction fails because the smart contract is trying to transfer the ether to himself, and the smart contract doesn't have defined the receive function so it can receive ether that way, for your example you could simply remove all the code inside the function and make another function to check the contract balance and it will work交易失败是因为智能合约试图将以太币转移给自己,而智能合约没有定义接收函数,因此它可以通过这种方式接收以太币,例如,您可以简单地删除函数内的所有代码并制作另一个功能来检查合同余额,它将起作用
pragma solidity >=0.7.0 <0.9.0;
contract Test {
function testTransfer() external payable {}
function getBalance() external view returns (uint256) {
return address(this).balance;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.