繁体   English   中英

如何从EOA向合约发送以太币

[英]How to send ether from eoa to contract

我需要将以太币从外部账户发送至合同。 到目前为止,我发现的所有代码都像这样

contract Contract {
   mapping (address => uint) balances;

   event Transfer(address indexed _from, uint256 _value);

   function deposit() public returns (uint) {
      balances[msg.sender] += msg.value;
      Transfer(msg.sender, msg.value);
      return balances[msg.sender];
   }
}

但是我不明白它是如何工作的。 我认为应该是这样的:我们应该运行一些发送功能,该功能将使用当前合同地址,发件人地址和金额。

有人可以向我解释其背后的逻辑吗?

我也找到了与此逻辑相对应的解决方案

contract Contract {
   function pay() payable {}
}

而不是像这样从控制台调用它

var contract
Contract.deployed().then(function(instance) { contract = instance; })
contract.pay.sendTransaction({from: eoa_address,to: contract_address,value: web3.toWei(amount,"ether"), gas:1000000})

但是在这种情况下, sendTransaction函数在联系人外部调用。 this角度来看,合同内部有什么办法称呼它?

发送以太合约:

如果需要执行此功能,我们可以创建一个应付款功能

contract Contract {
   function do_somthing() payable {
action1
action2 
...
}
}

如果我们只想向合约发送以太币而不执行任何功能,那么我们将按照您在问题中介绍的方式定义后备功能:

contract Contract {
   function pay() payable {}
}

您之前提供的示例:合同合同{

   mapping (address => uint) balances;

   event Transfer(address indexed _from, uint256 _value);

   function deposit() public returns (uint) {
      balances[msg.sender] += msg.value;
      Transfer(msg.sender, msg.value);
      return balances[msg.sender];
   }
}

正在记录用户发送到合同的余额(此函数需要声明为最近的编译器为应付: function deposit() public payable returns

function deposit() payable returns (uint) {
      balances[msg.sender] += msg.value;
      Transfer(msg.sender, msg.value); 
      return balances[msg.sender];
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM