pyth.move 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. module pyth::pyth {
  2. use pyth::batch_price_attestation::{Self};
  3. use pyth::price_identifier::{Self, PriceIdentifier};
  4. use pyth::price_info::{Self, PriceInfo};
  5. use pyth::price_feed::{Self};
  6. use aptos_framework::coin::{Self, Coin};
  7. use aptos_framework::aptos_coin::{AptosCoin};
  8. use pyth::price::Price;
  9. use pyth::price;
  10. use pyth::data_source::{Self, DataSource};
  11. use aptos_framework::timestamp;
  12. use std::vector;
  13. use pyth::state;
  14. use wormhole::vaa;
  15. use wormhole::u16;
  16. use wormhole::external_address;
  17. use std::account;
  18. use std::signer;
  19. use deployer::deployer;
  20. use pyth::error;
  21. use pyth::event;
  22. #[test_only]
  23. friend pyth::pyth_test;
  24. // -----------------------------------------------------------------------------
  25. // Initialisation functions
  26. public entry fun init(
  27. deployer: &signer,
  28. stale_price_threshold: u64,
  29. governance_emitter_chain_id: u64,
  30. governance_emitter_address: vector<u8>,
  31. data_sources_emitter_chain_ids: vector<u64>,
  32. data_sources_emitter_addresses: vector<vector<u8>>,
  33. update_fee: u64,
  34. ) {
  35. // Claim the signer capability from the deployer. Note that this is a one-time operation,
  36. // so that this function can only be called once.
  37. let signer_capability = deployer::claim_signer_capability(deployer, @pyth);
  38. init_internal(
  39. signer_capability,
  40. stale_price_threshold,
  41. governance_emitter_chain_id,
  42. governance_emitter_address,
  43. parse_data_sources(
  44. data_sources_emitter_chain_ids,
  45. data_sources_emitter_addresses,
  46. ),
  47. update_fee
  48. )
  49. }
  50. fun init_internal(
  51. signer_capability: account::SignerCapability,
  52. stale_price_threshold: u64,
  53. governance_emitter_chain_id: u64,
  54. governance_emitter_address: vector<u8>,
  55. data_sources: vector<DataSource>,
  56. update_fee: u64) {
  57. let pyth = account::create_signer_with_capability(&signer_capability);
  58. state::init(
  59. &pyth,
  60. stale_price_threshold,
  61. update_fee,
  62. data_source::new(
  63. governance_emitter_chain_id,
  64. external_address::from_bytes(governance_emitter_address)),
  65. data_sources,
  66. signer_capability
  67. );
  68. event::init(&pyth);
  69. if (!coin::is_account_registered<AptosCoin>(signer::address_of(&pyth))) {
  70. coin::register<AptosCoin>(&pyth);
  71. }
  72. }
  73. fun parse_data_sources(
  74. emitter_chain_ids: vector<u64>,
  75. emitter_addresses: vector<vector<u8>>): vector<DataSource> {
  76. assert!(vector::length(&emitter_chain_ids) == vector::length(&emitter_addresses),
  77. error::data_source_emitter_address_and_chain_ids_different_lengths());
  78. let sources = vector::empty();
  79. let i = 0;
  80. while (i < vector::length(&emitter_chain_ids)) {
  81. vector::push_back(&mut sources, data_source::new(
  82. *vector::borrow(&emitter_chain_ids, i),
  83. external_address::from_bytes(*vector::borrow(&emitter_addresses, i))
  84. ));
  85. i = i + 1;
  86. };
  87. sources
  88. }
  89. #[test_only]
  90. /// Expose a public initialization function for use in tests
  91. public fun init_test(
  92. signer_capability: account::SignerCapability,
  93. stale_price_threshold: u64,
  94. governance_emitter_chain_id: u64,
  95. governance_emitter_address: vector<u8>,
  96. data_sources: vector<DataSource>,
  97. update_fee: u64,
  98. ) {
  99. init_internal(
  100. signer_capability,
  101. stale_price_threshold,
  102. governance_emitter_chain_id,
  103. governance_emitter_address,
  104. data_sources,
  105. update_fee
  106. )
  107. }
  108. // -----------------------------------------------------------------------------
  109. // Update the cached prices
  110. /// Update the cached price feeds with the data in the given VAAs. This is a
  111. /// convenience wrapper around update_price_feeds(), which allows you to update the price feeds
  112. /// using an entry function.
  113. ///
  114. /// If possible, it is recommended to use update_price_feeds() instead, which avoids the need
  115. /// to pass a signer account. update_price_feeds_with_funder() should only be used when
  116. /// you need to call an entry function.
  117. ///
  118. /// This function will charge an update fee, transferring some AptosCoin's
  119. /// from the given funder account to the Pyth contract. The amount of coins that will be transferred
  120. /// to perform this update can be queried with get_update_fee(&vaas). The signer must have sufficient
  121. /// account balance to pay this fee, otherwise the transaction will abort.
  122. public entry fun update_price_feeds_with_funder(account: &signer, vaas: vector<vector<u8>>) {
  123. let coins = coin::withdraw<AptosCoin>(account, get_update_fee(&vaas));
  124. update_price_feeds(vaas, coins);
  125. }
  126. /// Update the cached price feeds with the data in the given VAAs.
  127. /// The vaas argument is a vector of VAAs encoded as bytes.
  128. ///
  129. /// The javascript https://github.com/pyth-network/pyth-js/tree/main/pyth-aptos-js package
  130. /// should be used to fetch these VAAs from the Price Service. More information about this
  131. /// process can be found at https://docs.pyth.network/consume-data.
  132. ///
  133. /// The given fee must contain a sufficient number of coins to pay the update fee for the given vaas.
  134. /// The update fee amount can be queried by calling get_update_fee(&vaas).
  135. public fun update_price_feeds(vaas: vector<vector<u8>>, fee: Coin<AptosCoin>) {
  136. // Charge the message update fee
  137. assert!(get_update_fee(&vaas) <= coin::value(&fee), error::insufficient_fee());
  138. coin::deposit(@pyth, fee);
  139. // Update the price feed from each VAA
  140. while (!vector::is_empty(&vaas)) {
  141. update_price_feed_from_single_vaa(vector::pop_back(&mut vaas));
  142. };
  143. }
  144. fun update_price_feed_from_single_vaa(vaa: vector<u8>) {
  145. // Deserialize the VAA
  146. let vaa = vaa::parse_and_verify(vaa);
  147. // Check that the VAA is from a valid data source (emitter)
  148. assert!(
  149. state::is_valid_data_source(
  150. data_source::new(
  151. u16::to_u64(vaa::get_emitter_chain(&vaa)),
  152. vaa::get_emitter_address(&vaa))),
  153. error::invalid_data_source());
  154. // Deserialize the batch price attestation
  155. update_cache(batch_price_attestation::destroy(batch_price_attestation::deserialize(vaa::destroy(vaa))));
  156. }
  157. /// Update the cache with given price updates, if they are newer than the ones currently cached.
  158. public(friend) fun update_cache(updates: vector<PriceInfo>) {
  159. while (!vector::is_empty(&updates)) {
  160. let update = vector::pop_back(&mut updates);
  161. if (is_fresh_update(&update)) {
  162. let price_feed = *price_info::get_price_feed(&update);
  163. let price_identifier = price_feed::get_price_identifier(&price_feed);
  164. state::set_latest_price_info(
  165. *price_identifier,
  166. update,
  167. );
  168. event::emit_price_feed_update(price_feed, timestamp::now_microseconds());
  169. }
  170. };
  171. vector::destroy_empty(updates);
  172. }
  173. /// A convenience wrapper around update_price_feeds_if_fresh(), allowing you to conditionally
  174. /// update the price feeds using an entry function.
  175. ///
  176. /// If possible, it is recommended to use update_price_feeds_if_fresh() instead, which avoids the need
  177. /// to pass a signer account. update_price_feeds_if_fresh_with_funder() should only be used when
  178. /// you need to call an entry function.
  179. public entry fun update_price_feeds_if_fresh_with_funder(
  180. account: &signer,
  181. vaas: vector<vector<u8>>,
  182. price_identifiers: vector<vector<u8>>,
  183. publish_times: vector<u64>) {
  184. let coins = coin::withdraw<AptosCoin>(account, get_update_fee(&vaas));
  185. update_price_feeds_if_fresh(vaas, price_identifiers, publish_times, coins);
  186. }
  187. /// Update the cached price feeds with the data in the given VAAs, using
  188. /// update_price_feeds(). However, this function will only have an effect if any of the
  189. /// prices in the update are fresh. The price_identifiers and publish_times parameters
  190. /// are used to determine if the update is fresh without doing any serialisation or verification
  191. /// of the VAAs, potentially saving time and gas. If the update contains no fresh data, this function
  192. /// will revert with error::no_fresh_data().
  193. ///
  194. /// For a given price update i in the batch, that price is considered fresh if the current cached
  195. /// price for price_identifiers[i] is older than publish_times[i].
  196. public entry fun update_price_feeds_if_fresh(
  197. vaas: vector<vector<u8>>,
  198. price_identifiers: vector<vector<u8>>,
  199. publish_times: vector<u64>,
  200. fee: Coin<AptosCoin>) {
  201. assert!(vector::length(&price_identifiers) == vector::length(&publish_times),
  202. error::invalid_publish_times_length());
  203. let fresh_data = false;
  204. let i = 0;
  205. while (i < vector::length(&publish_times)) {
  206. let price_identifier = price_identifier::from_byte_vec(
  207. *vector::borrow(&price_identifiers, i));
  208. if (!state::price_info_cached(price_identifier)) {
  209. fresh_data = true;
  210. break
  211. };
  212. let cached_timestamp = price::get_timestamp(&get_price_unsafe(price_identifier));
  213. if (cached_timestamp < *vector::borrow(&publish_times, i)) {
  214. fresh_data = true;
  215. break
  216. };
  217. i = i + 1;
  218. };
  219. assert!(fresh_data, error::no_fresh_data());
  220. update_price_feeds(vaas, fee);
  221. }
  222. /// Determine if the given price update is "fresh": we have nothing newer already cached for that
  223. /// price feed.
  224. fun is_fresh_update(update: &PriceInfo): bool {
  225. // Get the timestamp of the update's current price
  226. let price_feed = price_info::get_price_feed(update);
  227. let update_timestamp = price::get_timestamp(&price_feed::get_price(price_feed));
  228. // Get the timestamp of the cached data for the price identifier
  229. let price_identifier = price_feed::get_price_identifier(price_feed);
  230. if (!price_feed_exists(*price_identifier)) {
  231. return true
  232. };
  233. let cached_timestamp = price::get_timestamp(&get_price_unsafe(*price_identifier));
  234. update_timestamp > cached_timestamp
  235. }
  236. // -----------------------------------------------------------------------------
  237. // Query the cached prices
  238. //
  239. // It is strongly recommended to update the cached prices using the functions above,
  240. // before using the functions below to query the cached data.
  241. /// Determine if a price feed for the given price_identifier exists
  242. public fun price_feed_exists(price_identifier: PriceIdentifier): bool {
  243. state::price_info_cached(price_identifier)
  244. }
  245. /// Get the latest available price cached for the given price identifier, if that price is
  246. /// no older than the stale price threshold.
  247. ///
  248. /// Please refer to the documentation at https://docs.pyth.network/consumers/best-practices for
  249. /// how to how this price safely.
  250. ///
  251. /// Important: it is recommended to call update_price_feeds() to update the cached price
  252. /// before calling this function, as get_price() will abort if the cached price is older
  253. /// than the stale price threshold.
  254. ///
  255. /// Note that the price_identifier does not correspond to a seperate Aptos account:
  256. /// all price feeds are stored in the single pyth account. The price identifier is an
  257. /// opaque identifier for a price feed.
  258. public fun get_price(price_identifier: PriceIdentifier): Price {
  259. get_price_no_older_than(price_identifier, state::get_stale_price_threshold_secs())
  260. }
  261. /// Get the latest available price cached for the given price identifier, if that price is
  262. /// no older than the given age.
  263. public fun get_price_no_older_than(price_identifier: PriceIdentifier, max_age_secs: u64): Price {
  264. let price = get_price_unsafe(price_identifier);
  265. check_price_is_fresh(&price, max_age_secs);
  266. price
  267. }
  268. /// Get the latest available price cached for the given price identifier.
  269. ///
  270. /// WARNING: the returned price can be from arbitrarily far in the past.
  271. /// This function makes no guarantees that the returned price is recent or
  272. /// useful for any particular application. Users of this function should check
  273. /// the returned timestamp to ensure that the returned price is sufficiently
  274. /// recent for their application. The checked get_price_no_older_than()
  275. /// function should be used in preference to this.
  276. public fun get_price_unsafe(price_identifier: PriceIdentifier): Price {
  277. price_feed::get_price(
  278. price_info::get_price_feed(&state::get_latest_price_info(price_identifier)))
  279. }
  280. fun abs_diff(x: u64, y: u64): u64 {
  281. if (x > y) {
  282. return x - y
  283. } else {
  284. return y - x
  285. }
  286. }
  287. /// Get the stale price threshold: the amount of time after which a cached price
  288. /// is considered stale and no longer returned by get_price()/get_ema_price().
  289. public fun get_stale_price_threshold_secs(): u64 {
  290. state::get_stale_price_threshold_secs()
  291. }
  292. fun check_price_is_fresh(price: &Price, max_age_secs: u64) {
  293. let age = abs_diff(timestamp::now_seconds(), price::get_timestamp(price));
  294. assert!(age < max_age_secs, error::stale_price_update());
  295. }
  296. /// Get the latest available exponentially moving average price cached for the given
  297. /// price identifier, if that price is no older than the stale price threshold.
  298. ///
  299. /// Important: it is recommended to call update_price_feeds() to update the cached EMA price
  300. /// before calling this function, as get_ema_price() will abort if the cached EMA price is older
  301. /// than the stale price threshold.
  302. public fun get_ema_price(price_identifier: PriceIdentifier): Price {
  303. get_ema_price_no_older_than(price_identifier, state::get_stale_price_threshold_secs())
  304. }
  305. /// Get the latest available exponentially moving average price cached for the given price identifier,
  306. /// if that price is no older than the given age.
  307. public fun get_ema_price_no_older_than(price_identifier: PriceIdentifier, max_age_secs: u64): Price {
  308. let price = get_ema_price_unsafe(price_identifier);
  309. check_price_is_fresh(&price, max_age_secs);
  310. price
  311. }
  312. /// Get the latest available exponentially moving average price cached for the given price identifier.
  313. ///
  314. /// WARNING: the returned price can be from arbitrarily far in the past.
  315. /// This function makes no guarantees that the returned price is recent or
  316. /// useful for any particular application. Users of this function should check
  317. /// the returned timestamp to ensure that the returned price is sufficiently
  318. /// recent for their application. The checked get_ema_price_no_older_than()
  319. /// function should be used in preference to this.
  320. public fun get_ema_price_unsafe(price_identifier: PriceIdentifier): Price {
  321. price_feed::get_ema_price(
  322. price_info::get_price_feed(&state::get_latest_price_info(price_identifier)))
  323. }
  324. /// Get the number of AptosCoin's required to perform the given price updates.
  325. public fun get_update_fee(update_data: &vector<vector<u8>>): u64 {
  326. state::get_base_update_fee() * vector::length(update_data)
  327. }
  328. }
  329. // -----------------------------------------------------------------------------
  330. // Tests
  331. #[test_only]
  332. module pyth::pyth_test {
  333. use pyth::pyth;
  334. use pyth::price_identifier::{Self};
  335. use pyth::price_info::{Self, PriceInfo};
  336. use pyth::price_feed::{Self};
  337. use aptos_framework::coin::{Self, Coin, BurnCapability, MintCapability};
  338. use aptos_framework::aptos_coin::{Self, AptosCoin};
  339. use pyth::i64;
  340. use pyth::price;
  341. use pyth::data_source::{Self, DataSource};
  342. use aptos_framework::timestamp;
  343. use std::vector;
  344. use wormhole::external_address;
  345. use std::account;
  346. use std::signer;
  347. #[test_only]
  348. fun setup_test(
  349. aptos_framework: &signer,
  350. stale_price_threshold: u64,
  351. governance_emitter_chain_id: u64,
  352. governance_emitter_address: vector<u8>,
  353. data_sources: vector<DataSource>,
  354. update_fee: u64,
  355. to_mint: u64): (BurnCapability<AptosCoin>, MintCapability<AptosCoin>, Coin<AptosCoin>) {
  356. // Initialize wormhole with a large message collection fee
  357. wormhole::wormhole_test::setup(100000);
  358. // Set the current time
  359. timestamp::update_global_time_for_test_secs(1663680745);
  360. // Deploy and initialize a test instance of the Pyth contract
  361. let deployer = account::create_signer_with_capability(&
  362. account::create_test_signer_cap(@0x277fa055b6a73c42c0662d5236c65c864ccbf2d4abd21f174a30c8b786eab84b));
  363. let (_pyth, signer_capability) = account::create_resource_account(&deployer, b"pyth");
  364. pyth::init_test(signer_capability, stale_price_threshold, governance_emitter_chain_id, governance_emitter_address, data_sources, update_fee);
  365. let (burn_capability, mint_capability) = aptos_coin::initialize_for_test(aptos_framework);
  366. let coins = coin::mint(to_mint, &mint_capability);
  367. (burn_capability, mint_capability, coins)
  368. }
  369. #[test_only]
  370. fun cleanup_test(burn_capability: BurnCapability<AptosCoin>, mint_capability: MintCapability<AptosCoin>) {
  371. coin::destroy_mint_cap(mint_capability);
  372. coin::destroy_burn_cap(burn_capability);
  373. }
  374. #[test_only]
  375. fun get_mock_price_infos(): vector<PriceInfo> {
  376. vector<PriceInfo>[
  377. price_info::new(
  378. 1663680747,
  379. 1663074349,
  380. price_feed::new(
  381. price_identifier::from_byte_vec(x"c6c75c89f14810ec1c54c03ab8f1864a4c4032791f05747f560faec380a695d1"),
  382. price::new(i64::new(1557, false), 7, i64::new(5, true), 1663680740),
  383. price::new(i64::new(1500, false), 3, i64::new(5, true), 1663680740),
  384. ),
  385. ),
  386. price_info::new(
  387. 1663680747,
  388. 1663074349,
  389. price_feed::new(
  390. price_identifier::from_byte_vec(x"3b9551a68d01d954d6387aff4df1529027ffb2fee413082e509feb29cc4904fe"),
  391. price::new(i64::new(1050, false), 3, i64::new(5, true), 1663680745),
  392. price::new(i64::new(1483, false), 3, i64::new(5, true), 1663680745),
  393. ),
  394. ),
  395. price_info::new(
  396. 1663680747,
  397. 1663074349,
  398. price_feed::new(
  399. price_identifier::from_byte_vec(x"33832fad6e36eb05a8972fe5f219b27b5b2bb2230a79ce79beb4c5c5e7ecc76d"),
  400. price::new(i64::new(1010, false), 2, i64::new(5, true), 1663680745),
  401. price::new(i64::new(1511, false), 3, i64::new(5, true), 1663680745),
  402. ),
  403. ),
  404. price_info::new(
  405. 1663680747,
  406. 1663074349,
  407. price_feed::new(
  408. price_identifier::from_byte_vec(x"21a28b4c6619968bd8c20e95b0aaed7df2187fd310275347e0376a2cd7427db8"),
  409. price::new(i64::new(1739, false), 1, i64::new(5, true), 1663680745),
  410. price::new(i64::new(1508, false), 3, i64::new(5, true), 1663680745),
  411. ),
  412. ),
  413. ]
  414. }
  415. #[test_only]
  416. /// A vector containing a single VAA with:
  417. /// - emitter chain ID 17
  418. /// - emitter address 0x71f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b
  419. /// - payload corresponding to the batch price attestation of the prices returned by get_mock_price_infos()
  420. const TEST_VAAS: vector<vector<u8>> = vector[x"0100000000010036eb563b80a24f4253bee6150eb8924e4bdf6e4fa1dfc759a6664d2e865b4b134651a7b021b7f1ce3bd078070b688b6f2e37ce2de0d9b48e6a78684561e49d5201527e4f9b00000001001171f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b0000000000000001005032574800030000000102000400951436e0be37536be96f0896366089506a59763d036728332d3e3038047851aea7c6c75c89f14810ec1c54c03ab8f1864a4c4032791f05747f560faec380a695d1000000000000049a0000000000000008fffffffb00000000000005dc0000000000000003000000000100000001000000006329c0eb000000006329c0e9000000006329c0e400000000000006150000000000000007215258d81468614f6b7e194c5d145609394f67b041e93e6695dcc616faadd0603b9551a68d01d954d6387aff4df1529027ffb2fee413082e509feb29cc4904fe000000000000041a0000000000000003fffffffb00000000000005cb0000000000000003010000000100000001000000006329c0eb000000006329c0e9000000006329c0e4000000000000048600000000000000078ac9cf3ab299af710d735163726fdae0db8465280502eb9f801f74b3c1bd190333832fad6e36eb05a8972fe5f219b27b5b2bb2230a79ce79beb4c5c5e7ecc76d00000000000003f20000000000000002fffffffb00000000000005e70000000000000003010000000100000001000000006329c0eb000000006329c0e9000000006329c0e40000000000000685000000000000000861db714e9ff987b6fedf00d01f9fea6db7c30632d6fc83b7bc9459d7192bc44a21a28b4c6619968bd8c20e95b0aaed7df2187fd310275347e0376a2cd7427db800000000000006cb0000000000000001fffffffb00000000000005e40000000000000003010000000100000001000000006329c0eb000000006329c0e9000000006329c0e400000000000007970000000000000001"];
  421. #[test(aptos_framework = @aptos_framework)]
  422. fun test_get_update_fee(aptos_framework: &signer) {
  423. let single_update_fee = 50;
  424. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", vector[], 50, 0);
  425. // Pass in a single VAA
  426. assert!(pyth::get_update_fee(&vector[
  427. x"fb1543888001083cf2e6ef3afdcf827e89b11efd87c563638df6e1995ada9f93",
  428. ]) == single_update_fee, 1);
  429. // Pass in multiple VAAs
  430. assert!(pyth::get_update_fee(&vector[
  431. x"4ee17a1a4524118de513fddcf82b77454e51be5d6fc9e29fc72dd6c204c0e4fa",
  432. x"c72fdf81cfc939d4286c93fbaaae2eec7bae28a5926fa68646b43a279846ccc1",
  433. x"d9a8123a793529c31200339820a3210059ecace6c044f81ecad62936e47ca049",
  434. x"84e4f21b3e65cef47fda25d15b4eddda1edf720a1d062ccbf441d6396465fbe6",
  435. x"9e73f9041476a93701a0b9c7501422cc2aa55d16100bec628cf53e0281b6f72f"
  436. ]) == 250, 1);
  437. coin::destroy_zero(coins);
  438. cleanup_test(burn_capability, mint_capability);
  439. }
  440. #[test(aptos_framework = @aptos_framework)]
  441. #[expected_failure(abort_code = 6)]
  442. fun test_update_price_feeds_corrupt_vaa(aptos_framework: &signer) {
  443. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", vector[], 50, 100);
  444. // Pass in a corrupt VAA, which should fail deseriaizing
  445. let corrupt_vaa = x"90F8bf6A479f320ead074411a4B0e7944Ea8c9C1";
  446. pyth::update_price_feeds(vector[corrupt_vaa], coins);
  447. cleanup_test(burn_capability, mint_capability);
  448. }
  449. #[test(aptos_framework = @aptos_framework)]
  450. #[expected_failure(abort_code = 65539)]
  451. fun test_update_price_feeds_invalid_data_source(aptos_framework: &signer) {
  452. // Initialize the contract with some valid data sources, excluding our test VAA's source
  453. let data_sources = vector<DataSource>[
  454. data_source::new(
  455. 4, external_address::from_bytes(x"0000000000000000000000000000000000000000000000000000000000007742")),
  456. data_source::new(
  457. 5, external_address::from_bytes(x"0000000000000000000000000000000000000000000000000000000000007637"))
  458. ];
  459. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources, 50, 100);
  460. pyth::update_price_feeds(TEST_VAAS, coins);
  461. cleanup_test(burn_capability, mint_capability);
  462. }
  463. #[test_only]
  464. fun data_sources_for_test_vaa(): vector<DataSource> {
  465. // Set some valid data sources, including our test VAA's source
  466. vector<DataSource>[
  467. data_source::new(
  468. 1, external_address::from_bytes(x"0000000000000000000000000000000000000000000000000000000000000004")),
  469. data_source::new(
  470. 5, external_address::from_bytes(x"0000000000000000000000000000000000000000000000000000000000007637")),
  471. data_source::new(
  472. 17, external_address::from_bytes(x"71f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b"))
  473. ]
  474. }
  475. #[test(aptos_framework = @aptos_framework)]
  476. #[expected_failure(abort_code = 65542)]
  477. fun test_update_price_feeds_insufficient_fee(aptos_framework: &signer) {
  478. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 500, 1,
  479. x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92",
  480. data_sources_for_test_vaa(),
  481. // Update fee
  482. 50,
  483. // Coins provided to update < update fee
  484. 20);
  485. pyth::update_price_feeds(TEST_VAAS, coins);
  486. cleanup_test(burn_capability, mint_capability);
  487. }
  488. #[test(aptos_framework = @aptos_framework)]
  489. fun test_update_price_feeds_success(aptos_framework: &signer) {
  490. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources_for_test_vaa(), 50, 100);
  491. // Update the price feeds from the VAA
  492. pyth::update_price_feeds(TEST_VAAS, coins);
  493. // Check that the cache has been updated
  494. let expected = get_mock_price_infos();
  495. check_price_feeds_cached(&expected);
  496. cleanup_test(burn_capability, mint_capability);
  497. }
  498. #[test(aptos_framework = @aptos_framework)]
  499. fun test_update_price_feeds_with_funder(aptos_framework: &signer) {
  500. let update_fee = 50;
  501. let initial_balance = 75;
  502. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources_for_test_vaa(), update_fee, initial_balance);
  503. // Create a test funder account and register it to store funds
  504. let funder_addr = @0xbfbffd8e2af9a3e3ce20d2d2b22bd640;
  505. let funder = account::create_account_for_test(funder_addr);
  506. coin::register<AptosCoin>(&funder);
  507. coin::deposit(funder_addr, coins);
  508. assert!(pyth::get_update_fee(&TEST_VAAS) == update_fee, 1);
  509. assert!(coin::balance<AptosCoin>(signer::address_of(&funder)) == initial_balance, 1);
  510. assert!(coin::balance<AptosCoin>(@pyth) == 0, 1);
  511. // Update the price feeds using the funder
  512. pyth::update_price_feeds_with_funder(&funder, TEST_VAAS);
  513. // Check that the price feeds are now cached
  514. check_price_feeds_cached(&get_mock_price_infos());
  515. // Check that the funder's balance has decreased by the update_fee amount
  516. assert!(coin::balance<AptosCoin>(signer::address_of(&funder)) == initial_balance - pyth::get_update_fee(&TEST_VAAS), 1);
  517. // Check that the amount has been transferred to the Pyth contract
  518. assert!(coin::balance<AptosCoin>(@pyth) == pyth::get_update_fee(&TEST_VAAS), 1);
  519. cleanup_test(burn_capability, mint_capability);
  520. }
  521. #[test(aptos_framework = @aptos_framework)]
  522. #[expected_failure(abort_code = 65542)]
  523. fun test_update_price_feeds_with_funder_insufficient_balance(aptos_framework: &signer) {
  524. let update_fee = 50;
  525. let initial_balance = 25;
  526. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources_for_test_vaa(), update_fee, initial_balance);
  527. // Create a test funder account and register it to store funds
  528. let funder_addr = @0xbfbffd8e2af9a3e3ce20d2d2b22bd640;
  529. let funder = account::create_account_for_test(funder_addr);
  530. coin::register<AptosCoin>(&funder);
  531. coin::deposit(funder_addr, coins);
  532. assert!(pyth::get_update_fee(&TEST_VAAS) == update_fee, 1);
  533. assert!(coin::balance<AptosCoin>(signer::address_of(&funder)) == initial_balance, 1);
  534. assert!(coin::balance<AptosCoin>(@pyth) == 0, 1);
  535. // Update the price feeds using the funder
  536. pyth::update_price_feeds_with_funder(&funder, TEST_VAAS);
  537. cleanup_test(burn_capability, mint_capability);
  538. }
  539. #[test_only]
  540. fun check_price_feeds_cached(expected: &vector<PriceInfo>) {
  541. // Check that we can retrieve the correct current price and ema price for each price feed
  542. let i = 0;
  543. while (i < vector::length(expected)) {
  544. let price_feed = price_info::get_price_feed(vector::borrow(expected, i));
  545. let price = price_feed::get_price(price_feed);
  546. let price_identifier = *price_feed::get_price_identifier(price_feed);
  547. assert!(pyth::price_feed_exists(price_identifier), 1);
  548. let cached_price = pyth::get_price(price_identifier);
  549. assert!(cached_price == price, 1);
  550. let ema_price = price_feed::get_ema_price(price_feed);
  551. let cached_ema_price = pyth::get_ema_price(price_identifier);
  552. assert!(cached_ema_price == ema_price, 1);
  553. i = i + 1;
  554. };
  555. }
  556. #[test(aptos_framework = @aptos_framework)]
  557. fun test_update_cache(aptos_framework: &signer) {
  558. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources_for_test_vaa(), 50, 0);
  559. let updates = get_mock_price_infos();
  560. // Check that initially the price feeds are not cached
  561. let i = 0;
  562. while (i < vector::length(&updates)) {
  563. let price_feed = price_info::get_price_feed(vector::borrow(&updates, i));
  564. assert!(!pyth::price_feed_exists(*price_feed::get_price_identifier(price_feed)), 1);
  565. i = i + 1;
  566. };
  567. // Submit the updates
  568. pyth::update_cache(updates);
  569. // Check that the price feeds are now cached
  570. check_price_feeds_cached(&updates);
  571. cleanup_test(burn_capability, mint_capability);
  572. coin::destroy_zero(coins);
  573. }
  574. #[test(aptos_framework = @aptos_framework)]
  575. fun test_update_cache_old_update(aptos_framework: &signer) {
  576. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 1000, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources_for_test_vaa(), 50, 0);
  577. // Submit a price update
  578. let timestamp = 1663680700;
  579. let price_identifier = price_identifier::from_byte_vec(x"baa284eaf23edf975b371ba2818772f93dbae72836bbdea28b07d40f3cf8b485");
  580. let price = price::new(i64::new(7648, false), 674, i64::new(8, true), timestamp);
  581. let ema_price = price::new(i64::new(1536, true), 869, i64::new(100, false), timestamp);
  582. let update = price_info::new(
  583. 1257278600,
  584. 1690226180,
  585. price_feed::new(
  586. price_identifier,
  587. price,
  588. ema_price,
  589. )
  590. );
  591. pyth::update_cache(vector<PriceInfo>[update]);
  592. // Check that we can retrieve the current price
  593. assert!(pyth::get_price(price_identifier) == price, 1);
  594. // Attempt to update the price with an update older than the current cached one
  595. let old_price = price::new(i64::new(1243, true), 9802, i64::new(6, false), timestamp - 200);
  596. let old_ema_price = price::new(i64::new(8976, true), 234, i64::new(897, false), timestamp - 200);
  597. let old_update = price_info::new(
  598. 1257278600,
  599. 1690226180,
  600. price_feed::new(
  601. price_identifier,
  602. old_price,
  603. old_ema_price,
  604. )
  605. );
  606. pyth::update_cache(vector<PriceInfo>[old_update]);
  607. // Confirm that the current price and ema price didn't change
  608. assert!(pyth::get_price(price_identifier) == price, 1);
  609. assert!(pyth::get_ema_price(price_identifier) == ema_price, 1);
  610. // Update the cache with a fresh update
  611. let fresh_price = price::new(i64::new(4857, true), 9979, i64::new(243, false), timestamp + 200);
  612. let fresh_ema_price = price::new(i64::new(74637, false), 9979, i64::new(1433, false), timestamp + 1);
  613. let fresh_update = price_info::new(
  614. 1257278600,
  615. 1690226180,
  616. price_feed::new(
  617. price_identifier,
  618. fresh_price,
  619. fresh_ema_price,
  620. )
  621. );
  622. pyth::update_cache(vector<PriceInfo>[fresh_update]);
  623. // Confirm that the current price was updated
  624. assert!(pyth::get_price(price_identifier) == fresh_price, 1);
  625. assert!(pyth::get_ema_price(price_identifier) == fresh_ema_price, 1);
  626. cleanup_test(burn_capability, mint_capability);
  627. coin::destroy_zero(coins);
  628. }
  629. #[test(aptos_framework = @aptos_framework)]
  630. #[expected_failure(abort_code = 524292)]
  631. fun test_stale_price_threshold_exceeded(aptos_framework: &signer) {
  632. let stale_price_threshold = 500;
  633. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, stale_price_threshold, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources_for_test_vaa(), 50, 0);
  634. // Submit a price update
  635. let current_timestamp = timestamp::now_seconds();
  636. let price_identifier = price_identifier::from_byte_vec(x"baa284eaf23edf975b371ba2818772f93dbae72836bbdea28b07d40f3cf8b485");
  637. let price = price::new(i64::new(7648, false), 674, i64::new(8, true), current_timestamp);
  638. let update = price_info::new(
  639. 1257278600,
  640. 1690226180,
  641. price_feed::new(
  642. price_identifier,
  643. price,
  644. price::new(i64::new(1536, true), 869, i64::new(100, false), 1257212500),
  645. )
  646. );
  647. pyth::update_cache(vector<PriceInfo>[update]);
  648. assert!(pyth::get_price(price_identifier) == price, 1);
  649. // Now advance the clock on the target chain, until the age of the cached update exceeds the
  650. // stale_price_threshold.
  651. timestamp::update_global_time_for_test_secs(current_timestamp + stale_price_threshold);
  652. // Check that we can access the price if we increase the threshold by 1
  653. assert!(pyth::get_price_no_older_than(
  654. price_identifier, pyth::get_stale_price_threshold_secs() + 1) == price, 1);
  655. // However, retrieving the latest price fails
  656. assert!(pyth::get_price(price_identifier) == price, 1);
  657. cleanup_test(burn_capability, mint_capability);
  658. coin::destroy_zero(coins);
  659. }
  660. #[test(aptos_framework = @aptos_framework)]
  661. #[expected_failure(abort_code = 524292)]
  662. fun test_stale_price_threshold_exceeded_ema(aptos_framework: &signer) {
  663. let stale_price_threshold = 500;
  664. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, stale_price_threshold, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources_for_test_vaa(), 50, 0);
  665. // Submit a price update
  666. let current_timestamp = timestamp::now_seconds();
  667. let price_identifier = price_identifier::from_byte_vec(x"baa284eaf23edf975b371ba2818772f93dbae72836bbdea28b07d40f3cf8b485");
  668. let ema_price = price::new(i64::new(1536, true), 869, i64::new(100, false), current_timestamp);
  669. let update = price_info::new(
  670. 1257278600,
  671. 1690226180,
  672. price_feed::new(
  673. price_identifier,
  674. price::new(i64::new(7648, false), 674, i64::new(8, true), 1257212500),
  675. ema_price,
  676. )
  677. );
  678. pyth::update_cache(vector<PriceInfo>[update]);
  679. // Check that the EMA price has been updated
  680. assert!(pyth::get_ema_price(price_identifier) == ema_price, 1);
  681. // Now advance the clock on the target chain, until the age of the cached update exceeds the
  682. // stale_price_threshold.
  683. timestamp::update_global_time_for_test_secs(current_timestamp + stale_price_threshold);
  684. // Check that we can access the EMA price if we increase the threshold by 1
  685. assert!(pyth::get_ema_price_no_older_than(
  686. price_identifier, pyth::get_stale_price_threshold_secs() + 1) == ema_price, 1);
  687. // However, retrieving the latest EMA price fails
  688. assert!(pyth::get_ema_price(price_identifier) == ema_price, 1);
  689. cleanup_test(burn_capability, mint_capability);
  690. coin::destroy_zero(coins);
  691. }
  692. #[test(aptos_framework = @aptos_framework)]
  693. #[expected_failure(abort_code = 65541)]
  694. fun test_update_price_feeds_if_fresh_invalid_length(aptos_framework: &signer) {
  695. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources_for_test_vaa(), 50, 0);
  696. // Update the price feeds
  697. let bytes = vector[vector[0u8, 1u8, 2u8]];
  698. let price_identifiers = vector[
  699. x"baa284eaf23edf975b371ba2818772f93dbae72836bbdea28b07d40f3cf8b485",
  700. x"c9d5fe0d836688f4c88c221415d23e4bcabee21a6a21124bfcc9a5410a297818",
  701. x"eaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a",
  702. ];
  703. let publish_times = vector[
  704. 734639463
  705. ];
  706. pyth::update_price_feeds_if_fresh(bytes, price_identifiers, publish_times, coins);
  707. cleanup_test(burn_capability, mint_capability);
  708. }
  709. #[test(aptos_framework = @aptos_framework)]
  710. fun test_update_price_feeds_if_fresh_fresh_data(aptos_framework: &signer) {
  711. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources_for_test_vaa(), 50, 50);
  712. // Update the price feeds
  713. let bytes = TEST_VAAS;
  714. let price_identifiers = vector[
  715. x"c6c75c89f14810ec1c54c03ab8f1864a4c4032791f05747f560faec380a695d1",
  716. x"3b9551a68d01d954d6387aff4df1529027ffb2fee413082e509feb29cc4904fe",
  717. x"33832fad6e36eb05a8972fe5f219b27b5b2bb2230a79ce79beb4c5c5e7ecc76d",
  718. x"21a28b4c6619968bd8c20e95b0aaed7df2187fd310275347e0376a2cd7427db8",
  719. ];
  720. let publish_times = vector[
  721. 1663680745, 1663680730, 1663680760, 1663680720
  722. ];
  723. pyth::update_price_feeds_if_fresh(bytes, price_identifiers, publish_times, coins);
  724. // Check that the cache has been updated
  725. let expected = get_mock_price_infos();
  726. check_price_feeds_cached(&expected);
  727. cleanup_test(burn_capability, mint_capability);
  728. }
  729. #[test(aptos_framework = @aptos_framework)]
  730. fun test_update_price_feeds_if_fresh_with_funder_fresh_data(aptos_framework: &signer) {
  731. let update_fee = 50;
  732. let initial_balance = 75;
  733. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources_for_test_vaa(), update_fee, initial_balance);
  734. // Create a test funder account and register it to store funds
  735. let funder_addr = @0xbfbffd8e2af9a3e3ce20d2d2b22bd640;
  736. let funder = account::create_account_for_test(funder_addr);
  737. coin::register<AptosCoin>(&funder);
  738. coin::deposit(funder_addr, coins);
  739. assert!(pyth::get_update_fee(&TEST_VAAS) == update_fee, 1);
  740. assert!(coin::balance<AptosCoin>(signer::address_of(&funder)) == initial_balance, 1);
  741. assert!(coin::balance<AptosCoin>(@pyth) == 0, 1);
  742. // Update the price feeds using the funder
  743. let bytes = TEST_VAAS;
  744. let price_identifiers = vector[
  745. x"c6c75c89f14810ec1c54c03ab8f1864a4c4032791f05747f560faec380a695d1",
  746. x"3b9551a68d01d954d6387aff4df1529027ffb2fee413082e509feb29cc4904fe",
  747. x"33832fad6e36eb05a8972fe5f219b27b5b2bb2230a79ce79beb4c5c5e7ecc76d",
  748. x"21a28b4c6619968bd8c20e95b0aaed7df2187fd310275347e0376a2cd7427db8",
  749. ];
  750. let publish_times = vector[
  751. 1663680790, 1663680730, 1663680760, 1663680720
  752. ];
  753. pyth::update_price_feeds_if_fresh_with_funder(&funder, bytes, price_identifiers, publish_times);
  754. // Check that the price feeds are now cached
  755. check_price_feeds_cached(&get_mock_price_infos());
  756. // Check that the funder's balance has decreased by the update_fee amount
  757. assert!(coin::balance<AptosCoin>(signer::address_of(&funder)) == initial_balance - pyth::get_update_fee(&TEST_VAAS), 1);
  758. // Check that the amount has been transferred to the Pyth contract
  759. assert!(coin::balance<AptosCoin>(@pyth) == pyth::get_update_fee(&TEST_VAAS), 1);
  760. cleanup_test(burn_capability, mint_capability);
  761. }
  762. #[test(aptos_framework = @aptos_framework)]
  763. #[expected_failure(abort_code = 524295)]
  764. fun test_update_price_feeds_if_fresh_stale_data(aptos_framework: &signer) {
  765. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources_for_test_vaa(), 50, 50);
  766. // First populate the cache
  767. pyth::update_cache(get_mock_price_infos());
  768. // Now attempt to update the price feeds with publish_times that are older than those we have cached
  769. // This should abort with error::no_fresh_data()
  770. let bytes = TEST_VAAS;
  771. let price_identifiers = vector[
  772. x"c6c75c89f14810ec1c54c03ab8f1864a4c4032791f05747f560faec380a695d1",
  773. x"3b9551a68d01d954d6387aff4df1529027ffb2fee413082e509feb29cc4904fe",
  774. x"33832fad6e36eb05a8972fe5f219b27b5b2bb2230a79ce79beb4c5c5e7ecc76d",
  775. x"21a28b4c6619968bd8c20e95b0aaed7df2187fd310275347e0376a2cd7427db8",
  776. ];
  777. let publish_times = vector[
  778. 67, 35, 26, 64
  779. ];
  780. pyth::update_price_feeds_if_fresh(bytes, price_identifiers, publish_times, coins);
  781. cleanup_test(burn_capability, mint_capability);
  782. }
  783. #[test(aptos_framework = @aptos_framework)]
  784. #[expected_failure(abort_code = 524295)]
  785. fun test_update_price_feeds_if_fresh_with_funder_stale_data(aptos_framework: &signer) {
  786. let update_fee = 50;
  787. let initial_balance = 75;
  788. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources_for_test_vaa(), update_fee, initial_balance);
  789. // Create a test funder account and register it to store funds
  790. let funder_addr = @0xbfbffd8e2af9a3e3ce20d2d2b22bd640;
  791. let funder = account::create_account_for_test(funder_addr);
  792. coin::register<AptosCoin>(&funder);
  793. coin::deposit(funder_addr, coins);
  794. assert!(pyth::get_update_fee(&TEST_VAAS) == update_fee, 1);
  795. assert!(coin::balance<AptosCoin>(signer::address_of(&funder)) == initial_balance, 1);
  796. assert!(coin::balance<AptosCoin>(@pyth) == 0, 1);
  797. // First populate the cache
  798. pyth::update_cache(get_mock_price_infos());
  799. // Now attempt to update the price feeds with publish_times that are older than those we have cached
  800. // This should abort with error::no_fresh_data()
  801. let bytes = TEST_VAAS;
  802. let price_identifiers = vector[
  803. x"c6c75c89f14810ec1c54c03ab8f1864a4c4032791f05747f560faec380a695d1",
  804. x"3b9551a68d01d954d6387aff4df1529027ffb2fee413082e509feb29cc4904fe",
  805. x"33832fad6e36eb05a8972fe5f219b27b5b2bb2230a79ce79beb4c5c5e7ecc76d",
  806. x"21a28b4c6619968bd8c20e95b0aaed7df2187fd310275347e0376a2cd7427db8",
  807. ];
  808. let publish_times = vector[
  809. 100, 76, 29, 64
  810. ];
  811. pyth::update_price_feeds_if_fresh_with_funder(&funder, bytes, price_identifiers, publish_times);
  812. cleanup_test(burn_capability, mint_capability);
  813. }
  814. }