Cross-Chain Swap
Here is an example app that allows swapping one token on chain1 to another token on chain2 through cBridge and DEXes on both chain1 and chain2.
For the simplicity of explanation, let's say we deploy this contract on chain1 and chain2, and we want to input tokenA on chain1 and gain tokenC on chain2.
Public functions transferWithSwap
and transferWithSwapNative
are called by a user to initiate the entire process. These functions takes in a SwapInfo
struct that specifies the behavior or "route" of the execution, and execute the process in the following fashion:
Swap tokenA on the source chain to gain tokenB
Packages a
SwapRequest
as a "message", which indicates the swap behavior on chain2sendMessageWithTransfer
is then called internally to send the message along with the tokenB through the bridge to chain2On chain2,
executeMessageWithTransfer
is automatically called when the bridge determines that the execution conditions are met.This contract parses the message received to a
SwapRequest
struct, then executes the swap using the tokenB received to gain tokenC. (Note: whenexecuteMessageWithTransfer
is called, it is guaranteed that tokenB already arrives at the TransferSwap contract address on chain2. You can check out this part of verification logic in MessageBusReceiver.sol'sexecuteMessageWithTransfer
).If the execution of
executeMessageWithTransfer
of TransferSwap contract on chain2 reverts, or if theexecuteMessageWithTransfer
call returnsfalse
, then MessageBus would callexecuteMessageWithTransferFallback
. This is the place where you implement logic to decide what to do with the received tokenB.
The following is a more graphical explanation of all the supported flows of this demo app:
Last updated