SwapLib
Last updated
Was this helpful?
Last updated
Was this helpful?
The SwapLib
library provides functionality for swapping tokens to stablecoins using DEX aggregators. It handles the logic for distributing swapped amounts proportionally between releaseable pools and fee pools. The library is used by the V1_2 versions of the fulfillable contracts to enable stablecoin swapping capabilities.
The library consists of two main components:
SwapLib
: For handling ERC20 token swaps to stablecoins
SwapNativeLib
: For handling native currency swaps to stablecoins
Both components share similar functionality but are optimized for their respective token types. The library is responsible for:
Validating swap parameters and token addresses
Performing the actual swap call to the DEX aggregator
Calculating the received stablecoin amount
Distributing the swapped stablecoins proportionally between releaseable pools and fee pools
The SwapLib
responsibilities can be broken down into the following concepts:
SwapData
The SwapData
struct captures all the information needed to perform a swap:
toToken
: The destination stablecoin address
amount
: The amount of tokens to swap
callTo
: The DEX aggregator contract address
callData
: The encoded call data for the aggregator
swapERC20ToStable
Swaps ERC20 token pools to stablecoins in a single transaction. The function validates the token addresses and swap amount, then performs the swap and distributes the received stablecoins proportionally between the releaseable and fees pools.
Effects:
Validates the token addresses and swap amount
Calculates the total available balance from releaseable pools and accumulated fees
Subtracts the swap amount from the appropriate pools
Calls _callSwap
to perform the actual swap
Distributes the received stablecoins proportionally using _distributeStableAmounts
Updates the releaseable pools and accumulated fees with the distributed stablecoin amounts
Emits PoolsSwappedToStable
event
Requirements:
fulfillmentRecord.token
MUST NOT be the zero address
swapData.toToken
MUST NOT be the zero address
swapData.amount
MUST be greater than zero
The total available balance MUST be greater than or equal to swapData.amount
swapNativeToStable
Swaps native currency pools to stablecoins in a single transaction. The function is similar to swapERC20ToStable
but is optimized for native currency.
_callSwap
Performs the actual swap call to the DEX aggregator and calculates the received stablecoin amount. The function approves the aggregator to spend the tokens, calls the aggregator with the provided call data, and calculates the received stablecoin amount by comparing the balance before and after the swap.
_distributeStableAmounts
Distributes the stable amount proportionally between the releaseable and fees pools. The function calculates the releaseable share based on the proportion of the releaseable amount to the total swap amount, and the fees share as the remainder.