get-price-unsafe.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { readApi, solidity, ethersJS } from "./common";
  2. import { ParameterType } from "../../components/EvmApi";
  3. export const getPriceUnsafe = readApi<"id">({
  4. name: "getPriceUnsafe",
  5. summary:
  6. "Get the **last updated** price object for the requested price feed ID. _Caution: This function may return a price from arbitrarily in the the past_",
  7. description: `
  8. This method returns the price object containing **last updated** price for the requested price feed ID.
  9. **This function may return a price from arbitrarily far in the past.** It is the
  10. caller's responsibility to check the returned \`publishTime\` to ensure that the
  11. update is recent enough for their use case. If you need the latest price, update the price using [\`updatePriceFeeds()\`](updatePriceFeeds) and then call [\`getPrice()\`](getPrice).
  12. The price object contains the following fields:
  13. 1. \`price\`: The latest price of the price feed.
  14. 2. \`conf\`: The confidence level of the price feed.
  15. 3. \`expo\`: The exponent of the price feed.
  16. 4. \`publishtime\`: The time when the price feed was last updated.
  17. Sample \`price\` object:
  18. \`\`\`json
  19. {
  20. price: 123456789n,
  21. conf: 180726074n,
  22. expo: -8,
  23. publishTime: 1721765108n
  24. }
  25. \`\`\`
  26. The \`price\` above is in the format of \`price * 10^expo\`. So, the \`price\` in above
  27. mentioned sample represents the number \`123456789 * 10(-8) = 1.23456789\` in
  28. this case.
  29. ### Error Response
  30. The above method can return the following error response:
  31. - \`StalePrice\`: The on-chain price has not been updated within the last
  32. [\`getValidTimePeriod()\`](getValidTimePeriod) seconds. Try calling
  33. [\`updatePriceFeeds()\`](updatePriceFeeds) to update the price feed with the
  34. latest price.
  35. - \`PriceFeedNotFound\`: The requested price feed has never received a price
  36. update or does not exist. Try calling
  37. [\`updatePriceFeeds()\`](updatePriceFeeds) to update the price feed.
  38. `,
  39. parameters: [
  40. {
  41. name: "id",
  42. type: ParameterType.PriceFeedId,
  43. description: "The ID of the price feed you want to read",
  44. },
  45. ],
  46. code: [
  47. solidity(
  48. ({ id }) => `
  49. bytes32 priceId = ${id ?? "/* <id> */"};
  50. PythStructs.Price memory currentBasePrice = pyth.getPriceUnsafe(priceId);
  51. `,
  52. ),
  53. ethersJS(
  54. ({ id }) => `
  55. const priceId = ${id ? `'${id}'` : "/* <id> */"};
  56. const [price, conf, expo, timestamp] = await contract.getPriceUnsafe(priceId);
  57. `,
  58. ),
  59. ],
  60. });