Pyth.sol 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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 "@pythnetwork/pyth-sdk-solidity/PythUtils.sol";
  8. import "./PythAccumulator.sol";
  9. import "./PythGetters.sol";
  10. import "./PythSetters.sol";
  11. import "./PythInternalStructs.sol";
  12. abstract contract Pyth is
  13. PythGetters,
  14. PythSetters,
  15. AbstractPyth,
  16. PythAccumulator
  17. {
  18. function _initialize(
  19. address wormhole,
  20. uint16[] calldata dataSourceEmitterChainIds,
  21. bytes32[] calldata dataSourceEmitterAddresses,
  22. uint16 governanceEmitterChainId,
  23. bytes32 governanceEmitterAddress,
  24. uint64 governanceInitialSequence,
  25. uint validTimePeriodSeconds,
  26. uint singleUpdateFeeInWei
  27. ) internal {
  28. setWormhole(wormhole);
  29. if (
  30. dataSourceEmitterChainIds.length !=
  31. dataSourceEmitterAddresses.length
  32. ) revert PythErrors.InvalidArgument();
  33. for (uint i = 0; i < dataSourceEmitterChainIds.length; i++) {
  34. PythInternalStructs.DataSource memory ds = PythInternalStructs
  35. .DataSource(
  36. dataSourceEmitterChainIds[i],
  37. dataSourceEmitterAddresses[i]
  38. );
  39. if (PythGetters.isValidDataSource(ds.chainId, ds.emitterAddress))
  40. revert PythErrors.InvalidArgument();
  41. _state.isValidDataSource[hashDataSource(ds)] = true;
  42. _state.validDataSources.push(ds);
  43. }
  44. {
  45. PythInternalStructs.DataSource memory ds = PythInternalStructs
  46. .DataSource(governanceEmitterChainId, governanceEmitterAddress);
  47. PythSetters.setGovernanceDataSource(ds);
  48. PythSetters.setLastExecutedGovernanceSequence(
  49. governanceInitialSequence
  50. );
  51. }
  52. PythSetters.setValidTimePeriodSeconds(validTimePeriodSeconds);
  53. PythSetters.setSingleUpdateFeeInWei(singleUpdateFeeInWei);
  54. }
  55. function updatePriceFeeds(
  56. bytes[] calldata updateData
  57. ) public payable override {
  58. uint totalNumUpdates = 0;
  59. for (uint i = 0; i < updateData.length; ) {
  60. totalNumUpdates += updatePriceInfosFromAccumulatorUpdate(
  61. updateData[i]
  62. );
  63. unchecked {
  64. i++;
  65. }
  66. }
  67. uint requiredFee = getTotalFee(totalNumUpdates);
  68. if (msg.value < requiredFee) revert PythErrors.InsufficientFee();
  69. }
  70. /// This method is deprecated, please use the `getUpdateFee(bytes[])` instead.
  71. function getUpdateFee(
  72. uint updateDataSize
  73. ) public view returns (uint feeAmount) {
  74. // In the accumulator update data a single update can contain
  75. // up to 255 messages and we charge a singleUpdateFee per each
  76. // message
  77. return
  78. 255 *
  79. singleUpdateFeeInWei() *
  80. updateDataSize +
  81. transactionFeeInWei();
  82. }
  83. function getUpdateFee(
  84. bytes[] calldata updateData
  85. ) public view override returns (uint feeAmount) {
  86. uint totalNumUpdates = 0;
  87. for (uint i = 0; i < updateData.length; i++) {
  88. if (
  89. updateData[i].length > 4 &&
  90. UnsafeCalldataBytesLib.toUint32(updateData[i], 0) ==
  91. ACCUMULATOR_MAGIC
  92. ) {
  93. (
  94. uint offset,
  95. UpdateType updateType
  96. ) = extractUpdateTypeFromAccumulatorHeader(updateData[i]);
  97. if (updateType != UpdateType.WormholeMerkle) {
  98. revert PythErrors.InvalidUpdateData();
  99. }
  100. totalNumUpdates += parseWormholeMerkleHeaderNumUpdates(
  101. updateData[i],
  102. offset
  103. );
  104. } else {
  105. revert PythErrors.InvalidUpdateData();
  106. }
  107. }
  108. return getTotalFee(totalNumUpdates);
  109. }
  110. // This is an overwrite of the same method in AbstractPyth.sol
  111. // to be more gas efficient.
  112. function updatePriceFeedsIfNecessary(
  113. bytes[] calldata updateData,
  114. bytes32[] calldata priceIds,
  115. uint64[] calldata publishTimes
  116. ) external payable override {
  117. if (priceIds.length != publishTimes.length)
  118. revert PythErrors.InvalidArgument();
  119. for (uint i = 0; i < priceIds.length; ) {
  120. // If the price does not exist, then the publish time is zero and
  121. // this condition will work fine.
  122. if (latestPriceInfoPublishTime(priceIds[i]) < publishTimes[i]) {
  123. updatePriceFeeds(updateData);
  124. return;
  125. }
  126. unchecked {
  127. i++;
  128. }
  129. }
  130. revert PythErrors.NoFreshUpdate();
  131. }
  132. // This is an overwrite of the same method in AbstractPyth.sol
  133. // to be more gas efficient. It cannot move to PythGetters as it
  134. // is overwriting the interface. Even indirect calling of a similar
  135. // method from PythGetter has some gas overhead.
  136. function getPriceUnsafe(
  137. bytes32 id
  138. ) public view override returns (PythStructs.Price memory price) {
  139. PythInternalStructs.PriceInfo storage info = _state.latestPriceInfo[id];
  140. price.publishTime = info.publishTime;
  141. price.expo = info.expo;
  142. price.price = info.price;
  143. price.conf = info.conf;
  144. if (price.publishTime == 0) revert PythErrors.PriceFeedNotFound();
  145. }
  146. // This is an overwrite of the same method in AbstractPyth.sol
  147. // to be more gas efficient. It cannot move to PythGetters as it
  148. // is overwriting the interface. Even indirect calling of a similar
  149. // method from PythGetter has some gas overhead.
  150. function getEmaPriceUnsafe(
  151. bytes32 id
  152. ) public view override returns (PythStructs.Price memory price) {
  153. PythInternalStructs.PriceInfo storage info = _state.latestPriceInfo[id];
  154. price.publishTime = info.publishTime;
  155. price.expo = info.expo;
  156. price.price = info.emaPrice;
  157. price.conf = info.emaConf;
  158. if (price.publishTime == 0) revert PythErrors.PriceFeedNotFound();
  159. }
  160. /// @dev Helper function to parse a single price update within a Merkle proof.
  161. /// Parsed price feeds will be stored in the context.
  162. function _parseSingleMerkleUpdate(
  163. PythInternalStructs.MerkleData memory merkleData,
  164. bytes calldata encoded,
  165. uint offset,
  166. PythInternalStructs.UpdateParseContext memory context
  167. ) internal pure returns (uint newOffset) {
  168. PythInternalStructs.PriceInfo memory priceInfo;
  169. bytes32 priceId;
  170. uint64 prevPublishTime;
  171. (
  172. newOffset,
  173. priceInfo,
  174. priceId,
  175. prevPublishTime
  176. ) = extractPriceInfoFromMerkleProof(merkleData.digest, encoded, offset);
  177. uint k = 0;
  178. for (; k < context.priceIds.length; k++) {
  179. if (context.priceIds[k] == priceId) {
  180. break;
  181. }
  182. }
  183. // Check if the priceId was requested and not already filled
  184. if (k < context.priceIds.length && context.priceFeeds[k].id == 0) {
  185. uint publishTime = uint(priceInfo.publishTime);
  186. if (
  187. publishTime >= context.config.minPublishTime &&
  188. publishTime <= context.config.maxPublishTime &&
  189. (!context.config.checkUniqueness ||
  190. context.config.minPublishTime > prevPublishTime)
  191. ) {
  192. context.priceFeeds[k].id = priceId;
  193. context.priceFeeds[k].price.price = priceInfo.price;
  194. context.priceFeeds[k].price.conf = priceInfo.conf;
  195. context.priceFeeds[k].price.expo = priceInfo.expo;
  196. context.priceFeeds[k].price.publishTime = publishTime;
  197. context.priceFeeds[k].emaPrice.price = priceInfo.emaPrice;
  198. context.priceFeeds[k].emaPrice.conf = priceInfo.emaConf;
  199. context.priceFeeds[k].emaPrice.expo = priceInfo.expo;
  200. context.priceFeeds[k].emaPrice.publishTime = publishTime;
  201. context.slots[k] = merkleData.slot;
  202. }
  203. }
  204. }
  205. /// @dev Processes a single entry from the updateData array.
  206. function _processSingleUpdateDataBlob(
  207. bytes calldata singleUpdateData,
  208. PythInternalStructs.UpdateParseContext memory context
  209. ) internal view {
  210. // Check magic number and length first
  211. if (
  212. singleUpdateData.length <= 4 ||
  213. UnsafeCalldataBytesLib.toUint32(singleUpdateData, 0) !=
  214. ACCUMULATOR_MAGIC
  215. ) {
  216. revert PythErrors.InvalidUpdateData();
  217. }
  218. uint offset;
  219. {
  220. UpdateType updateType;
  221. (offset, updateType) = extractUpdateTypeFromAccumulatorHeader(
  222. singleUpdateData
  223. );
  224. if (updateType != UpdateType.WormholeMerkle) {
  225. revert PythErrors.InvalidUpdateData();
  226. }
  227. }
  228. // Extract Merkle data
  229. PythInternalStructs.MerkleData memory merkleData;
  230. bytes calldata encoded;
  231. (
  232. offset,
  233. merkleData.digest,
  234. merkleData.numUpdates,
  235. encoded,
  236. merkleData.slot
  237. ) = extractWormholeMerkleHeaderDigestAndNumUpdatesAndEncodedAndSlotFromAccumulatorUpdate(
  238. singleUpdateData,
  239. offset
  240. );
  241. // Process each update within the Merkle proof
  242. for (uint j = 0; j < merkleData.numUpdates; j++) {
  243. offset = _parseSingleMerkleUpdate(
  244. merkleData,
  245. encoded,
  246. offset,
  247. context
  248. );
  249. }
  250. // Check final offset
  251. if (offset != encoded.length) {
  252. revert PythErrors.InvalidUpdateData();
  253. }
  254. }
  255. function parsePriceFeedUpdatesInternal(
  256. bytes[] calldata updateData,
  257. bytes32[] calldata priceIds,
  258. PythInternalStructs.ParseConfig memory config
  259. )
  260. internal
  261. returns (
  262. PythStructs.PriceFeed[] memory priceFeeds,
  263. uint64[] memory slots
  264. )
  265. {
  266. {
  267. uint requiredFee = getUpdateFee(updateData);
  268. if (msg.value < requiredFee) revert PythErrors.InsufficientFee();
  269. }
  270. // Create the context struct that holds all shared parameters
  271. PythInternalStructs.UpdateParseContext memory context;
  272. context.priceIds = priceIds;
  273. context.config = config;
  274. context.priceFeeds = new PythStructs.PriceFeed[](priceIds.length);
  275. context.slots = new uint64[](priceIds.length);
  276. unchecked {
  277. // Process each update, passing the context struct
  278. // Parsed results will be filled in context.priceFeeds and context.slots
  279. for (uint i = 0; i < updateData.length; i++) {
  280. _processSingleUpdateDataBlob(updateData[i], context);
  281. }
  282. }
  283. // Check all price feeds were found
  284. for (uint k = 0; k < priceIds.length; k++) {
  285. if (context.priceFeeds[k].id == 0) {
  286. revert PythErrors.PriceFeedNotFoundWithinRange();
  287. }
  288. }
  289. // Return results
  290. return (context.priceFeeds, context.slots);
  291. }
  292. function parsePriceFeedUpdates(
  293. bytes[] calldata updateData,
  294. bytes32[] calldata priceIds,
  295. uint64 minPublishTime,
  296. uint64 maxPublishTime
  297. )
  298. external
  299. payable
  300. override
  301. returns (PythStructs.PriceFeed[] memory priceFeeds)
  302. {
  303. (priceFeeds, ) = parsePriceFeedUpdatesInternal(
  304. updateData,
  305. priceIds,
  306. PythInternalStructs.ParseConfig(
  307. minPublishTime,
  308. maxPublishTime,
  309. false
  310. )
  311. );
  312. }
  313. function parsePriceFeedUpdatesWithSlots(
  314. bytes[] calldata updateData,
  315. bytes32[] calldata priceIds,
  316. uint64 minPublishTime,
  317. uint64 maxPublishTime
  318. )
  319. external
  320. payable
  321. override
  322. returns (
  323. PythStructs.PriceFeed[] memory priceFeeds,
  324. uint64[] memory slots
  325. )
  326. {
  327. return
  328. parsePriceFeedUpdatesInternal(
  329. updateData,
  330. priceIds,
  331. PythInternalStructs.ParseConfig(
  332. minPublishTime,
  333. maxPublishTime,
  334. false
  335. )
  336. );
  337. }
  338. function processSingleTwapUpdate(
  339. bytes calldata updateData
  340. )
  341. private
  342. view
  343. returns (
  344. /// @return newOffset The next position in the update data after processing this TWAP update
  345. /// @return twapPriceInfo The extracted time-weighted average price information
  346. /// @return priceId The unique identifier for this price feed
  347. uint newOffset,
  348. PythStructs.TwapPriceInfo memory twapPriceInfo,
  349. bytes32 priceId
  350. )
  351. {
  352. UpdateType updateType;
  353. uint offset;
  354. bytes20 digest;
  355. uint8 numUpdates;
  356. bytes calldata encoded;
  357. // Extract and validate the header for start data
  358. (offset, updateType) = extractUpdateTypeFromAccumulatorHeader(
  359. updateData
  360. );
  361. if (updateType != UpdateType.WormholeMerkle) {
  362. revert PythErrors.InvalidUpdateData();
  363. }
  364. (
  365. offset,
  366. digest,
  367. numUpdates,
  368. encoded,
  369. // slot ignored
  370. ) = extractWormholeMerkleHeaderDigestAndNumUpdatesAndEncodedAndSlotFromAccumulatorUpdate(
  371. updateData,
  372. offset
  373. );
  374. // Add additional validation before extracting TWAP price info
  375. if (offset >= updateData.length) {
  376. revert PythErrors.InvalidUpdateData();
  377. }
  378. // Extract start TWAP data with robust error checking
  379. (offset, twapPriceInfo, priceId) = extractTwapPriceInfoFromMerkleProof(
  380. digest,
  381. encoded,
  382. offset
  383. );
  384. if (offset != encoded.length) {
  385. revert PythErrors.InvalidTwapUpdateData();
  386. }
  387. newOffset = offset;
  388. }
  389. function parseTwapPriceFeedUpdates(
  390. bytes[] calldata updateData,
  391. bytes32[] calldata priceIds
  392. )
  393. external
  394. payable
  395. override
  396. returns (PythStructs.TwapPriceFeed[] memory twapPriceFeeds)
  397. {
  398. // TWAP requires exactly 2 updates - one for the start point and one for the end point
  399. // to calculate the time-weighted average price between those two points
  400. if (updateData.length != 2) {
  401. revert PythErrors.InvalidUpdateData();
  402. }
  403. uint requiredFee = getUpdateFee(updateData);
  404. if (msg.value < requiredFee) revert PythErrors.InsufficientFee();
  405. unchecked {
  406. twapPriceFeeds = new PythStructs.TwapPriceFeed[](priceIds.length);
  407. for (uint i = 0; i < updateData.length - 1; i++) {
  408. if (
  409. (updateData[i].length > 4 &&
  410. UnsafeCalldataBytesLib.toUint32(updateData[i], 0) ==
  411. ACCUMULATOR_MAGIC) &&
  412. (updateData[i + 1].length > 4 &&
  413. UnsafeCalldataBytesLib.toUint32(updateData[i + 1], 0) ==
  414. ACCUMULATOR_MAGIC)
  415. ) {
  416. uint offsetStart;
  417. uint offsetEnd;
  418. bytes32 priceIdStart;
  419. bytes32 priceIdEnd;
  420. PythStructs.TwapPriceInfo memory twapPriceInfoStart;
  421. PythStructs.TwapPriceInfo memory twapPriceInfoEnd;
  422. (
  423. offsetStart,
  424. twapPriceInfoStart,
  425. priceIdStart
  426. ) = processSingleTwapUpdate(updateData[i]);
  427. (
  428. offsetEnd,
  429. twapPriceInfoEnd,
  430. priceIdEnd
  431. ) = processSingleTwapUpdate(updateData[i + 1]);
  432. if (priceIdStart != priceIdEnd)
  433. revert PythErrors.InvalidTwapUpdateDataSet();
  434. validateTwapPriceInfo(twapPriceInfoStart, twapPriceInfoEnd);
  435. uint k = findIndexOfPriceId(priceIds, priceIdStart);
  436. // If priceFeed[k].id != 0 then it means that there was a valid
  437. // update for priceIds[k] and we don't need to process this one.
  438. if (k == priceIds.length || twapPriceFeeds[k].id != 0) {
  439. continue;
  440. }
  441. twapPriceFeeds[k] = calculateTwap(
  442. priceIdStart,
  443. twapPriceInfoStart,
  444. twapPriceInfoEnd
  445. );
  446. } else {
  447. revert PythErrors.InvalidUpdateData();
  448. }
  449. }
  450. for (uint k = 0; k < priceIds.length; k++) {
  451. if (twapPriceFeeds[k].id == 0) {
  452. revert PythErrors.PriceFeedNotFoundWithinRange();
  453. }
  454. }
  455. }
  456. }
  457. function validateTwapPriceInfo(
  458. PythStructs.TwapPriceInfo memory twapPriceInfoStart,
  459. PythStructs.TwapPriceInfo memory twapPriceInfoEnd
  460. ) private pure {
  461. // First validate each individual price's uniqueness
  462. if (
  463. twapPriceInfoStart.prevPublishTime >= twapPriceInfoStart.publishTime
  464. ) {
  465. revert PythErrors.InvalidTwapUpdateData();
  466. }
  467. if (twapPriceInfoEnd.prevPublishTime >= twapPriceInfoEnd.publishTime) {
  468. revert PythErrors.InvalidTwapUpdateData();
  469. }
  470. // Then validate the relationship between the two data points
  471. if (twapPriceInfoStart.expo != twapPriceInfoEnd.expo) {
  472. revert PythErrors.InvalidTwapUpdateDataSet();
  473. }
  474. if (twapPriceInfoStart.publishSlot > twapPriceInfoEnd.publishSlot) {
  475. revert PythErrors.InvalidTwapUpdateDataSet();
  476. }
  477. if (twapPriceInfoStart.publishTime > twapPriceInfoEnd.publishTime) {
  478. revert PythErrors.InvalidTwapUpdateDataSet();
  479. }
  480. }
  481. function parsePriceFeedUpdatesUnique(
  482. bytes[] calldata updateData,
  483. bytes32[] calldata priceIds,
  484. uint64 minPublishTime,
  485. uint64 maxPublishTime
  486. )
  487. external
  488. payable
  489. override
  490. returns (PythStructs.PriceFeed[] memory priceFeeds)
  491. {
  492. (priceFeeds, ) = parsePriceFeedUpdatesInternal(
  493. updateData,
  494. priceIds,
  495. PythInternalStructs.ParseConfig(
  496. minPublishTime,
  497. maxPublishTime,
  498. true
  499. )
  500. );
  501. }
  502. function getTotalFee(
  503. uint totalNumUpdates
  504. ) private view returns (uint requiredFee) {
  505. return
  506. (totalNumUpdates * singleUpdateFeeInWei()) + transactionFeeInWei();
  507. }
  508. function findIndexOfPriceId(
  509. bytes32[] calldata priceIds,
  510. bytes32 targetPriceId
  511. ) private pure returns (uint index) {
  512. uint k = 0;
  513. for (; k < priceIds.length; k++) {
  514. if (priceIds[k] == targetPriceId) {
  515. break;
  516. }
  517. }
  518. return k;
  519. }
  520. function fillPriceFeedFromPriceInfo(
  521. PythStructs.PriceFeed[] memory priceFeeds,
  522. uint k,
  523. bytes32 priceId,
  524. PythInternalStructs.PriceInfo memory info,
  525. uint publishTime,
  526. uint64[] memory slots,
  527. uint64 slot
  528. ) private pure {
  529. priceFeeds[k].id = priceId;
  530. priceFeeds[k].price.price = info.price;
  531. priceFeeds[k].price.conf = info.conf;
  532. priceFeeds[k].price.expo = info.expo;
  533. priceFeeds[k].price.publishTime = publishTime;
  534. priceFeeds[k].emaPrice.price = info.emaPrice;
  535. priceFeeds[k].emaPrice.conf = info.emaConf;
  536. priceFeeds[k].emaPrice.expo = info.expo;
  537. priceFeeds[k].emaPrice.publishTime = publishTime;
  538. slots[k] = slot;
  539. }
  540. function queryPriceFeed(
  541. bytes32 id
  542. ) public view override returns (PythStructs.PriceFeed memory priceFeed) {
  543. // Look up the latest price info for the given ID
  544. PythInternalStructs.PriceInfo memory info = latestPriceInfo(id);
  545. if (info.publishTime == 0) revert PythErrors.PriceFeedNotFound();
  546. priceFeed.id = id;
  547. priceFeed.price.price = info.price;
  548. priceFeed.price.conf = info.conf;
  549. priceFeed.price.expo = info.expo;
  550. priceFeed.price.publishTime = uint(info.publishTime);
  551. priceFeed.emaPrice.price = info.emaPrice;
  552. priceFeed.emaPrice.conf = info.emaConf;
  553. priceFeed.emaPrice.expo = info.expo;
  554. priceFeed.emaPrice.publishTime = uint(info.publishTime);
  555. }
  556. function priceFeedExists(bytes32 id) public view override returns (bool) {
  557. return (latestPriceInfoPublishTime(id) != 0);
  558. }
  559. function getValidTimePeriod() public view override returns (uint) {
  560. return validTimePeriodSeconds();
  561. }
  562. function version() public pure returns (string memory) {
  563. return "1.4.4-alpha.5";
  564. }
  565. function calculateTwap(
  566. bytes32 priceId,
  567. PythStructs.TwapPriceInfo memory twapPriceInfoStart,
  568. PythStructs.TwapPriceInfo memory twapPriceInfoEnd
  569. ) private pure returns (PythStructs.TwapPriceFeed memory) {
  570. return
  571. PythUtils.calculateTwap(
  572. priceId,
  573. twapPriceInfoStart,
  574. twapPriceInfoEnd
  575. );
  576. }
  577. }