Lesson 14 of 25
Ether & Wei
Denominations of ETH, sending and receiving ether, and balance tracking.
IntermediateDenominations
Ether has multiple denominations. All values in Solidity are denominated in wei (the smallest unit) by default. Solidity provides built-in literals.
Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Denominations {
// Built-in unit literals
uint256 public oneWei = 1 wei; // 1
uint256 public oneGwei = 1 gwei; // 1_000_000_000
uint256 public oneEther = 1 ether; // 1_000_000_000_000_000_000
function toWei(uint256 _ether) public pure returns (uint256) {
return _ether * 1 ether;
}
function toEther(uint256 _wei) public pure returns (uint256) {
return _wei / 1 ether; // Note: integer division — loses decimals
}
}
Checking Balances
Every address has a balance. Use
address(this).balance for the contract's balance, or address(user).balance for any externally owned account.
Solidity
contract BalanceChecker {
function contractBalance() public view returns (uint256) {
return address(this).balance;
}
function accountBalance(address user) public view returns (uint256) {
return user.balance;
}
function isRich(address user) public view returns (bool) {
return user.balance >= 100 ether;
}
}
Sending Ether — Three Methods
There are three ways to send ETH from a contract. The recommended method is
call.
Solidity
contract SendEther {
// ❌ transfer() — hard 2300 gas limit, can fail with smart contract recipients
function sendViaTransfer(address payable to) public payable {
to.transfer(msg.value);
}
// ❌ send() — returns false instead of reverting, easy to miss errors
function sendViaSend(address payable to) public payable {
bool sent = to.send(msg.value);
require(sent, "Send failed");
}
// ✅ call() — recommended, forwards all gas, check return value
function sendViaCall(address payable to) public payable {
(bool success, ) = to.call{value: msg.value}("");
require(success, "Call failed");
}
}