🔁Swap

Introduction

Swapping tokens on Lovely Swap provides a straightforward method for exchanging one ERC-20 token for another. For users, the process is intuitive: they select an input token and an output token, specify the input amount, and the protocol calculates the amount of the output token they will receive. With a single click, they execute the swap and receive the output token in their wallet immediately.

In this guide, we’ll delve into the mechanics of what happens during a swap at the protocol level to better understand how Lovely Swap functions.

How Swaps Differ from Traditional Trades

Unlike traditional trading platforms, Lovely Swap does not use an order book to manage liquidity or determine prices. Instead, Lovely Swap utilizes an automated market maker (AMM) mechanism, which provides instant feedback on rates and slippage.

As covered in the Protocol Overview, each trading pair on Lovely Swap is supported by a liquidity pool. These pools are smart contracts that hold balances of two distinct tokens and enforce rules for depositing and withdrawing them based on the constant product formula. This formula ensures that when one token is withdrawn (purchased), a proportional amount of the other token must be deposited (sold) to maintain balance.

Anatomy of a Swap

At its core, every swap in Lovely Swap is executed through a single function, aptly named swap:

function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data);

Receiving Tokens

From the function signature, it's clear that swap callers must specify the amount of output tokens they wish to receive using the amount{0,1}Out parameters, which correspond to the desired amounts of token{0,1}.

Sending Tokens

What may not be immediately clear is how Lovely Swap receives tokens as payment for the swap. Typically, smart contracts that require tokens for functionality ask callers to approve the token transfer first and then call a function that invokes transferFrom on the token contract. Lovely Swap pairs handle this differently. Instead of relying on token transfer approvals, pairs check their token balances at the end of each interaction. At the beginning of the next interaction, the current balances are compared against stored values to determine the amount of tokens sent by the current interactor. For more details, refer to the whitepaper.

The crucial point is that tokens must be transferred to the pairs before calling swap (with the exception of Flash Swaps). Thus, to safely use the swap function, it should be called from another smart contract. Transferring tokens to the pair and then calling swap separately is not safe to do non-atomically because the sent tokens could be exposed to arbitrage.

Developer Resources

  • To learn how to implement token swaps within a smart contract, refer to the guide on Trading from a Smart Contract.

  • To understand how to execute a swap from an interface, check out the guide on Trading (SDK).

Last updated