Pyth.sol 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. // SPDX-License-Identifier: Apache 2
  2. pragma solidity ^0.8.0;
  3. import "../libraries/external/UnsafeBytesLib.sol";
  4. import "@pythnetwork/pyth-sdk-solidity/AbstractPyth.sol";
  5. import "@pythnetwork/pyth-sdk-solidity/PythStructs.sol";
  6. import "@pythnetwork/pyth-sdk-solidity/PythErrors.sol";
  7. import "./PythAccumulator.sol";
  8. import "./PythGetters.sol";
  9. import "./PythSetters.sol";
  10. import "./PythInternalStructs.sol";
  11. abstract contract Pyth is
  12. PythGetters,
  13. PythSetters,
  14. AbstractPyth,
  15. PythAccumulator
  16. {
  17. function _initialize(
  18. address wormhole,
  19. uint16[] calldata dataSourceEmitterChainIds,
  20. bytes32[] calldata dataSourceEmitterAddresses,
  21. uint16 governanceEmitterChainId,
  22. bytes32 governanceEmitterAddress,
  23. uint64 governanceInitialSequence,
  24. uint validTimePeriodSeconds,
  25. uint singleUpdateFeeInWei
  26. ) internal {
  27. setWormhole(wormhole);
  28. if (
  29. dataSourceEmitterChainIds.length !=
  30. dataSourceEmitterAddresses.length
  31. ) revert PythErrors.InvalidArgument();
  32. for (uint i = 0; i < dataSourceEmitterChainIds.length; i++) {
  33. PythInternalStructs.DataSource memory ds = PythInternalStructs
  34. .DataSource(
  35. dataSourceEmitterChainIds[i],
  36. dataSourceEmitterAddresses[i]
  37. );
  38. if (PythGetters.isValidDataSource(ds.chainId, ds.emitterAddress))
  39. revert PythErrors.InvalidArgument();
  40. _state.isValidDataSource[hashDataSource(ds)] = true;
  41. _state.validDataSources.push(ds);
  42. }
  43. {
  44. PythInternalStructs.DataSource memory ds = PythInternalStructs
  45. .DataSource(governanceEmitterChainId, governanceEmitterAddress);
  46. PythSetters.setGovernanceDataSource(ds);
  47. PythSetters.setLastExecutedGovernanceSequence(
  48. governanceInitialSequence
  49. );
  50. }
  51. PythSetters.setValidTimePeriodSeconds(validTimePeriodSeconds);
  52. PythSetters.setSingleUpdateFeeInWei(singleUpdateFeeInWei);
  53. }
  54. function updatePriceFeeds(
  55. bytes[] calldata updateData
  56. ) public payable override {
  57. uint totalNumUpdates = 0;
  58. for (uint i = 0; i < updateData.length; ) {
  59. totalNumUpdates += updatePriceInfosFromAccumulatorUpdate(
  60. updateData[i]
  61. );
  62. unchecked {
  63. i++;
  64. }
  65. }
  66. uint requiredFee = getTotalFee(totalNumUpdates);
  67. if (msg.value < requiredFee) revert PythErrors.InsufficientFee();
  68. }
  69. /// This method is deprecated, please use the `getUpdateFee(bytes[])` instead.
  70. function getUpdateFee(
  71. uint updateDataSize
  72. ) public view returns (uint feeAmount) {
  73. // In the accumulator update data a single update can contain
  74. // up to 255 messages and we charge a singleUpdateFee per each
  75. // message
  76. return
  77. 255 *
  78. singleUpdateFeeInWei() *
  79. updateDataSize +
  80. transactionFeeInWei();
  81. }
  82. function getUpdateFee(
  83. bytes[] calldata updateData
  84. ) public view override returns (uint feeAmount) {
  85. uint totalNumUpdates = 0;
  86. for (uint i = 0; i < updateData.length; i++) {
  87. if (
  88. updateData[i].length > 4 &&
  89. UnsafeCalldataBytesLib.toUint32(updateData[i], 0) ==
  90. ACCUMULATOR_MAGIC
  91. ) {
  92. (
  93. uint offset,
  94. UpdateType updateType
  95. ) = extractUpdateTypeFromAccumulatorHeader(updateData[i]);
  96. if (updateType != UpdateType.WormholeMerkle) {
  97. revert PythErrors.InvalidUpdateData();
  98. }
  99. totalNumUpdates += parseWormholeMerkleHeaderNumUpdates(
  100. updateData[i],
  101. offset
  102. );
  103. } else {
  104. revert PythErrors.InvalidUpdateData();
  105. }
  106. }
  107. return getTotalFee(totalNumUpdates);
  108. }
  109. function getTwapUpdateFee(
  110. bytes[] calldata updateData
  111. ) public view override returns (uint feeAmount) {
  112. uint totalNumUpdates = 0;
  113. // For TWAP updates, updateData is always length 2 (start and end points),
  114. // but each VAA can contain multiple price feeds. We only need to count
  115. // the number of updates in the first VAA since both VAAs will have the
  116. // same number of price feeds.
  117. if (
  118. updateData[0].length > 4 &&
  119. UnsafeCalldataBytesLib.toUint32(updateData[0], 0) ==
  120. ACCUMULATOR_MAGIC
  121. ) {
  122. (
  123. uint offset,
  124. UpdateType updateType
  125. ) = extractUpdateTypeFromAccumulatorHeader(updateData[0]);
  126. if (updateType != UpdateType.WormholeMerkle) {
  127. revert PythErrors.InvalidUpdateData();
  128. }
  129. totalNumUpdates += parseWormholeMerkleHeaderNumUpdates(
  130. updateData[0],
  131. offset
  132. );
  133. } else {
  134. revert PythErrors.InvalidUpdateData();
  135. }
  136. return getTotalFee(totalNumUpdates);
  137. }
  138. // This is an overwrite of the same method in AbstractPyth.sol
  139. // to be more gas efficient.
  140. function updatePriceFeedsIfNecessary(
  141. bytes[] calldata updateData,
  142. bytes32[] calldata priceIds,
  143. uint64[] calldata publishTimes
  144. ) external payable override {
  145. if (priceIds.length != publishTimes.length)
  146. revert PythErrors.InvalidArgument();
  147. for (uint i = 0; i < priceIds.length; ) {
  148. // If the price does not exist, then the publish time is zero and
  149. // this condition will work fine.
  150. if (latestPriceInfoPublishTime(priceIds[i]) < publishTimes[i]) {
  151. updatePriceFeeds(updateData);
  152. return;
  153. }
  154. unchecked {
  155. i++;
  156. }
  157. }
  158. revert PythErrors.NoFreshUpdate();
  159. }
  160. // This is an overwrite of the same method in AbstractPyth.sol
  161. // to be more gas efficient. It cannot move to PythGetters as it
  162. // is overwriting the interface. Even indirect calling of a similar
  163. // method from PythGetter has some gas overhead.
  164. function getPriceUnsafe(
  165. bytes32 id
  166. ) public view override returns (PythStructs.Price memory price) {
  167. PythInternalStructs.PriceInfo storage info = _state.latestPriceInfo[id];
  168. price.publishTime = info.publishTime;
  169. price.expo = info.expo;
  170. price.price = info.price;
  171. price.conf = info.conf;
  172. if (price.publishTime == 0) revert PythErrors.PriceFeedNotFound();
  173. }
  174. // This is an overwrite of the same method in AbstractPyth.sol
  175. // to be more gas efficient. It cannot move to PythGetters as it
  176. // is overwriting the interface. Even indirect calling of a similar
  177. // method from PythGetter has some gas overhead.
  178. function getEmaPriceUnsafe(
  179. bytes32 id
  180. ) public view override returns (PythStructs.Price memory price) {
  181. PythInternalStructs.PriceInfo storage info = _state.latestPriceInfo[id];
  182. price.publishTime = info.publishTime;
  183. price.expo = info.expo;
  184. price.price = info.emaPrice;
  185. price.conf = info.emaConf;
  186. if (price.publishTime == 0) revert PythErrors.PriceFeedNotFound();
  187. }
  188. /// @dev Helper function to parse a single price update within a Merkle proof.
  189. /// Parsed price feeds will be stored in the context.
  190. function _parseSingleMerkleUpdate(
  191. PythInternalStructs.MerkleData memory merkleData,
  192. bytes calldata encoded,
  193. uint offset,
  194. PythInternalStructs.UpdateParseContext memory context
  195. ) internal pure returns (uint newOffset) {
  196. PythInternalStructs.PriceInfo memory priceInfo;
  197. bytes32 priceId;
  198. uint64 prevPublishTime;
  199. (
  200. newOffset,
  201. priceInfo,
  202. priceId,
  203. prevPublishTime
  204. ) = extractPriceInfoFromMerkleProof(merkleData.digest, encoded, offset);
  205. uint k = 0;
  206. for (; k < context.priceIds.length; k++) {
  207. if (context.priceIds[k] == priceId) {
  208. break;
  209. }
  210. }
  211. // Check if the priceId was requested and not already filled
  212. if (k < context.priceIds.length && context.priceFeeds[k].id == 0) {
  213. uint publishTime = uint(priceInfo.publishTime);
  214. if (
  215. publishTime >= context.minAllowedPublishTime &&
  216. publishTime <= context.maxAllowedPublishTime &&
  217. (!context.checkUniqueness ||
  218. context.minAllowedPublishTime > prevPublishTime)
  219. ) {
  220. context.priceFeeds[k].id = priceId;
  221. context.priceFeeds[k].price.price = priceInfo.price;
  222. context.priceFeeds[k].price.conf = priceInfo.conf;
  223. context.priceFeeds[k].price.expo = priceInfo.expo;
  224. context.priceFeeds[k].price.publishTime = publishTime;
  225. context.priceFeeds[k].emaPrice.price = priceInfo.emaPrice;
  226. context.priceFeeds[k].emaPrice.conf = priceInfo.emaConf;
  227. context.priceFeeds[k].emaPrice.expo = priceInfo.expo;
  228. context.priceFeeds[k].emaPrice.publishTime = publishTime;
  229. context.slots[k] = merkleData.slot;
  230. }
  231. }
  232. }
  233. /// @dev Processes a single entry from the updateData array.
  234. function _processSingleUpdateDataBlob(
  235. bytes calldata singleUpdateData,
  236. PythInternalStructs.UpdateParseContext memory context
  237. ) internal view returns (uint64 numUpdates) {
  238. // Check magic number and length first
  239. if (
  240. singleUpdateData.length <= 4 ||
  241. UnsafeCalldataBytesLib.toUint32(singleUpdateData, 0) !=
  242. ACCUMULATOR_MAGIC
  243. ) {
  244. revert PythErrors.InvalidUpdateData();
  245. }
  246. uint offset;
  247. {
  248. UpdateType updateType;
  249. (offset, updateType) = extractUpdateTypeFromAccumulatorHeader(
  250. singleUpdateData
  251. );
  252. if (updateType != UpdateType.WormholeMerkle) {
  253. revert PythErrors.InvalidUpdateData();
  254. }
  255. }
  256. // Extract Merkle data
  257. PythInternalStructs.MerkleData memory merkleData;
  258. bytes calldata encoded;
  259. (
  260. offset,
  261. merkleData.digest,
  262. merkleData.numUpdates,
  263. encoded,
  264. merkleData.slot
  265. ) = extractWormholeMerkleHeaderDigestAndNumUpdatesAndEncodedAndSlotFromAccumulatorUpdate(
  266. singleUpdateData,
  267. offset
  268. );
  269. // Process each update within the Merkle proof
  270. for (uint j = 0; j < merkleData.numUpdates; j++) {
  271. offset = _parseSingleMerkleUpdate(
  272. merkleData,
  273. encoded,
  274. offset,
  275. context
  276. );
  277. }
  278. // Check final offset
  279. if (offset != encoded.length) {
  280. revert PythErrors.InvalidUpdateData();
  281. }
  282. // Return the number of updates in this blob for tracking
  283. return merkleData.numUpdates;
  284. }
  285. function parsePriceFeedUpdatesWithConfig(
  286. bytes[] calldata updateData,
  287. bytes32[] calldata priceIds,
  288. uint64 minAllowedPublishTime,
  289. uint64 maxAllowedPublishTime,
  290. bool checkUniqueness,
  291. bool checkUpdateDataIsMinimal,
  292. bool storeUpdatesIfFresh
  293. )
  294. public
  295. payable
  296. returns (
  297. PythStructs.PriceFeed[] memory priceFeeds,
  298. uint64[] memory slots
  299. )
  300. {
  301. if (msg.value < getUpdateFee(updateData))
  302. revert PythErrors.InsufficientFee();
  303. // Create the context struct that holds all shared parameters
  304. PythInternalStructs.UpdateParseContext
  305. memory context = PythInternalStructs.UpdateParseContext({
  306. priceIds: priceIds,
  307. minAllowedPublishTime: minAllowedPublishTime,
  308. maxAllowedPublishTime: maxAllowedPublishTime,
  309. checkUniqueness: checkUniqueness,
  310. checkUpdateDataIsMinimal: checkUpdateDataIsMinimal,
  311. priceFeeds: new PythStructs.PriceFeed[](priceIds.length),
  312. slots: new uint64[](priceIds.length)
  313. });
  314. // Track total updates for minimal update data check
  315. uint64 totalUpdatesAcrossBlobs = 0;
  316. unchecked {
  317. // Process each update, passing the context struct
  318. // Parsed results will be filled in context.priceFeeds and context.slots
  319. for (uint i = 0; i < updateData.length; i++) {
  320. totalUpdatesAcrossBlobs += _processSingleUpdateDataBlob(
  321. updateData[i],
  322. context
  323. );
  324. }
  325. for (uint j = 0; j < priceIds.length; j++) {
  326. PythStructs.PriceFeed memory pf = context.priceFeeds[j];
  327. if (storeUpdatesIfFresh && pf.id != 0) {
  328. updateLatestPriceIfNecessary(
  329. priceIds[j],
  330. PythInternalStructs.PriceInfo({
  331. publishTime: uint64(pf.price.publishTime),
  332. expo: pf.price.expo,
  333. price: pf.price.price,
  334. conf: pf.price.conf,
  335. emaPrice: pf.emaPrice.price,
  336. emaConf: pf.emaPrice.conf
  337. })
  338. );
  339. }
  340. }
  341. }
  342. // In minimal update data mode, revert if we have more or less updates than price IDs
  343. if (
  344. checkUpdateDataIsMinimal &&
  345. totalUpdatesAcrossBlobs != priceIds.length
  346. ) {
  347. revert PythErrors.InvalidArgument();
  348. }
  349. // Check all price feeds were found
  350. for (uint k = 0; k < priceIds.length; k++) {
  351. if (context.priceFeeds[k].id == 0) {
  352. revert PythErrors.PriceFeedNotFoundWithinRange();
  353. }
  354. }
  355. // Return results
  356. return (context.priceFeeds, context.slots);
  357. }
  358. function parsePriceFeedUpdates(
  359. bytes[] calldata updateData,
  360. bytes32[] calldata priceIds,
  361. uint64 minPublishTime,
  362. uint64 maxPublishTime
  363. )
  364. external
  365. payable
  366. override
  367. returns (PythStructs.PriceFeed[] memory priceFeeds)
  368. {
  369. (priceFeeds, ) = parsePriceFeedUpdatesWithConfig(
  370. updateData,
  371. priceIds,
  372. minPublishTime,
  373. maxPublishTime,
  374. false,
  375. false,
  376. false
  377. );
  378. }
  379. function extractTwapPriceInfos(
  380. bytes calldata updateData
  381. )
  382. private
  383. view
  384. returns (
  385. /// @return newOffset The next position in the update data after processing this TWAP update
  386. /// @return priceInfos Array of extracted TWAP price information
  387. /// @return priceIds Array of corresponding price feed IDs
  388. uint newOffset,
  389. PythStructs.TwapPriceInfo[] memory twapPriceInfos,
  390. bytes32[] memory priceIds
  391. )
  392. {
  393. UpdateType updateType;
  394. uint offset;
  395. bytes20 digest;
  396. uint8 numUpdates;
  397. bytes calldata encoded;
  398. // Extract and validate the header for start data
  399. (offset, updateType) = extractUpdateTypeFromAccumulatorHeader(
  400. updateData
  401. );
  402. if (updateType != UpdateType.WormholeMerkle) {
  403. revert PythErrors.InvalidUpdateData();
  404. }
  405. (
  406. offset,
  407. digest,
  408. numUpdates,
  409. encoded,
  410. // slot ignored
  411. ) = extractWormholeMerkleHeaderDigestAndNumUpdatesAndEncodedAndSlotFromAccumulatorUpdate(
  412. updateData,
  413. offset
  414. );
  415. // Add additional validation before extracting TWAP price info
  416. if (offset >= updateData.length) {
  417. revert PythErrors.InvalidUpdateData();
  418. }
  419. // Initialize arrays to store all price infos and ids from this update
  420. twapPriceInfos = new PythStructs.TwapPriceInfo[](numUpdates);
  421. priceIds = new bytes32[](numUpdates);
  422. // Extract each TWAP price info from the merkle proof
  423. for (uint i = 0; i < numUpdates; i++) {
  424. PythStructs.TwapPriceInfo memory twapPriceInfo;
  425. bytes32 priceId;
  426. (
  427. offset,
  428. twapPriceInfo,
  429. priceId
  430. ) = extractTwapPriceInfoFromMerkleProof(digest, encoded, offset);
  431. twapPriceInfos[i] = twapPriceInfo;
  432. priceIds[i] = priceId;
  433. }
  434. if (offset != encoded.length) {
  435. revert PythErrors.InvalidTwapUpdateData();
  436. }
  437. newOffset = offset;
  438. }
  439. function parseTwapPriceFeedUpdates(
  440. bytes[] calldata updateData,
  441. bytes32[] calldata priceIds
  442. )
  443. external
  444. payable
  445. override
  446. returns (PythStructs.TwapPriceFeed[] memory twapPriceFeeds)
  447. {
  448. // TWAP requires exactly 2 updates: one for the start point and one for the end point
  449. if (updateData.length != 2) {
  450. revert PythErrors.InvalidUpdateData();
  451. }
  452. uint requiredFee = getTwapUpdateFee(updateData);
  453. if (msg.value < requiredFee) revert PythErrors.InsufficientFee();
  454. // Process start update data
  455. PythStructs.TwapPriceInfo[] memory startTwapPriceInfos;
  456. bytes32[] memory startPriceIds;
  457. {
  458. uint offsetStart;
  459. (
  460. offsetStart,
  461. startTwapPriceInfos,
  462. startPriceIds
  463. ) = extractTwapPriceInfos(updateData[0]);
  464. }
  465. // Process end update data
  466. PythStructs.TwapPriceInfo[] memory endTwapPriceInfos;
  467. bytes32[] memory endPriceIds;
  468. {
  469. uint offsetEnd;
  470. (offsetEnd, endTwapPriceInfos, endPriceIds) = extractTwapPriceInfos(
  471. updateData[1]
  472. );
  473. }
  474. // Verify that we have the same number of price feeds in start and end updates
  475. if (startPriceIds.length != endPriceIds.length) {
  476. revert PythErrors.InvalidTwapUpdateDataSet();
  477. }
  478. // Hermes always returns price feeds in the same order for start and end updates
  479. // This allows us to assume startPriceIds[i] == endPriceIds[i] for efficiency
  480. for (uint i = 0; i < startPriceIds.length; i++) {
  481. if (startPriceIds[i] != endPriceIds[i]) {
  482. revert PythErrors.InvalidTwapUpdateDataSet();
  483. }
  484. }
  485. // Initialize the output array
  486. twapPriceFeeds = new PythStructs.TwapPriceFeed[](priceIds.length);
  487. // For each requested price ID, find matching start and end data points
  488. for (uint i = 0; i < priceIds.length; i++) {
  489. bytes32 requestedPriceId = priceIds[i];
  490. int startIdx = -1;
  491. // Find the index of this price ID in the startPriceIds array
  492. // (which is the same as the endPriceIds array based on our validation above)
  493. for (uint j = 0; j < startPriceIds.length; j++) {
  494. if (startPriceIds[j] == requestedPriceId) {
  495. startIdx = int(j);
  496. break;
  497. }
  498. }
  499. // If we found the price ID
  500. if (startIdx >= 0) {
  501. uint idx = uint(startIdx);
  502. // Validate the pair of price infos
  503. validateTwapPriceInfo(
  504. startTwapPriceInfos[idx],
  505. endTwapPriceInfos[idx]
  506. );
  507. // Calculate TWAP from these data points
  508. twapPriceFeeds[i] = calculateTwap(
  509. requestedPriceId,
  510. startTwapPriceInfos[idx],
  511. endTwapPriceInfos[idx]
  512. );
  513. }
  514. }
  515. // Ensure all requested price IDs were found
  516. for (uint k = 0; k < priceIds.length; k++) {
  517. if (twapPriceFeeds[k].id == 0) {
  518. revert PythErrors.PriceFeedNotFoundWithinRange();
  519. }
  520. }
  521. }
  522. function validateTwapPriceInfo(
  523. PythStructs.TwapPriceInfo memory twapPriceInfoStart,
  524. PythStructs.TwapPriceInfo memory twapPriceInfoEnd
  525. ) private pure {
  526. // First validate each individual price's uniqueness
  527. if (
  528. twapPriceInfoStart.prevPublishTime >= twapPriceInfoStart.publishTime
  529. ) {
  530. revert PythErrors.InvalidTwapUpdateData();
  531. }
  532. if (twapPriceInfoEnd.prevPublishTime >= twapPriceInfoEnd.publishTime) {
  533. revert PythErrors.InvalidTwapUpdateData();
  534. }
  535. // Then validate the relationship between the two data points
  536. if (twapPriceInfoStart.expo != twapPriceInfoEnd.expo) {
  537. revert PythErrors.InvalidTwapUpdateDataSet();
  538. }
  539. if (twapPriceInfoStart.publishSlot > twapPriceInfoEnd.publishSlot) {
  540. revert PythErrors.InvalidTwapUpdateDataSet();
  541. }
  542. if (twapPriceInfoStart.publishTime > twapPriceInfoEnd.publishTime) {
  543. revert PythErrors.InvalidTwapUpdateDataSet();
  544. }
  545. }
  546. function parsePriceFeedUpdatesUnique(
  547. bytes[] calldata updateData,
  548. bytes32[] calldata priceIds,
  549. uint64 minPublishTime,
  550. uint64 maxPublishTime
  551. )
  552. external
  553. payable
  554. override
  555. returns (PythStructs.PriceFeed[] memory priceFeeds)
  556. {
  557. (priceFeeds, ) = parsePriceFeedUpdatesWithConfig(
  558. updateData,
  559. priceIds,
  560. minPublishTime,
  561. maxPublishTime,
  562. true,
  563. false,
  564. false
  565. );
  566. }
  567. function getTotalFee(
  568. uint totalNumUpdates
  569. ) private view returns (uint requiredFee) {
  570. return
  571. (totalNumUpdates * singleUpdateFeeInWei()) + transactionFeeInWei();
  572. }
  573. function findIndexOfPriceId(
  574. bytes32[] calldata priceIds,
  575. bytes32 targetPriceId
  576. ) private pure returns (uint index) {
  577. uint k = 0;
  578. for (; k < priceIds.length; k++) {
  579. if (priceIds[k] == targetPriceId) {
  580. break;
  581. }
  582. }
  583. return k;
  584. }
  585. function fillPriceFeedFromPriceInfo(
  586. PythStructs.PriceFeed[] memory priceFeeds,
  587. uint k,
  588. bytes32 priceId,
  589. PythInternalStructs.PriceInfo memory info,
  590. uint publishTime,
  591. uint64[] memory slots,
  592. uint64 slot
  593. ) private pure {
  594. priceFeeds[k].id = priceId;
  595. priceFeeds[k].price.price = info.price;
  596. priceFeeds[k].price.conf = info.conf;
  597. priceFeeds[k].price.expo = info.expo;
  598. priceFeeds[k].price.publishTime = publishTime;
  599. priceFeeds[k].emaPrice.price = info.emaPrice;
  600. priceFeeds[k].emaPrice.conf = info.emaConf;
  601. priceFeeds[k].emaPrice.expo = info.expo;
  602. priceFeeds[k].emaPrice.publishTime = publishTime;
  603. slots[k] = slot;
  604. }
  605. function queryPriceFeed(
  606. bytes32 id
  607. ) public view override returns (PythStructs.PriceFeed memory priceFeed) {
  608. // Look up the latest price info for the given ID
  609. PythInternalStructs.PriceInfo memory info = latestPriceInfo(id);
  610. if (info.publishTime == 0) revert PythErrors.PriceFeedNotFound();
  611. priceFeed.id = id;
  612. priceFeed.price.price = info.price;
  613. priceFeed.price.conf = info.conf;
  614. priceFeed.price.expo = info.expo;
  615. priceFeed.price.publishTime = uint(info.publishTime);
  616. priceFeed.emaPrice.price = info.emaPrice;
  617. priceFeed.emaPrice.conf = info.emaConf;
  618. priceFeed.emaPrice.expo = info.expo;
  619. priceFeed.emaPrice.publishTime = uint(info.publishTime);
  620. }
  621. function priceFeedExists(bytes32 id) public view override returns (bool) {
  622. return (latestPriceInfoPublishTime(id) != 0);
  623. }
  624. function getValidTimePeriod() public view override returns (uint) {
  625. return validTimePeriodSeconds();
  626. }
  627. function version() public pure returns (string memory) {
  628. return "1.4.5-alpha.1";
  629. }
  630. /// @notice Calculates TWAP from two price points
  631. /// @dev The calculation is done by taking the difference of cumulative values and dividing by the time difference
  632. /// @param priceId The price feed ID
  633. /// @param twapPriceInfoStart The starting price point
  634. /// @param twapPriceInfoEnd The ending price point
  635. /// @return twapPriceFeed The calculated TWAP price feed
  636. function calculateTwap(
  637. bytes32 priceId,
  638. PythStructs.TwapPriceInfo memory twapPriceInfoStart,
  639. PythStructs.TwapPriceInfo memory twapPriceInfoEnd
  640. ) private pure returns (PythStructs.TwapPriceFeed memory twapPriceFeed) {
  641. twapPriceFeed.id = priceId;
  642. twapPriceFeed.startTime = twapPriceInfoStart.publishTime;
  643. twapPriceFeed.endTime = twapPriceInfoEnd.publishTime;
  644. // Calculate differences between start and end points for slots and cumulative values
  645. uint64 slotDiff = twapPriceInfoEnd.publishSlot -
  646. twapPriceInfoStart.publishSlot;
  647. int128 priceDiff = twapPriceInfoEnd.cumulativePrice -
  648. twapPriceInfoStart.cumulativePrice;
  649. uint128 confDiff = twapPriceInfoEnd.cumulativeConf -
  650. twapPriceInfoStart.cumulativeConf;
  651. // Calculate time-weighted average price (TWAP) and confidence by dividing
  652. // the difference in cumulative values by the number of slots between data points
  653. int128 twapPrice = priceDiff / int128(uint128(slotDiff));
  654. uint128 twapConf = confDiff / uint128(slotDiff);
  655. // The conversion from int128 to int64 is safe because:
  656. // 1. Individual prices fit within int64 by protocol design
  657. // 2. TWAP is essentially an average price over time (cumulativePrice₂-cumulativePrice₁)/slotDiff
  658. // 3. This average must be within the range of individual prices that went into the calculation
  659. // We use int128 only as an intermediate type to safely handle cumulative sums
  660. twapPriceFeed.twap.price = int64(twapPrice);
  661. twapPriceFeed.twap.conf = uint64(twapConf);
  662. twapPriceFeed.twap.expo = twapPriceInfoStart.expo;
  663. twapPriceFeed.twap.publishTime = twapPriceInfoEnd.publishTime;
  664. // Calculate downSlotsRatio as a value between 0 and 1,000,000
  665. // 0 means no slots were missed, 1,000,000 means all slots were missed
  666. uint64 totalDownSlots = twapPriceInfoEnd.numDownSlots -
  667. twapPriceInfoStart.numDownSlots;
  668. uint64 downSlotsRatio = (totalDownSlots * 1_000_000) / slotDiff;
  669. // Safely downcast to uint32 (sufficient for value range 0-1,000,000)
  670. twapPriceFeed.downSlotsRatio = uint32(downSlotsRatio);
  671. return twapPriceFeed;
  672. }
  673. }