Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Base direct bridging #750

Closed
4 tasks done
lukasz-zimnoch opened this issue Nov 16, 2023 · 0 comments · Fixed by #798
Closed
4 tasks done

Support for Base direct bridging #750

lukasz-zimnoch opened this issue Nov 16, 2023 · 0 comments · Fixed by #798
Assignees
Labels
⛓️ solidity Solidity contracts 🔌 typescript TypeScript library

Comments

@lukasz-zimnoch
Copy link
Member

lukasz-zimnoch commented Nov 16, 2023

This task is about implementing support for Base direct bridging, based on the exploratory work done in #704.

The scope of this task includes:

  • Implementation of the necessary L1 and L2 contracts
  • Necessary contract deployments and upgrades
  • Implementation of the support in the tBTC SDK

Tasks

Preview Give feedback
  1. ⛓️ solidity
    lukasz-zimnoch
  2. ⛓️ solidity
    nkuba
  3. ⛓️ solidity
    lukasz-zimnoch
  4. 🔌 typescript
    lukasz-zimnoch
@lukasz-zimnoch lukasz-zimnoch self-assigned this Nov 16, 2023
@lukasz-zimnoch lukasz-zimnoch added ⛓️ solidity Solidity contracts 🔌 typescript TypeScript library labels Nov 16, 2023
nkuba added a commit that referenced this issue Feb 1, 2024
Refs: #750

Here we introduce the `AbstractTBTCDepositor ` contract meant to
facilitate integration of protocols aiming to use tBTC as an underlying
Bitcoin bridge.

### Usage of the `AbstractTBTCDepositor` contract

An integrator willing to leverage the `AbstractTBTCDepositor` contract
is supposed to:
- Create a child contract inheriting from this abstract contract
- Call the `__AbstractTBTCDepositor_initialize` initializer function
- Use the `_initializeDeposit` and `_finalizeDeposit` as part of their
business logic in order to initialize and finalize deposits.

Example code:

```solidity                                                           
// Example upgradeable integrator contract.                   
contract ExampleTBTCIntegrator is AbstractTBTCDepositor, Initializable {          
    /// @Custom:oz-upgrades-unsafe-allow constructor                           
    constructor() {                                                            
        // Prevents the contract from being initialized again.                 
        _disableInitializers();                                                
    }                                                                          
                                                                               
    function initialize(                                                       
        address _bridge,                                                       
        address _tbtcVault                                                     
    ) external initializer {                                                   
        __AbstractTBTCDepositor_initialize(_bridge, _tbtcVault);                  
    }                                                                          
                                                                               
    function startProcess(                                                     
        IBridgeTypes.BitcoinTxInfo calldata fundingTx,                         
        IBridgeTypes.DepositRevealInfo calldata reveal                         
    ) external {                                                               
        // Embed necessary context as extra data.                              
        bytes32 extraData = ...;                                               
                                                                               
        uint256 depositKey = _initializeDeposit(                               
            fundingTx,                                                         
            reveal,                                                            
            extraData                                                          
        );                                                                     
                                                                               
        // Use the depositKey to track the process.                            
    }                                                                          
                                                                               
    function finalizeProcess(uint256 depositKey) external {                    
        (uint256 tbtcAmount, bytes32 extraData) = _finalizeDeposit(depositKey);
                                                                               
        // Do something with the minted TBTC using context                     
        // embedded in the extraData.                                          
    }                                                                          
}                                                                                                                                           
```

### The `tbtcAmount` caveat

The `tbtcAmount` computed by `_calculateTbtcAmount` and returned by
`_finalizeDeposit` may not correspond to the actual amount of TBTC
minted for the deposit. Although the treasury fee cut upon minting is
known precisely, this is not the case for the optimistic minting fee and
the Bitcoin transaction fee. To overcome that problem, this contract
just takes the current maximum values of both fees, at the moment of
deposit finalization. For the great majority of the deposits, such an
algorithm will return a `tbtcAmount` slightly lesser than the actual
amount of TBTC minted for the deposit. This will cause some TBTC to be
left in the contract and ensure there is enough liquidity to finalize
the deposit. However, in some rare cases, where the actual values of
those fees change between the deposit minting and finalization, the
`tbtcAmount` returned by this function may be greater than the actual
amount of TBTC minted for the deposit. If this happens and the reserve
coming from previous deposits leftovers does not provide enough
liquidity, the deposit will have to wait for finalization until the
reserve is refilled by subsequent deposits or a manual top-up. The
integrator is responsible for handling such cases.
tomaszslabon added a commit that referenced this issue Mar 13, 2024
Refs: #750

Here we present the smart contracts necessary to enable the L2 direct
bridging (a.k.a native bridging) feature. This mechanism allows getting
canonical TBTC on the given supported L2 chain, without the need to
touch the L1 Ethereum chain the tBTC protocol is deployed on.

Changes made as part of this pull request introduce a generic mechanism
that can be deployed on all supported L2 EVM-based chains and deploy the
mechanism on Ethereum Sepolia and Base Sepolia chains for testing
purposes.

