Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
PancakeSwap Token Price
import Web3 from 'web3';
import { Fetcher, ChainId, Token } from '@pancakeswap/sdk';
import { JsonRpcProvider } from '@ethersproject/providers';
import { BNB_ADDRESS, MAINNET_URL } from '../constants';
const provider = new JsonRpcProvider('');
class Web3Service {
constructor() {
this.web3 = new Web3(MAINNET_URL);
this.eth = this.web3.eth;
this.wallet = this.eth.accounts.wallet;
getTokenPrice = async (address) => {
const BNB = new Token(ChainId.MAINNET, BNB_ADDRESS, 18);
const token = await Fetcher.fetchTokenData(
const pair = await Fetcher.fetchPairData(BNB, token, provider);
const price = pair.token0Price.toSignificant(10);
return price;
export default Web3Service;
Copy link

Syloid commented Jul 11, 2021

Your code works perfectly, but do you know if there is a way to get the updated price more frequently? Cheers


Copy link

david-mart commented Jul 11, 2021

@Syloid so apparently there's an issue on BSC itself, resulting in some token prices not being updated with every block updated, i.e. pancakeswap's SDK price is actually different than you'd see if you go to the their website and try to exchange. Reported here and here as well as in lots of other issues on github.

The best solution that I found so far is to check the latest block number (or the timestamp) in the price object returned by fetchPairData, see if it differs from latest block significantly (for example, more than 1 minute), and then get the latest price from 0x API if it is too outdated. LMK if you find better solutions!


Copy link

furkancelik commented Nov 9, 2021

@david-mart Hi, how can I see the price instantly? (Poocoin like)


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment