How can i fetch BNB price from pancakeswap in solidity??

Pendem Shiva Shankar
2 min readSep 21, 2022

Fetching BNB price from pancakeswap pool to my smart contract is quite important for every contract that is related to market trades comparing the prices in other platforms.

the price can be obtained from chain.link , various contracts are deployed for various contracts for each combination specified.

we do have various contracts on various chains like test-net goes with different address and the main-net goes with different address.

Before we get them in detail, first lets get start with getting the price and its references to our existing solidity code.

pragma solidity 0.6.0; 
pragma experimental ABIEncoderV2;
import “@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol”;

declare these references to get the contract library.

declaring object to this Aggregator library.

constructor() public { 
priceFeed = AggregatorV3Interface(priceAddress);
}

the price address plays a major role in getting the price and this price will be of no use if we get confused. here are the addresses for BNB_USDT prices in both networks,

address private priceAddress = 0x0567F2323251f0Aab15c8dFb1967E4e8A7D42aeE; // BNB/USD Mainnet 
address private priceAddress = 0x2514895c72f50D8bd4B4F9b1110F0D6bD2c97526; // BNB/USD Testnet

this example specifies only one one pair in main-net and test-net, but looking for other networks and other combinations, just have a look at
https://docs.chain.link/docs/bnb-chain-addresses/

after the declaration, here is the method to get the final price,

function getLatestPrice() public view returns (uint) { 
(,int price,,uint timeStamp,)= priceFeed.latestRoundData();
// If the round is not complete yet, timestamp is 0
require(timeStamp > 0, “Round not complete”);
return (uint)(price);
}

this returns the price with a decimal of 8, and this varies with pair to pair based on the combination.

note: the frequency of price update is dependent with market value, some of the price gets updated for every minute or so and some other pairs get updated with a frequency of 24 hours.

here is the working example on github,

https://github.com/shivapendem/dexpricecontract/blob/main/contract.sol

--

--