Uniswap V2 is a decentralized exchange that uses liquidity pools instead of order books, where anyone can create trading pairs (requiring WETH as one token), provide liquidity by depositing equal values of both tokens to earn trading fees, and trade through Router contracts that enable complex multi-hop swaps and Ether conversions. Developers can interact with Uniswap using the JavaScript SDK (v3) for price calculations and trade simulation, or by calling Router contract functions directly from Solidity smart contracts, with the SDK handling complex calculations while the Router contract executes transactions on the Ethereum blockchain.
Uniswap V2: A Developer's Guide to Solidity and JavaScript
Added:uni swap is exploding its trading volume is growing exponentially and is already larger than a couple of big centralized exchanges so if you are a blockchain developer you need to become familiar with uni swap so in this video i will explain what is uni swab how it worked and how to interact with it in javascript using the uni swap sdk and also how to interact with uni swap from a spot contract using solidity and i will focus on uni swept v2 the latest version so this video is up to date if you don't know me i'm julianne and on my channel idoblox i teach blockchain development and how to find your first blockchain job and before we continue quick announcement i'm working on a new course on advanced solidity so that's a great way to specialize yourself and stand out from other blockchain developers if you want to get informed when it comes out and receive some exclusive preview register with the link down below [Music] so what is uni swap and how does it work so uni swap is a decentralized exchange for es20 tokens you can buy and sell yes 20 tokens in a decentralized way using a smart contract on ethereum this is not the first decentralized exchange and what is different with uni swap is that under the hood it uses a liquidity pool so that means you don't trade directly with any specific trader but instead you go through this sort of intermediary concept of the liquidity pool and that's a mechanism that significantly improved the liquidity of the exchange so we're going to see the difference but contract of uni swaps so first we have the factory so the role of the factory is to create the different market of uniswep and act as a registry for all these different markets each bucket is represented by another spot contract that we call the pair smart contract and so in each pair you have two tokens for example die and rap ether or usdc and wrap ether then you have the router's particle track which is a utility that helps you to use uni swap in a most simple way and finally there are all the different yes 20 smart contracts that are manipulated by unisoi but these aren't strictly part of uni swap you need to have just interact with all these tokens so now we're going to see how the smart contract interact with each other so first as i said before the factory can create different pair smart contract so we can have pairs but contract with any combination so it can be two token like for example it's not an snx or it can be a token and a wrap ether so if you never heard of rap ether that is basically an es20 token version of ethers that's a token where inside you have that is backed by ether so one rock ether token equal one ether so in uni swap v1 we were able to create some market with ether but in v2 we can only create pair with wrap ether anybody can create a new pair this is a permissionless system all you have to do is to call the factory spot contract with the correct parameter so next i'm going to explain how we can interact with a pair spot contract contracts one kind of actor is called a liquidity provider so a liquidity provider can be anybody who has some tokens and who want to act as a market maker for a specific market so as a liquidity provider you will send a combination of the two token of the pair so for example if the pair is die and wrap ether so you will send the same value of dye and wrap ether to the spot contract and in exchange you get what is called a liquidity provider token and at any time in the future you can redeem your liquidity provider token against the die and wrap it the token that you initially provided plus you're also gonna get the trading fee that will earn by the spare spot contract in the meantime so next if you are a trader and you want to buy some rap ether with the spare smart contract what you're going to do is you're going to send some rap ether to the spot contract of the pair plus the trading fee and in exchange you're gonna get the die tokens so it can be a bit tricky to interact directly with a pair spot contracts so that's why the team of uni swap created another smart contract called a router that can be used as a convenience in order to interact with the pair contract so if you are building your own system around uni swap it's recommended that you use the router smart contract instead of directly interfacing with pair contracts but in some rare cases if you really need more flexibility that's when you would directly interact with the pair contract another advantage of using a router contract is that you can have some complex trading for example let's say that we have two pairs so dye wrap eater and usdc wrap ether but what we want to do is to trade between die and usdc but in the system you can see that we don't have this market well we can specify a route to the router spot contract so in the route we will first use the direct ether pair and then the usdc wrap ether pair and so that way we can synthetically create the dye usdc market and another advantage of using the router is that you can use ether in order to trade on uniswep and the router will automatically convert back and forth between ether and wrap either otherwise if you trade directly with the pair you have to take care of yourself of wrapping your ether into a wrap ether token first okay so that's it for the high level overview of uni swap next i'm going to show you how you can use javascript to interact with the uni swap smart contract using the unix of sdk [Music] so in this section i'm going to show you how you can interact with uni swap with javascript using the uniswap sdk which is a javascript library created by uni swap so this is what we call an isomorphic library that means you can use it on the front end in web browser or on the back end with node.js so there is one thing a little bit confusing even though this is for uni swap v2 actually the version of the library is unisoft sdk v3 so i'm going to show you how you can use it from node.js but it's very similar if you want to use it from the front and so here i am in my terminal i'm going to initiate an npm project like this and after i'm going to install the uniswep sdk like this at uni swap slash sdk so now if you check out what we have in package.json and independency we have uni swap sdk here all right so i'm going to create a file so we need to import a couple of stuff from uni swap so first we're going to import the chain id to identify which block blockchain you want to interact with and then an object called the fetcher i'm going to show you how to work after and we require this from uni swap sdk so for the front end you need to change the syntax with import from as you would do with any es6 module so next we're going to define the chain id we're going to select main net and after for the token address we're going to take the address of dice already copy pasted it from ether scan and after i'm going to create a pointer to the die token so for this you need to use the await keyword and by the way if we use the await keyword we need to wrap everything into a function otherwise node.js is not going to be super happy all right and so now with the fetcher object we're gonna fetch the token data and we specify the chain id and the token address and now with this object we can represent the die token in unison there is another way to initialize token object without using this fetcher object but this is a little bit more verbal so i prefer this way also by default when you use this notation here it's going to use the default provider defined by ether.js so in other terms it's going to connect to mannet but you can change this by passing it a ether.js provider so next we're going to create a pair object pair object allows to interact with a specific market so with a specific market we gonna need two tokens so we have die already and for the other one we're going to choose wrap ether so we can actually get this from the uni swap sdk here so let's do it and after we need to select the right network so wrap ether of chin id and after we're going to define a pair object like this once again we're gonna use the fetcher object fetch pair data and we give it the two token we want die and wrap ether so here the order doesn't have any importance it could be wrap ether die or die wrap ether this is the same pair and close this and now we can interact with this pair so like before it's also possible to instantiate this pair object in a more manual way without using fetcher but this is a little bit more of a boss so i prefer this way and next we're going to create a rot object and with this rod object we'll finally be able to do something interesting we create a new write object like this new route by the way i have to import it here and we're going to pass an array with the different pair that we want to use in our route so in our case we just want to use a single pair but if you want to access markets that don't directly exist like i explained in the previous section then you will pass several elements in this array and after you will put here the input token so for us that's gonna be wrap ether and so now we're going to be able to get the mid price so console log rod read price so this is going to return a token object so this is a custom object created by uniso but under the hood it uses jsbi which is javascript library to manipulate big number and so one method we can use is to simply can't this is going to transform this into an actual number we can represent actually this is going to be a string to be exact so we want six significant digit right in we're gonna get the number of die token that we can get with one wrap ether but if you want the opposite price what you can do is use the invert method here all right oh and i just realized there is a typo here let me remove the d all right save this and let's try to run this it cannot find this module okay so let's try to fix this by installing npm install ethers so this is probably a peer dependency that i had to install all right so now node index and this time is it going to work yes currently for one ether we can get 411 die and here we have the invert price so this is working well so the missing instruction in the documentation of unison sdk was that i had to install ether like this okay so we're gonna return to our script and so the price i show you here is the meat price so that's a theoretical price that you will actually never get if you buy or if you sell the token what you'll actually get is the execution price so to get this execution price we need something else so to get this execution price we need to build a trade and for that first we need to import a few extra stuff so first we're going to import a trade object it took an amount in a trade type okay and after here we're gonna create this trade new trade it we going to pass it the rat we define b4 and we need to specify a token amount that we want to trade so here first we pass a pointer to the token so wrap token and let's say that we want to provide 100 ether in input so we specified this here as a string so 100 and then we need 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 okay then we specify the trade type exact input so that means that we provide exactly this amount in input and you want to get as much possible die as output that's probably the trade type that you're going to use the most often and so after we're going to log trade dot execution price to significant [Music] and after we can also print the next mid price after this trade so just to be clear here we are we're not actually sending any transaction to the ethereum blockchain we're just asking unity swap hey you need swap if i trade this amount of token what would be the execution price and what would be the next mid price that's it and i think we have problem of parenthesis here we are missing a parenthesis here okay so let's save this let's run the script and we can see that the execution price will be slightly worse than the meat price and also after the trade the meat price is going down so that's normal so next how can we actually send this transaction to the ethereum blockchain so for that we're going to have a look at the solidity code of the router contract of uni swap and we need to provide a couple of arguments so first we need to provide the minimum amount of output token that we want then an array of the addresses for the different token we're gonna go through so in our case it's gonna be wrap ether and die then the recipient address and finally the deadline after which the trade order is not valid anymore so we are going to prepare all these parameters so let's go back to our script so first we're gonna import another object from uni swap that's called person that's going to allow us to define a tolerance for our trade that's going to be useful for specifying how much tokens we want in output so let's define this parameter here slippage top layer once so let's say that autoly runs is half a percent so that means compared to the price the execution price we got from the trade we are willing to tolerate a price that is up to 0.5 percent worst so we express this like this 50 and here at 10 000. so this is going to be 50 bips so beeps is a unit that is commonly used in finance one beep equal 0.001 percent so 50 beep that's basically 0.050 so that's 0.5 percent you can also specify percent directly if you want like if you wanted to do one percent then you would specify like this but here since we want to do less than one percent then we need to have a bigger number here so now we can define the minimum amount as output and we can use the trade object that we built before so dot minimum amount out and we pass our slippage tolerance and it is going to give us a token amount this is not the format that we want we want the raw format that's gonna be a string next we specify the paths of the traits that's gonna be an array of addresses so first the address of wrap ether and then the address of die so then the address of the recipient that should be checksum then we need then we need the deadline so this is a timestamp in second so we divide this by 1000 because date dot now give us a timestamp but in millisecond and after that we're gonna add for example 20 minute but it's up to you here to define what's your tolerance here basically the longer you wait the more the market will move in a certain direction and the more the price that you specify might be wrong so it becomes more risky and after we're going to specify how much ether we are willing to send so that's going to be trade dot input amount dot row and now we need to create this transaction so the units of sdk only allow you to read data from uniswell but not to send transactions so we're going to need another library and we're going to use ethers so we've already installed if there's before so we can require it directly and then below we're going to create an ethers provider so that represents a connection to the ethereum blockchain get default provider so we specify we want minute then we're going to specify the connection string on infrared so we're not going to run an ethereum node ourself that's too difficult we're going to use the infra service so you go to a website of infra you create a free account you log in after you go to your ethereum dashboard and you click on create new project so i've already reached the maximum for free account but after you will see your project requiring here so you click on it and in settings then you will take the https url you make sure you are on mainnet then you specify your url here and after you're gonna create a signer object new ethers well it was an uppercase w and so here you're gonna specify your private key and after you're gonna connect the provider to the signer like this so with this you'll be able to send a transaction and after you need to build an object that represents the smart contract of uni swap ethers.contract with an uppercase c okay and after you're gonna need the address and the abi of the router smart contract so for that you go to the website of uni swap you go to the dock click on smart contract router02 [Music] so that's this address so back to the terminal this is the first parameter here and after you need the abi and after i don't find the api here but that's okay because we can do something more simple with ether so what we need is swap exact if tokens yeah that's the function that oh no this one yes what exact if token so we copy this and after we're gonna pass an array with the different function we want to use so in our case we just want to use a single one let me put everything on the same line so ethers has something very nice which is called human readable abi so you can basically pass an array like this and you can build the api yourself very easily let's remove this here okay so now we have the api and finally we're gonna pass the account so now with the uni swap object we can send transaction to the ethereum blockchain so now you can send a transaction like this uni swap dot send exact if for tokens so here we have the unison there's a typo here so first we need amount out mean then the path then the recipient address then the dead line and after that we're going to configure the transaction so we gonna pass this value of ether well actually with modern version of javascript you don't need to repeat the key and the value so we can use this notation instead that's the same thing and we need to specify the gas price so for example 20 grey this is probably not going to be enough but you can check out east gas station dot info otherwise there is also a method with ethers to have this programmatically okay so at this point the transaction was not mine it was just sent to the network so here you can console log the transaction hash if you want [Music] and after if you want to wait for the transaction to be mine you're going to wait for the receipt you use the transaction object we got from b4 and now you can know in which block it was mine transaction was mine in block we see that block number okay great so now you know how to interact with your new swap using javascript and the uni swap sdk and you even know how to send a transaction by combining combining units of sdk and ethers so in the next section i'm going to show you how you can interact with uni swap but from a smart contract in solidity [Music] so in this section i'm going to show you how we can interact with uni swap from a smart contract in soviet t we're gonna build a function that allows us to buy some ether with tokens here i mean remix the online id for so det i'm gonna create a new file i'm gonna call this my d5 project and i'm using solidity 0.7 so i'm going to start with the pragma statement as usual and first i'm going to define an interface for the router contract of uni swap so for that i'm going to do a github repo of uni swap in uniswap v2 periphery that's where we're going to find the router smart contract it's important to note that this is a different repo from the report where you will find the pair smart contract the pair contract and another repo core so periphery is different then we go in contracts then here we'll see the router so we'll go into router 0 2 and we're not going to copy everything because we only need one function so we need the function swap exact tokens for ether here so we're gonna copy this go back to remix and copy this i'm going to format it a little bit so that it's a little bit more readable so in the previous section we used a similar function but that was the country that was swap exact if token so here the parameters are very very similar to what we had before but this time we also have to specify the amount in so that's the amount of token we're gonna send so let me clean up here the function signature because we don't need everything okay so and we're gonna go back to the github repo of uni swap because we need another thing in we're going to need another function signature here in router01 that's this function here it returned the address of wrap ether okay so next we need another interface for erc 20 token so we're going to take the one of open ziplining so that's a very popular library for solidity i'm in the gita repo i go in contracts token yes 20 i yes 20 and we're gonna cop p from here okay so now we're good with the interfaces and now we're going to create our smart contract my d5 project so we're going to create a pointer to uni swap with i uh swap we call this uni swap and then in a constructor we are going to pass it the address of the router of uni swap so this is 3dt 0.7 so we don't need the public keyword here that was only up to 3dt 0.6 so here we initialize our pointer very easily like this we pass it the address okay and after we're gonna create our main function to swap tokens for [Music] eve first we find the address of the token and after the amount of token that we're going to provide in input and the amount of ether that the minimum amount of ether that we want and then the deadline after which the trade is not valid anymore so first we need to move the tokens from the sending address to the spot contract so for that we create a pointer to the token then we use a transfer from function we transfer it from the sender to the address of this contract and for the amount that's going to be amount in so that means that before you call this function with the this msg sender you need to call the proof on the es20 token that you want to send then we need to build the arguments for the swap exact token for if so here first we're gonna build this pass that's the two tokens that we want to trade so that's an array of addresses [Music] of length two oops that's the country okay like this now for the first element of the past that's our token the second element is wrap ether so here we can use the uni swap contract it's going to return us the address of wrap ether like this and now we can call the function of uni swap swap exact token for if so the first argument is the amount of token we're going to provide so the amount in then the amount out mean so that's the minimum amount of ethers as output then the path then the sender the recipient so that's going to be msg sender so the ether is going to be sent directly to the center of the transaction it's not going to stay on our contract in the deadline and i realized that i forgot an operation here because before we call the swap exact token function from uni swap we need to approve uni swap to spend our token code because at this stage to token are inside our contract and unisab is going to try to pull the token to his contract but it's not going to work unless we approve it so for that we're going to need an extra line of code so here we're going to approve the address of uni swap to span amount in and here we will need to add this function to the signature of our interface here so i'm back in the interface of open zip link let's scroll up i'm gonna copy this function approve okay and so now we are able to exchange tokens against ethereum by using unit swap how can you decide all these different parameters well for the tokens that's the token that you want to spend so that's up to you the deadline that's basically your total runs for how long you want to keep the basically the implied price that you give with these two parameters so for this parameter that's basically how much ether you want to buy an amount in that's how much token you're willing to spend to buy this ether so you can reuse the example that i gave in the previous section with uni swap sdk in order to calculate these parameters it's also important to know that it's quite dangerous to try to evaluate the current price inside our function here in solidity because it's very easy for someone to manipulate the price on-chain so you really need to evaluate the correct market price of chen by using the uni swap sdk and if you really can't do an off-chance but you have to do it on-chain then you need to build your own oracle smart contract that cannot be manipulated by other people basically at the end of each block you will update this oracle smart contract with the price of uni swap at the end of the previous block so there are many variations of this function here exact tokens against ease exact if again token you have exact tokens against tokens and if you want to have the full list then you go to the official documentation of uni swap in router02 and here you will see all the different version of this swap function there also some other cool stuff that you can do with uni swap such as flash launch they call this flash swap so i probably will cover this in another video so now you become familiar with uni swap you know how it work you know how to interact with it from javascript and also from a 3dt smart contract so what do you do with this knowledge well one thing you could try is build a dashboard that shows the price of the different market of uni swap another idea is to combine your knowledge of uni swap with flash loan to try to do some arbitrage between uni swap and other decentralized exchanges and if you're interested in this i have a full playlist on flashlight on my channel and also if you want to keep learning about other d5 protocol on ethereum i also have a theory on this i'll see you there
Up Next

Understanding Ethereum Front Running: Sandwiches & Mempool
@CryptoWizards
26.4K views•2023-01-20

Torrent File Format & Bencoding: A Technical Deep Dive
@AsliEngineering
12.5K views•2022-08-08

Solidity Timelock Contract Tutorial: Delaying Transactions Securely
@EatTheBlocks
6.7K views•2022-08-02

Understanding Ethereum: A Comprehensive Beginner's Overview
@99Bitcoins
3.1M views•2018-06-26
Related Study Plans & Knowledge Roadmaps
Structured learning paths in Blockchain & Crypto







































