Ethereum Address Explained with Code Examples

ยท

What is an Ethereum Address?

An Ethereum address is a unique identifier representing an externally owned account (EOA) or smart contract on the blockchain. Technically, it's a 20-byte hexadecimal value derived from the last 20 bytes of the Keccak-256 hash of a public key generated using ECDSA cryptography.

Types of Ethereum Accounts

1. Externally Owned Accounts (EOA)

2. Contract Accounts

Key Address Operations with Solidity Examples

1. Getting Contract Address

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

contract AddressDemo {
    function getContractAddress() external view returns(address) {
        return address(this); // Proper address conversion
    }
}
Important: Always use address() for explicit type conversion. Returning this directly causes compilation errors.

2. Retrieving msg.sender

function getSender() external view returns(address) {
    return msg.sender; // Returns current caller's address
}

msg.sender represents the immediate caller, which could be:

๐Ÿ‘‰ Learn more about Ethereum address security

3. Checking Account Balances

address owner;

constructor() {
    owner = msg.sender; // Sets deployer as permanent owner
}

function getBalances() external view returns(uint, uint, uint) {
    uint contractBalance = address(this).balance;
    uint callerBalance = msg.sender.balance;
    uint ownerBalance = owner.balance;
    return (contractBalance, callerBalance, ownerBalance);
}

Practical Considerations

  1. Permission Control: Store msg.sender in constructors for permanent owner records
  2. Balance Checks: Use .balance property to query ETH amounts
  3. Type Safety: Always verify address types in function returns

Frequently Asked Questions

Q: Can contract addresses initiate transactions?

A: No, only EOAs can initiate transactions. Contracts execute code in response to incoming transactions.

Q: Why does msg.sender change?

A: It's context-dependent โ€“ always reflects the immediate caller, whether it's a user or another contract.

Q: How are addresses generated for EOAs?

A: From private keys โ†’ public keys โ†’ Keccak-256 hash โ†’ last 20 bytes.

Q: Are Ethereum addresses case-sensitive?

A: Yes, but checksum addresses (with mixed case) help prevent input errors.

๐Ÿ‘‰ Discover advanced Ethereum development techniques

Security Best Practices

Remember: Addresses are fundamental to all Ethereum interactions, whether you're sending ETH, calling contracts, or implementing access control systems.