Branded types representing Ethereum denominations. Wei is a branded bigint (whole numbers only). Ether and Gwei are branded string types that support decimal values like "1.5". Each denomination prevents accidental unit mixing at compile time while enabling seamless conversions.
import * as Wei from 'tevm/Wei'import * as Gwei from 'tevm/Gwei'import * as Ether from 'tevm/Ether'// Create valuesconst wei = Wei(1_000_000_000n) // 1 Gwei in Wei (bigint)const gwei = Gwei("21") // 21 Gwei (string - supports decimals)const ether = Ether("1.5") // 1.5 Ether (string - supports decimals)// Convert between unitsconst weiFromGwei = Gwei.toWei(gwei) // 21_000_000_000n Weiconst gweiFromEther = Ether.toGwei(ether) // "1500000000" Gweiconst etherFromWei = Wei.toEther(wei) // "0.000000001" Ether (preserves precision)// Type safety prevents mixingconst total = wei + gwei // ✗ Type error - cannot mix Wei and Gwei
Copy
Ask AI
import * as Wei from 'tevm/Wei'import * as Gwei from 'tevm/Gwei'import * as Uint from 'tevm/Uint'// Gas price in Gwei (common format)const gasPriceGwei = Gwei("50") // 50 Gwei// Convert to Wei for calculationconst gasPriceWei = Gwei.toWei(gasPriceGwei)// Calculate total cost: gasPrice * gasUsedconst gasUsed = Uint(21_000n)const txCostWei = Uint.times(gasPriceWei, gasUsed)// Convert to Ether for displayconst txCostEther = Wei.toEther(Wei(txCostWei))console.log(`Cost: ${txCostEther} ETH`) // "0.00105"
Copy
Ask AI
import * as Ether from 'tevm/Ether'import * as Wei from 'tevm/Wei'// User inputs value in Ether with decimalsconst valueEther = Ether("0.5") // 0.5 ETH// Transaction requires Weiconst valueWei = Ether.toWei(valueEther) // 500_000_000_000_000_000n Weiconst tx = { to: "0x...", value: valueWei, // Wei.Type ensures correct unit gasPrice: Gwei.toWei(Gwei("50"))}
Ether and Gwei use decimal strings to preserve fractional values:
Copy
Ask AI
import * as Wei from 'tevm/Wei'import * as Ether from 'tevm/Ether'// 500 Wei = 0.0000000000000005 Etherconst wei = Wei(500n)const ether = Wei.toEther(wei) // "0.0000000000000005" (preserved)// Fractional Ether supported nativelyconst fractional = Ether("1.5")const weiValue = Ether.toWei(fractional) // 1_500_000_000_000_000_000n
Round-trip conversions preserve full precision:
Copy
Ask AI
import * as Wei from 'tevm/Wei'import * as Ether from 'tevm/Ether'const originalWei = Wei(1_500_000_000_000_000_000n) // 1.5 Ether in Wei// Convert to Ether and backconst etherValue = Wei.toEther(originalWei) // "1.5"const backToWei = Ether.toWei(etherValue) // 1_500_000_000_000_000_000nconsole.log(originalWei === backToWei) // true - no precision loss