paint-brush
A Comprehensive Dive into Bridgesby@razacodes
105 reads

A Comprehensive Dive into Bridges

by RazaOctober 18th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Bridges in the Web3 ecosystem enable the transfer of assets and data between different blockchains, serving vital roles like promoting cross-chain transfers and scalability. They can be categorized into token, data, and interoperability bridges. While building, developers must balance performance, security, and cost. However, using bridges carries risks, including potential vulnerabilities like frontrunning and replay attacks. As showcased by Scroll’s bridge, developers can interact with bridges using APIs and smart contracts. Regular audits and updates are essential for bridge security in the ever-evolving blockchain space.
featured image - A Comprehensive Dive into Bridges
Raza HackerNoon profile picture


Why bridges aren’t so simple, how to interact with them, and how to utilize Scroll’s bridge


Before we start…

At first glance, bridges in Web3 might seem simple enough. But bridges are incredibly complex when it comes to their design, development, and implementation. They are responsible for the movement of highly sensitive resources like liquidity, and just like the bridges we drive on, it is important for builders and users alike to understand how they work. This guide will provide devs with hands-on insights for bridges, along with details on how to properly utilize the Scroll bridge.


What is a bridge?

Bridges serve as the vital connectors between different blockchains that enable seamless asset transfers. Whether you’re moving tokens, NFTs, or other digital assets, a bridge facilitates these transfers through smart contracts, ensuring the integrity of the assets are maintained across both chains. In a world of expanding blockchain interoperability, it is essential for Web3 engineers to understand how bridges work.


Purpose of a bridge

As outlined by the Ethereum Foundation, bridges have several key purposes:

  • Bridges enable the cross-chain transfer of assets and data, allowing decentralized applications (dApps) to tap into the unique strengths of various blockchains. This enhances the capabilities of dApps and opens up new avenues for innovation.
  • Bridges unlock access to new platforms for end-users, empowering them to leverage the benefits of different chains for diverse needs.
  • Bridges foster collaboration among developers from distinct blockchain ecosystems, encouraging them to build innovative platforms for users.
  • Bridges significantly contribute to interoperability by allowing specialized networks to communicate and share resources.
  • Bridges promote scalability by facilitating the movement of assets between Layer 2 solutions and sidechains, which are designed for more efficient transaction processing.
  • Bridges enable resource optimization, giving users the flexibility to utilize multiple chains for various tasks, ranging from computation and storage to governance.

How a bridge works

Bridges are complex and finicky. In other words, two bridges that serve the same purpose (like transferring tokens) might still operate differently. We will dive into factors that influence the design of a bridge later, but for now, let’s take a look at how a bridge would work if we want to transfer an asset such as an ERC20 token.

Bridging ERC20 tokens

In a typical bridge setup, there are two primary blockchains involved: the source blockchain and the target blockchain. The source blockchain is where the asset, such as an ERC20 token, originates from, and the target blockchain is where the asset is intended to be moved.


Smart contracts on both sides facilitate this transfer. For example, when transferring an ERC20 token from Ethereum to Binance Smart Chain, the source contract on Ethereum would lock the original tokens, and a corresponding target contract on Binance Smart Chain would mint an equivalent amount of wrapped tokens.

Bridging ERC20 tokens


Communication between two blockchains can be either unidirectional or bidirectional. In a unidirectional bridge, assets can only move from the source blockchain to the target blockchain, not the other way around. In contrast, bidirectional bridges allow for the free flow of assets between chains in both directions.

How two bridge contracts on different chains communicate

Looking at the above illustration, you might ask, how do two bridge contracts communicate? The answer is that bridge contracts on different blockchains don't directly communicate with each other due to the isolated nature of blockchain networks. Instead, they rely on external agents like "Relayers" to facilitate communication between them.


Now if you’re a bit savvy with bridges, you know there are different types of bridge architectures with regards to trusted parties or agents. We’ll cover that later on.