### Motivation

Right now, a user of the supported L2 chain willing to obtain canonical
L2 TBTC has to go the following path:
1. Generate a Bitcoin deposit address (using tBTC dApp or SDK)
2. Make a deposit transaction on Bitcoin
3. Reveal the Bitcoin transaction to the tBTC Bridge to start the
minting process (Ethereum transaction)
4. Once TBTC is minted on Ethereum, go to the [Wormhole Token
Portal](https://portalbridge.com) and bridge minted TBTC to the given L2
(another Ethereum transaction)
5. Canonical L2 TBTC lands on the user account automatically

This flow is unwieldy and has major drawbacks:
- It's complicated and requires multiple transactions
- It requires L2 users to interact with the L1 Ethereum chain
- It requires interacting with the Wormhole Token Portal

The idea behind direct bridging is simplifying the above flow to
something like:
1. Generate a Bitcoin deposit address (using dApp or SDK)
2. Make a deposit transaction on Bitcoin
3. Reveal the Bitcoin transaction to the tBTC Bridge **using a single
transaction on the L2 chain**
4. Canonical L2 TBTC lands on the user account automatically

Although this flow still relies on Wormhole underneath, the advantages
are:
- Simpler flow with fewer transactions
- L2 users interact only with the given L2 chain
- No need to touch the Wormhole Token Portal
- As a next iteration, we can even get rid of the reveal deposit
transaction on L2 and use Bitcoin deposit transactions as a trigger.
This will improve UX even more. See the **Next iteration: Gasless
bridging** section for details.

### High-level architecture

The high-level architecture of the direct briding mechanism is presented
on the chart below:

<img width="2144" alt="bob-i1"
src="https://github.com/keep-network/tbtc-v2/assets/11180469/6a32050d-6bc4-44cb-a299-1bc3e8009364">

- The **green** contracts are existing tBTC contracts that form the
current bridging flow based on the Wormhole Token Portal (see [RFC
8](https://github.com/keep-network/tbtc-v2/blob/main/docs/rfc/rfc-8.adoc#37-smart-contracts)).
The `TBTC Bridge` component is the `Bridge` contract deployed on L1
Ethereum responsible for minting the L1 TBTC token. The
`L2WormholeGateway` contract has the authority to mint canonical L2 TBTC
on the given L2, based on received Wormhole L2 TBTC tokens. The `L2TBTC`
component is the canonical L2 TBTC token contract.
- The **blue** contracts are the new contracts that enable the new
direct bridging flow. The `AbstractTBTCDepositor` contract (introduced
by #778) provides some
useful tooling facilitating integration with the tBTC `Bridge` and its
new **deposit with extra data** function (developed in
#760) which is the
foundation of the L2 direct bridging mechanism. The `L1BitcoinDepositor`
and `L2BitcoinDepositor` components are smart contracts handling the
actual direct bridging actions on the L1 and L2 chains respectively.
Those two contracts are introduced by this pull request.
- The **red** contracts belong to the Wormhole protocol that handles
cross-chain operations. In the context of the direct bridging mechanism,
that means the transfer of minted L1 TBTC to the L2 chain. The
`TokenBridge` contract handles the bookkeeping part of the transfer. The
`Relayer` contract handles the actual execution of it.
- The **yellow** off-chain relayer bot is the planned component
(implemented as an immediate next step) that will "turn the crank" of
the direct bridging mechanism. It will initialize deposits on the L1
chain (based on L2 events in the first iteration) and finalize them once
L1 TBTC is minted by the tBTC `Bridge` contract.

The above components interact with each other in the following way:
1. The user makes the BTC deposit funding transaction and calls the
`L2BitcoinDepositor.initializeDeposit` function to initiate the deposit
process on L2 (the call is made through a dApp and tBTC SDK).
2. The off-chain relayer bot observes the `DepositInitialized` event
emitted by the `L2BitcoinDepositor` contract.
3. After assessing the deposit validity, the off-chain relayer bot calls
the `L1BitcoinDepositor.initializeDeposit` function on L1.
4. The `L1BitcoinDepositor` contract calls the
`Bridge.revealDepositWithExtra` function under the hood (through the
`AbstractTBTCDepositor` abstract contract).
5. After some time (several hours), the `Bridge` contract mints L1 TBTC
to the `L1BitcoinDepositor` contract.
6. The off-chain bot observes the mint event and calls
`L1BitcoinDepositor.finalizeDeposit` to start the finalization process
and move L1 TBTC to the L2 chain.
7. The `L1BitcoinDepositor` calls Wormhole's
`TokenBridge.transferTokensWithPayload` function to initiate the
cross-chain transfer of L1 TBTC. This call pulls out the L1 TBTC from
the `L1BitcoinDepositor` contract and locks it in the `TokenBridge`.
8. The `L1BitcoinDepositor` calls Wormhole's `Relay.sendVaasToEvm` to
send a cross-chain message to `L2BitcoinDepositor` and notify it about a
pending cross-chain transfer.
9. The Wormhole protocol calls the
`L2BitcoinDepositor.receiveWormholeMessages` function to deliver the
cross-chain message.
10. The `L2BitcoinDepositor` contract calls the
`L2WormholeGateway.receiveTbtc` function under the hood. It passes the
VAA representing the cross-chain transfer as an argument of the call.
11. The `L2WormholeGateway` uses the obtained VAA to finalize the
cross-chain transfer by calling the Wormhole's
`TokenBridge.completeTransferWithPayload` function. This call redeems
Wormhole-wrapped L2 TBTC from the `TokenBridge`.
12. The `L2WormholeGateway` uses obtained Wormhole-wrapped L2 TBTC to
call `L2TBTC.mint` and mint canonical L2 TBTC.
13. Minted canonical L2 TBTC is transferred to the L2 user.

### Immediate next steps

Changes presented in this pull request introduce the on-chain components
of the direct bridging mechanism. To make the mechanism complete, the
following steps need to take place:
- Expose the L2 direct bridging feature in the tBTC Typescript SDK. This
feature will be incrementally exposed for specific L2 chains the
mechanism will be deployed for. The first L2 chain will be Base.
- Implement the off-chain relayer bot

### Next iteration: Gasless bridging

The plans for the future include some improvements to the first
iteration of the direct bridging mechanism described above. Namely, the
next iteration will bring gasless direct bridging that will not require
any L2 transaction to initiate the process and will rely on a single
Bitcoin funding transaction issued by the L2 user. On the technical
level, the first two steps of the flow will be replaced by a direct call
to the off-chain relayer's REST endpoint:

<img width="2144" alt="bob-i2"
src="https://github.com/keep-network/tbtc-v2/assets/11180469/f6a01138-0354-4b41-b3f1-4f4a38be7f91">
michalsmiarowski added a commit that referenced this issue Mar 19, 2024
Closes: #750

This pull request enhances the tBTC Typescript SDK with support of the L2 direct
bridging mechanism introduced by
#792. Moreover, we are adding Base
as the first L2 chain with direct bridging enabled.

### Initialization of the cross-chain contracts

To enable the SDK to work with a supported L2 chain, we introduce a new
`initializeCrossChain` method that is exposed from the main `TBTC` component.
This function sets up the SDK to work with the given L2 chain and attaches the
provided signer to the tBTC cross-chain contracts deployed there. It's worth
noting that the signer can be read-only (e.g. Ethers provider) but in that case,
only read functions of the L2 contracts will be available.

After initialization, the cross-chain contracts for the given chain can be
directly accessed using the new `TBTC.crossChainContracts` method. This
low-level access method is especially useful for reading data, e.g. get
canonical L2 TBTC balance for the given address.

### Cross-chain deposits

To leverage the new L2 direct bridging mechanism, the SDK adds the concept of a
cross-chain deposit. A cross-chain deposit is a deposit that targets an L2 chain
other than the L1 chain the tBTC system is deployed on. Such a deposit is
currently initiated using a transaction on the L2 chain (plans for the future
include gas-less initiation). On the technical level, this is handled by the new
`initiateCrossChainDeposit` method exposed by the `DepositsService` component. 

### Usage

```typescript
import { Hex, TBTC } from "../src"
import { JsonRpcProvider, Provider } from "@ethersproject/providers"
import { Signer, Wallet } from "ethers"

async function main() {
  // Create a readonly Ethers provider for the Ethereum L1 chain.
  const ethereumProvider: Provider = new JsonRpcProvider("...")
  // Create an instance of the tBTC SDK. It is enough to pass a readonly
  // Ethers provider as parameter. In this example, the SDK does not issue
  // transactions on the Ethereum L1 chain.
  const sdk: TBTC = await TBTC.initializeMainnet(ethereumProvider)

  // Create a signer for Base. This signer will be used to issue transactions
  // on the Base chain and will be used as the owner of the deposit.
  const baseSigner: Signer = new Wallet("...", new JsonRpcProvider("..."))
  // Initialize cross-chain contracts for the Base chain.
  await sdk.initializeCrossChain("Base", baseSigner)

  // Get BTC recovery address for the deposit.
  const bitcoinRecoveryAddress: string = "..."

  // Initiate a cross-chain deposit to the Base chain.
  const deposit = await sdk.deposits.initiateCrossChainDeposit(
    bitcoinRecoveryAddress,
    "Base"
  )
  // Get BTC deposit address and send funds to it.
  const depositAddress: string = await deposit.getBitcoinAddress()
  // Initiate minting once BTC transaction is made. This will call
  // revealDepositOnBehalf function of the ExampleDepositor contract
  // under the hood.
  const baseTxHash: Hex = await deposit.initiateMinting()

  console.log(
    `Minting initiated. Base transaction hash: ${baseTxHash.toPrefixedString()}`
  )
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⛓️ solidity Solidity contracts 🔌 typescript TypeScript library
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant