How to use just-in-time gas to execute cross-chain transactions
There are some actions and contracts where cross-chain execution with a relayer doesn’t work. For example, most ‘sell’ actions depend on msg.sender
Selling a nft
Swapping an erc20
Bidding in an auction
To get around this, you can simply bridge a small amount of ETH for gas and have the user execute the transaction themselves. This is only now possible because of how fast and cheap Relay makes bridging.We will soon add functionality to our SDK to handle this flow completely, but until then, this guide will demonstrate how you could implement this ux yourself.
We start by using viem’s estimateContractGas to calculate the gas required to successfully execute the transaction we want to make on the Destination Chain. We also use getGasPrice to get the current price of gas on the Destination chain. We multiply these two values together to get the total gas estimate and add a 5% buffer to handle any fluctuation.
This step is optional and the amount you bridge back would depend on your use case. In this example, we attempt to bridge back all of the ETH that the user has on the Destination chain. We first fetch the user’s ETH balance on Destination. We then calculate the required fees in order to bridge that ETH back (gas fee + relayer fee). Once we subtract those fees from the user’s Destination ETH balance, we get the total amount that we can afford to bridge and we can execute the bridge action.