getLatestPrice
Retrieve real-time price data for specific trading pairs across blockchains using Chainlink decentralized feeds, enabling integration into AI systems and autonomous agents.
Instructions
Fetches the latest price for a given pair on a specified chain
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
No arguments | |||
Implementation Reference
- index.js:41-90 (handler)The handler function that implements the getLatestPrice tool logic: validates inputs, finds the Chainlink feed, initializes ethers provider and contract, fetches latest round data and decimals, formats the price, and returns structured JSON response or error.async ({ pair, chain }) => { try { // Validate inputs const chainKey = chain.toLowerCase(); latestPriceSchema.parse({ pair, chain }); // Find feed by pair const feed = feedsData[chainKey].feeds.find((f) => f.name.toLowerCase() === pair.toLowerCase()); if (!feed) { throw new Error(`Pair ${pair} not found on chain ${chain}`); } // Initialize provider and contract const provider = new ethers.JsonRpcProvider(`${feedsData[chainKey].baseUrl}/${process.env.INFURA_API_KEY}`); const priceFeedContract = new ethers.Contract(feed.proxyAddress, priceFeedAbi, provider); // Fetch decimals and latest round data const [decimals, roundData] = await Promise.all([ priceFeedContract.decimals(), priceFeedContract.latestRoundData() ]); const price = ethers.formatUnits(roundData.answer, decimals); const timestamp = Number(roundData.updatedAt) * 1000; return { content: [{ type: 'text', text: JSON.stringify({ chain, pair, price: Number(price), decimals: Number(decimals), roundId: roundData.roundId.toString(), timestamp: new Date(timestamp).toISOString(), proxyAddress: feed.proxyAddress, feedCategory: feed.feedCategory }, null, 2) }] }; } catch (error) { return { content: [{ type: 'text', text: `Error: ${error.message}` }], isError: true }; } }
- index.js:29-34 (schema)Zod input schema for the getLatestPrice tool, defining 'pair' and 'chain' parameters with validation for supported chains.const latestPriceSchema = z.object({ pair: z.string().describe('The price feed pair, e.g., FIL/ETH or FDUSD/USD'), chain: z.string().refine((val) => feedsData[val.toLowerCase()], { message: 'Unsupported chain' }).describe('The blockchain network, e.g., ethereum or base') });
- index.js:37-91 (registration)Registration of the 'getLatestPrice' tool using server.tool, providing name, description, input schema, and inline handler function.server.tool( 'getLatestPrice', 'Fetches the latest price for a given pair on a specified chain', latestPriceSchema, async ({ pair, chain }) => { try { // Validate inputs const chainKey = chain.toLowerCase(); latestPriceSchema.parse({ pair, chain }); // Find feed by pair const feed = feedsData[chainKey].feeds.find((f) => f.name.toLowerCase() === pair.toLowerCase()); if (!feed) { throw new Error(`Pair ${pair} not found on chain ${chain}`); } // Initialize provider and contract const provider = new ethers.JsonRpcProvider(`${feedsData[chainKey].baseUrl}/${process.env.INFURA_API_KEY}`); const priceFeedContract = new ethers.Contract(feed.proxyAddress, priceFeedAbi, provider); // Fetch decimals and latest round data const [decimals, roundData] = await Promise.all([ priceFeedContract.decimals(), priceFeedContract.latestRoundData() ]); const price = ethers.formatUnits(roundData.answer, decimals); const timestamp = Number(roundData.updatedAt) * 1000; return { content: [{ type: 'text', text: JSON.stringify({ chain, pair, price: Number(price), decimals: Number(decimals), roundId: roundData.roundId.toString(), timestamp: new Date(timestamp).toISOString(), proxyAddress: feed.proxyAddress, feedCategory: feed.feedCategory }, null, 2) }] }; } catch (error) { return { content: [{ type: 'text', text: `Error: ${error.message}` }], isError: true }; } } );