I'm starting to learn solidity, and I'm trying to build a sendEther contract where some address sends an amount of ether to another address. I'm building it on remix, and I'm having trouble while setting up the receiver's address. This is my code so far.
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
contract sendEther {
address payable public owner;
address payable public receiver;
uint256 public value;
error insufficientBalance();
error transferAlreadyCalled();
event Log(string message);
constructor() payable {
owner = payable(msg.sender);
}
modifier inBalance(address owner_) {
if (owner.balance < value) {
emit Log("Insufficient balance");
revert insufficientBalance();
_;
}
}
function transferEther() external payable {
owner = payable(msg.sender);
(
bool sent, /* bytes memory data */
) = owner.call{value: msg.value}("");
require(sent, "Failed to send Ether");
}
}
I'm struggling to understand how the owner.call()
will send ether to receiver since receiver wasn't set to any address. That said, how should I get the desired address input from the user?
how the
owner.call()
will send ether to receiver since receiver wasn't set to any address
It sends an internal transaction to the owner
address.
If you want the user to specify a custom receiver, you can define the receiver address as a param of the function:
function transferEther(address receiver) external payable {
payable(receiver).call{value: msg.value}("");
}
Mind that on the first line of the transferEther()
function body, you're owerwriting the existing owner
value with msg.sender
(the user executing the function). Which effectively just sends the funds back to the sender (plus sets them as the owner).
address payable public owner;
function transferEther() external payable {
// overwrite the existing `owner`
owner = payable(msg.sender);
// ...
// send ETH to the (new) `owner`
owner.call{value: msg.value}("");
You most likely wanted to omit the owner = ...
assigning.