Pyth.sol 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // contracts/Bridge.sol
  2. // SPDX-License-Identifier: Apache 2
  3. pragma solidity ^0.8.0;
  4. import "../libraries/external/BytesLib.sol";
  5. import "@pythnetwork/pyth-sdk-solidity/AbstractPyth.sol";
  6. import "@pythnetwork/pyth-sdk-solidity/PythStructs.sol";
  7. import "./PythGetters.sol";
  8. import "./PythSetters.sol";
  9. import "./PythInternalStructs.sol";
  10. abstract contract Pyth is PythGetters, PythSetters, AbstractPyth {
  11. using BytesLib for bytes;
  12. function initialize(
  13. address wormhole,
  14. uint16 pyth2WormholeChainId,
  15. bytes32 pyth2WormholeEmitter
  16. ) virtual public {
  17. setWormhole(wormhole);
  18. setPyth2WormholeChainId(pyth2WormholeChainId);
  19. setPyth2WormholeEmitter(pyth2WormholeEmitter);
  20. }
  21. function updatePriceBatchFromVm(bytes memory encodedVm) private returns (PythInternalStructs.BatchPriceAttestation memory bpa) {
  22. (IWormhole.VM memory vm, bool valid, string memory reason) = wormhole().parseAndVerifyVM(encodedVm);
  23. require(valid, reason);
  24. require(verifyPythVM(vm), "invalid data source chain/emitter ID");
  25. PythInternalStructs.BatchPriceAttestation memory batch = parseBatchPriceAttestation(vm.payload);
  26. uint freshPrices = 0;
  27. for (uint i = 0; i < batch.attestations.length; i++) {
  28. PythInternalStructs.PriceAttestation memory attestation = batch.attestations[i];
  29. PythInternalStructs.PriceInfo memory latestPrice = latestPriceInfo(attestation.priceId);
  30. bool fresh = false;
  31. if(attestation.attestationTime > latestPrice.attestationTime) {
  32. freshPrices += 1;
  33. fresh = true;
  34. setLatestPriceInfo(attestation.priceId, newPriceInfo(attestation));
  35. }
  36. emit PriceFeedUpdate(attestation.priceId, fresh, vm.emitterChainId, vm.sequence, latestPrice.priceFeed.publishTime,
  37. attestation.publishTime, attestation.price, attestation.conf);
  38. }
  39. emit BatchPriceFeedUpdate(vm.emitterChainId, vm.sequence, batch.attestations.length, freshPrices);
  40. return batch;
  41. }
  42. function updatePriceFeeds(bytes[] calldata updateData) public override payable {
  43. uint requiredFee = getUpdateFee(updateData.length);
  44. require(msg.value >= requiredFee, "Insufficient paid fee amount");
  45. payable(msg.sender).transfer(msg.value - requiredFee);
  46. for(uint i = 0; i < updateData.length; i++) {
  47. updatePriceBatchFromVm(updateData[i]);
  48. }
  49. emit UpdatePriceFeeds(msg.sender, updateData.length, requiredFee);
  50. }
  51. function getUpdateFee(uint updateDataSize) public override view returns (uint feeAmount) {
  52. return singleUpdateFeeInWei() * updateDataSize;
  53. }
  54. function newPriceInfo(PythInternalStructs.PriceAttestation memory pa) private view returns (PythInternalStructs.PriceInfo memory info) {
  55. info.attestationTime = pa.attestationTime;
  56. info.arrivalTime = block.timestamp;
  57. info.arrivalBlock = block.number;
  58. info.priceFeed.id = pa.priceId;
  59. info.priceFeed.price = pa.price;
  60. info.priceFeed.conf = pa.conf;
  61. info.priceFeed.expo = pa.expo;
  62. info.priceFeed.status = PythStructs.PriceStatus(pa.status);
  63. info.priceFeed.emaPrice = pa.emaPrice;
  64. info.priceFeed.emaConf = pa.emaConf;
  65. info.priceFeed.productId = pa.productId;
  66. info.priceFeed.numPublishers = pa.numPublishers;
  67. info.priceFeed.maxNumPublishers = pa.maxNumPublishers;
  68. info.priceFeed.prevConf = pa.prevConf;
  69. info.priceFeed.prevPublishTime = pa.prevPublishTime;
  70. info.priceFeed.prevPrice = pa.prevPrice;
  71. info.priceFeed.publishTime = pa.publishTime;
  72. return info;
  73. }
  74. function verifyPythVM(IWormhole.VM memory vm) private view returns (bool valid) {
  75. return isValidDataSource(vm.emitterChainId, vm.emitterAddress);
  76. }
  77. function parseBatchPriceAttestation(bytes memory encoded) public pure returns (PythInternalStructs.BatchPriceAttestation memory bpa) {
  78. uint index = 0;
  79. // Check header
  80. bpa.header.magic = encoded.toUint32(index);
  81. index += 4;
  82. require(bpa.header.magic == 0x50325748, "invalid magic value");
  83. bpa.header.versionMajor = encoded.toUint16(index);
  84. index += 2;
  85. require(bpa.header.versionMajor == 3, "invalid version major, expected 3");
  86. bpa.header.versionMinor = encoded.toUint16(index);
  87. index += 2;
  88. require(bpa.header.versionMinor >= 0, "invalid version minor, expected 0 or more");
  89. bpa.header.hdrSize = encoded.toUint16(index);
  90. index += 2;
  91. // NOTE(2022-04-19): Currently, only payloadId comes after
  92. // hdrSize. Future extra header fields must be read using a
  93. // separate offset to respect hdrSize, i.e.:
  94. //
  95. // uint hdrIndex = 0;
  96. // bpa.header.payloadId = encoded.toUint8(index + hdrIndex);
  97. // hdrIndex += 1;
  98. //
  99. // bpa.header.someNewField = encoded.toUint32(index + hdrIndex);
  100. // hdrIndex += 4;
  101. //
  102. // // Skip remaining unknown header bytes
  103. // index += bpa.header.hdrSize;
  104. bpa.header.payloadId = encoded.toUint8(index);
  105. // Skip remaining unknown header bytes
  106. index += bpa.header.hdrSize;
  107. // Payload ID of 2 required for batch headerBa
  108. require(bpa.header.payloadId == 2, "invalid payload ID, expected 2 for BatchPriceAttestation");
  109. // Parse the number of attestations
  110. bpa.nAttestations = encoded.toUint16(index);
  111. index += 2;
  112. // Parse the attestation size
  113. bpa.attestationSize = encoded.toUint16(index);
  114. index += 2;
  115. require(encoded.length == (index + (bpa.attestationSize * bpa.nAttestations)), "invalid BatchPriceAttestation size");
  116. bpa.attestations = new PythInternalStructs.PriceAttestation[](bpa.nAttestations);
  117. // Deserialize each attestation
  118. for (uint j=0; j < bpa.nAttestations; j++) {
  119. // NOTE: We don't advance the global index immediately.
  120. // attestationIndex is an attestation-local offset used
  121. // for readability and easier debugging.
  122. uint attestationIndex = 0;
  123. // Attestation
  124. bpa.attestations[j].productId = encoded.toBytes32(index + attestationIndex);
  125. attestationIndex += 32;
  126. bpa.attestations[j].priceId = encoded.toBytes32(index + attestationIndex);
  127. attestationIndex += 32;
  128. bpa.attestations[j].price = int64(encoded.toUint64(index + attestationIndex));
  129. attestationIndex += 8;
  130. bpa.attestations[j].conf = encoded.toUint64(index + attestationIndex);
  131. attestationIndex += 8;
  132. bpa.attestations[j].expo = int32(encoded.toUint32(index + attestationIndex));
  133. attestationIndex += 4;
  134. bpa.attestations[j].emaPrice = int64(encoded.toUint64(index + attestationIndex));
  135. attestationIndex += 8;
  136. bpa.attestations[j].emaConf = encoded.toUint64(index + attestationIndex);
  137. attestationIndex += 8;
  138. bpa.attestations[j].status = encoded.toUint8(index + attestationIndex);
  139. attestationIndex += 1;
  140. bpa.attestations[j].numPublishers = encoded.toUint32(index + attestationIndex);
  141. attestationIndex += 4;
  142. bpa.attestations[j].maxNumPublishers = encoded.toUint32(index + attestationIndex);
  143. attestationIndex += 4;
  144. bpa.attestations[j].attestationTime = encoded.toUint64(index + attestationIndex);
  145. attestationIndex += 8;
  146. bpa.attestations[j].publishTime = encoded.toUint64(index + attestationIndex);
  147. attestationIndex += 8;
  148. bpa.attestations[j].prevPublishTime = encoded.toUint64(index + attestationIndex);
  149. attestationIndex += 8;
  150. bpa.attestations[j].prevPrice = int64(encoded.toUint64(index + attestationIndex));
  151. attestationIndex += 8;
  152. bpa.attestations[j].prevConf = encoded.toUint64(index + attestationIndex);
  153. attestationIndex += 8;
  154. require(attestationIndex <= bpa.attestationSize, "INTERNAL: Consumed more than `attestationSize` bytes");
  155. // Respect specified attestation size for forward-compat
  156. index += bpa.attestationSize;
  157. }
  158. }
  159. function queryPriceFeed(bytes32 id) public view override returns (PythStructs.PriceFeed memory priceFeed){
  160. // Look up the latest price info for the given ID
  161. PythInternalStructs.PriceInfo memory info = latestPriceInfo(id);
  162. require(info.priceFeed.id != 0, "no price feed found for the given price id");
  163. // Check that there is not a significant difference between this chain's time
  164. // and the price publish time.
  165. if (info.priceFeed.status == PythStructs.PriceStatus.TRADING &&
  166. absDiff(block.timestamp, info.priceFeed.publishTime) > validTimePeriodSeconds()) {
  167. info.priceFeed.status = PythStructs.PriceStatus.UNKNOWN;
  168. // getLatestAvailablePrice* gets prevPrice when status is
  169. // unknown. So, now that status is being set to unknown,
  170. // we should move the current price to the previous
  171. // price to ensure getLatestAvailablePrice* works
  172. // as intended.
  173. info.priceFeed.prevPrice = info.priceFeed.price;
  174. info.priceFeed.prevConf = info.priceFeed.conf;
  175. info.priceFeed.prevPublishTime = info.priceFeed.publishTime;
  176. }
  177. return info.priceFeed;
  178. }
  179. function absDiff(uint x, uint y) private pure returns (uint) {
  180. if (x > y) {
  181. return x - y;
  182. } else {
  183. return y - x;
  184. }
  185. }
  186. }