Create Publication

We are looking for publications that demonstrate building dApps or smart contracts!
See the full list of Gitcoin bounties that are eligible for rewards.

Solution Thumbnail

Instant Finality - What makes Algorand stand among blockchains

Overview

Welcome back to our next comparison article on Instant Finality. I’m sure you’ve heard of this term when talking about Algorand but perhaps it’s not clear the full extent of what it provides to your project.

Many blockchains suffer from forking or block reorganization (reorgs) that require significant time to pass before the transaction can be considered final.
This article discusses what instant finality is and how Algorand handles finalizing a transaction.

In a nutshell it means that each time you see a transaction in a block, it is already safe to consider it committed to the blockchain. This is a guarantee that is extremely hard to achieve without sacrificing on security, performance or decentralization but Algorand does just that.
Thanks to its unique consensus protocol, it guarantees Instant Finality without compromises!

Table of Content - Instant Finality

Forks & Finality Delay

Ok so what happens usually in other blockchains and why is Finality a big deal?
Finality is the moment in time when a transaction is considered immutable and irreversible. The Finality Delay associated with it is the time between a transaction appearing in a block and Finality.

Blockchains, being the distributed systems they are, suffer from the same problems that affect other traditional distributed systems. The most notorious example is the CAP theorem which states that out of consistency; availability, and partition tolerance, any distributed system may only choose two. In reality this is more of a spectrum than a black & white design decision and each project chooses to prioritize some more than others while still providing good enough guarantees for all three.
(This concept is not to be confused with the Blockchain Trilemma which is just informal and relates to security, decentralization and performance)

As a consequence of this, most blockchains need a way to resolve network partitions. Network partitions usually refer to the physical layer of the network being unplugged which creates two (or more) sub-groups in place of a cohesive network. Aside from the traditional meaning, a partition in a blockchain network could also be sub-groups sharing different ideas about the state of the chain or the state of the pending transactions (aka the mempool).
If we want network tolerance the CAP theorem tells us that we should implement a tradeoff with either consistency or availability. Indeed most blockchains allow the network to diverge into sub-groups which will be reconciled later.
The network divergence is a fork and the reconciliation algorithm is a fork resolution algorithm.

What this means concretely for your project is that you should write code that handles the possibility of the transaction being reverted. If you can just wait for true Finality, that’s one strategy but that’s not always possible because of real-time constraints and because some blockchains only offer a probabilistic delayed Finality.
Most approaches that deal with certainty and time are much more speculative than just waiting for true Finality. Some decide to take a statistical approach and study, based on past behavior, how much you should wait for 99.9% of transactions to not revert.
Some others may go ahead and assume that a transaction will be final in the future and have a contingency plan ready for the event that it will not.

As an example, if you are tracking the value of your portfolio it might even be desirable to look at recent transactions that are not valid yet to monitor the most recent asset price. If you then decide to buy/sell at certain points according to your strategy, you should make sure that your order goes through (retrying it, upping the offered fees if need be, …).
A contingency plan in case of a fork is to drop the buy/sell order if prices revert to the beginning of the fork.
In this diagram, it is represented the state of the chain if a price change happens in a different fork than the order that is sent in.

                Tip of the Chain
                ----------------
                | price of     |
                | tokenY =     |
                | 20 USD       |
                ----------------
                /          \
               /            \
      ----------------   ----------------
      | price of     |   | price        |
      | tokenY =     |   | unchanged;   |
      | 19 USD       |   |              |
      |              |   | sell tokenY  |
      |              |   | at 19 USD    |
      ----------------   ----------------

It’s important to know that visibility over the number and type of active forks is, in some cases, severely limited. A fork may reach one node much later than it did for other nodes in the network.

Instant Finality

Now for a more concrete definition of Instant Finality: it’s Finality with a 0-seconds Finality Delay.

Note that we are not qualifying this further. It’s not near-instant finality. It’s not probabilistic instant finality. It’s certainly not instant finality at the expense of decentralization or performance.
Each transaction that makes it into a new block, is instantly final because Algorand does not fork.

The Pure Proof-of-Stake Algorand consensus protocol relies on VRF to select a representative sample of all the online accounts that will participate in each round. Each round is composed of three voting stages (and three independent juries):

  • Block proposal
    Each component of the first jury compiles its proposal for the new block based on its knowledge of the state of the chain and the messages that it has seen. This proposal is sent across the network
  • Soft vote
    A second jury deterministically selects a single proposal based on the hash of the proposed block
  • Certify vote
    The third, and final, jury checks the unique proposal for fraud

Since each jury is selected at random based on the stake of the participants, they keep each other in check for honest behavior. The fact that the number of proposals is reduced until there’s only one means that the honest network is not allowed to diverge.

(By the way, if you are interested in a technical dive into VRFs and how Algorand leverages then check out this page)

In case of a dishonest network or physical network partitions, Algorand will enter recovery mode until a quorum of nodes agrees to resume block production again.
This design prioritizes consistency over availability.

Tooling

The advantage of developing with Instant Finality is that you can react quickly to on-chain events.
Any transaction from a payment, to an Asset Transfer, to an application call to a financial or bringing protocol is an event that can be observed and acted upon with certainty that it will never be rolled back by the time the reaction takes place.
It also means that off-chain systems can react instantaneously to events.
For example, imagine monitoring the chain to detect DEX swaps and sending an arbitrage. Did you know that you can implement flash-loaned financial transactions easily with Algorand?

Check out this article on Flash Loans!

Algokit Subscriber

The Algorand Foundation is developing tools for TypeScript (Python soon) that implement a pub/sub pattern for clients connecting to nodes. This allows projects to easily receive irreversible and fast updates on the state of the chain.

This is a code snipped that allows you to monitor USDT events anywhere in the chain instantaneously:

const algod = await algokit.getAlgoClient()
const indexer = await algokit.getAlgoIndexerClient()
let watermark = 0

const subscriber = new AlgorandSubscriber(
  {
    events: [
      {
        eventName: 'usdc',
        filter: {
          type: TransactionType.axfer,
          assetId: 31566704, // MainNet: USDC
          minAmount: 1_000_000, // $1
        },
      },
    ],
    waitForBlockWhenAtTip: true,
    syncBehaviour: 'skip-sync-newest',
    watermarkPersistence: {
      get: async () => watermark,
      set: async (newWatermark) => {
        watermark = newWatermark
      },
    },
  },
  algod,
  indexer,
)
subscriber.on('usdc', (transfer) => {
  // eslint-disable-next-line no-console
  console.log(
    `${transfer.sender} sent ${transfer['asset-transfer-transaction']?.receiver} USDC$${(
      (transfer['asset-transfer-transaction']?.amount ?? 0) / 1_000_000
    ).toFixed(2)} in transaction ${transfer.id}`,
  )
})

subscriber.start()

Conclusion

Whether you think of Algorand as a decentralized database, a source of events, a platform for applications, etc… it shouldn’t change the fact that the products that you choose are available, fast, consistent, and coherent. Instant Finality is a feature that we take for granted in traditional systems but one that is rare in blockchains.
Algorand solves this with a unique consensus protocol that prevents this problem from even happening.