Unit Utilities
Convert between Ethereum denominations (wei, gwei, ether) and human-readable formats
Convert between Ethereum denominations (wei, gwei, ether) and human-readable formats.
Overview
Ethereum uses wei as the base unit (1 ETH = 10^18 wei). These utilities help convert between different denominations.
| Unit | Wei | Symbol |
|---|---|---|
| Wei | 1 | wei |
| Gwei | 10^9 | gwei |
| Ether | 10^18 | ETH |
parseEther
Convert ETH to wei:
1import "github.com/ChefBingbong/viem-go/utils/unit"23// Parse "1.5" ETH to wei4wei, err := unit.ParseEther("1.5")5if err != nil {6 log.Fatal(err)7}8fmt.Println(wei.String())9// 1500000000000000000
formatEther
Convert wei to ETH string:
1wei := big.NewInt(1500000000000000000)23eth := unit.FormatEther(wei)4fmt.Println(eth)5// "1.5"
parseGwei
Convert gwei to wei (commonly used for gas prices):
1// Parse "20" gwei to wei2wei, err := unit.ParseGwei("20")3fmt.Println(wei.String())4// 20000000000
formatGwei
Convert wei to gwei string:
1wei := big.NewInt(20000000000)23gwei := unit.FormatGwei(wei)4fmt.Println(gwei)5// "20"
parseUnits
Convert a string to a big integer with custom decimals:
1// Parse USDC amount (6 decimals)2amount, err := unit.ParseUnits("100.50", 6)3fmt.Println(amount.String())4// 10050000056// Parse DAI amount (18 decimals)7amount, err = unit.ParseUnits("100.50", 18)8fmt.Println(amount.String())9// 100500000000000000000
formatUnits
Convert a big integer to a string with custom decimals:
1// Format USDC amount (6 decimals)2amount := big.NewInt(100500000)3formatted := unit.FormatUnits(amount, 6)4fmt.Println(formatted)5// "100.5"67// Format with more precision8amount = big.NewInt(100500001)9formatted = unit.FormatUnits(amount, 6)10fmt.Println(formatted)11// "100.500001"
Common Use Cases
Display Token Balance
// Fetch raw balance (in smallest unit)
balance, _ := token.BalanceOf(ctx, address)
// Get token decimals
decimals, _ := token.Decimals(ctx)
// Format for display
displayBalance := unit.FormatUnits(balance, int(decimals))
fmt.Printf("Balance: %s USDC\n", displayBalance)
Set Gas Price
// User inputs gas price in gwei
gasPriceGwei := "25.5"
gasPrice, _ := unit.ParseGwei(gasPriceGwei)
tx := &transaction.Transaction{
GasPrice: gasPrice,
// ...
}
Parse User Input for Transfer
// User wants to send 1.5 ETH
amountStr := "1.5"
amount, _ := unit.ParseEther(amountStr)
tx := &transaction.Transaction{
Value: amount,
// ...
}
Calculate Transaction Cost
gasUsed := big.NewInt(21000)
gasPrice := big.NewInt(20e9) // 20 gwei
// Cost in wei
cost := new(big.Int).Mul(gasUsed, gasPrice)
// Display in ETH
fmt.Printf("Cost: %s ETH\n", unit.FormatEther(cost))
// Cost: 0.00042 ETH
Error Handling
// Invalid input
_, err := unit.ParseEther("not-a-number")
if err != nil {
fmt.Println("Invalid input:", err)
}
// Too many decimal places
_, err = unit.ParseUnits("1.1234567", 6) // More than 6 decimals
if err != nil {
fmt.Println("Too many decimals:", err)
}