A tutorial that teaches how to use Pyth Price Feeds to access real-time asset data, directly from your smart contracts on the Base testnet.
curl -L https://foundry.paradigm.xyz | bash
foundryup
, to install the latest (nightly) build of Foundryforge install
.
To install Pyth oracle contracts, run:
foundry.toml
file by appending the following line:
ExampleContract
. The code uses the IPyth
interface from the Pyth Solidity SDK.
An instance ofIPyth
is defined within the contract that provides functions for consuming Pyth price feeds. The constructor for the IPyth
interface expects a contract address to be provided. This address provided in the code example below (0xA2aa501b19aff244D90cc15a4Cf739D2725B5729
) corresponds to the Pyth contract address for the Base Sepolia testnet.
getLatestPrice
. This function takes a provided priceUpdateData
that is used to get updated price data, and returns the price given a priceId
of a price feed. The smart contract provided below uses a priceId
of 0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace
, which corresponds to the price feed for ETH / USD
.
src/ExampleContract.sol
and delete the src/Counter.sol
contract that was generated with the project (You can also delete the test/Counter.t.sol
and script/Counter.s.sol
files).
To compile the new smart contract, run:
cast wallet import
command to import the private key of the wallet into Foundry’s securely encrypted keystore:
deployer
account in your Foundry project, run:
.env
file in the home directory of your project, and add the RPC URL for the Base Sepolia testnet:
.env
file has been created, run the following command to load the environment variables in the current command line session:
forge create
command. The command requires you to specify the smart contract you want to deploy, an RPC URL of the network you want to deploy to, and the account you want to deploy with.
To deploy the ExampleContract
smart contract to the Base Sepolia test network, run the following command:
getLatestPrice(bytes[])
function of the deployed contract takes a priceUpdateData
argument that is used to get the latest price. This data can be fetched using the Hermes web service. Hermes allows users to easily query for recent price updates via a REST API. Make a curl request to fetch the priceUpdateData
the priceId
, 0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace
:
priceUpdateData
, you can use Foundry’s cast
command-line tool to interact with the smart contract and call the getLatestPrice(bytes[])
function to fetch the latest price of ETH.
To call the getLatestPrice(bytes[])
function of the smart contract, run the following command, replacing <DEPLOYED_ADDRESS>
with the address of your deployed contract, and <PRICE_UPDATE_DATA>
with the priceUpdateData
returned by the Hermes endpoint:
ETH / USD
price in hexadecimal form.