pyth.move 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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, BurnCapability, MintCapability};
  7. use aptos_framework::aptos_coin::{Self, AptosCoin};
  8. use pyth::price_status;
  9. use pyth::i64;
  10. use pyth::price::Price;
  11. use pyth::price;
  12. use pyth::data_source::{Self, DataSource};
  13. use aptos_framework::timestamp;
  14. use std::vector;
  15. use pyth::state;
  16. use wormhole::vaa;
  17. use wormhole::u16;
  18. use wormhole::external_address;
  19. use std::account;
  20. use deployer::deployer;
  21. use pyth::error;
  22. // -----------------------------------------------------------------------------
  23. // Initialisation functions
  24. public entry fun init(
  25. deployer: &signer,
  26. chain_id: u64,
  27. stale_price_threshold: u64,
  28. governance_emitter_chain_id: u64,
  29. governance_emitter_address: vector<u8>,
  30. update_fee: u64,
  31. ) {
  32. // Claim the signer capability from the deployer. Note that this is a one-time operation,
  33. // so that this function can only be called once.
  34. let signer_capability = deployer::claim_signer_capability(deployer, @pyth);
  35. init_internal(
  36. signer_capability,
  37. chain_id,
  38. stale_price_threshold,
  39. governance_emitter_chain_id,
  40. governance_emitter_address,
  41. update_fee
  42. )
  43. }
  44. fun init_internal(
  45. signer_capability: account::SignerCapability,
  46. chain_id: u64,
  47. stale_price_threshold: u64,
  48. governance_emitter_chain_id: u64,
  49. governance_emitter_address: vector<u8>,
  50. update_fee: u64) {
  51. let pyth = account::create_signer_with_capability(&signer_capability);
  52. state::init(
  53. &pyth,
  54. chain_id,
  55. stale_price_threshold,
  56. update_fee,
  57. data_source::new(
  58. governance_emitter_chain_id,
  59. external_address::from_bytes(governance_emitter_address)),
  60. signer_capability
  61. );
  62. coin::register<AptosCoin>(&pyth);
  63. }
  64. #[test_only]
  65. /// Expose a public initialization function for use in tests
  66. public fun init_test(
  67. signer_capability: account::SignerCapability,
  68. chain_id: u64,
  69. stale_price_threshold: u64,
  70. governance_emitter_chain_id: u64,
  71. governance_emitter_address: vector<u8>,
  72. update_fee: u64,
  73. ) {
  74. init_internal(
  75. signer_capability,
  76. chain_id,
  77. stale_price_threshold,
  78. governance_emitter_chain_id,
  79. governance_emitter_address,
  80. update_fee
  81. )
  82. }
  83. // -----------------------------------------------------------------------------
  84. // Update the cached prices
  85. /// Update the cached price feeds with the data in the given vaa_bytes payload.
  86. /// The given fee must contain a sufficient number of coins to pay the update fee:
  87. /// this amount can be queried by calling get_update_fee().
  88. public entry fun update_price_feeds(vaa_bytes: vector<u8>, fee: Coin<AptosCoin>) {
  89. // Deserialize the VAA
  90. let vaa = vaa::parse_and_verify(vaa_bytes);
  91. // Charge the message update fee
  92. assert!(state::get_update_fee() <= coin::value(&fee), error::insufficient_fee());
  93. coin::deposit(@pyth, fee);
  94. // Check that the VAA is from a valid data source (emitter)
  95. assert!(
  96. state::is_valid_data_source(
  97. data_source::new(
  98. u16::to_u64(vaa::get_emitter_chain(&vaa)),
  99. vaa::get_emitter_address(&vaa))),
  100. error::invalid_data_source());
  101. // Deserialize the batch price attestation
  102. update_cache(batch_price_attestation::destroy(
  103. batch_price_attestation::deserialize(vaa::destroy(vaa))));
  104. }
  105. /// Update the cache with given price updates, if they are newer than the ones currently cached.
  106. fun update_cache(updates: vector<PriceInfo>) {
  107. while (!vector::is_empty(&updates)) {
  108. let update = vector::pop_back(&mut updates);
  109. if (is_fresh_update(&update)) {
  110. let price_feed = price_info::get_price_feed(&update);
  111. let price_identifier = price_feed::get_price_identifier(price_feed);
  112. state::set_latest_price_info(
  113. *price_identifier,
  114. update,
  115. )
  116. }
  117. };
  118. vector::destroy_empty(updates);
  119. }
  120. /// Update the cached price feeds with the data in the given vaa_bytes payload, using
  121. /// update_price_feeds(). However, this function will only have an effect if any of the
  122. /// prices in the update are fresh. The price_identifiers and publish_times paramaters
  123. /// are used to determine if the update is fresh without doing any serialisation or verification
  124. /// of the VAA, potentially saving time and gas. If the update contains no fresh data, this function
  125. /// will revert with error::no_fresh_data().
  126. ///
  127. /// For a given price update i in the batch, that price is considered fresh if the current cached
  128. /// price for price_identifiers[i] is older than publish_times[i].
  129. public entry fun update_price_feeds_if_fresh(
  130. vaa_bytes: vector<u8>,
  131. price_identifiers: vector<PriceIdentifier>,
  132. publish_times: vector<u64>,
  133. fee: Coin<AptosCoin>) {
  134. assert!(vector::length(&price_identifiers) == vector::length(&publish_times),
  135. error::invalid_publish_times_length());
  136. let fresh_data = false;
  137. let i = 0;
  138. while (i < vector::length(&publish_times)) {
  139. let price_identifier = vector::borrow(&price_identifiers, i);
  140. if (!state::price_info_cached(*price_identifier)) {
  141. fresh_data = true;
  142. break
  143. };
  144. let price_feed = price_info::get_price_feed(&state::get_latest_price_info(*price_identifier));
  145. let cached_timestamp = price::get_timestamp(&price_feed::get_price(price_feed));
  146. if (cached_timestamp < *vector::borrow(&publish_times, i)) {
  147. fresh_data = true;
  148. break
  149. };
  150. i = i + 1;
  151. };
  152. assert!(fresh_data, error::no_fresh_data());
  153. update_price_feeds(vaa_bytes, fee);
  154. }
  155. /// Determine if the given price update is "fresh": we have nothing newer already cached for that
  156. /// price feed.
  157. fun is_fresh_update(update: &PriceInfo): bool {
  158. // Get the timestamp of the update's current price
  159. let price_feed = price_info::get_price_feed(update);
  160. let update_timestamp = price::get_timestamp(&price_feed::get_price(price_feed));
  161. // Get the timestamp of the cached data for the price identifier
  162. let price_identifier = price_feed::get_price_identifier(price_feed);
  163. if (!price_feed_exists(*price_identifier)) {
  164. return true
  165. };
  166. let cached_timestamp = price::get_timestamp(
  167. &price_feed::get_price(price_info::get_price_feed(&state::get_latest_price_info(*price_identifier))));
  168. update_timestamp > cached_timestamp
  169. }
  170. // -----------------------------------------------------------------------------
  171. // Query the cached prices
  172. //
  173. // It is strongly recommended to update the cached prices using the functions above,
  174. // before using the functions below to query the cached data.
  175. /// Determine if a price feed for the given price_identifier exists
  176. public fun price_feed_exists(price_identifier: PriceIdentifier): bool {
  177. state::price_info_cached(price_identifier)
  178. }
  179. /// Get the latest cached data for the given price identifier, if that data is
  180. /// no older than the stale price threshold.
  181. ///
  182. /// Important: it is recommended to call update_price_feeds() to update the cached data
  183. /// before calling this function.
  184. public fun get_price(price_identifier: PriceIdentifier): Price {
  185. get_price_no_older_than(price_identifier, state::get_stale_price_threshold_secs())
  186. }
  187. /// Get the latest cached data for the given price identifier, if that data is
  188. /// no older than the given age.
  189. public fun get_price_no_older_than(price_identifier: PriceIdentifier, max_age_secs: u64): Price {
  190. let price = get_price_unsafe(price_identifier);
  191. let age = abs_diff(timestamp::now_seconds(), price::get_timestamp(&price));
  192. assert!(age < max_age_secs, error::stale_price_update());
  193. price
  194. }
  195. /// Get the latest cached exponential moving average price for the given price_identifier.
  196. public fun get_ema_price(price_identifier: PriceIdentifier): Price {
  197. price_feed::get_ema_price(
  198. price_info::get_price_feed(&state::get_latest_price_info(price_identifier)))
  199. }
  200. /// Get the latest available price for the given price identifier.
  201. ///
  202. /// WARNING: the returned price can be from arbitrarily far in the past.
  203. /// This function makes no guarantees that the returned price is recent or
  204. /// useful for any particular application. Users of this function should check
  205. /// the returned timestamp to ensure that the returned price is sufficiently
  206. /// recent for their application. The checked get_price_no_older_than()
  207. /// function should be used in preference to this.
  208. public fun get_price_unsafe(price_identifier: PriceIdentifier): Price {
  209. let price_feed = price_info::get_price_feed(&state::get_latest_price_info(price_identifier));
  210. // If the current price has a status of TRADING, return that
  211. let is_trading = price_feed::get_status(price_feed) == price_status::new_trading();
  212. if (is_trading) {
  213. return price_feed::get_price(price_feed)
  214. };
  215. // Otherwise return the most recent price which has a status of TRADING
  216. return price_feed::get_previous_price(price_feed)
  217. }
  218. fun abs_diff(x: u64, y: u64): u64 {
  219. if (x > y) {
  220. return x - y
  221. } else {
  222. return y - x
  223. }
  224. }
  225. /// Get the stale price threshold: the amount of time after which a cached price
  226. /// is considered stale and no longer returned by get_price().
  227. public fun get_stale_price_threshold_secs(): u64 {
  228. state::get_stale_price_threshold_secs()
  229. }
  230. /// Get the number of AptosCoin's requried to perform one batch update
  231. public fun get_update_fee(): u64 {
  232. state::get_update_fee()
  233. }
  234. // -----------------------------------------------------------------------------
  235. // Tests
  236. #[test_only]
  237. fun setup_test(
  238. aptos_framework: &signer,
  239. chain_id: u64,
  240. stale_price_threshold: u64,
  241. governance_emitter_chain_id: u64,
  242. governance_emitter_address: vector<u8>,
  243. update_fee: u64,
  244. to_mint: u64): (BurnCapability<AptosCoin>, MintCapability<AptosCoin>, Coin<AptosCoin>) {
  245. // Initialize wormhole with a large message collection fee
  246. wormhole::wormhole_test::setup(100000);
  247. // Set the current time
  248. timestamp::update_global_time_for_test_secs(1663680745);
  249. // Deploy and initialize a test instance of the Pyth contract
  250. let deployer = account::create_signer_with_capability(&
  251. account::create_test_signer_cap(@0x277fa055b6a73c42c0662d5236c65c864ccbf2d4abd21f174a30c8b786eab84b));
  252. let (_pyth, signer_capability) = account::create_resource_account(&deployer, b"pyth");
  253. init_test(signer_capability, chain_id, stale_price_threshold, governance_emitter_chain_id, governance_emitter_address, update_fee);
  254. let (burn_capability, mint_capability) = aptos_coin::initialize_for_test(aptos_framework);
  255. let coins = coin::mint(to_mint, &mint_capability);
  256. (burn_capability, mint_capability, coins)
  257. }
  258. #[test_only]
  259. fun cleanup_test(burn_capability: BurnCapability<AptosCoin>, mint_capability: MintCapability<AptosCoin>) {
  260. coin::destroy_mint_cap(mint_capability);
  261. coin::destroy_burn_cap(burn_capability);
  262. }
  263. #[test_only]
  264. fun get_mock_price_infos(): vector<PriceInfo> {
  265. vector<PriceInfo>[
  266. price_info::new(
  267. 1663680747,
  268. 1663074349,
  269. price_feed::new(
  270. price_identifier::from_byte_vec(x"c6c75c89f14810ec1c54c03ab8f1864a4c4032791f05747f560faec380a695d1"),
  271. price_status::new_trading(),
  272. price::new(i64::new(1178, false), 8, i64::new(5, true), 1663680745),
  273. price::new(i64::new(1500, false), 3, i64::new(5, true), 1663680745),
  274. price::new(i64::new(1557, false), 7, i64::new(5, true), 1663680740),
  275. ),
  276. ),
  277. price_info::new(
  278. 1663680747,
  279. 1663074349,
  280. price_feed::new(
  281. price_identifier::from_byte_vec(x"3b9551a68d01d954d6387aff4df1529027ffb2fee413082e509feb29cc4904fe"),
  282. price_status::new_trading(),
  283. price::new(i64::new(1050, false), 3, i64::new(5, true), 1663680745),
  284. price::new(i64::new(1483, false), 3, i64::new(5, true), 1663680745),
  285. price::new(i64::new(1158, false), 7, i64::new(5, true), 1663680740),
  286. ),
  287. ),
  288. price_info::new(
  289. 1663680747,
  290. 1663074349,
  291. price_feed::new(
  292. price_identifier::from_byte_vec(x"33832fad6e36eb05a8972fe5f219b27b5b2bb2230a79ce79beb4c5c5e7ecc76d"),
  293. price_status::new_trading(),
  294. price::new(i64::new(1010, false), 2, i64::new(5, true), 1663680745),
  295. price::new(i64::new(1511, false), 3, i64::new(5, true), 1663680745),
  296. price::new(i64::new(1669, false), 8, i64::new(5, true), 1663680740),
  297. ),
  298. ),
  299. price_info::new(
  300. 1663680747,
  301. 1663074349,
  302. price_feed::new(
  303. price_identifier::from_byte_vec(x"21a28b4c6619968bd8c20e95b0aaed7df2187fd310275347e0376a2cd7427db8"),
  304. price_status::new_trading(),
  305. price::new(i64::new(1739, false), 1, i64::new(5, true), 1663680745),
  306. price::new(i64::new(1508, false), 3, i64::new(5, true), 1663680745),
  307. price::new(i64::new(1943, false), 1, i64::new(5, true), 1663680740),
  308. ),
  309. ),
  310. ]
  311. }
  312. #[test_only]
  313. /// A VAA with:
  314. /// - emitter chain ID 17
  315. /// - emitter address 0x71f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b
  316. /// - payload corresponding to the batch price attestation of the prices returned by get_mock_price_infos()
  317. const TEST_VAA: vector<u8> = x"01000000000100e000fb400939c4cb52ffbf8e91d03d749f6e00868cd056e9d0289f60428971386080d8b98e39b910bbbdeb4c8a7767a3053d1d2884c0a5e297476334d35feb8e00527e4f9b00000001001171f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b0000000000000000005032574800030000000102000400951436e0be37536be96f0896366089506a59763d036728332d3e3038047851aea7c6c75c89f14810ec1c54c03ab8f1864a4c4032791f05747f560faec380a695d1000000000000049a0000000000000008fffffffb00000000000005dc0000000000000003010000000100000001000000006329c0eb000000006329c0e9000000006329c0e400000000000006150000000000000007215258d81468614f6b7e194c5d145609394f67b041e93e6695dcc616faadd0603b9551a68d01d954d6387aff4df1529027ffb2fee413082e509feb29cc4904fe000000000000041a0000000000000003fffffffb00000000000005cb0000000000000003010000000100000001000000006329c0eb000000006329c0e9000000006329c0e4000000000000048600000000000000078ac9cf3ab299af710d735163726fdae0db8465280502eb9f801f74b3c1bd190333832fad6e36eb05a8972fe5f219b27b5b2bb2230a79ce79beb4c5c5e7ecc76d00000000000003f20000000000000002fffffffb00000000000005e70000000000000003010000000100000001000000006329c0eb000000006329c0e9000000006329c0e40000000000000685000000000000000861db714e9ff987b6fedf00d01f9fea6db7c30632d6fc83b7bc9459d7192bc44a21a28b4c6619968bd8c20e95b0aaed7df2187fd310275347e0376a2cd7427db800000000000006cb0000000000000001fffffffb00000000000005e40000000000000003010000000100000001000000006329c0eb000000006329c0e9000000006329c0e400000000000007970000000000000001";
  318. #[test(aptos_framework = @aptos_framework)]
  319. #[expected_failure(abort_code = 6)]
  320. fun test_update_price_feeds_corrupt_vaa(aptos_framework: &signer) {
  321. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 27, 500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", 50, 100);
  322. // Pass in a corrupt VAA, which should fail deseriaizing
  323. let corrupt_vaa = x"90F8bf6A479f320ead074411a4B0e7944Ea8c9C1";
  324. update_price_feeds(corrupt_vaa, coins);
  325. cleanup_test(burn_capability, mint_capability);
  326. }
  327. #[test(aptos_framework = @aptos_framework)]
  328. #[expected_failure(abort_code = 65539)]
  329. fun test_update_price_feeds_invalid_data_source_initially(aptos_framework: &signer) {
  330. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 27, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", 50, 100);
  331. // Without setting any valid data source, the check should fail
  332. update_price_feeds(TEST_VAA, coins);
  333. cleanup_test(burn_capability, mint_capability);
  334. }
  335. #[test(aptos_framework = @aptos_framework)]
  336. #[expected_failure(abort_code = 65539)]
  337. fun test_update_price_feeds_invalid_data_source(aptos_framework: &signer) {
  338. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 27, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", 50, 100);
  339. // Set some valid data sources, excluding our test VAA's source
  340. state::set_data_sources(vector<DataSource>[
  341. data_source::new(
  342. 4, external_address::from_bytes(x"0000000000000000000000000000000000000000000000000000000000007742")),
  343. data_source::new(
  344. 5, external_address::from_bytes(x"0000000000000000000000000000000000000000000000000000000000007637"))
  345. ]);
  346. update_price_feeds(TEST_VAA, coins);
  347. cleanup_test(burn_capability, mint_capability);
  348. }
  349. #[test_only]
  350. fun set_data_source_for_test_vaa() {
  351. // Set some valid data sources, including our test VAA's source
  352. state::set_data_sources(vector<DataSource>[
  353. data_source::new(
  354. 1, external_address::from_bytes(x"0000000000000000000000000000000000000000000000000000000000000004")),
  355. data_source::new(
  356. 5, external_address::from_bytes(x"0000000000000000000000000000000000000000000000000000000000007637")),
  357. data_source::new(
  358. 17, external_address::from_bytes(x"71f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b"))
  359. ]);
  360. }
  361. #[test(aptos_framework = @aptos_framework)]
  362. #[expected_failure(abort_code = 65542)]
  363. fun test_update_price_feeds_insufficient_fee(aptos_framework: &signer) {
  364. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 27, 500, 1,
  365. x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92",
  366. // Update fee
  367. 50,
  368. // Coins provided to update < update fee
  369. 20);
  370. // Set some valid data sources, excluding our test VAA's source
  371. state::set_data_sources(vector<DataSource>[
  372. data_source::new(
  373. 1, external_address::from_bytes(x"0000000000000000000000000000000000000000000000000000000000000004")),
  374. data_source::new(
  375. 5, external_address::from_bytes(x"0000000000000000000000000000000000000000000000000000000000007637"))
  376. ]);
  377. update_price_feeds(TEST_VAA, coins);
  378. cleanup_test(burn_capability, mint_capability);
  379. }
  380. #[test(aptos_framework = @aptos_framework)]
  381. fun test_update_price_feeds_success(aptos_framework: &signer) {
  382. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 27, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", 50, 100);
  383. set_data_source_for_test_vaa();
  384. // Update the price feeds from the VAA
  385. update_price_feeds(TEST_VAA, coins);
  386. // Check that the cache has been updated
  387. let expected = get_mock_price_infos();
  388. check_price_feeds_cached(&expected);
  389. cleanup_test(burn_capability, mint_capability);
  390. }
  391. #[test_only]
  392. fun check_price_feeds_cached(expected: &vector<PriceInfo>) {
  393. // Check that we can retrieve the correct current price and ema price for each price feed
  394. let i = 0;
  395. while (i < vector::length(expected)) {
  396. let price_feed = price_info::get_price_feed(vector::borrow(expected, i));
  397. let price = price_feed::get_price(price_feed);
  398. let price_identifier = *price_feed::get_price_identifier(price_feed);
  399. assert!(price_feed_exists(price_identifier), 1);
  400. let cached_price = get_price(price_identifier);
  401. assert!(cached_price == price, 1);
  402. let ema_price = price_feed::get_ema_price(price_feed);
  403. let cached_ema_price = get_ema_price(price_identifier);
  404. assert!(cached_ema_price == ema_price, 1);
  405. i = i + 1;
  406. };
  407. }
  408. #[test(aptos_framework = @aptos_framework)]
  409. fun test_update_cache(aptos_framework: &signer) {
  410. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 27, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", 50, 0);
  411. let updates = get_mock_price_infos();
  412. // Check that initially the price feeds are not cached
  413. let i = 0;
  414. while (i < vector::length(&updates)) {
  415. let price_feed = price_info::get_price_feed(vector::borrow(&updates, i));
  416. assert!(!price_feed_exists(*price_feed::get_price_identifier(price_feed)), 1);
  417. i = i + 1;
  418. };
  419. // Submit the updates
  420. update_cache(updates);
  421. // Check that the price feeds are now cached
  422. check_price_feeds_cached(&updates);
  423. cleanup_test(burn_capability, mint_capability);
  424. coin::destroy_zero(coins);
  425. }
  426. #[test(aptos_framework = @aptos_framework)]
  427. fun test_update_cache_old_update(aptos_framework: &signer) {
  428. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 27, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", 50, 0);
  429. // Submit a price update
  430. let timestamp = 1663680700;
  431. let price_identifier = price_identifier::from_byte_vec(x"baa284eaf23edf975b371ba2818772f93dbae72836bbdea28b07d40f3cf8b485");
  432. let price = price::new(i64::new(7648, false), 674, i64::new(8, true), timestamp);
  433. let ema_price = price::new(i64::new(1536, true), 869, i64::new(100, false), 1257212500);
  434. let prev_price = price::new(i64::new(74637846, false), 8784, i64::new(8768, false), 1257212400);
  435. let update = price_info::new(
  436. 1257278600,
  437. 1690226180,
  438. price_feed::new(
  439. price_identifier,
  440. price_status::new_trading(),
  441. price,
  442. ema_price,
  443. prev_price,
  444. )
  445. );
  446. update_cache(vector<PriceInfo>[update]);
  447. // Check that we can retrieve the current price
  448. assert!(get_price(price_identifier) == price, 1);
  449. // Attempt to update the price with an update older than the current cached one
  450. let old_price = price::new(i64::new(1243, true), 9802, i64::new(6, false), timestamp - 200);
  451. let old_ema_price = price::new(i64::new(8976, true), 234, i64::new(897, false), timestamp - 200);
  452. let old_update = price_info::new(
  453. 1257278600,
  454. 1690226180,
  455. price_feed::new(
  456. price_identifier,
  457. price_status::new_trading(),
  458. old_price,
  459. old_ema_price,
  460. prev_price,
  461. )
  462. );
  463. update_cache(vector<PriceInfo>[old_update]);
  464. // Confirm that the current price and ema price didn't change
  465. assert!(get_price(price_identifier) == price, 1);
  466. assert!(get_ema_price(price_identifier) == ema_price, 1);
  467. // Update the cache with a fresh update
  468. let fresh_price = price::new(i64::new(4857, true), 9979, i64::new(243, false), timestamp + 200);
  469. let fresh_ema_price = price::new(i64::new(74637, false), 9979, i64::new(1433, false), timestamp + 1);
  470. let fresh_update = price_info::new(
  471. 1257278600,
  472. 1690226180,
  473. price_feed::new(
  474. price_identifier,
  475. price_status::new_trading(),
  476. fresh_price,
  477. fresh_ema_price,
  478. prev_price,
  479. )
  480. );
  481. update_cache(vector<PriceInfo>[fresh_update]);
  482. // Confirm that the current price was updated
  483. assert!(get_price(price_identifier) == fresh_price, 1);
  484. assert!(get_ema_price(price_identifier) == fresh_ema_price, 1);
  485. cleanup_test(burn_capability, mint_capability);
  486. coin::destroy_zero(coins);
  487. }
  488. #[test(aptos_framework = @aptos_framework)]
  489. fun test_get_latest_available_price_unsafe(aptos_framework: &signer) {
  490. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 27, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", 50, 0);
  491. // Submit a price update with a status of trading
  492. let timestamp = 1257212500;
  493. let price_identifier = price_identifier::from_byte_vec(x"baa284eaf23edf975b371ba2818772f93dbae72836bbdea28b07d40f3cf8b485");
  494. let price = price::new(i64::new(7648, false), 674, i64::new(8, true), timestamp);
  495. let update = price_info::new(
  496. 1257278600,
  497. 1690226180,
  498. price_feed::new(
  499. price_identifier,
  500. price_status::new_trading(),
  501. price,
  502. price::new(i64::new(1536, true), 869, i64::new(100, false), 1257212500),
  503. price::new(i64::new(74637846, false), 8784, i64::new(8768, false), 1257212400),
  504. )
  505. );
  506. update_cache(vector<PriceInfo>[update]);
  507. assert!(get_price_unsafe(price_identifier) == price, 1);
  508. // Submit a second, newer, update, this time with unknown and a different "previous trading price"
  509. let second_timestamp = timestamp + 50;
  510. let second_price = price::new(i64::new(7648, false), 674, i64::new(8, true), second_timestamp);
  511. let second_previous_price = price::new(i64::new(8794, true), 989, i64::new(10, false), second_timestamp - 100);
  512. let second_update = price_info::new(
  513. 1257278600,
  514. 1690226180,
  515. price_feed::new(
  516. price_identifier,
  517. price_status::new_unknown(),
  518. second_price,
  519. price::new(i64::new(87876, false), 46659, i64::new(9978, false), 1257212400),
  520. second_previous_price
  521. )
  522. );
  523. update_cache(vector<PriceInfo>[second_update]);
  524. // This time, the latest "unsafe" available price should be second_previous_price,
  525. // because the second update had unknown status
  526. assert!(get_price_unsafe(price_identifier) == second_previous_price, 1);
  527. cleanup_test(burn_capability, mint_capability);
  528. coin::destroy_zero(coins);
  529. }
  530. #[test(aptos_framework = @aptos_framework)]
  531. #[expected_failure(abort_code = 524292)]
  532. fun test_stale_price_threshold_exceeded(aptos_framework: &signer) {
  533. let stale_price_threshold = 500;
  534. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 27, stale_price_threshold, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", 50, 0);
  535. // Submit a price update
  536. let current_timestamp = timestamp::now_seconds();
  537. let price_identifier = price_identifier::from_byte_vec(x"baa284eaf23edf975b371ba2818772f93dbae72836bbdea28b07d40f3cf8b485");
  538. let price = price::new(i64::new(7648, false), 674, i64::new(8, true), current_timestamp);
  539. let update = price_info::new(
  540. 1257278600,
  541. 1690226180,
  542. price_feed::new(
  543. price_identifier,
  544. price_status::new_trading(),
  545. price,
  546. price::new(i64::new(1536, true), 869, i64::new(100, false), 1257212500),
  547. price::new(i64::new(74637846, false), 8784, i64::new(8768, false), 1257212400),
  548. )
  549. );
  550. update_cache(vector<PriceInfo>[update]);
  551. assert!(get_price(price_identifier) == price, 1);
  552. // Now advance the clock on the target chain, until the age of the cached update exceeds the
  553. // stale_price_threshold.
  554. timestamp::update_global_time_for_test_secs(current_timestamp + stale_price_threshold);
  555. // Check that we can access the price if we increase the threshold by 1
  556. assert!(get_price_no_older_than(
  557. price_identifier, get_stale_price_threshold_secs() + 1) == price, 1);
  558. // However, retrieving the latest price fails
  559. assert!(get_price(price_identifier) == price, 1);
  560. cleanup_test(burn_capability, mint_capability);
  561. coin::destroy_zero(coins);
  562. }
  563. #[test(aptos_framework = @aptos_framework)]
  564. #[expected_failure(abort_code = 65541)]
  565. fun test_update_price_feeds_if_fresh_invalid_length(aptos_framework: &signer) {
  566. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 27, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", 50, 0);
  567. // Update the price feeds
  568. let bytes = vector[0u8, 1u8, 2u8];
  569. let price_identifiers = vector[
  570. price_identifier::from_byte_vec(x"baa284eaf23edf975b371ba2818772f93dbae72836bbdea28b07d40f3cf8b485"),
  571. price_identifier::from_byte_vec(x"c9d5fe0d836688f4c88c221415d23e4bcabee21a6a21124bfcc9a5410a297818"),
  572. price_identifier::from_byte_vec(x"eaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a"),
  573. ];
  574. let publish_times = vector[
  575. 734639463
  576. ];
  577. update_price_feeds_if_fresh(bytes, price_identifiers, publish_times, coins);
  578. cleanup_test(burn_capability, mint_capability);
  579. }
  580. #[test(aptos_framework = @aptos_framework)]
  581. fun test_update_price_feeds_if_fresh_fresh_data(aptos_framework: &signer) {
  582. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 27, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", 50, 50);
  583. set_data_source_for_test_vaa();
  584. // Update the price feeds
  585. let bytes = TEST_VAA;
  586. let price_identifiers = vector[
  587. price_identifier::from_byte_vec(x"c6c75c89f14810ec1c54c03ab8f1864a4c4032791f05747f560faec380a695d1"),
  588. price_identifier::from_byte_vec(x"3b9551a68d01d954d6387aff4df1529027ffb2fee413082e509feb29cc4904fe"),
  589. price_identifier::from_byte_vec(x"33832fad6e36eb05a8972fe5f219b27b5b2bb2230a79ce79beb4c5c5e7ecc76d"),
  590. price_identifier::from_byte_vec(x"21a28b4c6619968bd8c20e95b0aaed7df2187fd310275347e0376a2cd7427db8"),
  591. ];
  592. let publish_times = vector[
  593. 1663680745, 1663680730, 1663680760, 1663680720
  594. ];
  595. update_price_feeds_if_fresh(bytes, price_identifiers, publish_times, coins);
  596. // Check that the cache has been updated
  597. let expected = get_mock_price_infos();
  598. check_price_feeds_cached(&expected);
  599. cleanup_test(burn_capability, mint_capability);
  600. }
  601. #[test(aptos_framework = @aptos_framework)]
  602. #[expected_failure(abort_code = 524295)]
  603. fun test_update_price_feeds_if_fresh_stale_data(aptos_framework: &signer) {
  604. let (burn_capability, mint_capability, coins) = setup_test(aptos_framework, 27, 500, 1, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", 50, 50);
  605. set_data_source_for_test_vaa();
  606. // First populate the cache
  607. update_cache(get_mock_price_infos());
  608. // Now attempt to update the price feeds with publish_times that are older than those we have cached
  609. // This should abort with error::no_fresh_data()
  610. let bytes = TEST_VAA;
  611. let price_identifiers = vector[
  612. price_identifier::from_byte_vec(x"c6c75c89f14810ec1c54c03ab8f1864a4c4032791f05747f560faec380a695d1"),
  613. price_identifier::from_byte_vec(x"3b9551a68d01d954d6387aff4df1529027ffb2fee413082e509feb29cc4904fe"),
  614. price_identifier::from_byte_vec(x"33832fad6e36eb05a8972fe5f219b27b5b2bb2230a79ce79beb4c5c5e7ecc76d"),
  615. price_identifier::from_byte_vec(x"21a28b4c6619968bd8c20e95b0aaed7df2187fd310275347e0376a2cd7427db8"),
  616. ];
  617. let publish_times = vector[
  618. 67, 35, 26, 64
  619. ];
  620. update_price_feeds_if_fresh(bytes, price_identifiers, publish_times, coins);
  621. cleanup_test(burn_capability, mint_capability);
  622. }
  623. }