< Back
Transfer Ether (#10) Solution
Sidd

We are given a function transfer, where we must transfer _amount ether from the contract to address payable _to. Here's one approach to solving this problem:

pragma solidity ^0.8.4;

contract Solution {
    event EtherTransferred(address indexed _to, uint256 _amount);

    function transfer(address payable _to, uint256 _amount) public {
        require(_amount <= address(this).balance, "Insufficient balance");
        _to.transfer(_amount);
        emit EtherTransferred(_to, _amount);
    }

    function getBalance(address payable _address) public payable returns (uint256) {
        return _address.balance;
    }
}

Let's look at the transfer function. First, we add a require statement, which checks if the contract has enough balance to perform the transfer. This can be done by comparing the _amount variable to address(this).balance (the contracts balance). If there is enough balance, we can use Solidity's built-in function transfer which transfers ether from the current contract to the specified address _to. The amount of ether transferred is specified by _amount. Our last remaining task is to add an event that emits when ether is transferred. As per the problem description: "The event should include the amount of ether transferred and the address it was transferred to.". To do this first lets create an event, in this case we are calling it EtherTransferred(address indexed _to, uint256 _amount). This creates an event that can be listened to on the Ethereum network. It takes two arguments: the address that the ether was transferred to and the amount transferred. Now that we have created the event, we can emit it in our function. We can simply use the emit keyword followed by the event name and it's respective arguments, _to and _amount.

This function can be used primarily to send payments: Purchase goods or services, Refunds for a specific transaction, Token swaps, Rewarding users, or Donations.

Comments: 0

Be the first to comment...