pyth.move 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. module pyth::pyth {
  2. use std::vector;
  3. use sui::tx_context::{TxContext};
  4. use sui::coin::{Self, Coin};
  5. use sui::sui::{SUI};
  6. use sui::transfer::{Self};
  7. use sui::clock::{Self, Clock};
  8. use sui::package::{UpgradeCap};
  9. use pyth::event::{Self as pyth_event};
  10. use pyth::data_source::{Self, DataSource};
  11. use pyth::state::{Self as state, State as PythState, DeployerCap};
  12. use pyth::price_info::{Self, PriceInfo, PriceInfoObject};
  13. use pyth::batch_price_attestation::{Self};
  14. use pyth::price_feed::{Self};
  15. use pyth::price::{Self, Price};
  16. use pyth::price_identifier::{PriceIdentifier};
  17. use wormhole::external_address::{Self};
  18. use wormhole::vaa::{Self};
  19. use wormhole::state::{State as WormState};
  20. use wormhole::bytes32::{Self};
  21. const E_DATA_SOURCE_EMITTER_ADDRESS_AND_CHAIN_IDS_DIFFERENT_LENGTHS: u64 = 0;
  22. const E_INVALID_DATA_SOURCE: u64 = 1;
  23. const E_INSUFFICIENT_FEE: u64 = 2;
  24. const E_STALE_PRICE_UPDATE: u64 = 3;
  25. const E_PRICE_INFO_OBJECT_NOT_FOUND: u64 = 4;
  26. const E_INVALID_PUBLISH_TIMES_LENGTH: u64 = 5;
  27. const E_NO_FRESH_DATA: u64 = 6;
  28. friend pyth::pyth_tests;
  29. /// Call init_and_share_state with deployer cap to initialize
  30. /// state and emit event corresponding to Pyth initialization.
  31. public entry fun init_pyth(
  32. deployer: DeployerCap,
  33. upgrade_cap: UpgradeCap,
  34. stale_price_threshold: u64,
  35. governance_emitter_chain_id: u64,
  36. governance_emitter_address: vector<u8>,
  37. data_sources_emitter_chain_ids: vector<u64>,
  38. data_sources_emitter_addresses: vector<vector<u8>>,
  39. update_fee: u64,
  40. ctx: &mut TxContext
  41. ) {
  42. state::init_and_share_state(
  43. deployer,
  44. upgrade_cap,
  45. stale_price_threshold,
  46. update_fee,
  47. data_source::new(
  48. governance_emitter_chain_id,
  49. external_address::new((bytes32::from_bytes(governance_emitter_address)))
  50. ),
  51. parse_data_sources(
  52. data_sources_emitter_chain_ids,
  53. data_sources_emitter_addresses,
  54. ),
  55. ctx
  56. );
  57. // Emit Pyth initialization event.
  58. pyth_event::emit_pyth_initialization_event();
  59. }
  60. fun parse_data_sources(
  61. emitter_chain_ids: vector<u64>,
  62. emitter_addresses: vector<vector<u8>>
  63. ): vector<DataSource> {
  64. assert!(vector::length(&emitter_chain_ids) == vector::length(&emitter_addresses),
  65. E_DATA_SOURCE_EMITTER_ADDRESS_AND_CHAIN_IDS_DIFFERENT_LENGTHS);
  66. let sources = vector::empty();
  67. let i = 0;
  68. while (i < vector::length(&emitter_chain_ids)) {
  69. vector::push_back(&mut sources, data_source::new(
  70. *vector::borrow(&emitter_chain_ids, i),
  71. external_address::new(bytes32::from_bytes(*vector::borrow(&emitter_addresses, i)))
  72. ));
  73. i = i + 1;
  74. };
  75. sources
  76. }
  77. /// Create and share new price feed objects if they don't already exist.
  78. public fun create_price_feeds(
  79. worm_state: &WormState,
  80. pyth_state: &mut PythState,
  81. vaas: vector<vector<u8>>,
  82. clock: &Clock,
  83. ctx: &mut TxContext
  84. ){
  85. while (!vector::is_empty(&vaas)) {
  86. let vaa = vector::pop_back(&mut vaas);
  87. // Deserialize the VAA
  88. let vaa = vaa::parse_and_verify(worm_state, vaa, clock);
  89. // Check that the VAA is from a valid data source (emitter)
  90. assert!(
  91. state::is_valid_data_source(
  92. pyth_state,
  93. data_source::new(
  94. (vaa::emitter_chain(&vaa) as u64),
  95. vaa::emitter_address(&vaa))
  96. ),
  97. E_INVALID_DATA_SOURCE);
  98. // Deserialize the batch price attestation
  99. let price_infos = batch_price_attestation::destroy(batch_price_attestation::deserialize(vaa::take_payload(vaa), clock));
  100. while (!vector::is_empty(&price_infos)){
  101. let cur_price_info = vector::pop_back(&mut price_infos);
  102. // Only create new Sui PriceInfoObject if not already
  103. // registered with the Pyth State object.
  104. if (!state::price_feed_object_exists(
  105. pyth_state,
  106. price_feed::get_price_identifier(
  107. price_info::get_price_feed(&cur_price_info)
  108. )
  109. )
  110. ){
  111. // Create and share newly created Sui PriceInfoObject containing a price feed,
  112. // and then register a copy of its ID with State.
  113. let new_price_info_object = price_info::new_price_info_object(cur_price_info, ctx);
  114. let price_identifier = price_info::get_price_identifier(&cur_price_info);
  115. let id = price_info::uid_to_inner(&new_price_info_object);
  116. state::register_price_info_object(pyth_state, price_identifier, id);
  117. transfer::public_share_object(new_price_info_object);
  118. }
  119. }
  120. };
  121. }
  122. /// Update PriceInfo objects and corresponding price feeds with the
  123. /// data in the given VAAs.
  124. ///
  125. /// The vaas argument is a vector of VAAs encoded as bytes.
  126. ///
  127. /// The javascript https://github.com/pyth-network/pyth-js/tree/main/pyth-sui-js package
  128. /// should be used to fetch these VAAs from the Price Service. More information about this
  129. /// process can be found at https://docs.pyth.network/consume-data.
  130. ///
  131. /// The given fee must contain a sufficient number of coins to pay the update fee for the given vaas.
  132. /// The update fee amount can be queried by calling get_update_fee(&vaas).
  133. ///
  134. /// Please read more information about the update fee here: https://docs.pyth.network/consume-data/on-demand#fees
  135. public fun update_price_feeds(
  136. worm_state: &WormState,
  137. pyth_state: &PythState,
  138. vaas: vector<vector<u8>>,
  139. price_info_objects: &mut vector<PriceInfoObject>,
  140. fee: Coin<SUI>,
  141. clock: &Clock
  142. ){
  143. // Charge the message update fee
  144. assert!(get_total_update_fee(pyth_state, &vaas) <= coin::value(&fee), E_INSUFFICIENT_FEE);
  145. // TODO: use Wormhole fee collector instead of transferring funds to deployer address.
  146. transfer::public_transfer(fee, @pyth);
  147. // Update the price feed from each VAA
  148. while (!vector::is_empty(&vaas)) {
  149. update_price_feed_from_single_vaa(
  150. worm_state,
  151. pyth_state,
  152. vector::pop_back(&mut vaas),
  153. price_info_objects,
  154. clock
  155. );
  156. };
  157. }
  158. /// Precondition: A Sui object of type PriceInfoObject must exist for each update
  159. /// encoded in the worm_vaa (batch_attestation_vaa). These should be passed in
  160. /// via the price_info_objects argument.
  161. fun update_price_feed_from_single_vaa(
  162. worm_state: &WormState,
  163. pyth_state: &PythState,
  164. worm_vaa: vector<u8>,
  165. price_info_objects: &mut vector<PriceInfoObject>,
  166. clock: &Clock
  167. ) {
  168. // Deserialize the VAA
  169. let vaa = vaa::parse_and_verify(worm_state, worm_vaa, clock);
  170. // Check that the VAA is from a valid data source (emitter)
  171. assert!(
  172. state::is_valid_data_source(
  173. pyth_state,
  174. data_source::new(
  175. (vaa::emitter_chain(&vaa) as u64),
  176. vaa::emitter_address(&vaa))
  177. ),
  178. E_INVALID_DATA_SOURCE);
  179. // Deserialize the batch price attestation
  180. let price_infos = batch_price_attestation::destroy(batch_price_attestation::deserialize(vaa::take_payload(vaa), clock));
  181. // Update price info objects.
  182. update_cache(price_infos, price_info_objects, clock);
  183. }
  184. /// Update PriceInfoObjects using up-to-date PriceInfos.
  185. public(friend) fun update_cache(
  186. updates: vector<PriceInfo>,
  187. price_info_objects: &mut vector<PriceInfoObject>,
  188. clock: &Clock,
  189. ){
  190. while (!vector::is_empty(&updates)) {
  191. let update = vector::pop_back(&mut updates);
  192. let i = 0;
  193. let found = false;
  194. // Find PriceInfoObjects corresponding to the current update (PriceInfo).
  195. // TODO - Construct an in-memory table to make look-ups faster?
  196. // This loop might be expensive if there are a large number
  197. // of updates and/or price_info_objects we are updating.
  198. while (i < vector::length<PriceInfoObject>(price_info_objects) && found == false){
  199. // Check if the current price info object corresponds to the price feed that
  200. // the update is meant for.
  201. let price_info = price_info::get_price_info_from_price_info_object(vector::borrow(price_info_objects, i));
  202. if (price_info::get_price_identifier(&price_info) ==
  203. price_info::get_price_identifier(&update)){
  204. found = true;
  205. pyth_event::emit_price_feed_update(price_feed::from(price_info::get_price_feed(&update)), clock::timestamp_ms(clock)/1000);
  206. // Update the price info object with the new updated price info.
  207. if (is_fresh_update(&update, vector::borrow(price_info_objects, i))){
  208. price_info::update_price_info_object(
  209. vector::borrow_mut(price_info_objects, i),
  210. update
  211. );
  212. }
  213. };
  214. i = i + 1;
  215. };
  216. if (!found){
  217. abort(E_PRICE_INFO_OBJECT_NOT_FOUND)
  218. }
  219. };
  220. vector::destroy_empty(updates);
  221. }
  222. /// Update the cached price feeds with the data in the given VAAs, using
  223. /// update_price_feeds(). However, this function will only have an effect if any of the
  224. /// prices in the update are fresh. The price_identifiers and publish_times parameters
  225. /// are used to determine if the update is fresh without doing any serialisation or verification
  226. /// of the VAAs, potentially saving time and gas. If the update contains no fresh data, this function
  227. /// will revert with error::no_fresh_data().
  228. ///
  229. /// For a given price update i in the batch, that price is considered fresh if the current cached
  230. /// price for price_identifiers[i] is older than publish_times[i].
  231. public fun update_price_feeds_if_fresh(
  232. vaas: vector<vector<u8>>,
  233. worm_state: &WormState,
  234. pyth_state: &PythState,
  235. price_info_objects: &mut vector<PriceInfoObject>,
  236. publish_times: vector<u64>,
  237. fee: Coin<SUI>,
  238. clock: &Clock
  239. ) {
  240. assert!(vector::length(price_info_objects) == vector::length(&publish_times),
  241. E_INVALID_PUBLISH_TIMES_LENGTH
  242. );
  243. let fresh_data = false;
  244. let i = 0;
  245. while (i < vector::length(&publish_times)) {
  246. let cur_price_info = price_info::get_price_info_from_price_info_object(vector::borrow(price_info_objects, i));
  247. let cur_price_feed = price_info::get_price_feed(&cur_price_info);
  248. let cur_price = price_feed::get_price(cur_price_feed);
  249. let cached_timestamp = price::get_timestamp(&cur_price);
  250. if (cached_timestamp < *vector::borrow(&publish_times, i)) {
  251. fresh_data = true;
  252. break
  253. };
  254. i = i + 1;
  255. };
  256. assert!(fresh_data, E_NO_FRESH_DATA);
  257. update_price_feeds(worm_state, pyth_state, vaas, price_info_objects, fee, clock);
  258. }
  259. /// Determine if the given price update is "fresh": we have nothing newer already cached for that
  260. /// price feed within a PriceInfoObject.
  261. fun is_fresh_update(update: &PriceInfo, price_info_object: &PriceInfoObject): bool {
  262. // Get the timestamp of the update's current price
  263. let price_feed = price_info::get_price_feed(update);
  264. let update_timestamp = price::get_timestamp(&price_feed::get_price(price_feed));
  265. // Get the timestamp of the cached data for the price identifier
  266. let cached_price_info = price_info::get_price_info_from_price_info_object(price_info_object);
  267. let cached_price_feed = price_info::get_price_feed(&cached_price_info);
  268. let cached_timestamp = price::get_timestamp(&price_feed::get_price(cached_price_feed));
  269. update_timestamp > cached_timestamp
  270. }
  271. // -----------------------------------------------------------------------------
  272. // Query the cached prices
  273. //
  274. // It is strongly recommended to update the cached prices using the functions above,
  275. // before using the functions below to query the cached data.
  276. /// Determine if a price feed for the given price_identifier exists
  277. public fun price_feed_exists(state: &PythState, price_identifier: PriceIdentifier): bool {
  278. state::price_feed_object_exists(state, price_identifier)
  279. }
  280. /// Get the latest available price cached for the given price identifier, if that price is
  281. /// no older than the stale price threshold.
  282. ///
  283. /// Please refer to the documentation at https://docs.pyth.network/consumers/best-practices for
  284. /// how to how this price safely.
  285. ///
  286. /// Important: Pyth uses an on-demand update model, where consumers need to update the
  287. /// cached prices before using them. Please read more about this at https://docs.pyth.network/consume-data/on-demand.
  288. /// get_price() is likely to abort unless you call update_price_feeds() to update the cached price
  289. /// beforehand, as the cached prices may be older than the stale price threshold.
  290. ///
  291. /// The price_info_object is a Sui object with the key ability that uniquely
  292. /// contains a price feed for a given price_identifier.
  293. ///
  294. public fun get_price(state: &PythState, price_info_object: &PriceInfoObject, clock: &Clock): Price {
  295. get_price_no_older_than(price_info_object, clock, state::get_stale_price_threshold_secs(state))
  296. }
  297. /// Get the latest available price cached for the given price identifier, if that price is
  298. /// no older than the given age.
  299. public fun get_price_no_older_than(price_info_object: &PriceInfoObject, clock: &Clock, max_age_secs: u64): Price {
  300. let price = get_price_unsafe(price_info_object);
  301. check_price_is_fresh(&price, clock, max_age_secs);
  302. price
  303. }
  304. /// Get the latest available price cached for the given price identifier.
  305. ///
  306. /// WARNING: the returned price can be from arbitrarily far in the past.
  307. /// This function makes no guarantees that the returned price is recent or
  308. /// useful for any particular application. Users of this function should check
  309. /// the returned timestamp to ensure that the returned price is sufficiently
  310. /// recent for their application. The checked get_price_no_older_than()
  311. /// function should be used in preference to this.
  312. public fun get_price_unsafe(price_info_object: &PriceInfoObject): Price {
  313. // TODO: extract Price from this guy...
  314. let price_info = price_info::get_price_info_from_price_info_object(price_info_object);
  315. price_feed::get_price(
  316. price_info::get_price_feed(&price_info)
  317. )
  318. }
  319. fun abs_diff(x: u64, y: u64): u64 {
  320. if (x > y) {
  321. return x - y
  322. } else {
  323. return y - x
  324. }
  325. }
  326. /// Get the stale price threshold: the amount of time after which a cached price
  327. /// is considered stale and no longer returned by get_price()/get_ema_price().
  328. public fun get_stale_price_threshold_secs(state: &PythState): u64 {
  329. state::get_stale_price_threshold_secs(state)
  330. }
  331. fun check_price_is_fresh(price: &Price, clock: &Clock, max_age_secs: u64) {
  332. let age = abs_diff(clock::timestamp_ms(clock)/1000, price::get_timestamp(price));
  333. assert!(age < max_age_secs, E_STALE_PRICE_UPDATE);
  334. }
  335. /// Please read more information about the update fee here: https://docs.pyth.network/consume-data/on-demand#fees
  336. public fun get_total_update_fee(pyth_state: &PythState, update_data: &vector<vector<u8>>): u64 {
  337. state::get_base_update_fee(pyth_state) * vector::length(update_data)
  338. }
  339. }
  340. module pyth::pyth_tests{
  341. use std::vector::{Self};
  342. use sui::sui::SUI;
  343. use sui::coin::{Self, Coin};
  344. use sui::clock::{Self, Clock};
  345. use sui::test_scenario::{Self, Scenario, ctx, take_shared, return_shared};
  346. use sui::package::Self;
  347. use sui::object::{Self, ID};
  348. use pyth::state::{Self, State as PythState};
  349. use pyth::price_identifier::{Self};
  350. use pyth::price_info::{Self, PriceInfo, PriceInfoObject};
  351. use pyth::price_feed::{Self};
  352. use pyth::data_source::{Self, DataSource};
  353. use pyth::i64::{Self};
  354. use pyth::price::{Self};
  355. use pyth::pyth::{Self};
  356. use wormhole::setup::{Self as wormhole_setup, DeployerCap};
  357. use wormhole::external_address::{Self};
  358. use wormhole::bytes32::{Self};
  359. use wormhole::state::{State as WormState};
  360. const DEPLOYER: address = @0x1234;
  361. #[test_only]
  362. /// A vector containing a single VAA with:
  363. /// - emitter chain ID 17
  364. /// - emitter address 0x71f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b
  365. /// - payload corresponding to the batch price attestation of the prices returned by get_mock_price_infos()
  366. const TEST_VAAS: vector<vector<u8>> = vector[x"0100000000010036eb563b80a24f4253bee6150eb8924e4bdf6e4fa1dfc759a6664d2e865b4b134651a7b021b7f1ce3bd078070b688b6f2e37ce2de0d9b48e6a78684561e49d5201527e4f9b00000001001171f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b0000000000000001005032574800030000000102000400951436e0be37536be96f0896366089506a59763d036728332d3e3038047851aea7c6c75c89f14810ec1c54c03ab8f1864a4c4032791f05747f560faec380a695d1000000000000049a0000000000000008fffffffb00000000000005dc0000000000000003000000000100000001000000006329c0eb000000006329c0e9000000006329c0e400000000000006150000000000000007215258d81468614f6b7e194c5d145609394f67b041e93e6695dcc616faadd0603b9551a68d01d954d6387aff4df1529027ffb2fee413082e509feb29cc4904fe000000000000041a0000000000000003fffffffb00000000000005cb0000000000000003010000000100000001000000006329c0eb000000006329c0e9000000006329c0e4000000000000048600000000000000078ac9cf3ab299af710d735163726fdae0db8465280502eb9f801f74b3c1bd190333832fad6e36eb05a8972fe5f219b27b5b2bb2230a79ce79beb4c5c5e7ecc76d00000000000003f20000000000000002fffffffb00000000000005e70000000000000003010000000100000001000000006329c0eb000000006329c0e9000000006329c0e40000000000000685000000000000000861db714e9ff987b6fedf00d01f9fea6db7c30632d6fc83b7bc9459d7192bc44a21a28b4c6619968bd8c20e95b0aaed7df2187fd310275347e0376a2cd7427db800000000000006cb0000000000000001fffffffb00000000000005e40000000000000003010000000100000001000000006329c0eb000000006329c0e9000000006329c0e400000000000007970000000000000001"];
  367. #[test_only]
  368. /// Init Wormhole core bridge state.
  369. /// Init Pyth state.
  370. /// Set initial Sui clock time.
  371. /// Mint some SUI fee coins.
  372. fun setup_test(
  373. stale_price_threshold: u64,
  374. governance_emitter_chain_id: u64,
  375. governance_emitter_address: vector<u8>,
  376. data_sources: vector<DataSource>,
  377. base_update_fee: u64,
  378. to_mint: u64
  379. ): (Scenario, Coin<SUI>) {
  380. let scenario = test_scenario::begin(DEPLOYER);
  381. // Initialize Wormhole core bridge.
  382. wormhole_setup::init_test_only(ctx(&mut scenario));
  383. test_scenario::next_tx(&mut scenario, DEPLOYER);
  384. // Take the `DeployerCap` from the sender of the transaction.
  385. let deployer_cap =
  386. test_scenario::take_from_address<DeployerCap>(
  387. &scenario,
  388. DEPLOYER
  389. );
  390. // This will be created and sent to the transaction sender automatically
  391. // when the contract is published. This exists in place of grabbing
  392. // it from the sender.
  393. let upgrade_cap =
  394. package::test_publish(
  395. object::id_from_address(@wormhole),
  396. test_scenario::ctx(&mut scenario)
  397. );
  398. let governance_chain = 1234;
  399. let governance_contract =
  400. x"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
  401. let initial_guardians =
  402. vector[
  403. x"beFA429d57cD18b7F8A4d91A2da9AB4AF05d0FBe"
  404. ];
  405. let guardian_set_seconds_to_live = 5678;
  406. let message_fee = 350;
  407. wormhole_setup::complete(
  408. deployer_cap,
  409. upgrade_cap,
  410. governance_chain,
  411. governance_contract,
  412. initial_guardians,
  413. guardian_set_seconds_to_live,
  414. message_fee,
  415. test_scenario::ctx(&mut scenario)
  416. );
  417. // Create and share a global clock object for timekeeping.
  418. clock::create_for_testing(ctx(&mut scenario));
  419. // Initialize Pyth state.
  420. let pyth_upgrade_cap=
  421. package::test_publish(
  422. object::id_from_address(@pyth),
  423. test_scenario::ctx(&mut scenario)
  424. );
  425. state::init_test_only(ctx(&mut scenario));
  426. test_scenario::next_tx(&mut scenario, DEPLOYER);
  427. let pyth_deployer_cap = test_scenario::take_from_address<state::DeployerCap>(
  428. &scenario,
  429. DEPLOYER
  430. );
  431. state::init_and_share_state(
  432. pyth_deployer_cap,
  433. pyth_upgrade_cap,
  434. stale_price_threshold,
  435. base_update_fee,
  436. data_source::new(governance_emitter_chain_id, external_address::new(bytes32::from_bytes(governance_emitter_address))),
  437. data_sources,
  438. ctx(&mut scenario)
  439. );
  440. let coins = coin::mint_for_testing<SUI>(to_mint, ctx(&mut scenario));
  441. (scenario, coins)
  442. }
  443. #[test_only]
  444. fun get_mock_price_infos(): vector<PriceInfo> {
  445. vector<PriceInfo>[
  446. price_info::new_price_info(
  447. 1663680747,
  448. 1663074349,
  449. price_feed::new(
  450. price_identifier::from_byte_vec(x"c6c75c89f14810ec1c54c03ab8f1864a4c4032791f05747f560faec380a695d1"),
  451. price::new(i64::new(1557, false), 7, i64::new(5, true), 1663680740),
  452. price::new(i64::new(1500, false), 3, i64::new(5, true), 1663680740),
  453. ),
  454. ),
  455. price_info::new_price_info(
  456. 1663680747,
  457. 1663074349,
  458. price_feed::new(
  459. price_identifier::from_byte_vec(x"3b9551a68d01d954d6387aff4df1529027ffb2fee413082e509feb29cc4904fe"),
  460. price::new(i64::new(1050, false), 3, i64::new(5, true), 1663680745),
  461. price::new(i64::new(1483, false), 3, i64::new(5, true), 1663680745),
  462. ),
  463. ),
  464. price_info::new_price_info(
  465. 1663680747,
  466. 1663074349,
  467. price_feed::new(
  468. price_identifier::from_byte_vec(x"33832fad6e36eb05a8972fe5f219b27b5b2bb2230a79ce79beb4c5c5e7ecc76d"),
  469. price::new(i64::new(1010, false), 2, i64::new(5, true), 1663680745),
  470. price::new(i64::new(1511, false), 3, i64::new(5, true), 1663680745),
  471. ),
  472. ),
  473. price_info::new_price_info(
  474. 1663680747,
  475. 1663074349,
  476. price_feed::new(
  477. price_identifier::from_byte_vec(x"21a28b4c6619968bd8c20e95b0aaed7df2187fd310275347e0376a2cd7427db8"),
  478. price::new(i64::new(1739, false), 1, i64::new(5, true), 1663680745),
  479. price::new(i64::new(1508, false), 3, i64::new(5, true), 1663680745),
  480. ),
  481. ),
  482. ]
  483. }
  484. #[test_only]
  485. /// Compare the expected price feed with the actual Pyth price feeds.
  486. fun check_price_feeds_cached(expected: &vector<PriceInfo>, actual: &vector<PriceInfoObject>) {
  487. // Check that we can retrieve the correct current price and ema price for each price feed
  488. let i = 0;
  489. while (i < vector::length(expected)) {
  490. let price_feed = price_info::get_price_feed(vector::borrow(expected, i));
  491. let price = price_feed::get_price(price_feed);
  492. let ema_price = price_feed::get_ema_price(price_feed);
  493. let price_identifier = price_info::get_price_identifier(vector::borrow(expected, i));
  494. let actual_price_info = price_info::get_price_info_from_price_info_object(vector::borrow(actual, i));
  495. let actual_price_feed = price_info::get_price_feed(&actual_price_info);
  496. let actual_price = price_feed::get_price(actual_price_feed);
  497. let actual_ema_price = price_feed::get_ema_price(actual_price_feed);
  498. let actual_price_identifier = price_info::get_price_identifier(&actual_price_info);
  499. assert!(price == actual_price, 0);
  500. assert!(ema_price == actual_ema_price, 0);
  501. assert!(price_identifier::get_bytes(&price_identifier) == price_identifier::get_bytes(&actual_price_identifier), 0);
  502. i = i + 1;
  503. };
  504. }
  505. #[test]
  506. fun test_get_update_fee() {
  507. let single_update_fee = 50;
  508. let (scenario, test_coins) = setup_test(500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", vector[], single_update_fee, 0);
  509. test_scenario::next_tx(&mut scenario, DEPLOYER, );
  510. let pyth_state = take_shared<PythState>(&scenario);
  511. // Pass in a single VAA
  512. assert!(pyth::get_total_update_fee(&pyth_state, &vector[
  513. x"fb1543888001083cf2e6ef3afdcf827e89b11efd87c563638df6e1995ada9f93",
  514. ]) == single_update_fee, 1);
  515. // Pass in multiple VAAs
  516. assert!(pyth::get_total_update_fee(&pyth_state, &vector[
  517. x"4ee17a1a4524118de513fddcf82b77454e51be5d6fc9e29fc72dd6c204c0e4fa",
  518. x"c72fdf81cfc939d4286c93fbaaae2eec7bae28a5926fa68646b43a279846ccc1",
  519. x"d9a8123a793529c31200339820a3210059ecace6c044f81ecad62936e47ca049",
  520. x"84e4f21b3e65cef47fda25d15b4eddda1edf720a1d062ccbf441d6396465fbe6",
  521. x"9e73f9041476a93701a0b9c7501422cc2aa55d16100bec628cf53e0281b6f72f"
  522. ]) == 250, 1);
  523. return_shared(pyth_state);
  524. coin::burn_for_testing<SUI>(test_coins);
  525. test_scenario::end(scenario);
  526. }
  527. #[test]
  528. #[expected_failure(abort_code = wormhole::vaa::E_WRONG_VERSION)]
  529. fun test_create_price_feeds_corrupt_vaa() {
  530. let (scenario, test_coins) = setup_test(500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", vector[], 50, 0);
  531. test_scenario::next_tx(&mut scenario, DEPLOYER);
  532. let pyth_state = take_shared<PythState>(&scenario);
  533. let worm_state = take_shared<WormState>(&scenario);
  534. let clock = take_shared<Clock>(&scenario);
  535. // Pass in a corrupt VAA, which should fail deseriaizing
  536. let corrupt_vaa = x"90F8bf6A479f320ead074411a4B0e7944Ea8c9C1";
  537. // Create Pyth price feed
  538. pyth::create_price_feeds(
  539. &mut worm_state,
  540. &mut pyth_state,
  541. vector[corrupt_vaa],
  542. &clock,
  543. ctx(&mut scenario)
  544. );
  545. return_shared(pyth_state);
  546. return_shared(worm_state);
  547. return_shared(clock);
  548. coin::burn_for_testing<SUI>(test_coins);
  549. test_scenario::end(scenario);
  550. }
  551. #[test]
  552. #[expected_failure(abort_code = pyth::pyth::E_INVALID_DATA_SOURCE)]
  553. fun test_create_price_feeds_invalid_data_source() {
  554. // Initialize the contract with some valid data sources, excluding our test VAA's source
  555. let data_sources = vector<DataSource>[
  556. data_source::new(
  557. 4, external_address::new(bytes32::new(x"0000000000000000000000000000000000000000000000000000000000007742"))
  558. ),
  559. data_source::new(
  560. 5, external_address::new(bytes32::new(x"0000000000000000000000000000000000000000000000000000000000007637"))
  561. )
  562. ];
  563. let (scenario, test_coins) = setup_test(500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources, 50, 0);
  564. test_scenario::next_tx(&mut scenario, DEPLOYER);
  565. let pyth_state = take_shared<PythState>(&scenario);
  566. let worm_state = take_shared<WormState>(&scenario);
  567. let clock = take_shared<Clock>(&scenario);
  568. pyth::create_price_feeds(
  569. &mut worm_state,
  570. &mut pyth_state,
  571. TEST_VAAS,
  572. &clock,
  573. ctx(&mut scenario)
  574. );
  575. return_shared(pyth_state);
  576. return_shared(worm_state);
  577. return_shared(clock);
  578. coin::burn_for_testing<SUI>(test_coins);
  579. test_scenario::end(scenario);
  580. }
  581. #[test_only]
  582. fun data_sources_for_test_vaa(): vector<DataSource> {
  583. // Set some valid data sources, including our test VAA's source
  584. vector<DataSource>[
  585. data_source::new(
  586. 1, external_address::new(bytes32::from_bytes(x"0000000000000000000000000000000000000000000000000000000000000004"))),
  587. data_source::new(
  588. 5, external_address::new(bytes32::new(x"0000000000000000000000000000000000000000000000000000000000007637"))),
  589. data_source::new(
  590. 17, external_address::new(bytes32::new(x"71f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b")))
  591. ]
  592. }
  593. #[test]
  594. fun test_create_and_update_price_feeds_success() {
  595. let data_sources = data_sources_for_test_vaa();
  596. let base_update_fee = 50;
  597. let coins_to_mint = 5000;
  598. let (scenario, test_coins) = setup_test(500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources, base_update_fee, coins_to_mint);
  599. test_scenario::next_tx(&mut scenario, DEPLOYER);
  600. let pyth_state = take_shared<PythState>(&scenario);
  601. let worm_state = take_shared<WormState>(&scenario);
  602. let clock = take_shared<Clock>(&scenario);
  603. pyth::create_price_feeds(
  604. &mut worm_state,
  605. &mut pyth_state,
  606. TEST_VAAS,
  607. &clock,
  608. ctx(&mut scenario)
  609. );
  610. // Affirm that 4 objects, which correspond to the 4 new price info objects
  611. // containing the price feeds were created and shared.
  612. let effects = test_scenario::next_tx(&mut scenario, DEPLOYER);
  613. let shared_ids = test_scenario::shared(&effects);
  614. let created_ids = test_scenario::created(&effects);
  615. assert!(vector::length<ID>(&shared_ids)==4, 0);
  616. assert!(vector::length<ID>(&created_ids)==4, 0);
  617. let price_info_object_1 = take_shared<PriceInfoObject>(&scenario);
  618. let price_info_object_2 = take_shared<PriceInfoObject>(&scenario);
  619. let price_info_object_3 = take_shared<PriceInfoObject>(&scenario);
  620. let price_info_object_4 = take_shared<PriceInfoObject>(&scenario);
  621. // Create vector of price info objects (Sui objects with key ability and living in global store),
  622. // which contain the price feeds we want to update. Note that these can be passed into
  623. // update_price_feeds in any order!
  624. let price_info_object_vec = vector[price_info_object_1, price_info_object_2, price_info_object_3, price_info_object_4];
  625. pyth::update_price_feeds(
  626. &mut worm_state,
  627. &mut pyth_state,
  628. TEST_VAAS,
  629. &mut price_info_object_vec,
  630. test_coins,
  631. &clock
  632. );
  633. price_info_object_4 = vector::pop_back(&mut price_info_object_vec);
  634. price_info_object_3 = vector::pop_back(&mut price_info_object_vec);
  635. price_info_object_2 = vector::pop_back(&mut price_info_object_vec);
  636. price_info_object_1 = vector::pop_back(&mut price_info_object_vec);
  637. vector::destroy_empty(price_info_object_vec);
  638. return_shared(pyth_state);
  639. return_shared(worm_state);
  640. return_shared(price_info_object_1);
  641. return_shared(price_info_object_2);
  642. return_shared(price_info_object_3);
  643. return_shared(price_info_object_4);
  644. return_shared(clock);
  645. test_scenario::end(scenario);
  646. }
  647. #[test]
  648. #[expected_failure(abort_code = pyth::pyth::E_PRICE_INFO_OBJECT_NOT_FOUND)]
  649. fun test_create_and_update_price_feeds_price_info_object_not_found_failure() {
  650. let data_sources = data_sources_for_test_vaa();
  651. let base_update_fee = 50;
  652. let coins_to_mint = 5000;
  653. let (scenario, test_coins) = setup_test(500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources, base_update_fee, coins_to_mint);
  654. test_scenario::next_tx(&mut scenario, DEPLOYER);
  655. let pyth_state = take_shared<PythState>(&scenario);
  656. let worm_state = take_shared<WormState>(&scenario);
  657. let clock = take_shared<Clock>(&scenario);
  658. pyth::create_price_feeds(
  659. &mut worm_state,
  660. &mut pyth_state,
  661. TEST_VAAS,
  662. &clock,
  663. ctx(&mut scenario)
  664. );
  665. // Affirm that 4 objects, which correspond to the 4 new price info objects
  666. // containing the price feeds were created and shared.
  667. let effects = test_scenario::next_tx(&mut scenario, DEPLOYER);
  668. let shared_ids = test_scenario::shared(&effects);
  669. let created_ids = test_scenario::created(&effects);
  670. assert!(vector::length<ID>(&shared_ids)==4, 0);
  671. assert!(vector::length<ID>(&created_ids)==4, 0);
  672. let price_info_object_1 = take_shared<PriceInfoObject>(&scenario);
  673. let price_info_object_2 = take_shared<PriceInfoObject>(&scenario);
  674. let price_info_object_3 = take_shared<PriceInfoObject>(&scenario);
  675. let price_info_object_4 = take_shared<PriceInfoObject>(&scenario);
  676. // Note that here we only pass in 3 price info objects corresponding to 3 out
  677. // of the 4 price feeds.
  678. let price_info_object_vec = vector[price_info_object_1, price_info_object_2, price_info_object_3];
  679. pyth::update_price_feeds(
  680. &mut worm_state,
  681. &mut pyth_state,
  682. TEST_VAAS,
  683. &mut price_info_object_vec,
  684. test_coins,
  685. &clock
  686. );
  687. price_info_object_3 = vector::pop_back(&mut price_info_object_vec);
  688. price_info_object_2 = vector::pop_back(&mut price_info_object_vec);
  689. price_info_object_1 = vector::pop_back(&mut price_info_object_vec);
  690. vector::destroy_empty(price_info_object_vec);
  691. return_shared(pyth_state);
  692. return_shared(worm_state);
  693. return_shared(price_info_object_1);
  694. return_shared(price_info_object_2);
  695. return_shared(price_info_object_3);
  696. return_shared(price_info_object_4);
  697. return_shared(clock);
  698. test_scenario::end(scenario);
  699. }
  700. #[test]
  701. #[expected_failure(abort_code = pyth::pyth::E_INSUFFICIENT_FEE)]
  702. fun test_create_and_update_price_feeds_insufficient_fee() {
  703. let data_sources = data_sources_for_test_vaa();
  704. let base_update_fee = 50;
  705. let coins_to_mint = 5;
  706. let (scenario, test_coins) = setup_test(500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources, base_update_fee, coins_to_mint);
  707. test_scenario::next_tx(&mut scenario, DEPLOYER);
  708. let pyth_state = take_shared<PythState>(&scenario);
  709. let worm_state = take_shared<WormState>(&scenario);
  710. let clock = take_shared<Clock>(&scenario);
  711. pyth::create_price_feeds(
  712. &mut worm_state,
  713. &mut pyth_state,
  714. TEST_VAAS,
  715. &clock,
  716. ctx(&mut scenario)
  717. );
  718. test_scenario::next_tx(&mut scenario, DEPLOYER);
  719. let price_info_object = take_shared<PriceInfoObject>(&scenario);
  720. let price_info_object_vec = vector[price_info_object];
  721. pyth::update_price_feeds(
  722. &mut worm_state,
  723. &mut pyth_state,
  724. TEST_VAAS,
  725. &mut price_info_object_vec,
  726. test_coins,
  727. &clock
  728. );
  729. price_info_object = vector::pop_back(&mut price_info_object_vec);
  730. vector::destroy_empty(price_info_object_vec);
  731. return_shared(pyth_state);
  732. return_shared(worm_state);
  733. return_shared(price_info_object);
  734. return_shared(clock);
  735. test_scenario::end(scenario);
  736. }
  737. #[test]
  738. fun test_update_cache(){
  739. let data_sources = data_sources_for_test_vaa();
  740. let base_update_fee = 50;
  741. let coins_to_mint = 5000;
  742. let (scenario, test_coins) = setup_test(500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources, base_update_fee, coins_to_mint);
  743. test_scenario::next_tx(&mut scenario, DEPLOYER);
  744. let pyth_state = take_shared<PythState>(&scenario);
  745. let worm_state = take_shared<WormState>(&scenario);
  746. let clock = take_shared<Clock>(&scenario);
  747. pyth::create_price_feeds(
  748. &mut worm_state,
  749. &mut pyth_state,
  750. TEST_VAAS,
  751. &clock,
  752. ctx(&mut scenario)
  753. );
  754. test_scenario::next_tx(&mut scenario, DEPLOYER);
  755. let price_info_object_1 = take_shared<PriceInfoObject>(&scenario);
  756. let price_info_object_2 = take_shared<PriceInfoObject>(&scenario);
  757. let price_info_object_3 = take_shared<PriceInfoObject>(&scenario);
  758. let price_info_object_4 = take_shared<PriceInfoObject>(&scenario);
  759. // These updates are price infos that correspond to the ones in TEST_VAAS.
  760. let updates = get_mock_price_infos();
  761. let price_info_object_vec = vector[
  762. price_info_object_1,
  763. price_info_object_2,
  764. price_info_object_3,
  765. price_info_object_4
  766. ];
  767. // Check that TEST_VAAS was indeed used to instantiate the price feeds correctly,
  768. // by confirming that the info in updates is contained in price_info_object_vec.
  769. check_price_feeds_cached(&updates, &price_info_object_vec);
  770. price_info_object_4 = vector::pop_back(&mut price_info_object_vec);
  771. price_info_object_3 = vector::pop_back(&mut price_info_object_vec);
  772. price_info_object_2 = vector::pop_back(&mut price_info_object_vec);
  773. price_info_object_1 = vector::pop_back(&mut price_info_object_vec);
  774. vector::destroy_empty(price_info_object_vec);
  775. return_shared(pyth_state);
  776. return_shared(worm_state);
  777. return_shared(price_info_object_1);
  778. return_shared(price_info_object_2);
  779. return_shared(price_info_object_3);
  780. return_shared(price_info_object_4);
  781. coin::burn_for_testing<SUI>(test_coins);
  782. return_shared(clock);
  783. test_scenario::end(scenario);
  784. }
  785. #[test]
  786. fun test_update_cache_old_update() {
  787. let data_sources = data_sources_for_test_vaa();
  788. let base_update_fee = 50;
  789. let coins_to_mint = 5000;
  790. let (scenario, test_coins) = setup_test(500, 23, x"5d1f252d5de865279b00c84bce362774c2804294ed53299bc4a0389a5defef92", data_sources, base_update_fee, coins_to_mint);
  791. test_scenario::next_tx(&mut scenario, DEPLOYER);
  792. let pyth_state = take_shared<PythState>(&scenario);
  793. let worm_state = take_shared<WormState>(&scenario);
  794. let clock = take_shared<Clock>(&scenario);
  795. pyth::create_price_feeds(
  796. &mut worm_state,
  797. &mut pyth_state,
  798. TEST_VAAS,
  799. &clock,
  800. ctx(&mut scenario)
  801. );
  802. test_scenario::next_tx(&mut scenario, DEPLOYER);
  803. let price_info_object_1 = take_shared<PriceInfoObject>(&scenario);
  804. let price_info_object_2 = take_shared<PriceInfoObject>(&scenario);
  805. let price_info_object_3 = take_shared<PriceInfoObject>(&scenario);
  806. let price_info_object_4 = take_shared<PriceInfoObject>(&scenario);
  807. let price_info_object_vec = vector[
  808. price_info_object_1,
  809. price_info_object_2,
  810. price_info_object_3,
  811. price_info_object_4
  812. ];
  813. // Hardcode the price identifier, price, and ema_price for price_info_object_1, because
  814. // it's easier than unwrapping price_info_object_1 and getting the quantities via getters.
  815. let timestamp = 1663680740;
  816. let price_identifier = price_identifier::from_byte_vec(x"c6c75c89f14810ec1c54c03ab8f1864a4c4032791f05747f560faec380a695d1");
  817. let price = price::new(i64::new(1557, false), 7, i64::new(5, true), timestamp);
  818. let ema_price = price::new(i64::new(1500, false), 3, i64::new(5, true), timestamp);
  819. // Attempt to update the price with an update older than the current cached one.
  820. let old_price = price::new(i64::new(1243, true), 9802, i64::new(6, false), timestamp - 200);
  821. let old_ema_price = price::new(i64::new(8976, true), 234, i64::new(897, false), timestamp - 200);
  822. let old_update = price_info::new_price_info(
  823. 1257278600,
  824. 1690226180,
  825. price_feed::new(
  826. price_identifier,
  827. old_price,
  828. old_ema_price,
  829. )
  830. );
  831. pyth::update_cache(vector<PriceInfo>[old_update], &mut price_info_object_vec, &clock);
  832. price_info_object_4 = vector::pop_back(&mut price_info_object_vec);
  833. price_info_object_3 = vector::pop_back(&mut price_info_object_vec);
  834. price_info_object_2 = vector::pop_back(&mut price_info_object_vec);
  835. price_info_object_1 = vector::pop_back(&mut price_info_object_vec);
  836. vector::destroy_empty(price_info_object_vec);
  837. // Confirm that the current price and ema price didn't change
  838. let current_price_info = price_info::get_price_info_from_price_info_object(&price_info_object_1);
  839. let current_price_feed = price_info::get_price_feed(&current_price_info);
  840. let current_price = price_feed::get_price(current_price_feed);
  841. let current_ema_price = price_feed::get_ema_price(current_price_feed);
  842. // Confirm that no price update occurred when we tried to update cache with an
  843. // outdated update: old_update.
  844. assert!(current_price == price, 1);
  845. assert!(current_ema_price == ema_price, 1);
  846. test_scenario::next_tx(&mut scenario, DEPLOYER);
  847. // Update the cache with a fresh update.
  848. let fresh_price = price::new(i64::new(5243, true), 2, i64::new(3, false), timestamp + 200);
  849. let fresh_ema_price = price::new(i64::new(8976, true), 21, i64::new(32, false), timestamp + 200);
  850. let fresh_update = price_info::new_price_info(
  851. 1257278600,
  852. 1690226180,
  853. price_feed::new(
  854. price_identifier,
  855. fresh_price,
  856. fresh_ema_price,
  857. )
  858. );
  859. let price_info_object_vec = vector[
  860. price_info_object_1,
  861. price_info_object_2,
  862. price_info_object_3,
  863. price_info_object_4
  864. ];
  865. pyth::update_cache(vector<PriceInfo>[fresh_update], &mut price_info_object_vec, &clock);
  866. price_info_object_4 = vector::pop_back(&mut price_info_object_vec);
  867. price_info_object_3 = vector::pop_back(&mut price_info_object_vec);
  868. price_info_object_2 = vector::pop_back(&mut price_info_object_vec);
  869. price_info_object_1 = vector::pop_back(&mut price_info_object_vec);
  870. vector::destroy_empty(price_info_object_vec);
  871. // Confirm that the Pyth cached price got updated to fresh_price
  872. let current_price_info = price_info::get_price_info_from_price_info_object(&price_info_object_1);
  873. let current_price_feed = price_info::get_price_feed(&current_price_info);
  874. let current_price = price_feed::get_price(current_price_feed);
  875. let current_ema_price = price_feed::get_ema_price(current_price_feed);
  876. assert!(current_price==fresh_price, 0);
  877. assert!(current_ema_price==fresh_ema_price, 0);
  878. return_shared(pyth_state);
  879. return_shared(worm_state);
  880. return_shared(price_info_object_1);
  881. return_shared(price_info_object_2);
  882. return_shared(price_info_object_3);
  883. return_shared(price_info_object_4);
  884. coin::burn_for_testing<SUI>(test_coins);
  885. return_shared(clock);
  886. test_scenario::end(scenario);
  887. }
  888. }
  889. // TODO - pyth tests
  890. // https://github.com/pyth-network/pyth-crosschain/blob/main/target_chains/aptos/contracts/sources/pyth.move#L384