pyth.move 44 KB

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