pyth.move 37 KB

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