StargateComposer.sol
Wrapper Contract that wraps IStargateRouter to add additional functionality to Stargate Composed calls.
swap()
This code snippet shows how the StargateComposer.sol uses the IStargateRouter to swap tokens using Stargate to another chain.
/**
* @param _dstChainId - destination chain identifier
* @param _srcPoolId - source pool identifier
* @param _dstPoolId - destination pool identifier
* @param _refundAddress - refund address
* @param _amountLD - amount (local decimals) to swap on source
* @param _minAmountLD - min amount (local decimals) to receive on destination
* @param _lzTxParams - struct: dstGasForCall,dstNativeAmount,dstNativeAddr
* @param _to - destination address (the sgReceive() implementer)
* @param _payload - bytes payload
*/
function swap(
uint16 _dstChainId,
uint256 _srcPoolId,
uint256 _dstPoolId,
address payable _refundAddress,
uint256 _amountLD,
uint256 _minAmountLD,
IStargateRouter.lzTxObj memory _lzTxParams,
bytes calldata _to,
bytes calldata _payload
) external override payable nonSwapReentrant {
bytes memory newPayload;
bytes memory peer;
if(_payload.length > 0) {
newPayload = _buildPayload(_to, _payload);
peer = _getPeer(_dstChainId);
// overhead for calling composer's sgReceive()
_lzTxParams.dstGasForCall += dstGasReserve + transferOverhead;
} else {
newPayload = "";
peer = _to;
}
if(isEthPool(_srcPoolId)) {
require(msg.value > _amountLD, "Stargate: msg.value must be > _swapAmount.amountLD");
IStargateEthVault(stargateEthVaults[_srcPoolId]).deposit{value: _amountLD}();
IStargateEthVault(stargateEthVaults[_srcPoolId]).approve(address(stargateRouter), _amountLD);
} else {
PoolInfo memory poolInfo = _getPoolInfo(_srcPoolId);
// remove dust
if (poolInfo.convertRate > 1) _amountLD = _amountLD.div(poolInfo.convertRate).mul(poolInfo.convertRate);
// transfer token to this contract
IERC20(poolInfo.token).safeTransferFrom(msg.sender, address(this), _amountLD);
}
stargateRouter.swap{value: isEthPool(_srcPoolId) ? msg.value - _amountLD : msg.value}(
_dstChainId,
_srcPoolId,
_dstPoolId,
_refundAddress,
_amountLD,
_minAmountLD,
_lzTxParams,
peer, // swap the to address with the peer address
newPayload
);
}buildPayload()
In the swap function it calls buildPayload to include the msg.sender in the payload.
sgReceive()
StargateComposer.sol implements IStargateReceiver so it can implement the sgReceive function and receive the tokens and payload from the IStargateRouter on the destination chain. It then forwards the sgReceive call to the intended receiver with the original msg.sender who initialed the swap on source.
Last updated
