H
H
Hanry6542021-12-24 05:00:53
Node.js
Hanry654, 2021-12-24 05:00:53

How to find out the price of tokens through web3?

How to find out the price of a token through web3?
If you know the quantity, no problem

const contract = new web3.eth.Contract(erc20abi, tokenAddress);
const tokenBalance = await contract.methods.balanceOf(address).call();
console.log(tokenBalance)

Then how to find out the total cost of tokens as on etherscan`e?
61c5299e16789677021519.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2021-12-24
@Hanry654

There is no information about the price in the smart contract of the token itself (ERC-20), in which you receive the balance.
Price information must be obtained from exchanges, i.e. where these tokens are traded.
The easiest way to get the price is via the exchange API, usually HTTP or WebSocket.
For example, for those pairs that are traded on binance, you can get it like this https://binance-docs.github.io/apidocs/spot/en/#sy...
If you need to get prices from a decentralized exchange or get a price inside your smart -contracts - then you need to take prices from the smart contracts of the DEXs themselves.
For example, for Pancake, this is how you can find out the price

// 0.0001 - кол-во токена1
// 18 - кол-во знаков после запятой
const token1AmountIn = ethers.utils.parseUnits('0.0001', 18)
const amounts = await pancakeRouterV2Contract.getAmountsOut(token1AmountIn, [Token1Address, Token2Address])
// в amounts[1] будет кол-во токенов2, которые можно получить после обмена на кол-во токена 1
const price = amounts[1] / token1AmountIn

The Pancake Router contract code can be viewed here https://bscscan.com/address/0x10ed43c718714eb63d5a...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question