04 Sep 2024
Kotlin Multiplatform (KMP) lets you write code once in Kotlin and use it on Android, iOS, desktop, web and server. For mobile apps, the usual approach is to share the business logic (networking, data storage, validation, state) and keep each platform’s UI native, though you can also share the UI with Compose Multiplatform. This guide explains how a KMP project is structured, how shared code reaches each platform, the libraries you’ll use, and when KMP is a better fit than React Native or Flutter.
I first wrote about KMP in 2024, mostly listing its benefits. Since then it has matured a lot, so I rewrote the post to show how it actually works.
Where KMP stands
- KMP has been stable since Kotlin 1.9.20 in late 2023.
- Google officially supports KMP for sharing business logic between Android and iOS, and several Jetpack libraries now publish multiplatform versions, including Room, DataStore, ViewModel and Lifecycle.
- Compose Multiplatform for iOS reached stable in 2025, so sharing UI is now a supported option too.
How a project is structured
A typical mobile KMP project has three parts:
my-app/
├── shared/ # Kotlin Multiplatform module
│ └── src/
│ ├── commonMain/ # code for all platforms
│ ├── androidMain/ # Android-specific implementations
│ └── iosMain/ # iOS-specific implementations
├── androidApp/ # regular Android app, depends on :shared
└── iosApp/ # Xcode project, uses the shared framework
The Kotlin compiler builds shared into a normal Android library for the Android app (running on the JVM/ART) and into a native framework for iOS through Kotlin/Native. Your iOS code imports that framework like any other Swift dependency. There’s no JavaScript bridge and no runtime interpreter: on iOS, shared Kotlin code is compiled to native machine code.
Most of your code goes in commonMain, which can only use multiplatform libraries and the Kotlin standard library. Platform folders exist for the parts that genuinely differ.
expect and actual
When common code needs something only the platform provides, declare it with expect in commonMain and implement it with actual in each platform folder:
// commonMain
expect fun platformName(): String
class Greeting {
fun greet(): String = "Hello from ${platformName()}"
}
// androidMain
actual fun platformName(): String = "Android ${android.os.Build.VERSION.SDK_INT}"
// iosMain
import platform.UIKit.UIDevice
actual fun platformName(): String =
UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
In iosMain, you can call Apple’s frameworks (UIKit, Foundation and others) directly from Kotlin. In practice, I’d keep expect/actual for small, low-level pieces. For bigger platform differences, define an interface in common code and pass in a platform implementation, which is easier to test and to fake.
Libraries you’ll actually use
You can’t use Android-only or JVM-only libraries (Retrofit, Gson, OkHttp) in commonMain. The multiplatform equivalents:
| Need |
Library |
| HTTP client |
Ktor client |
| JSON |
kotlinx.serialization |
| Async |
kotlinx.coroutines and Flow |
| Database |
Room (multiplatform) or SQLDelight |
| Key-value storage |
DataStore |
| Dates and times |
kotlinx-datetime |
| Dependency injection |
Koin, or manual DI |
| Shared ViewModels |
androidx.lifecycle ViewModel |
A shared repository then looks like ordinary Kotlin:
@Serializable
data class Article(val id: String, val title: String)
class ArticleRepository(private val client: HttpClient) {
suspend fun latest(): List<Article> =
client.get("https://api.example.com/articles").body()
}
Calling shared code from Swift
From Swift, the shared module looks like an Objective-C framework. Classes, functions and data classes work as you’d expect. A few things need attention:
- Suspend functions are exposed to Swift as
async functions (and as completion handlers), so try await repository.latest() works.
- Flows don’t map to anything in Swift out of the box. Most teams use SKIE or KMP-NativeCoroutines, which turn them into Swift
AsyncSequences.
- Sealed classes, generics and default arguments lose some of their expressiveness on the way through Objective-C. SKIE fixes several of these. JetBrains is also working on direct Swift export, which will remove the Objective-C layer.
That interop layer is where iOS developers on the team will form their opinion of KMP, so it’s worth making the shared API pleasant to use from Swift.
With Compose Multiplatform, the same Compose code you write for Android can render on iOS, desktop and web. If your team already writes Jetpack Compose, the learning curve is small.
You don’t have to choose all or nothing. A common path is to share logic first, keep native UIs, and then share individual screens where the design is the same on both platforms. Compose screens can be embedded in a SwiftUI app and SwiftUI views in a Compose screen.
KMP compared with React Native and Flutter
I work with both Kotlin and React Native, and they solve different problems:
| |
KMP |
React Native |
Flutter |
| Language |
Kotlin |
TypeScript/JavaScript |
Dart |
| What’s shared |
Logic by default, UI optional |
Logic and UI |
Logic and UI |
| UI |
Native, or Compose Multiplatform |
Native components driven from JS |
Its own rendering engine |
| Adopting in an existing native app |
Module by module |
Possible but more work |
Possible but more work |
| Best fit |
Teams with Android/Kotlin skills, apps with existing native code |
Teams with web/React skills |
Teams starting fresh that want one UI everywhere |
KMP’s biggest practical advantage is incremental adoption. You can add one shared module (say, your API client and models) to an existing Android and iOS app without rewriting anything else. That’s much harder to do with React Native or Flutter, which want to own the screen.
When to choose KMP
KMP is a good choice when:
- your team already knows Kotlin, especially Android developers;
- you have existing native Android and iOS apps and want to stop writing the same logic twice;
- you want native UIs, or want to decide screen by screen whether to share UI;
- you need direct access to platform APIs without writing bridges.
It’s a weaker fit when your team is mostly web developers (React Native will feel more natural), or when your iOS team doesn’t want to work with Kotlin at all. KMP works best when both platforms’ developers treat the shared module as their code.
The official Kotlin Multiplatform getting started guide sets up a project in a few minutes. If you’re weighing KMP against React Native, my post on Jetpack Compose and React Native similarities compares the two UI models.
02 Aug 2023
An Android app can read data from an ERC-20 token, like a user’s balance, without any blockchain SDK: it sends a JSON-RPC eth_call to an Ethereum node and decodes the result. Sending tokens is a different problem, because it needs a signed transaction and a private key that your app shouldn’t hold. This guide shows how to read a balance in Kotlin, how the ABI encoding works under the hood, and how to handle writes safely.
The first version of this post, from 2023, wasn’t really about Android. It described a Node.js GraphQL server and called a web3.eth.getToken method that doesn’t exist in web3.js. I rewrote it around what an Android developer actually needs.
How an app talks to Ethereum
Your app never connects to “the blockchain” directly. It talks to an Ethereum node over JSON-RPC, a simple protocol where you POST a JSON request and get JSON back. Most apps use a hosted node provider such as Infura, Alchemy or QuickNode rather than running their own.
For reading data, the method you need is eth_call. It runs a contract function on the node without creating a transaction, so it’s free and returns immediately. (My Solidity fundamentals guide explains the difference between calls and transactions in more detail.)
Encoding the call
Contracts don’t receive function names. They receive calldata: a 4-byte function selector followed by the arguments, each padded to 32 bytes. The selector is the first 4 bytes of the keccak-256 hash of the function signature.
For the ERC-20 functions you’ll use most:
| Function |
Selector |
balanceOf(address) |
0x70a08231 |
decimals() |
0x313ce567 |
symbol() |
0x95d89b41 |
transfer(address,uint256) |
0xa9059cbb |
So balanceOf(0xAbC…123) becomes 0x70a08231 followed by the address without its 0x, left-padded with zeros to 64 hex characters. The node returns the balance as a 32-byte hex number.
Reading a balance in Kotlin
Here’s a small client using OkHttp and coroutines. It doesn’t need any web3 library:
class Erc20Reader(
private val rpcUrl: String,
private val http: OkHttpClient = OkHttpClient()
) {
suspend fun balanceOf(token: String, owner: String): BigInteger {
val data = "0x70a08231" + owner.removePrefix("0x").lowercase().padStart(64, '0')
return ethCall(token, data).toBigInteger()
}
suspend fun decimals(token: String): Int =
ethCall(token, "0x313ce567").toBigInteger().toInt()
private suspend fun ethCall(to: String, data: String): String = withContext(Dispatchers.IO) {
val payload = JSONObject()
.put("jsonrpc", "2.0")
.put("id", 1)
.put("method", "eth_call")
.put("params", JSONArray()
.put(JSONObject().put("to", to).put("data", data))
.put("latest"))
val request = Request.Builder()
.url(rpcUrl)
.post(payload.toString().toRequestBody("application/json".toMediaType()))
.build()
http.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("HTTP ${response.code}")
val json = JSONObject(response.body?.string() ?: throw IOException("Empty body"))
json.optJSONObject("error")?.let { throw IOException(it.optString("message")) }
json.getString("result")
}
}
private fun String.toBigInteger(): BigInteger =
BigInteger(removePrefix("0x").ifEmpty { "0" }, 16)
}
A few details worth pointing out:
- The network call runs on
Dispatchers.IO, so balanceOf is safe to call from a ViewModel on the main thread.
- JSON-RPC errors come back with HTTP 200 and an
error object, so checking the status code isn’t enough.
- Balances can exceed
Long, so use BigInteger. A token with 18 decimals and a few million units already overflows a Long.
Turning units into a readable amount
ERC-20 balances are integers. A token with 18 decimals stores 1.5 tokens as 1500000000000000000. Convert with BigDecimal before showing anything to the user, never with Double:
fun formatTokenAmount(raw: BigInteger, decimals: Int): String =
BigDecimal(raw)
.movePointLeft(decimals)
.setScale(minOf(decimals, 4), RoundingMode.DOWN)
.stripTrailingZeros()
.toPlainString()
formatTokenAmount(BigInteger("1500000000000000000"), 18) returns "1.5". Round down for balances, so you never show a user more than they can actually send. And always read decimals() from the contract: USDC and USDT use 6, most other tokens use 18.
Using it from a ViewModel
class WalletViewModel(private val reader: Erc20Reader) : ViewModel() {
private val _balance = MutableStateFlow<String?>(null)
val balance: StateFlow<String?> = _balance.asStateFlow()
fun refresh(token: String, owner: String) {
viewModelScope.launch {
_balance.value = try {
val raw = reader.balanceOf(token, owner)
formatTokenAmount(raw, reader.decimals(token))
} catch (e: IOException) {
null
}
}
}
}
decimals() never changes for a given token, so in a real app you’d cache it instead of fetching it on every refresh. For live updates, either poll on an interval while the screen is visible or subscribe to the token’s Transfer events through a WebSocket provider.
Don’t ship your RPC key
Hosted node URLs usually contain an API key, like https://mainnet.infura.io/v3/YOUR_KEY. Anything inside an APK can be extracted, so a key in BuildConfig is effectively public. Someone can copy it and burn through your quota.
Options, from simplest to most robust:
- Restrict the key in the provider’s dashboard: most providers let you allowlist contract addresses and JSON-RPC methods and set rate limits.
- Put a small backend in front of the node that forwards only the calls your app needs.
- Use a public RPC endpoint for low-volume reads, accepting lower reliability.
Writing: let a wallet sign
Reading is free and needs no keys. Transferring tokens means sending a transaction to transfer(address,uint256), which must be signed with the user’s private key and pay gas.
Don’t generate or store users’ private keys in your app unless building a wallet is your product. Key storage, backup and recovery are hard, and a bug can lose people’s money for good. The usual approaches:
- Connect to the user’s wallet with WalletConnect (now Reown). Your app builds the transaction, the wallet app shows it to the user and signs it, and you get back the transaction hash.
- Do it on a backend, when the app’s operator is the one sending tokens, for example rewards. The backend holds its own key in a secrets manager and the app just calls an API.
My Nomad Token hackathon project used the second approach: the Android app called a Node.js backend that used ethers.js to talk to the contracts, and the contracts sent ERC-20 reward tokens to users’ wallets.
Where to go from here
Hand-encoding calls is fine for a few read-only functions and helps you understand what’s going on. Once you need many contract functions, events or transaction signing, use a library: web3j can generate type-safe Kotlin or Java wrappers from a contract’s ABI.
For how ERC-20 compares with NFT standards like ERC-721 and ERC-1155, see my guide to Ethereum token standards. The JSON-RPC reference on ethereum.org lists every method a node supports.
28 Jun 2023
Introduction
No significant change happened to the $1.9 trillion travel industry. The pandemic led to unprecedented low travel volumes and financial strain, and all those business trips year-round are now 30-minute Zoom meetings.
The travel and hospitality industries (and their customers) are stuck with dated solutions, where online booking, cheap flight platforms, and lousy loyalty mechanics are not sufficing modern travelers and modern challenges and needs. Nomad rethinks the role of blockchain, empowering travelers and companies alike with unprecedented opportunities and creating a harmonious ecosystem that fosters trust, transparency, and unforgettable experiences.
What it does
The user’s journey starts when he/she decides to book a flight. To do so, the user can install the Nomad App and check the flights available. Due to the hackathon, we are using a specific flight (YYC - SEA) as a use case but the project can be more flexible and include more flight legs.
The app’s home screen integrates with Nomad core (NodeJs app - Backend) which provides a list of flights based on Flights API (Aviation stack API). Our Backend is hosted on [Heroku platform] Nomad Backend.
The user can go through the sign-in flow and create an account. For this step, the Nomad app integrates with Firebase Authentication (Firebase Authentication) and lets the user choose a Google account. This step is crucial because it is part of the Seamless Web3 wallet creation - the user creates a Web3 wallet with 3 clicks and does not need to worry about the bureaucratic Web3 wallet creation. During this process, the Backend will store the user’s credentials on MongoDB (MongoDB Atlas). It will automagically ether.js create the user’s Ethereum wallet and store the private key on the MongoDB. We are not really concerned about security here since the wallet will not store a huge number of tokens/rewards initially.

The app also has two other screens: Admin and Profile. Admin screen provides triggers to the Backend force interactions with the smart contract NomadBadge and the Flights API for only testing purposes. The Profile gives some information about User’s data on the MongoDB database and also exposes the user’s private key for testing purposes.
A flight can be booked on the Home screen. The user can tap the Buy ticket button which will trigger the Backend to add a Flight (scheduled flight status) entry on the blockchain. Notice the user has to have Funds in his wallet in order to buy a flight ticket. After the flight is added on-chain, the user has an eligible flight and can get rewards from it. The Backend will update all the scheduled flight statuses and also update the smart contract.
Chainlink Automation executes the rewarding process for NomadBadge automatically. Once per pay, Chainlink Automation triggers the rewarding process for all the ACTIVE flights. The NomadBadge mints an NBG token if the user does not have an NBG token according to the Soulbound token specification.
We used a Soulbound token as a reference to a user’s non-transferable experience with the airline/flight. This and in conjunction with the reward system offers airlines a unique and dynamic loyalty system that engages users with their experience/status and rewards them with points they can use or transfer to others.
After that, the NomadBadge attributes rewards points to the user token and also transfers ERC20 tokens (NomadRewardToken - NRT) to the user’s wallet. The ERC20 tokens can be transferred at any time by the user. By the end of the process, NomadBadge changes the flight status to REWARDED.
Built With
- alchemyapi
- chainlink
- ethersjs
- express.js
- firebase
- heroku
- javascript
- kotlin
- mongodb
- node.js
- openzeppelin
- solidity
- typescript
12 Feb 2023
You don’t migrate an Android app from XML views to Jetpack Compose in one go. You do it screen by screen, sometimes component by component, while the app keeps shipping. Compose was designed for this: a Compose UI can live inside a View layout, and a View can live inside a Compose UI. This guide covers why teams migrate, the order that works, the interop APIs, and the problems you’ll run into on the way.
I’ve led migrations from XML to Compose on production apps, and the lessons below come from that work. This post also replaces two earlier posts on the benefits of Compose, which now redirect here.
Why migrate
The practical benefits, beyond “it’s the new thing”:
- Less code for the same UI. No XML layouts, no
findViewById or view binding, no adapters and view holders for lists. A LazyColumn with an item composable replaces a RecyclerView, an adapter, a view holder and an item layout.
- UI as a function of state. You describe what the screen looks like for a given state, and Compose updates it when the state changes. A whole class of bugs where a view wasn’t updated goes away.
- Reuse through functions. A component is just a function with parameters, so composing and reusing UI is much easier than with custom views or
<include> layouts.
- Faster iteration. Previews and Live Edit in Android Studio show changes without a full rebuild and redeploy.
- Where Android is going. New Material 3 components, Wear OS and TV libraries are built for Compose first.
None of these justify a big-bang rewrite. They justify building new UI in Compose and moving old screens over when you touch them anyway.
The order that works
- Set up the foundation. Add Compose to the build, then create a Compose theme (
MaterialTheme with your colours, typography and shapes) that matches your existing XML theme. Do this first, so every Compose piece looks right from day one.
- Build new features in Compose. Every new screen is Compose from the start. This stops the amount of XML from growing, and the team learns on fresh code.
- Build shared components. Buttons, text fields, cards and empty states your designers use everywhere. Once these exist in Compose, migrating a screen is mostly assembly.
- Migrate simple, low-risk screens. Settings, about pages, static content. They build confidence without risking core flows.
- Migrate complex screens when you’re changing them anyway. If a feature is getting a redesign, that’s the time to move it. Rewriting a stable, complex screen just to change its technology is usually poor value.
- Move navigation last. Switching to Navigation Compose is easiest once most screens are composables.
Interoperability: mixing Views and Compose
Compose inside a View layout
Use ComposeView, in XML or in code. Here’s a Fragment that renders Compose:
class ProfileFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = ComposeView(requireContext()).apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent {
AppTheme {
ProfileScreen()
}
}
}
}
The composition strategy matters inside Fragments. The default disposes the composition when the view is detached from the window, but a Fragment’s view lifecycle is different from its view’s attachment. DisposeOnViewTreeLifecycleDestroyed ties the composition to the Fragment’s view lifecycle, which avoids leaks and lost state.
You can also drop a ComposeView into an existing XML layout to migrate one part of a screen, like a header or a single card.
A View inside Compose
Some Views don’t have a Compose equivalent yet, or you rely on a third-party View (a map, an ad, a video player). Wrap them with AndroidView:
@Composable
fun LegacyChart(points: List<Float>, modifier: Modifier = Modifier) {
AndroidView(
modifier = modifier,
factory = { context -> LineChartView(context) },
update = { chart -> chart.setPoints(points) }
)
}
factory runs once to create the View, and update runs whenever the state it reads changes. Keep the View’s state flowing from Compose into the View through update, not the other way round. If you already have an XML layout, AndroidViewBinding lets you inflate it with view binding inside Compose.
Things that will bite you
Two themes during the transition
Until the migration is done, the XML theme and the Compose theme both exist and have to match. Define colours and dimensions in one place and reference them from both, and review new Compose screens next to old XML ones. Small differences in text styles are the most common thing designers notice.
State that lived in Views
Views kept some state themselves: the text in an EditText, the scroll position of a RecyclerView, which tab was selected. In Compose, you own that state. Hoist it to a ViewModel or use rememberSaveable, or users will lose their input on rotation. My post on state and side effects in Compose covers where state should live.
Lifecycle code in the wrong place
Code in onResume or onStart that touches views needs a new home. Lifecycle-aware Flow collection (collectAsStateWithLifecycle) and effects like LaunchedEffect and DisposableEffect replace most of it.
Compose is fast, but a few habits from the View world hurt it: doing heavy work inside a composable body (it can run on every recomposition), passing unstable types like plain List from data classes the compiler can’t prove are stable, and reading state higher up than needed so too much recomposes. Use Layout Inspector’s recomposition counts to find hot spots, and test performance with release builds and Baseline Profiles. Debug builds are much slower.
Tests
Espresso tests keep working for View screens, and Compose tests (createAndroidComposeRule) can find both composables and Views in a mixed screen. Add test tags or content descriptions while migrating. They make tests more robust, and good content descriptions make the screen accessible too.
Measuring progress
Track the migration so it doesn’t stall halfway. Simple metrics are enough: the number of XML layout files, the number of screens fully in Compose, and APK size. Celebrate when a dependency like the RecyclerView or Fragment library can finally be removed.
A migration is finished when nobody has to think about two UI systems anymore. Until then, the rule that keeps it moving is simple: anything new is Compose, and anything you touch moves to Compose if it’s cheap to do.
Android’s migration guide and interoperability API reference cover more edge cases, like using Compose in RecyclerView items.
12 Mar 2022
A consensus mechanism is how the computers in a blockchain network agree on one shared history of transactions without trusting a central authority. It decides who gets to add the next block, makes it expensive to cheat, and defines when a transaction can be considered final. This guide explains the main families (Proof of Work, Proof of Stake, BFT-style protocols, Delegated Proof of Stake, Proof of Authority and federated agreement) and the trade-offs between them.
I wrote the first version of this post in early 2022, a few months before Ethereum switched from Proof of Work to Proof of Stake. I’ve updated it to reflect how things work now.
The problem consensus solves
In a decentralized network, thousands of nodes receive transactions in different orders, some nodes go offline, and some may be actively trying to cheat. For example, an attacker might try to spend the same coins twice by sending two conflicting transactions to different parts of the network.
A consensus mechanism has to answer three questions:
- Who proposes the next block? Someone has to pick and order the transactions.
- How does everyone else agree it’s valid? Nodes check the rules and accept or reject it.
- When is a block final? At what point can you be confident a transaction will never be reversed?
The second question is easy: every node checks signatures and balances itself. The first and third are where the mechanisms differ. And they all need a way to stop one person from pretending to be thousands of participants (a Sybil attack), usually by tying influence to something scarce.
Proof of Work
In Proof of Work (PoW), the scarce resource is computing power. Miners compete to find a number that makes the block’s hash fall below a target. Finding it takes enormous numbers of guesses; checking it takes one hash. The winner adds the block and collects the block reward plus fees.
Bitcoin uses PoW, with a block about every 10 minutes. If two miners find blocks at the same time, the chain temporarily splits, and nodes follow the chain with the most accumulated work. That’s why PoW finality is probabilistic: each new block on top makes reversing a transaction much harder, and by convention six confirmations (about an hour) is treated as safe for large Bitcoin payments.
- Strengths: simple, battle-tested since 2009, and attacking it requires real-world hardware and electricity.
- Weaknesses: very high energy use, mining concentrates where electricity is cheap, and finality is never absolute.
Proof of Stake
In Proof of Stake (PoS), the scarce resource is the network’s own currency. Validators lock up (stake) tokens as collateral, the protocol picks validators to propose and vote on blocks, and anyone caught breaking the rules, for example by signing two conflicting blocks, loses part of their stake. That penalty is called slashing.
Ethereum moved to PoS in The Merge on September 15, 2022. According to ethereum.org, it cut the network’s energy use by about 99.95%. How it works today:
- A validator stakes 32 ETH (or joins a staking pool).
- Time is divided into slots of 12 seconds. In each slot, one randomly chosen validator proposes a block and a committee of others votes on it (attests).
- 32 slots make an epoch (6.4 minutes). Once two-thirds of the staked ETH has voted in favour across two epochs, blocks are finalized, in about 13 minutes.
Finalized blocks can’t be reverted unless validators holding at least a third of all staked ETH accept being slashed. That’s called economic finality: reversing history is possible in theory, but it would cost billions.
- Strengths: a tiny fraction of PoW’s energy use, explicit finality, and attackers lose their own stake.
- Weaknesses: influence grows with wealth, large staking providers concentrate power, and the protocol is more complex than PoW.
BFT-style protocols
Byzantine Fault Tolerant (BFT) protocols come from decades of distributed-systems research. A known set of validators vote in rounds, and a block is committed once more than two-thirds of them (by count or by stake) sign it. They tolerate up to a third of validators being faulty or malicious.
CometBFT (formerly Tendermint), used by many Cosmos chains, is the best-known example. It combines BFT voting with staking to choose the validator set.
- Strengths: instant finality: once a block is committed, it’s final. No waiting for confirmations.
- Weaknesses: every validator talks to every other one, so the validator set has to stay relatively small (usually tens to a few hundred), and the chain halts if more than a third go offline.
Delegated Proof of Stake
In Delegated Proof of Stake (DPoS), token holders vote for a small number of block producers, often around 20 or so, who take turns producing blocks. EOS and TRON popularized this model.
- Strengths: fast blocks and high throughput, because only a few nodes need to coordinate.
- Weaknesses: power concentrates in a handful of producers, and voting has been criticized for vote buying and cartels.
Proof of Authority
In Proof of Authority (PoA), validators are approved identities, such as known companies or institutions, and their reputation is what’s at stake. There’s no mining and no token staking.
PoA fits permissioned networks, like a consortium of banks or a company’s internal chain, and some test networks. Hyperledger Besu, for example, offers BFT-style PoA protocols (QBFT and IBFT 2.0) for private Ethereum networks.
- Strengths: fast, cheap and predictable.
- Weaknesses: it’s only as trustworthy as the validators, and the network isn’t open to anyone.
Federated Byzantine Agreement
Federated Byzantine Agreement (FBA), used by Stellar’s consensus protocol (SCP), lets each node choose which other nodes it trusts (its “quorum slices”). Consensus emerges where these trust choices overlap. Unlike classic BFT, there’s no single fixed validator list everyone has to agree on.
- Strengths: fast finality without mining or staking, and open membership.
- Weaknesses: safety depends on nodes choosing their quorum slices well. In practice, most nodes end up trusting the same well-known organizations.
Side by side
| Mechanism |
Sybil resistance |
Finality |
Example networks |
| Proof of Work |
Computing power |
Probabilistic (wait for confirmations) |
Bitcoin, Litecoin |
| Proof of Stake |
Staked tokens, slashing |
Economic (Ethereum: about 13 minutes) |
Ethereum, Cardano |
| BFT (with staking) |
Staked tokens, known validator set |
Instant |
Cosmos chains (CometBFT) |
| Delegated PoS |
Token-holder votes |
Fast |
EOS, TRON |
| Proof of Authority |
Approved identities |
Fast |
Private and consortium chains |
| Federated agreement |
Chosen trust relationships |
Fast |
Stellar |
How to think about the trade-offs
No mechanism wins on everything. The recurring tension is between decentralization (how many independent parties can participate), security (how expensive it is to attack) and performance (how fast and cheap transactions are). Fewer validators make a chain faster and cheaper but easier to capture. More validators make it more robust but slower to coordinate.
When you build on a chain, the mechanism mostly shows up as one practical question: how long do I wait before treating a transaction as done? On Bitcoin, wait for several confirmations. On Ethereum, wait for finality for large amounts, or accept a few blocks for small ones. On a BFT chain, the first commit is final. Getting this wrong is how exchanges and bridges have lost money to chain reorganizations.
The consensus mechanisms section on ethereum.org goes deeper into PoW and PoS. If you’re building on Ethereum, my Solidity fundamentals guide covers how transactions and gas work at the contract level.