Developer Docs
Search…
⌃K

How to Swap

Use Stargate to transfer an asset across blockchains.
You will need the Stargate router interface.
To perform a cross chain swap() in solidity, here is an example:
For the native gas fee required for swap() you need to call quoteLayerZero() on the Router.sol contract to get the amount you should send as msg.value.
First determine the swap fee, then call swap() to transfer the asset to the destination chain.
// perform a Stargate swap() in a solidity smart contract function
// the msg.value is the "fee" that Stargate needs to pay for the cross chain message
IStargateRouter(routerAddress).swap{value:msg.value}(
10006, // send to Fuji (use LayerZero chainId)
1, // source pool id
1, // dest pool id
msg.sender, // refund adddress. extra gas (if any) is returned to this address
qty, // quantity to swap
amountOutMin, // the min qty you would accept on the destination
IStargateRouter.lzTxObj(0, 0, "0x") // 0 additional gasLimit increase, 0 airdrop, at 0x address
abi.encodePacked(msg.sender), // the address to send the tokens to on the destination
bytes("") // bytes param, if you wish to send additional payload you can abi.encode() them here
);
To perform a swap() using ethers via a frontend, use the abi and call swap() on the Router contract instance:
let tx = await router.swap(
2, // destination chainId
1, // source poolId
1, // destination poolId
yourAddress, // refund address. extra gas (if any) is returned to this address
qty, // quantity to swap
amountOutMin, // the min qty you would accept on the destination
{ dstGasForCall: 0, dstNativeAmount: 0, dstNativeAddr: "0x" },
yourAddress, // the address to send the tokens to on the destination
"", // payload
{value: fee} // "fee" is the native gas to pay for the cross chain message fee. see
);
TESTNET ONLY: For the fee parameter, if you wish to simply guess the fee, you can do something like this, as Stargate will refund the caller the additional gas amount if they send too much.
let messageFee = ethers.utils.parseEther('0.025'); // send 0.02 eth converter to wei
await stargateRouter.swap(..., {value: messageFee}); // swap asset across chains
See how to get the cross chain message fee to pay enough native gas when calling swap()