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:
Here is the swap() interface:
function swap(
uint16 _dstChainId,
uint256 _srcPoolId,
uint256 _dstPoolId,
address payable _refundAddress,
uint256 _amountLD,
uint256 _minAmountLD,
lzTxObj memory _lzTxParams,
bytes calldata _to,
bytes calldata _payload
) external payable override nonReentrant {
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
_amountLD, // quantity to swap in LD, (local decimals)
_minAmountLD, // the min qty you would accept in LD (local decimals)
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
_amountLD, // quantity to swap in LD (local decimals)
_minAmountLD, // the min qty you would accept in LD (local decimals)
{ 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()
Last updated