Get Uniswap spot token prices programmatically | Coding tutorial | Ethers.js, Uniswap V3 SDK
Вставка
- Опубліковано 9 лют 2025
- Get my free EthersJS cheatsheet to master Web3!
👉 blockman-codes...
------------------------------------------
Courses:
👉 Build a Uniswap V3 interface that can do swaps: bit.ly/3JkXYqL
------------------------------------------
The Uniswap V3 docs for programmatically requesting spot prices are not beginner-friendly.
I've rewritten that code so anyone with JS experience can understand it.
Let's learn to query current prices on Uniswap.
This uses Node, Ethers.js, and the Uniswap V3 SDK.
---------------------
Mentioned URLs
docs.uniswap.o...
infura.io/
etherscan.io/
info.uniswap.o...
app.uniswap.or...
---------------------
Github Code
gist.github.co...
Learn to use all of Uniswap's swap and liquidity functionality with code. bit.ly/3JkXYqL
your channel gonna be a big channel because of the way you explain things and cover topics that nobody explains in the internet, keep it up brother.
Thanks brother!
wow you're de facto an Ambassador, the knowledge value is so high!!
Your code is so simple and the official tutorial of uniswap is so complicated
I agree lol. That's why I made this
@@blockmancodes Hey mate thanx for reply, I tested your code and it works, could you tell me how to sell my UNI then? I simply switch "tokenIn" and "tokenOut" params but it didnt work
Where did you get the quoteraddress?
yay this works! thanks! my wife's boyfriend is very happy... one issue i came with is that when certain contracts, for example USDC, is using a proxy and can't read token symbol or decimals, you will need to hard code the values. otherwise, this code works out of the box just by simply changing the contract pool address.
Very helpful! I am curious however about the price difference between the Uniswap site and the programme's output. I get the same on different pairs.
Thanks for the tutorial man! Is it possible to get a price for different LP? for EG I want to convert WBTC -> UNI
How would one transfer this over to let's say check pools on sushi swap for example?
gm! a really detailed and amazing tutorial, thank you bro!
Great Video :) I noticed that the quoter contract "quoteExactInputSingle" call didnt have a particular reference to the specific pool we are looking at ? It is taking the two token addresses plus the fee amount(which is specifically from the target pool). How do you get the exchange amount for specific pools if there are several pools with the same pair of tokens? Cheers :)
Oh, I think I answered my own question: Each token pair has only 1 Pool in Uniswap at each Fee level, so the fee itself would point at the pool being referenced(of THAT pair combination). Correct?
how to find the dollar amount for each currency i mean ho to get the value 42595.9 for WBTC and 42566.4 for ETH?
Thanks. Can you explain what callStatic function does?
Sends a write request to your node but tells it not to execute
Excellent video mate, tyvm
Thank you!
Thank you so much for the comprehensive video! May I ask if this will work with Uniswap V2 as well?
Unfortunately not. The documentation is a little better for V2 though so you may be able to figure it out
Thank you! This is the best video teaching how to calculate the execution price on UniSwap v3! Could you please also suggest how to calculate the execution price on UniSwap V2 (or DEXs based on UniSwap V2 Core, e.g. Pancake Swap, etc.) ?
Thank you! I'm hoping to start getting pancake swap tutorials out by the year's end.
@Buggs Bunny I've wanted to cover pancake swap for a long time. Will try by end of year
I got the prices for some pools on the polygon network, but I want to get prices at scale and noticed that it doesnt work for all the pools for some reason. Do you have an idea on why?
What error are you getting for pools that don't work?
@@blockmancodes I figured it out I just had to hard code in the decimals and the symbols for some pools. I was wondering if you could do some Kyberswap prices? I keep looking for tutorials but can't find any
@@viision8666 Good job!
And yes. Adding to my todo list
Hi pls how did you do so?
@@blockmancodes Im using Kyberswap aggregator api to fetch prices just confused on the params and making it work. This would be greatly appreciated if you could!
I finished a cheap flashloans courses. And a guy there uses Subgraph to fetch pairs and prices for triangular arbitrage (in phyton). But I noticed that subgraph has a very old data. UST is still 0.99 USD there. So I hope I'll be able to fetch the prices your way.
Interesting! I'm surprised the subgraph is outdated
🙏 thank you!
What I need to change if I’m trying to swap token on v2 uniswap ?
V2 and V3 have completely different documentation so I don't think it's as simple as a small change
yeah got it thanks!
Hi, I followed the official uniswap v3 sdk turtorial, and I can get the outputAmout using the Quoter Contract function -> quoteExactInputSingle when I try to swap WETH-> USDT, but I can't get outputAmout correctly when I try to swap USDT->WETH, I just changed the parameters of tokenIn and tokenOut, so can u help me with that?
What contract are you using for the swap?
great tutorial!
I see the free plan of etherscan API has a limit of 5 calls per second
is there any free alternatives if I want to make a lot of API calls per second? (e.g. scale up this crawler to quote more liquidity pools per second)
also, I notice the time to fetch the price is a bit slow (e.g. took me around 10 secs to fetch the price)
is there any way to optimise the runtime speed?
I used etherscan to get the ABI here. You can store your ABIs locally in advance. Will be much faster
Fantastic video! The official documentation proved to be confusing and I could not get it done. This was a great explanation of the whole process.
Also, I'm running into a typeerror: "tokenContract0.symbol is not a function" where your line 41-44 would be in the github. Do you know what may be the cause of this by chance?
I found the problem for anyone else using a different pool address. I was using the WETH/USDC pool but the USDC side was using a proxy contract and didn't have the decimals and symbols functions in the main contract. Setting these values manually made the whole thing work.
Just look at the respective addresses in the pool and make sure the methods line up
Well done brother! This will probably help some others too
this was helpful thanks. who ever is wondering, if using usdc as one of the tokens, set the following fields manually const tokenSymbol0 = "USDC" and const tokenDecimals0 = 6
Question, if the token and decimals are missing from the contract, is there a way to get it via code?
@@kingtut11 thanks a lot
This is amazing. Would be able to make some videos on how to calculate slippage and price impact?
Yes. I can definitely do that.
Amazing! Thanks
My pleasure
what would you use for it to update automatically when the price changes? I don't see any events for the quoter contract.
I would just poll it at some interval and update the UI when I get a response back
@@blockmancodes etherscan allows 5 calls every minute. So using setInterval() every 20 seconds and if the value is different then we'll change it?
@@RA-eg8tw My free plan allows 5 calls per second. Yours is probably the same. That should allow pinging it without remorse
@@blockmancodes Thanks. I do have this issue.
I need to get updated price of eth for another contract I'm coding so it can be used for calculation in minting/burn this token.
However I would need to run a transaction everytime the oracle updates the price. WHICH IS VERY EXPENSIVE IN GAS FEES.
How would you update the price of ETH for this contract without paying gas?
I thought of putting the eth price as a parameter in the mint/burn function and when the user calls the function it'll pass the updated ETH price and the user/signer will have to pay for the extra gas fees.
Not sure if there's a better way around it.
@@RA-eg8tw Without thinking too much, if I could pass it on to the user, I would
Is there any way of getting prices no matter the fee? I mean, for any existing pool for an specific pair
Hey brother. Can you elaborate on "getting prices no matter the fee"? I don't fully understand
Nice content boss.
Does this script have the GUI where user can connect to metamask and convert crypto?
How can j do it
It would be a lot more code to add that with a nice UI.
I have an example in my uniswap course. But you could also look at my old YT tutorial called "build a uniswap v3 interface" for inspiration
Great video. I have a problem and that is that I do not know what URL is referenced in INFURA_URL and if it should be linked to the ETHERSCAN_API_KEY.
I mention where to create it in the video around 3:40. Let me know if you need help with specifics
I am just stuck with the API key, where can get the .env variables:
INFURA_URL, ETHERSCAN_API_KEY.
I have re-used the existing one, which was created previously, By using that API key, I am getting an Undefined value for the "data:" attribute can you please help me with this?
Where did you get the existing one?
You need to create accounts on infura and etherscan and generate the API keys
@@blockmancodes Found the issue, it's my mistake. I have provided Infura project API key as the input to the .env file. I didn't know about
etherscan apikey. From your reply, I have checked etherscan API key & found the usage. Now the code is working and getting the result. Thank you so much.
@@gopikumar-vv3eo Good job!
Thank you for sharing your number.
Hello, what is different from "quote exact in" in AlphaRouter world and how to get the price when using AlphaRouter? Thanks you
I show how to get a price quote in the alpha router video. Did you check that out?
There are many different ways to get price quotes with Uniswap. It can be confusing :)
What else do you want to learn to do in Uniswap with code?
Hey thanks for the great video. I would love to see you create a tutorial for creating a new liquidity position in a pool. That would be super cool.
@@thomasini Thanks bro! I think I cover it here, ua-cam.com/video/Igld8EvmrRI/v-deo.html
Let me know if it's not
i wached 100 videos and your videos are the best :).... could you make a vesting lock system like if the vest for 3 months they get 4% extra tokens 6 months 7.5% and 1 year 10%. Early release fee of 10% if the pull out before the vesting end period or if you have a better vesting idea that would also do :) any type of vesting system x
@@Londontownboy Thank you! That means a lot.
Check out my ether staking tutorial, ua-cam.com/video/7QsqElEaWBQ/v-deo.html . I think it's similar to what you want to build
@@blockmancodes Do you think you could do one with locked staking for the period❤️
Hi, very good tutorial
I have a question concerning the fee. I cannot see the fee function when i inspect a pool contract.
For example if I select this pool contract : 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852
There is no field fee() in the read contract section
Do you have any idea what's going on ?
Thanks🙂
That's a V2 pool. V3 pools should have the fee
when i run the file, i am getting a "could not detect Network" error, do you know what the reason is for this? Thanks!
Could be an issue with your Infura URL. Try hardcoding your URL in the code like, ethers.providers.JsonRpcProvider("YOUR_URL")
@@blockmancodes Yes I think this is the problem too. Thanks for getting back to me. For a test scenario, does it matter what network I point Infura too? I am currently using Ropsten. I am guessing that this shouldn't matter, but am returning some data, just not price info... P.S. your video is amazing, the Uniswap docs written poorly!
Got it working, any pointers on how to adapt this for SushiSwap? Or would I need to use UniswapV2?
@@Nuggets_au It only matters for 2 reasons.
1. You need ETH in your wallet on that specific network
2. Token addresses are different on different networks. This could be the issue you're having.
@@Nuggets_au Sushiswap videos coming soon if I have time!
Will it work for Uniswap V2?
I'm not an expert at V2 but I believe it's completely different
Hi, tried to use this example on mainnet but with WBTC-USDC pair. It doesn't work. Any idea?
It seems that pool fee is a problem. Initially I tried with 0.05% but when set it to 0.3% I can get a functional pool address.
So far, I can say that getting the right pool address is everything but trivial (and predictable?). Perhaps it has so many "routes" (pools combinations) because of auto-routing feature? Maybe not, I tried to check what contact address appeared in live/real transactions on the mainnet. It seems that the same address is used for two different pairs: weth-wbtc and usdc-wbtc: 0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45 I'm completely lost.
Yea it's possible that a pair only exists on some fees.
So I always prefer to start with a pool you find at info.uniswap.org/#/ (or Uniswap graphql) , find that contract on etherscan and just use the stated fees/address/etc, because then you know it's a legit pool.
"0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45" is the router address. See: etherscan.io/address/0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45 .
This router address will be used for all swaps but is not the pair address itself.
@@blockmancodes Thanks for your reply. Don't know if I'm doing something wrong but it seems that pool addresses from mentioned site are "obsolete" in some way, i.e. I cannot see much recent activity for pair such as wbtc-usdc
Can you make a video on how to actually make your bot swap the coins based on the data the current bot has given?
For sure. I'll put out a video within the month
@@blockmancodes Awesome! Could you also talk quickly about how to set a custom gasPrice and gasLimit for 'approving' tokens on Uniswap? I am trying to help someone with a hacked wallet but we can't approve the 'swap usdt' because the instant withdraw bot from someone else is biding higher gas fees. :(
@@LukassenTutorials I'll try to remember to include that in the video!
@@blockmancodes Thank you so much. Looking forward to the video!
Hello! I am from China, I want to get the spot price on uniswap, but I can only order python. Is there any tutorial on this? I hope you can give me some pointers. Thank you
Hey! There's a web3 library for Python, web3py.readthedocs.io/en/stable/ (github.com/ethereum/web3.py).
I haven't tried it but it looks well used.
@@blockmancodes I know this module but I don't know how to use it, I mainly take the price on Uniswap
i wish i did find this video sooner
Thank you
At the end of the video. 13.09 + 0.03% = 13.13 (the price from uniswap interface)