Chapter 4. DeFi on Polygon, Part 2

We covered a lot of ground in the last tutorial, including a lot of theory. Let’s get right back to it for Part 2

Introduction

Welcome back! 👑

We’re going to jump right in and get our hands dirty for part 2 of this tutorial by writing a contract for swapping two ERC20 tokens.

Although it gets a bit more complex, the math is surprisingly simple. With just some basic arithmetic — and a lot of styling 😎 — we are going to build this:

swap-demo.mp4

Swapping Tokens

Whenever we buy something on the secondary market, we usually have more freedom as buyers and sellers to ask for and offer different prices, because we aren’t buying it directly from the producer.

🚗 So, let’s imagine we’re buying a used car. If the car we’re trying to buy is old and no one else is interested in it, we can probably get it for a good price. But if it’s a beautiful classic car with many interested buyers, we probably won’t be able to get it for the price we want, and will have more buyers making offers against us.

This is pretty much the same thing that happens when we buy and sell cryptocurrencies. If we want to trade one cryptocurrency for another, we go to a secondary market and trade directly with other people also looking to make a trade. There are currently two ways to trade cryptocurrencies easily: