> For the complete documentation index, see [llms.txt](https://shibatoken.gitbook.io/shiba-swap/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shibatoken.gitbook.io/shiba-swap/architecture/how-does-shibaswap-work/swap-dex.md).

# SWAP/DeX and AMM

The ShibaSwap DeCentralised Exchange

## SWAP

The **SWAP** part fulfils the requirements of a Decentralised Exchange /DeX.

Swap uses modified **UniSwap V2** and its associated Smart Contracts to perform an ERC-20 Token Swap

### Why Uniswap?

Uniswap is very gas efficient due to its minimalistic design.

### Contracts Involved&#x20;

**Router**\
[**ShibaSwap: Router v2**](https://etherscan.io/address/0x03f7724180aa6b939894b5ca4314783b0b36b329)&#x20;

As explained in [**this**](https://docs.uniswap.org/protocol/V2/guides/smart-contract-integration/trading-from-a-smart-contract) guide from Uniswap, the easiest way to safely swap tokens is to use the [**router**](https://docs.uniswap.org/protocol/V2/reference/smart-contracts/router-02), which provides a variety of methods to safely swap to and from different assets. There is a function for each permutation of swapping to/from an exact amount of ETH/tokens.

It is also recommended by Uniswap [**here**](https://docs.uniswap.org/protocol/V2/concepts/advanced-topics/pricing#pricing-trades) that swaps need access to a price *oracle*, (Unification) to be sure that the best execution they can get from Uniswap is close enough to what the oracle considers the "true" price.

There are a few things unique about how this is set up

1. It uses smart contracts to hold liquidity reserves of various tokens, and trades are executed directly against these reserves
2. Utilises factory/registry contracts (explained below) that can create and register token pairs&#x20;
   1. Each token pair holds its own reserve liquidity
      1. Each pair is underpinned by a liquidity pool. Liquidity pools are smart contracts that hold balances of two unique tokens and enforces rules around depositing and withdrawing them
   2. This allows trades between the two based on relative supply
3. It uses  [**constant product formula**](https://docs.uniswap.org/protocol/V2/concepts/protocol-overview/glossary#constant-product-formula)&#x20;
   1. The ratio of tokens in the pool, in combination with the constant product formula, ultimately determine the price that a swap executes at.
4. It is thus dependant on individual actors called Liquidity Providers to maintain and replenish  its reserves who are rewarded for this.

#### Adding Liquidity

1. Adding liquidity requires depositing an equivalent value of ERC20 tokens into the ERC20 token pairs' associated pool.
2. The first liquidity provider to join a pool sets the initial exchange rate by depositing what they believe to be an equivalent value of ETH and ERC20 tokens.
3. A subsequent trade reduces or increases the ratio of the tokens in the pool and thus affecting the price of the tokens involved.
4. If another trade does not balance the ratio or affects the price, this creates an arbitrate opportunity for an [**arbitrage**](/shiba-swap/glossary/glossary-of-terms-used-within-the-shiba-inu-ecosystem.md#arbitrageur) trader as the price of one of the tokens involved may have changed at another exchange.
5. Since such a system is isolated and does not depend on an order-book for prices an arbitrage trade essentially helps correct the price.
6. The easiest way to safely add liquidity to a pool is to use the [**router**](https://docs.uniswap.org/protocol/V2/reference/smart-contracts/router-02)**,** which provides simple methods to safely add liquidity to a pool

**Liquidity Tokens**

1. Liquidity tokens are minted to track the relative proportion of total reserves that each liquidity provider has contributed.&#x20;
2. They are then burned while removing liquidity at any time to return a proportional share of the markets liquidity to the provider.
3. The proportion of the pool's liquidity provided determines the number of liquidity tokens the provider receive&#x73;**.**
4. If the provider is minting a new pool, the number of liquidity tokens they will receive will equal s $$sqrt(x \* y)$$where x and y represent the amount of each token provided.
5. ERC20 tokens are withdrawn at the current exchange rate (reserve ratio), not the ratio of their original investment. This means some value **can be lost** from market fluctuations and arbitrage.
6. This loss , or a part of it is compensated by the fees taken during trades which are then distributed to the pool

{% hint style="warning" %}
**`Market making, in general, is a complex activity. There is a risk of losing money during large movement in the underlying asset price compared to simply holding an asset.`**
{% endhint %}

#### **Fees**

`UniswapV2 charges 0.3% fee, by default. However it offers a variation of customisable (smart contract controlled) fees called Protocol fee.`

[**`SushiSwap`**](https://docs.sushi.com/products/yield-farming#how-do-i-stack-yield)`uses this to reward`` `**`$SUSHI`**` ``tokens.`

**`ShibaSwap`**` ``uses this in 2 unique ways to provide a multi-token reward system`

1. Whenever a trade occurs, a **0.3%** fee is charged to the transaction sender.&#x20;
2. This fee is distributed *pro-rata* to all LPs in the pool upon completion of the trade. i.e the fee is split by liquidity providers proportional to their contribution to liquidity reserves.
3. Swapping fees are immediately deposited into liquidity reserves.&#x20;
4. Since total reserves are increased without adding any additional share tokens, this increases that value of all share tokens equally.&#x20;
5. No new liquidity tokens are minted, this has the effect of splitting the transaction fee proportionally between all existing liquidity providers.
6. This functions as a payout to liquidity providers that can be collected by burning shares.
7. Pool made of `token1 and token2`maintains a ratio represented by `token1_pool * token2_pool = k(invariant)`&#x20;
8. Since fees are added to liquidity pools, the invariant `k` increases at the end of every trade.

{% hint style="info" %}
**`On ShibaSwap a user can provide liquidity and choose to enter the Yield Farm/Woof Pools to earn more rewards apart from Swap Fees and Protocol fees.`**

**`If they choose to not enter the farm, they receive the swap fees proportional to their share in the pool excluding the Protocol Fees, they would recieve`**&#x20;

* **`0.2% of the fees from trades involving ETH,WBTC,USDC,USDT,DAI`**
* **`0.25% of the fees from all other trades`**

**`These fees are immediately deposited into liquidity reserves and is split by liquidity providers proportional to their contribution to liquidity reserves`**
{% endhint %}

**Factory**                                                                                                                                                              [**ShibaSwap: Factory v2**](https://etherscan.io/address/0x115934131916c8b277dd010ee02de363c09d037c)&#x20;

1. Serves both as factory and registry for Uniswap pools or coin pairs
2. A record of all tokens and their associated pools is stored in the factory.
3. it can create an LP token for every pair on the swap

## How does this all come together in Shibswap?

**ShibaSwap** is an *automated liquidity protocol* powered by a [**constant product formula**](https://docs.uniswap.org/protocol/V2/concepts/protocol-overview/glossary#constant-product-formula)**.**&#x20;

It uses an automated market maker mechanism provided by UniSwap V2 Contracts to provide instant feedback on rates and slippage.

Shibaswap's liquidity is actually underpinned by a liquidity pool which are smart contracts that hold balances of two unique tokens and enforces [**constant product formula**](https://docs.uniswap.org/protocol/V2/concepts/protocol-overview/glossary#constant-product-formula) rules around depositing and withdrawing them.

**`When one token is withdrawn (purchased), a proportional amount of the other must be deposited (sold), in order to maintain the constant.`**

The amount that is returned from swapping is based on an automated market maker formula. The graph below helps illustrate how the formula works. Essentially, the amount that is returned to you is based on the ratio of TokenA to TokenB in the pool.

![](https://3586859308-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Mf7kwzNuh1EgHo_mpth%2F-MiJJCNkimrE-_r8sFCp%2F-MiJOLAKTfcXi_q2xfQV%2Fimage.png?alt=media\&token=53b6654b-fb3c-4f30-82fd-36f61ebb1267)

### Role of [arbitraging](https://en.wikipedia.org/wiki/Arbitrage)

The ratio of TokenA to TokenB needs to be priced correctly relative to external markets. The pools maintain a ratio relative to the price of the rest of the market through people [**arbitraging**](https://en.wikipedia.org/wiki/Arbitrage) the pool.

### Protocol Fees

Uniswap v2 includes a 0.05% protocol fee that can be turned on and off. If turned on, this fee would be sent to a **feeTo** address specified in the factory contract.

ShibaSwap uses fees in 2 unique ways&#x20;

* **0.1%** of the fees is extracted from trades involving **ETH,WBTC,USDC,USDT,DAI** and paid as rewards in the form of **ETH,WBTC,USDC,USDT,DAI**&#x20;
  * **0.2%** is added back to the Liquidity Pool of the corresponding pair
* **0.05%** of the fees is extracted from all other trades and paid are rewards in the form of **SHIB/LEASH/BONE** tokens&#x20;
  * **0.25%** is added back to the Liquidity Pool of the corresponding pair

### An example trade

### Example: ETH → OMG <a href="#example-eth-omg" id="example-eth-omg"></a>

**Note:** This example uses a fee of 0.25%. The real ShibaSwap fees are either 0.2% or 0.25%.

10 ETH and 500 OMG (ERC20) are deposited into a smart contract by liquidity providers. An invariant is automatically set such that `ETH_pool * OMG_pool = invariant`.

> ETH\_pool = 10
>
> OMG\_pool = 500
>
> invariant = 10 \* 500 = 5000

An OMG buyer sends 1 ETH to the contract. A 0.25% fee is taken out for the liquidity providers, and the remaining 0.9975 ETH is added to `ETH_pool`. Next, the invariant is divided by the new amount of ETH in the liquidity pool to determine the new size of `OMG_pool`. The remaining OMG is sent to the buyer.

> Buyer sends: 1 ETH
>
> Fee = 1 ETH / 500 = 0.0025 ETH
>
> ETH\_pool = 10 + 1 - 0.0025 = 10.9975
>
> OMG\_pool = 5000/10.9975 = 454.65
>
> Buyer receives: 500 - 454.65 = 45.35 OMG

The fee is now added back into the liquidity pool, which acts as a payout to liquidity providers that is collected when liquidity is removed from the market. Since the fee is added after price calculation, the invariant increases slightly with every trade, making the system profitable for liquidity providers. In fact, what the invariant really represents is `ETH_pool * OMG_pool` at the end of the previous trade.

> ETH\_pool = 10.9975 + 0.0025 = 11
>
> OMG\_pool = 454.65
>
> new invariant = 11 \* 454.65 = 5,001.15

In this case the buyer received a rate of 45.35 OMG/ETH. However the price has shifted. If another buyer makes a trade in the same direction, they will get a slightly worse rate of OMG/ETH. However, if a buyer makes a trade in the opposite direction they will get a slightly better ETH/OMG rate.

> 1 ETH in\
> 44.5 OMG out\
> Rate = 45.35 OMG/ETH

Purchases that are large relative to the total size of the liquidity pools will cause price slippage. In an active market, arbitrage will ensure that the price will not shift too far from that of other exchanges.

![](https://i.imgur.com/HiHw6xL.png)

`Sourced from` [**`Uniswap V2 White Paper`**](https://uniswap.org/whitepaper.pdf) `Sourced from`[**`Uniswap V2 Overview`** ](https://uniswap.org/blog/uniswap-v2/) `Sourced from` [**`Uniswap V2Pool Overview`**](https://docs.uniswap.org/protocol/V2/concepts/core-concepts/pools) `Sourced from` [**`Understanding UniSwap Returns`**](https://docs.uniswap.org/protocol/V2/concepts/advanced-topics/understanding-returns)`Sourced from`[**`Uniswap Risks`**](https://pintail.medium.com/uniswap-a-good-deal-for-liquidity-providers-104c0b6816f2) `Sourced from` [**`Uniswap Intro`**](https://medium.com/scalar-capital/uniswap-a-unique-exchange-f4ef44f807bf) `Sourced from` [**`Uniswap Trade`**](https://docs.uniswap.org/protocol/V1/guides/trade-tokens) `Sourced from`[**`Uniswap A visual guide`**](https://docs.ethhub.io/guides/graphical-guide-for-understanding-uniswap/) `Sourced from` [**`Uniswap V1 White Paper`**](https://hackmd.io/C-DvwDSfSxuh-Gd4WKE_ig#Fee-Structure)
