I need derive price from decentralized exchanges, and I have finished some research about Uniswap v3.

It’s brand new for me, and after that I want to share some ideas about DeFi, and I think it would be helpful for you to understand Uniswap and some other decentralized exchanges.

DeFi from Scratch

We exchange stuffs very often, and we can exchange tokens in a centralized exchange.

For example, Alice owns some ETH, and Bob owns some DAI. Now, Alice want to swap some ETH for DAI, and Bob want to swap some DAI for ETH. How could they do?

A Centralized Exchange

Both Alice and Bob can goto a centralized exchange, like Binance.com, they can swap their tokens which they owned to the tokens which they want.

It’s very convenient. But how could they do if they don’t trust the centralized exchanges?

On-chain Swap Directly

They can swap directly, you may say so. Yes, they can communicate with each other, and consider a price, then they can do it. Now Alice send the ETH to Bob, and wait Bob to send DAI back. But now Bob don’t want to send DAI back, what can Alice do?

Nothing! Alice loss her ETH!

Swap via Smart Contract

Both Alice and Bob don’t want to meet such above situation. So they can use a smart contract:

  1. Alice send the proper ETH to the smart contract and mark it’s to Bob;
  2. Then Bob send the proper DAI to the smart contract and mark it’s to Alice;
  3. The smart contract determined that the condition is satisfied, then the smart contract:
    1. Send proper DAI to Alice;
    2. Send proper ETH to Bob;
  4. Otherwise, if Bob didn’t send the proper DAI to the smart contract, after some blocks(like timeout), the smart contract will send Alice’s ETH back, or both Alice and Bob can withdraw their tokens from the smart contract in any time.

That was a perfectly progress, both Alice and Bob are trust in the smart contract.

Liquidity Boost Decentralized Exchange

Let’s admit that it’s difficult to find people who want to exchange with you. The smart contract can do more, like Uniswap:

  1. Someone could be a liquidity provider:
    1. Put some tokens for exchanging into liquidity pool, let’s say you privode both ETH and DAI as liquidity;
    2. The Uniswap will give you a NFT to represent the position you hold(Non-Fungible Tokens vs. Fungible Tokens).
  2. Then someone else can swap tokens from liquidity, for example, Bob want to swap DAI for ETH:
    1. Bob will send DAI to the liquidity pool which hold by the smart contract;
    2. The smart contract then send back ETH from liquidity pool;

Now you don’t need to find someone to swap, you can swap when the liquidity is satisfied, to do so, the liquidity providers will charge some fee from your operations, that engage people who owns tokens to be the liquidity providers.