Skip to Content
Solidity ExamplesEthereum Denominations

Ethereum Denominations and Address Types

This example demonstrates Ethereum’s various denominations (wei, gwei, ether) and the differences between address types.

// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract EthereumDenominations { // Ethereum denominations uint public constant WEI_IN_GWEI = 1e9; // 1 gwei = 10^9 wei uint public constant WEI_IN_ETHER = 1e18; // 1 ether = 10^18 wei // Address types address public immutable owner; // Regular address (cannot receive ether) address payable public treasury; // Payable address (can receive ether) // Track balances mapping(address => uint256) public balances; constructor() { owner = msg.sender; treasury = payable(msg.sender); // Convert regular address to payable } // Demonstrate wei conversions function convertWeiToGwei(uint256 _wei) public pure returns (uint256) { return _wei / WEI_IN_GWEI; // Convert wei to gwei } function convertWeiToEther(uint256 _wei) public pure returns (uint256) { return _wei / WEI_IN_ETHER; // Convert wei to ether } // Demonstrate address payable functionality receive() external payable { balances[msg.sender] += msg.value; } function withdrawToTreasury() public { require(msg.sender == owner, "Only owner can withdraw"); uint256 balance = address(this).balance; // Transfer to payable address (bool success, ) = treasury.call{value: balance}(""); require(success, "Transfer failed"); } // Demonstrate address conversion function updateTreasury(address _newTreasury) public { require(msg.sender == owner, "Only owner can update treasury"); treasury = payable(_newTreasury); // Convert regular address to payable } // Get contract balance function getBalance() public view returns (uint256) { return address(this).balance; } }

Key Concepts

  1. Ethereum Denominations

    • 1 ether = 10^9 gwei = 10^18 wei
    • Wei is the smallest denomination
    • All internal calculations use wei
    • Gas prices typically quoted in gwei
  2. Address Types

    • address: Cannot receive ether
    • address payable: Can receive ether
    • Regular addresses can be converted to payable using payable()
  3. Common Denominations Table

    UnitWei ValueWeiCommon Usage
    wei11Raw calculations
    kwei1e31,000Rarely used
    mwei1e61,000,000Rarely used
    gwei1e91,000,000,000Gas prices
    szabo1e121,000,000,000,000Legacy unit
    finney1e151,000,000,000,000,000Legacy unit
    ether1e181,000,000,000,000,000,000Main unit

Best Practices

  1. Always use wei for internal calculations
  2. Convert human-readable ether values to wei when accepting input
  3. Use address payable only when ether transfers are needed
  4. Always check return value of ether transfers
  5. Include fallback functions (receive()) to accept ether
Last updated on