So our above illustration is incomplete. Usually the following steps are included:

  1. Initiation: A user initiates a transfer from the source blockchain by interacting with the bridge contract there. This usually involves sending tokens to the contract, which are then locked or burned.
  2. Event Emission: The source bridge contract emits an event, essentially a log entry, that captures the necessary information about the transaction, such as the amount and the destination address on the target blockchain.
  3. Listening: Relayers are nodes that monitor these events on the source blockchain.
  4. Validation: Once an event is detected, Validators validate the transaction to ensure its legitimacy. This may involve various consensus algorithms or cryptographic proofs.
  5. Relaying: After validation, Relayers take the information from the source blockchain and submit it to the bridge contract on the target blockchain. This usually requires them to sign a transaction on the target blockchain.
  6. Execution: Upon receiving and validating the information from the Relayers, the target bridge contract mints or releases the corresponding amount of tokens on the target blockchain, completing the bridge.


Our updated visual looks like this:

Updated visuals

How bridges are used today

We can categorize two types of transfers done by bridges:

  1. Messages & Data
  2. Function Calls


The first category, Messages & Data, involves the transmission of raw information or asset details from one blockchain to another. This is commonly seen in token transfers like our example above. An event on the source blockchain, such as locking or burning tokens, is communicated to a target blockchain for corresponding action like minting wrapped tokens. In data bridges, this could include transmitting oracle data or sharing state information between chains.


The second category, Function Calls, involves more complex interactions that trigger specific functions or smart contract methods on the target blockchain. Instead of merely passing along data, these function calls can initiate a range of activities such as executing smart contracts, triggering decentralized applications, or even initiating other transfers. This type of transfer is crucial for advanced interoperability bridges that aim to not just move assets or data, but also to extend the functionality and logic from one blockchain to another.


Both types of transfers contribute to the versatility and robustness of modern blockchain bridges.

Native vs third-party bridges

Often a blockchain organization or community will build bridges that connect their own chain to others. These types of bridges are called “native bridges.” Native bridges are generally well-integrated into the core ecosystem, offering a seamless user experience and usually higher security, as they are developed with deep understanding of the underlying protocol.


In contrast, “third-party bridges” are developed by external entities and serve to connect multiple, often disparate, blockchains. While these third party bridges expand the range of interoperability, they may not offer the same level of security or performance as native bridges, since they have to adapt to multiple protocols, each with its own set of rules and vulnerabilities.


The key trade-offs between the two come down to specialization versus generalization. Native bridges offer a more specialized, optimized experience but may lack the wide-ranging interoperability of third-party bridges, which offer more generalized solutions at the possible expense of performance and security.


Choosing between the two types of bridges often depends on your specific needs, the assets you are transferring, and the level of trust you have in the entities that maintain these bridges.

Types of bridges

Looking at the Web3 landscape right now, we can classify roughly three type of bridges:

1. Token bridge

Token bridges enable the migration of tokens from one blockchain to another. For example, you can move Ethereum's native ETH token to the Binance Smart Chain as a wrapped token.

2. Data or messaging bridge

Data or Messaging bridges allow the sharing of data between chains. This is particularly important for decentralized oracles.

3. Interoperability bridges

Interoperability bridges are the most sophisticated types of bridges, allowing not just tokens and data but also smart contracts and logic to be shared between chains.

Trusted vs Trustless

Depending on the design of the bridge, it can be classified as a trusted or trustless bridge. The Ethereum Foundation has provided a table with the following characteristics for trusted and trustless bridges (Ethereum).


Trusted bridges

  • Trusted bridges depend upon a central entity or system for their operations.
  • They have trust assumptions with respect to the custody of funds and the security of the bridge. Users mostly rely on the bridge operator's reputation.
  • Users need to give up control of their crypto assets.

Trustless bridges

  • Trustless bridges operate using smart contracts and algorithms.
  • They are trustless; the security of the bridge is the same as that of the underlying blockchain.
  • Through smart contracts, trustless bridges enable users to remain in control of their crypto assets.

Building bridges

Transferring data from one chain to another seems simple, but it’s much more complex than just that. Let’s take a deeper look at some of that complexity.

Performance vs security vs cost

When evaluating blockchain bridges, three critical factors come into play: Performance, Security, and Cost.

  • Performance refers to the speed and efficiency with which assets or data can be transferred between blockchains. Faster bridges offer better user experience, but may sometimes compromise on security features to achieve high throughput.
  • Security is crucial for ensuring the safe transit of assets and data, safeguarding against vulnerabilities like frontrunning, replay attacks, and locked funds. However, robust security measures may introduce latency or require more expensive cryptographic operations.
  • Cost is another pivotal factor, as users are often required to pay transaction fees for using the bridge. These fees can vary based on the consensus mechanism, the complexity of the smart contracts involved, and the need for validators or relayers.


Striking the right balance among these three aspects is a challenging task for bridge developers and often involves trade-offs based on the specific use-cases and requirements.

Blockchain characteristics

Different blockchains operate on different consensus mechanisms and have different technological characteristics. Some are more performant, others favor reliability. When transferring assets, these factors play a significant role in determining finality, TPS, and other metrics.

Atomic vs non-atomic transactions

Inherently blockchain transactions are atomic. In other words, the whole transaction is executed or it’s reverted and nothing is executed. However looking at bridges, transactions could be atomic or non-atomic. If a bridge operates on a set of sequential transactions and the transaction in the middle fails, what is the result?


For example, if ERC20 tokens are transferred from blockchain A to blockchain B, essentially the tokens are burned on blockchain A and minted on B. But what happens if the user doesn’t have enough crypto to pay for gas on Blockchain B to mint the tokens, but the tokens are burned on blockchain A? In this case, the user will lose their funds.


In crypto, users should always exercise caution to avoid careless mistakes like this and risk a loss of funds.

Who are you going to trust?

We covered bridges using agents or third parties as trusted entities to relay messages and data from the source blockchain to the target blockchain. Relayers are one type of agent that can be used, but are not the only type. Another type are attesters. Attesters are specialized agents in blockchain bridges that validate and confirm the authenticity of transactions or data before they are transferred from the source blockchain to the target blockchain.


Deciding who or what to trust is an important choice, especially when using agents like relayers or attesters to facilitate cross-chain communication. The nature of these agents —whether they are centralized entities or decentralized algorithms— affects the bridge's overall security and trust model. In addition, you'll need to consider the technical characteristics of the blockchains you're connecting, such as their consensus mechanisms and transaction throughput.


It is important to carefully consider transaction types (atomic vs. non-atomic) and the compensation model for infrastructure components like Relayers. It is also important to be mindful of potential security vulnerabilities, such as frontrunning and replay attacks; this is crucial for building a robust and secure bridge.

What do you want the bridge to do?

When building a blockchain bridge, it is essential to clearly define its purpose, as this will significantly influence its design and functionality. Remember that bridges can be geared towards two different types of executions: Function Calls and Messaging. Function Calls are more complex and allow for specific actions to be triggered on the target blockchain, such as executing smart contracts or initiating other transfers. On the other hand, Messaging focuses on the simpler task of transferring raw information or asset details from one blockchain to another. Understanding whether your bridge aims to facilitate advanced interoperability features or simply enable basic asset and data transfers will help you make informed decisions on its architecture, security considerations, and the types of agents like Relayers or attesters that you may need.

How do you proof successful transfers?

To ensure a transaction or asset transfer from one blockchain to another through a bridge is valid, a proof is created. Proofs are pieces of cryptographic evidence that help the target blockchain verify the legitimacy of the transaction. This maintains the integrity and security of the asset being transferred. A type of proof called a “Merkle proof” can play a crucial role in this process by providing a secure and efficient means of transaction verification across different blockchains.


When an asset moves from one chain to another, a Merkle proof encapsulating the transaction details can be generated. This proof can then be validated by the target blockchain, ensuring that the transaction is legitimate and enabling trustless, cross-chain asset transfers. Through the use of Merkle proofs, bridges can enhance their security and integrity, making them more resistant to fraudulent activities.

Questions to think about when building bridges

  • Who is being trusted?
  • How many transactions are needed to facilitate a transfer?
  • Who is submitting what transactions to which blockchain?
  • Can a user who has no value on the destination blockchain use this?
  • How are infrastructure components (relayers, attesters etc.) compensated?
  • Do infrastructure components need to handle requests from users?

Risk using bridges

Bridges have been around for less than ten years and are still in the early stages of development; it remains likely that the optimal bridge design has not yet been discovered. Interacting with any type of bridge carries risk:

  • Trust model risk: know whether the bridge operates in a trustless manner or requires trusted validators.
  • Smart contract risk: the risk of a bug in the code that can cause user funds to be lost.
  • Technology risk: software failure, buggy code, human error, spam, and malicious attacks can possibly disrupt user operations.

