# Built-in Token Bridge
## Abstract
Transferring funds between L1 and L2 blockchains is integral to the user experience of L2 blockchains. Typically, most platforms employ rudimentary bridge solutions to manage this task. However, these 'simple' bridges come with inherent challenges and potential vulnerabilities:
* Users often face delays as they must wait for transaction finalization before processing counter transfers.
* They pose significant security risks: the private key essential for counter transfers is retained on the bridge instance, creating a potential for unauthorized token minting and transfers.
Recognizing these challenges, we propose the Built-in Token Bridge — a Waves solution to address and overcome the typical issues associated with standard bridges.
## Basic design
At its core, the Built-in Token Bridge operates through a pair of smart contracts: one on the L1 blockchain and the other on L2. Rather than functioning as isolated entities, these contracts maintain a shared state, effectively acting as components of a singular bridge.
Operation of the bridge breaks down in following concepts:
1. **State Sharing:** To maintain the shared state, the two contracts cyclically exchange blocks of pending transactions. This alternating exchange ensures that both contracts remain synchronized.
2. **Transaction Validation:** Each transaction carries data reflecting the shared state prior to its execution. As a transaction is validated, the respective contract (either on L1 or L2) verifies if the transaction aligns with its current state and determines if it can be applied. If it's applicable, the contract updates the shared state, propelling the system forward.
3. **Handling Inapplicable Transactions:** If a transaction isn't applicable, it, along with any subsequent transactions, is discarded. The goal for both sides is to maintain the most valid shared state possible.
4. **Transaction Completion:** After two interaction cycles between the contracts, the sender verifies the transaction's status. A transaction that's successfully recorded in the shared state is considered complete on both the L1 and L2 blockchains.
This mechanism ensures a secure, synchronized, and efficient bridging process between the two blockchains.
## Sequence diagram
```mermaid
sequenceDiagram
autonumber
actor SL1 as Sender on L1
participant BL1 as Bridge SC on L1
participant L1M as L1 Generator
participant L2M as L2 Generator
participant BL2 as Bridge SC on L2
actor SL2 as Sender on L2
SL1->>BL1: Request Shared State Hash
BL1->>SL1: Current State Hash
SL1->>BL1: Signed Transaction
BL1-->>L1M:Apply Transactions
BL1->>BL1: Update Shared State
L1M->>L2M: Push Transactions Batch
L2M->>L2M: Extract Transactions Batch
L2M->>BL2: Invoke Batch Application
BL2->>BL2: Update Shared State
SL2->>BL2: Request Shared State Hash
BL2->>SL2: Current State Hash
SL2->>BL2: Signed Transaction
BL2-->>L2M:Apply Transactions
BL2->>BL2: Update Shared State
L2M->>BL1: Invoke Batch Application
BL1->>BL1: Update Shared State
SL1->>BL1: Request Shared State Hash
```
Imagine a sender on the L1 blockchain who wishes to transfer funds to the L2 blockchain. The process begins with the sender's invocation of the Bridge Smart Contract on L1. Here's how it unfolds:
1. The sender begins by requesting the current value of the Shared State Hash.
2. Using the received hash value, the sender then constructs a transaction. This transaction includes:
* The previously mentioned hash value.
* The sender's public key.
* The token name and the amount to be transferred.
* The receiver's address on L2.
3. The Sender hashes the transaction and singns this hash using their private key. This transaction signature is then sent to the Bridge Smart Contract along with transaction data. Finally, the specified token amount for the transfer is attached to the invocation.
4. The Bridge Smart Contract processes the transaction, yielding specific invocation results.
5. While applying the transaction, the Bridge Contract updates the value of the Shared State Hash.
6. A batch of transactions, structured as a block update, is relayed to L2 blockchain.
7. The L2 Generator identifies and extracts the Transaction Batch from the received block update.
8. Subsequently, the L2 Generator calls upon the Bridge Smart Contract on L2, submitting the transaction batch for processing.
9. The Bridge Contract on L2 processes the transactions from the batch, executes the outgoing transfers, and updates its version of the Shared State Hash.
The backward process of transfering funds from L2 to L1 blockchains goes as follow:
10. The sender on L2 starts by querying the Bridge Smart Contract on L2 for the current value of the Shared State Hash.
11. Using the retrieved Shared State Hash the sender constructs a transaction.
12. Once the transaction is ready, the sender signs it and forwards the signed transaction to the Bridge Contract on L2.
13. The Bridge Smart Contract on L2 then processes and applies the transaction.
14. The contract updates the Shared State.
15. When submitting the L2 block, the L2 Generator interacts with the Bridge Smart Contract on L1, transmitting a batch of transactions for its consideration.
16. The Bridge Contract on L1 applies the provided transaction batch.
In this process, the L2 Generator plays a main role, acting as the primary orchestrator.
## Bridge Transaction
A Bridge Transaction is comprised of the following fields:
1. Current Shared State Hash
2. Sender Public Key
3. Token Name
4. Token Amount
5. Receiver Address
6. Signature
The first five fields (1-5) together form the transaction body. This body is utilized to compute the transaction hash, which subsequently is used to derive the transaction signature.
## Shared State Hash
The calculation of the Shared State Hash is as follows:
Starting with an initial hash of 32 zeros, the current hash is concatenated with the transaction hash. This combined data is then hashed to produce the subsequent Shared State Hash.
## Resolving Conflicts
The design of the Built-in Token Bridge ensures that all transactions on both sides of the bridge are applied sequentially. Any inapplicable transactions can be reverted and refunded to their originators.
Here's how shared state collisions are resolved:
1. The Bridge Contract on L1 computes a State Hash, labeled SH1, by processing transaction TX1 from Sender S1.
2. Transaction TX1 is then transferred to L2 as part of a transaction batch.
3. Subsequently, Sender S2 on L1 initiates another transaction, TX2. Upon its application, the resulting Shared State Hash becomes SH2.
4. Simultaneously, Sender S3 on L2 initiates transaction TX3. Once applied, the Shared State Hash is updated to SH3.
5. Transaction TX3 is relayed from L2 back to L1, again as part of a transaction batch.
6. The Bridge Contract on L1 can not apply the incoming transaction TX3 since its state has already been modified by transaction TX2.
7. To address this, the Bridge Contract on L2 embarks on resolving the conflict. It does this by retracing to the last common Shared State Hash.
8. The previous State Hash from TX2 is extracted and compared with the previous State Hash from TX3.
9. If these previous state hashes match, the Bridge Contract on L1 reverses transaction TX2 and reimburses the originator, the Sender S2, with the corresponding token amount.
## Avoiding Conflicts
Although conflict resolution is achievable, the process is computationally demanding and could lead to substantial fee expenditures. Consequently, taking measures to prevent conflicts upfront is more cost-effective.
Several schemes can be developed to manage state modification. For instance, the right to process new user transactions could be derived from the blockchain height of L1. If the block number on L1 is even, then the Bridge Contract on L1 has the prerogative to receive and apply user transactions to the Shared State. Concurrently, the Bridge Contract on L2 is restricted to processing transaction batches from L1. Conversely, when the block number on L1 is odd, roles reverse: the Bridge Contract on L2 can process individual transactions, while the L1 contract is limited to applying batches.