Solidity Basics: Paying and Sending ETH in Smart Contracts

·

Introduction to ETH Transactions in Solidity

Solidity, Ethereum's programming language, enables smart contracts to handle Ether (ETH) transactions seamlessly. This guide explores foundational concepts for paying ETH to contracts and sending ETH from contracts using payable functions and transfer methods.


1. Contract Receiving ETH

To accept ETH payments, a contract must use the payable keyword:

pragma solidity >=0.7.0 <0.9.0;

contract Payable {
    address payable public owner; // Payable address can send/receive ETH

    constructor() {
        owner = payable(msg.sender);
    }

    // Payable function accepts ETH deposits
    function deposit() external payable {}

    function getBalance() external view returns (uint) {
        return address(this).balance;
    }
}

Key Features:

👉 Learn advanced Solidity techniques


2. Contract Sending ETH

Solidity offers three methods to send ETH:

Method 1: transfer()

_to.transfer(123);

Method 2: send()

bool sent = _to.send(123);
require(sent, "Send failed");

Method 3: call()

(bool success, ) = _to.call{value: 123}("");
require(success, "Call failed");

Example: ETH Receiver Contract

contract EthReceiver {
    event Log(uint amount, uint gas);

    receive() external payable {
        emit Log(msg.value, gasleft());
    }
}

Comparison of ETH Transfer Methods

MethodGas LimitReverts on Failure?Returns Data
transfer2300YesNo
send2300No (check bool)No
callAll gasNo (check bool)Yes (bytes data)

Best Practices for ETH Transactions

  1. Security: Use call with checks for reentrancy attacks.
  2. Gas Efficiency: Prefer transfer for fixed costs.
  3. Fallback Functions: Implement receive() to handle incoming ETH.

👉 Explore secure smart contract patterns


FAQs

Q1: Why does transfer revert on failure?

A: It ensures atomicity—either the full amount is sent or the transaction is canceled.

Q2: When should I use send() over transfer?

A: Rarely. send requires manual checks, while transfer automates failure handling.

Q3: Is call unsafe?

A: It can be vulnerable to reentrancy if not properly secured (e.g., using checks-effects-interactions).


Conclusion

Mastering ETH transactions in Solidity involves understanding payable addresses, gas costs, and transfer methods. Choose transfer for simplicity, call for flexibility, and always prioritize security audits.