简体   繁体   English

如何通过 msg.value 将以太币转入智能合约?

[英]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.

相关问题 如何在不使用设置 msg.value 的情况下将资金从 msg.sender(amount) 转移到收件人地址 - how to transfer fund from msg.sender(amount) to recipient address without using setting msg.value 无法从智能合约向 msg.sender 发送以太币 - Not able to send ether to msg.sender from smart contract msg.value 引发错误并且不会将 eth 发送到合同 - msg.value raises error and doesn't send eth to contract 调用super.owner()。transfer(msg.value)给出错误 - Call to super.owner().transfer(msg.value) giving errors 如何使用RPC / web3 / ether.js识别以太坊智能合约转让? - How to identify an Ethereum smart contract transfer using RPC / web3 / ether.js? Metamask 交易预计会在智能合约 function 上失败,该合约会批量进行以太币转账 - Metamask transaction is expected to fail on a Smart Contract function that batches ether transfer solidity中payable function如何通过msg.value方式收款? - How payable function in solidity receives money by msg.value method? 在智能合约上检索卡住的以太 - Retrieve stuck ether on smart contract opensea 拍卖智能合约如何在不存储以太币的情况下工作 - How opensea auction smart contract work without storing the ether 部署在 Polygon 链上时如何强制智能合约接受以太币 - How to force smart contract to accept ether when deployed on Polygon chain
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM