Skip to content

Instantly share code, notes, and snippets.

@david-mart
Created June 12, 2021 02:00
Show Gist options
  • Save david-mart/364198f4e5d74e49a23a1018468c3db1 to your computer and use it in GitHub Desktop.
Save david-mart/364198f4e5d74e49a23a1018468c3db1 to your computer and use it in GitHub Desktop.
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('https://bsc-dataseed1.binance.org/');
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(
ChainId.MAINNET,
address,
provider,
);
const pair = await Fetcher.fetchPairData(BNB, token, provider);
const price = pair.token0Price.toSignificant(10);
return price;
};
}
export default Web3Service;
@acastaneiras
Copy link

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

@david-mart
Copy link
Author

@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!

@furkancelik
Copy link

@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