Moreover, since trusted bridges add trust assumptions, they carry additional risks such as:

  • Censorship risk: bridge operators have the ability to stop users from transferring their assets using the bridge.
  • Custodial risk: bridge operators have the ability to collude to steal user funds.


User's funds are at risk if:

  • there is a bug in the smart contract.
  • the user makes an error.
  • the underlying blockchain is hacked.
  • the bridge operators have malicious intent in a trusted bridge.
  • the bridge gets hacked.


Common bridge hacks you should know about

Frontrunning

In a bridge setup, frontrunning occurs when malicious actors observe a pending transaction on the source blockchain and quickly submit a similar transaction with a higher gas fee. This allows the attacker's transaction to be processed first, potentially leading to unfavorable outcomes for the original transaction, such as price manipulation or asset theft.

Replay attacks

This type of attack involves taking a valid transaction from one blockchain and maliciously or fraudulently replaying it on another chain to duplicate the action. In a poorly designed bridge, if unique transaction identifiers are not properly managed, an attacker could exploit this to duplicate transfers or actions, leading to financial loss.

Locked funds

In some bridge architectures, assets are locked in a smart contract on the source blockchain before being minted on the target blockchain. If the smart contract has vulnerabilities or if the validators or relayers are compromised, these funds can become permanently locked, rendering them inaccessible to users.

Interacting with bridges and APIs

As a developer, you’re likely to start by interacting with existing bridges through APIs and smart contracts, rather than building a full-scale bridge of your own. This could be in the form of sending a message, transferring assets, or even making function calls to another contract on another blockchain.


Let’s take a look at Scroll’s bridge and see how one would go about interacting with it. We are going to follow this guide as a basis to do this.


Scroll has two relevant contracts that allow developers to send messages back and forth as part of the Scroll Messenger infrastructure: the L1ScrollMessenger and the L2ScrollMessenger. This is what the API looks like to send a message from L1 → L2 and using the L1ScrollMessenger or sending a message from L2→ L1 using the L2ScrollMessenger:


Interacting with bridges


And this is what the API looks like to send a message with proof from L2 → L1 using the sendMessage function on the L2ScrollMessenger and calling the relayMessageWithProof function on the L1ScrollMessenger. For more details, read this section of the Scroll docs.


relayMessage with Proof


As developers, we only need to use an interface contract that points to an existing deployment of the messenger contracts to send messages back and forth. As stated in the guide, this allows us to target a specific contract on L2.

Target smart contract


In order to call it, we deploy a smart contract on the L1 with a function that will take in the address of the L1ScrollMessenger contract, the address of the Greeter contract we deployed on Scroll earlier, the value we want to send the transaction with, the gasLimit that we want to purchase on the L2 (can be estimated using a library like ethers.js/rs or alloy.rs by querying an RPC node, you can use 100000 as a placeholder for this demo) and the greeting string that we want to set for the setGreeting function on our target contract. Everything put together will look something like this:


Operator Smart Contract


There are also some additional details in the docs:

Calling a Cross-chain Function


Once you deploy GreeterOperator on L1 and Greeter on Scroll, you can call executeFunctionCrosschain and you’ll see the setGreeting function called on L2 after a few minutes when the sequencer processes the sendMessage queue for L1→L2 messages.


Here is an example executeFunctionCrosschain call and its payload from GreeterOperator on Sepolia to Greeter on the Scroll tesnet (Etherscan):

ExecuteFunctionCrosschain


And you can see the Greeter’s setGreeting function was called from the L2ScrollMessenger correctly in this transaction (Scrollscan):


We managed to upgrade the greeting to “gm CT!” !

Upgrading a greeting

Conclusion

In time, bridges will continue to get more and more sophisticated, so it is important that devs stay up to date on the newest developments. As reflected by some of the most sensational heists in crypto you may have seen in the news, bridges are often the most vulnerable part of an ecosystem. Keeping this in mind, is it important to exercise due diligence, including regular security audits and battle-testing, as we are doing at Scroll. Though much in the blockchain space is regularly changing, one thing certain is that bridges will continue to be an important part of what links blockchains together, the success of which requires ongoing collaboration and vigilance from the wider Web3 community.


Also published here.