workspaces.rs 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  1. use {
  2. byteorder::BigEndian,
  3. near_sdk::json_types::U128,
  4. pyth::{
  5. governance::{
  6. GovernanceAction,
  7. GovernanceInstruction,
  8. GovernanceModule,
  9. },
  10. state::{
  11. Chain,
  12. Price,
  13. PriceIdentifier,
  14. Source,
  15. },
  16. },
  17. pyth_wormhole_attester_sdk::{
  18. BatchPriceAttestation,
  19. Identifier,
  20. PriceAttestation,
  21. PriceStatus,
  22. },
  23. pythnet_sdk::{
  24. accumulators::{
  25. merkle::MerkleTree,
  26. Accumulator,
  27. },
  28. hashers::keccak256_160::Keccak160,
  29. messages::{
  30. Message,
  31. PriceFeedMessage,
  32. },
  33. wire::{
  34. to_vec,
  35. v1::{
  36. AccumulatorUpdateData,
  37. MerklePriceUpdate,
  38. Proof,
  39. WormholeMerkleRoot,
  40. WormholeMessage,
  41. WormholePayload,
  42. },
  43. PrefixedVec,
  44. },
  45. },
  46. serde_json::json,
  47. std::io::{
  48. Cursor,
  49. Write,
  50. },
  51. wormhole::Chain as WormholeChain,
  52. };
  53. async fn initialize_chain() -> (
  54. workspaces::Worker<workspaces::network::Sandbox>,
  55. workspaces::Contract,
  56. workspaces::Contract,
  57. ) {
  58. let worker = workspaces::sandbox().await.expect("Workspaces Failed");
  59. // Deploy Pyth
  60. let contract = worker
  61. .dev_deploy(&std::fs::read("pyth.wasm").expect("Failed to find pyth.wasm"))
  62. .await
  63. .expect("Failed to deploy pyth.wasm");
  64. // Deploy Wormhole Stub, this is a dummy contract that always verifies VAA's correctly so we
  65. // can test the ext_wormhole API.
  66. let wormhole = worker
  67. .dev_deploy(
  68. &std::fs::read("wormhole_stub.wasm").expect("Failed to find wormhole_stub.wasm"),
  69. )
  70. .await
  71. .expect("Failed to deploy wormhole_stub.wasm");
  72. // Initialize Wormhole.
  73. let _ = wormhole
  74. .call("new")
  75. .args_json(&json!({}))
  76. .gas(300_000_000_000_000)
  77. .transact_async()
  78. .await
  79. .expect("Failed to initialize Wormhole")
  80. .await
  81. .unwrap();
  82. // Initialize Pyth, one time operation that sets the Wormhole contract address.
  83. let codehash = [0u8; 32];
  84. let _ = contract
  85. .call("new")
  86. .args_json(&json!({
  87. "wormhole": wormhole.id(),
  88. "codehash": codehash,
  89. "initial_source": Source::default(),
  90. "gov_source": Source::default(),
  91. "update_fee": U128::from(1u128),
  92. "stale_threshold": 32,
  93. }))
  94. .gas(300_000_000_000_000)
  95. .transact_async()
  96. .await
  97. .expect("Failed to initialize Pyth")
  98. .await
  99. .unwrap();
  100. (worker, contract, wormhole)
  101. }
  102. #[tokio::test]
  103. async fn test_set_sources() {
  104. let (_, contract, _) = initialize_chain().await;
  105. // Submit a new Source to the contract, this will trigger a cross-contract call to wormhole
  106. let vaa = wormhole::Vaa {
  107. emitter_chain: wormhole::Chain::Any,
  108. emitter_address: wormhole::Address([0; 32]),
  109. sequence: 1,
  110. payload: (),
  111. ..Default::default()
  112. };
  113. let vaa = {
  114. let mut cur = Cursor::new(Vec::new());
  115. serde_wormhole::to_writer(&mut cur, &vaa).expect("Failed to serialize VAA");
  116. cur.write_all(
  117. &GovernanceInstruction {
  118. target: Chain::from(WormholeChain::Any),
  119. module: GovernanceModule::Target,
  120. action: GovernanceAction::SetDataSources {
  121. data_sources: vec![
  122. Source::default(),
  123. Source {
  124. emitter: [1; 32],
  125. chain: Chain::from(WormholeChain::Solana),
  126. },
  127. ],
  128. },
  129. }
  130. .serialize()
  131. .unwrap(),
  132. )
  133. .expect("Failed to write Payload");
  134. hex::encode(cur.into_inner())
  135. };
  136. assert!(contract
  137. .call("execute_governance_instruction")
  138. .gas(300_000_000_000_000)
  139. .deposit(300_000_000_000_000_000_000_000)
  140. .args_json(&json!({
  141. "vaa": vaa,
  142. }))
  143. .transact_async()
  144. .await
  145. .expect("Failed to submit VAA")
  146. .await
  147. .unwrap()
  148. .failures()
  149. .is_empty());
  150. // There should now be a two sources in the contract state.
  151. assert_eq!(
  152. serde_json::from_slice::<Vec<Source>>(&contract.view("get_sources").await.unwrap().result)
  153. .unwrap(),
  154. &[
  155. Source::default(),
  156. Source {
  157. emitter: [1; 32],
  158. chain: Chain::from(WormholeChain::Solana),
  159. },
  160. ]
  161. );
  162. }
  163. #[tokio::test]
  164. async fn test_set_governance_source() {
  165. let (_, contract, _) = initialize_chain().await;
  166. // Submit a new Source to the contract, this will trigger a cross-contract call to wormhole
  167. let vaa = wormhole::Vaa {
  168. emitter_chain: wormhole::Chain::Any,
  169. emitter_address: wormhole::Address([0; 32]),
  170. payload: (),
  171. sequence: 2,
  172. ..Default::default()
  173. };
  174. let vaa = {
  175. let request_vaa = wormhole::Vaa {
  176. emitter_chain: wormhole::Chain::Solana,
  177. emitter_address: wormhole::Address([1; 32]),
  178. payload: (),
  179. sequence: 1,
  180. ..Default::default()
  181. };
  182. // Data Source Upgrades are submitted with an embedded VAA, generate that one here first
  183. // before we embed it.
  184. let request_vaa = {
  185. let mut cur = Cursor::new(Vec::new());
  186. serde_wormhole::to_writer(&mut cur, &request_vaa).expect("Failed to serialize VAA");
  187. cur.write_all(
  188. &GovernanceInstruction {
  189. target: Chain::from(WormholeChain::Near),
  190. module: GovernanceModule::Target,
  191. action: GovernanceAction::RequestGovernanceDataSourceTransfer {
  192. governance_data_source_index: 1,
  193. },
  194. }
  195. .serialize()
  196. .unwrap(),
  197. )
  198. .expect("Failed to write Payload");
  199. cur.into_inner()
  200. };
  201. let mut cur = Cursor::new(Vec::new());
  202. serde_wormhole::to_writer(&mut cur, &vaa).expect("Failed to serialize VAA");
  203. cur.write_all(
  204. &GovernanceInstruction {
  205. target: Chain::from(WormholeChain::Near),
  206. module: GovernanceModule::Target,
  207. action: GovernanceAction::AuthorizeGovernanceDataSourceTransfer {
  208. claim_vaa: request_vaa,
  209. },
  210. }
  211. .serialize()
  212. .unwrap(),
  213. )
  214. .expect("Failed to write Payload");
  215. hex::encode(cur.into_inner())
  216. };
  217. assert!(contract
  218. .call("execute_governance_instruction")
  219. .gas(300_000_000_000_000)
  220. .deposit(300_000_000_000_000_000_000_000)
  221. .args_json(&json!({
  222. "vaa": vaa,
  223. }))
  224. .transact_async()
  225. .await
  226. .expect("Failed to submit VAA")
  227. .await
  228. .unwrap()
  229. .failures()
  230. .is_empty());
  231. // An action from the new source should now be accepted.
  232. let vaa = wormhole::Vaa {
  233. sequence: 3, // NOTE: Incremented Governance Sequence
  234. emitter_chain: wormhole::Chain::Solana,
  235. emitter_address: wormhole::Address([1; 32]),
  236. payload: (),
  237. ..Default::default()
  238. };
  239. let vaa = {
  240. let mut cur = Cursor::new(Vec::new());
  241. serde_wormhole::to_writer(&mut cur, &vaa).expect("Failed to serialize VAA");
  242. cur.write_all(
  243. &GovernanceInstruction {
  244. target: Chain::from(WormholeChain::Near),
  245. module: GovernanceModule::Target,
  246. action: GovernanceAction::SetDataSources {
  247. data_sources: vec![
  248. Source::default(),
  249. Source {
  250. emitter: [2; 32],
  251. chain: Chain::from(WormholeChain::Solana),
  252. },
  253. ],
  254. },
  255. }
  256. .serialize()
  257. .unwrap(),
  258. )
  259. .expect("Failed to write Payload");
  260. hex::encode(cur.into_inner())
  261. };
  262. assert!(contract
  263. .call("execute_governance_instruction")
  264. .gas(300_000_000_000_000)
  265. .deposit(300_000_000_000_000_000_000_000)
  266. .args_json(&json!({
  267. "vaa": vaa,
  268. }))
  269. .transact_async()
  270. .await
  271. .expect("Failed to submit VAA")
  272. .await
  273. .unwrap()
  274. .failures()
  275. .is_empty());
  276. // But not from the old source.
  277. let vaa = wormhole::Vaa {
  278. sequence: 4, // NOTE: Incremented Governance Sequence
  279. emitter_chain: wormhole::Chain::Any,
  280. emitter_address: wormhole::Address([0; 32]),
  281. payload: (),
  282. ..Default::default()
  283. };
  284. let vaa = {
  285. let mut cur = Cursor::new(Vec::new());
  286. serde_wormhole::to_writer(&mut cur, &vaa).expect("Failed to serialize VAA");
  287. cur.write_all(
  288. &GovernanceInstruction {
  289. target: Chain::from(WormholeChain::Near),
  290. module: GovernanceModule::Target,
  291. action: GovernanceAction::SetDataSources {
  292. data_sources: vec![
  293. Source::default(),
  294. Source {
  295. emitter: [2; 32],
  296. chain: Chain::from(WormholeChain::Solana),
  297. },
  298. ],
  299. },
  300. }
  301. .serialize()
  302. .unwrap(),
  303. )
  304. .expect("Failed to write Payload");
  305. hex::encode(cur.into_inner())
  306. };
  307. assert!(contract
  308. .call("execute_governance_instruction")
  309. .gas(300_000_000_000_000)
  310. .deposit(300_000_000_000_000_000_000_000)
  311. .args_json(&json!({
  312. "vaa": vaa,
  313. }))
  314. .transact_async()
  315. .await
  316. .expect("Failed to submit VAA")
  317. .await
  318. .unwrap()
  319. .outcome()
  320. .is_success());
  321. }
  322. #[tokio::test]
  323. async fn test_stale_threshold() {
  324. let (_, contract, _) = initialize_chain().await;
  325. // Submit a Price Attestation to the contract.
  326. let vaa = wormhole::Vaa {
  327. emitter_chain: wormhole::Chain::Any,
  328. emitter_address: wormhole::Address([0; 32]),
  329. payload: (),
  330. sequence: 1,
  331. ..Default::default()
  332. };
  333. // Get current UNIX timestamp and subtract a minute from it to place the price attestation in
  334. // the past. This should be accepted but untrusted.
  335. let now = std::time::SystemTime::now()
  336. .duration_since(std::time::UNIX_EPOCH)
  337. .expect("Failed to get UNIX timestamp")
  338. .as_secs()
  339. - 60;
  340. let vaa = {
  341. let mut cur = Cursor::new(Vec::new());
  342. serde_wormhole::to_writer(&mut cur, &vaa).expect("Failed to serialize VAA");
  343. cur.write_all(
  344. &BatchPriceAttestation {
  345. price_attestations: vec![PriceAttestation {
  346. product_id: Identifier::default(),
  347. price_id: Identifier::default(),
  348. price: 100,
  349. conf: 1,
  350. expo: 8,
  351. ema_price: 100,
  352. ema_conf: 1,
  353. status: PriceStatus::Trading,
  354. num_publishers: 8,
  355. max_num_publishers: 8,
  356. attestation_time: now.try_into().unwrap(),
  357. publish_time: now.try_into().unwrap(),
  358. prev_publish_time: now.try_into().unwrap(),
  359. prev_price: 100,
  360. prev_conf: 1,
  361. last_attested_publish_time: now.try_into().unwrap(),
  362. }],
  363. }
  364. .serialize()
  365. .unwrap(),
  366. )
  367. .expect("Failed to write Payload");
  368. hex::encode(cur.into_inner())
  369. };
  370. let update_fee = serde_json::from_slice::<U128>(
  371. &contract
  372. .view("get_update_fee_estimate")
  373. .args_json(&json!({
  374. "vaa": vaa,
  375. }))
  376. .await
  377. .unwrap()
  378. .result,
  379. )
  380. .unwrap();
  381. // Submit price. As there are no prices this should succeed despite being old.
  382. assert!(contract
  383. .call("update_price_feed")
  384. .gas(300_000_000_000_000)
  385. .deposit(update_fee.into())
  386. .args_json(&json!({
  387. "data": vaa,
  388. }))
  389. .transact_async()
  390. .await
  391. .expect("Failed to submit VAA")
  392. .await
  393. .unwrap()
  394. .failures()
  395. .is_empty());
  396. // Despite succeeding, assert Price cannot be requested, 60 seconds in the past should be
  397. // considered stale. [tag:failed_price_check]
  398. assert_eq!(
  399. None,
  400. serde_json::from_slice::<Option<Price>>(
  401. &contract
  402. .view("get_price")
  403. .args_json(&json!({ "price_identifier": PriceIdentifier([0; 32]) }))
  404. .await
  405. .unwrap()
  406. .result
  407. )
  408. .unwrap(),
  409. );
  410. // Submit another Price Attestation to the contract with an even older timestamp. Which
  411. // should now fail due to the existing newer price.
  412. let vaa = wormhole::Vaa {
  413. emitter_chain: wormhole::Chain::Any,
  414. emitter_address: wormhole::Address([0; 32]),
  415. sequence: 2,
  416. payload: (),
  417. ..Default::default()
  418. };
  419. let vaa = {
  420. let mut cur = Cursor::new(Vec::new());
  421. serde_wormhole::to_writer(&mut cur, &vaa).expect("Failed to serialize VAA");
  422. cur.write_all(
  423. &BatchPriceAttestation {
  424. price_attestations: vec![PriceAttestation {
  425. product_id: Identifier::default(),
  426. price_id: Identifier::default(),
  427. price: 1000,
  428. conf: 1,
  429. expo: 8,
  430. ema_price: 1000,
  431. ema_conf: 1,
  432. status: PriceStatus::Trading,
  433. num_publishers: 8,
  434. max_num_publishers: 8,
  435. attestation_time: (now - 1024).try_into().unwrap(),
  436. publish_time: (now - 1024).try_into().unwrap(),
  437. prev_publish_time: (now - 1024).try_into().unwrap(),
  438. prev_price: 90,
  439. prev_conf: 1,
  440. last_attested_publish_time: (now - 1024).try_into().unwrap(),
  441. }],
  442. }
  443. .serialize()
  444. .unwrap(),
  445. )
  446. .expect("Failed to write Payload");
  447. hex::encode(cur.into_inner())
  448. };
  449. // The update handler should now succeed even if price is old, but simply not update the price.
  450. assert!(contract
  451. .call("update_price_feed")
  452. .gas(300_000_000_000_000)
  453. .deposit(update_fee.into())
  454. .args_json(&json!({
  455. "data": vaa,
  456. }))
  457. .transact_async()
  458. .await
  459. .expect("Failed to submit VAA")
  460. .await
  461. .unwrap()
  462. .failures()
  463. .is_empty());
  464. // The price however should _not_ have updated and if we check the unsafe stored price the
  465. // timestamp and price should be unchanged.
  466. assert_eq!(
  467. Price {
  468. price: 100,
  469. conf: 1,
  470. expo: 8,
  471. timestamp: now,
  472. },
  473. serde_json::from_slice::<Price>(
  474. &contract
  475. .view("get_price_unsafe")
  476. .args_json(&json!({ "price_identifier": PriceIdentifier([0; 32]) }))
  477. .await
  478. .unwrap()
  479. .result
  480. )
  481. .unwrap(),
  482. );
  483. // Now we extend the staleness threshold with a Governance VAA.
  484. let vaa = wormhole::Vaa {
  485. emitter_chain: wormhole::Chain::Any,
  486. emitter_address: wormhole::Address([0; 32]),
  487. sequence: 3,
  488. payload: (),
  489. ..Default::default()
  490. };
  491. let vaa = {
  492. let mut cur = Cursor::new(Vec::new());
  493. serde_wormhole::to_writer(&mut cur, &vaa).unwrap();
  494. cur.write_all(
  495. &GovernanceInstruction {
  496. target: Chain::from(WormholeChain::Near),
  497. module: GovernanceModule::Target,
  498. action: GovernanceAction::SetValidPeriod { valid_seconds: 256 },
  499. }
  500. .serialize()
  501. .unwrap(),
  502. )
  503. .unwrap();
  504. hex::encode(cur.into_inner())
  505. };
  506. assert!(contract
  507. .call("execute_governance_instruction")
  508. .gas(300_000_000_000_000)
  509. .deposit(300_000_000_000_000_000_000_000)
  510. .args_json(&json!({
  511. "vaa": vaa,
  512. }))
  513. .transact_async()
  514. .await
  515. .expect("Failed to submit VAA")
  516. .await
  517. .unwrap()
  518. .failures()
  519. .is_empty());
  520. // It should now be possible to request the price that previously returned None.
  521. // [ref:failed_price_check]
  522. assert_eq!(
  523. Some(Price {
  524. price: 100,
  525. conf: 1,
  526. expo: 8,
  527. timestamp: now,
  528. }),
  529. serde_json::from_slice::<Option<Price>>(
  530. &contract
  531. .view("get_price")
  532. .args_json(&json!({ "price_identifier": PriceIdentifier([0; 32]) }))
  533. .await
  534. .unwrap()
  535. .result
  536. )
  537. .unwrap(),
  538. );
  539. }
  540. #[tokio::test]
  541. async fn test_contract_fees() {
  542. let (_, contract, _) = initialize_chain().await;
  543. let now = std::time::SystemTime::now()
  544. .duration_since(std::time::UNIX_EPOCH)
  545. .expect("Failed to get UNIX timestamp")
  546. .as_secs();
  547. // Set a high fee for the contract needed to submit a price.
  548. let vaa = wormhole::Vaa {
  549. emitter_chain: wormhole::Chain::Any,
  550. emitter_address: wormhole::Address([0; 32]),
  551. payload: (),
  552. sequence: 1,
  553. ..Default::default()
  554. };
  555. let vaa = {
  556. let mut cur = Cursor::new(Vec::new());
  557. serde_wormhole::to_writer(&mut cur, &vaa).unwrap();
  558. cur.write_all(
  559. &GovernanceInstruction {
  560. target: Chain::from(WormholeChain::Near),
  561. module: GovernanceModule::Target,
  562. action: GovernanceAction::SetFee { base: 128, expo: 8 },
  563. }
  564. .serialize()
  565. .unwrap(),
  566. )
  567. .unwrap();
  568. hex::encode(cur.into_inner())
  569. };
  570. // Fetch Update fee before changing it.
  571. let update_fee = serde_json::from_slice::<U128>(
  572. &contract
  573. .view("get_update_fee_estimate")
  574. .args_json(&json!({
  575. "vaa": vaa,
  576. }))
  577. .await
  578. .unwrap()
  579. .result,
  580. )
  581. .unwrap();
  582. // Now set the update_fee so that it is too high for the deposit to cover.
  583. assert!(contract
  584. .call("execute_governance_instruction")
  585. .gas(300_000_000_000_000)
  586. .deposit(300_000_000_000_000_000_000_000)
  587. .args_json(&json!({
  588. "vaa": vaa,
  589. }))
  590. .transact_async()
  591. .await
  592. .expect("Failed to submit VAA")
  593. .await
  594. .unwrap()
  595. .failures()
  596. .is_empty());
  597. // Check the state has actually changed before we try and execute another VAA.
  598. assert_ne!(
  599. u128::from(update_fee),
  600. u128::from(
  601. serde_json::from_slice::<U128>(
  602. &contract
  603. .view("get_update_fee_estimate")
  604. .args_json(&json!({
  605. "vaa": vaa,
  606. }))
  607. .await
  608. .unwrap()
  609. .result,
  610. )
  611. .unwrap()
  612. )
  613. );
  614. // Attempt to update the price feed with a now too low deposit.
  615. let vaa = wormhole::Vaa {
  616. emitter_chain: wormhole::Chain::Any,
  617. emitter_address: wormhole::Address([0; 32]),
  618. sequence: 2,
  619. payload: (),
  620. ..Default::default()
  621. };
  622. let vaa = {
  623. let mut cur = Cursor::new(Vec::new());
  624. serde_wormhole::to_writer(&mut cur, &vaa).expect("Failed to serialize VAA");
  625. cur.write_all(
  626. &BatchPriceAttestation {
  627. price_attestations: vec![PriceAttestation {
  628. product_id: Identifier::default(),
  629. price_id: Identifier::default(),
  630. price: 1000,
  631. conf: 1,
  632. expo: 8,
  633. ema_price: 1000,
  634. ema_conf: 1,
  635. status: PriceStatus::Trading,
  636. num_publishers: 8,
  637. max_num_publishers: 8,
  638. attestation_time: (now - 1024).try_into().unwrap(),
  639. publish_time: (now - 1024).try_into().unwrap(),
  640. prev_publish_time: (now - 1024).try_into().unwrap(),
  641. prev_price: 90,
  642. prev_conf: 1,
  643. last_attested_publish_time: (now - 1024).try_into().unwrap(),
  644. }],
  645. }
  646. .serialize()
  647. .unwrap(),
  648. )
  649. .expect("Failed to write Payload");
  650. hex::encode(cur.into_inner())
  651. };
  652. assert!(contract
  653. .call("update_price_feed")
  654. .gas(300_000_000_000_000)
  655. .deposit(update_fee.into())
  656. .args_json(&json!({
  657. "data": vaa,
  658. }))
  659. .transact_async()
  660. .await
  661. .expect("Failed to submit VAA")
  662. .await
  663. .unwrap()
  664. .failures()
  665. .is_empty());
  666. // Submitting a Price should have failed because the fee was not enough.
  667. assert_eq!(
  668. None,
  669. serde_json::from_slice::<Option<Price>>(
  670. &contract
  671. .view("get_price")
  672. .args_json(&json!({ "price_identifier": PriceIdentifier([0; 32]) }))
  673. .await
  674. .unwrap()
  675. .result
  676. )
  677. .unwrap(),
  678. );
  679. }
  680. // A test that attempts to SetFee twice with the same governance action, the first should succeed,
  681. // the second should fail.
  682. #[tokio::test]
  683. async fn test_same_governance_sequence_fails() {
  684. let (_, contract, _) = initialize_chain().await;
  685. // Set a high fee for the contract needed to submit a price.
  686. let vaa = wormhole::Vaa {
  687. emitter_chain: wormhole::Chain::Any,
  688. emitter_address: wormhole::Address([0; 32]),
  689. payload: (),
  690. sequence: 1,
  691. ..Default::default()
  692. };
  693. let vaa = {
  694. let mut cur = Cursor::new(Vec::new());
  695. serde_wormhole::to_writer(&mut cur, &vaa).unwrap();
  696. cur.write_all(
  697. &GovernanceInstruction {
  698. target: Chain::from(WormholeChain::Near),
  699. module: GovernanceModule::Target,
  700. action: GovernanceAction::SetFee { base: 128, expo: 8 },
  701. }
  702. .serialize()
  703. .unwrap(),
  704. )
  705. .unwrap();
  706. hex::encode(cur.into_inner())
  707. };
  708. // Attempt our first SetFee.
  709. assert!(contract
  710. .call("execute_governance_instruction")
  711. .gas(300_000_000_000_000)
  712. .deposit(300_000_000_000_000_000_000_000)
  713. .args_json(&json!({
  714. "vaa": vaa,
  715. }))
  716. .transact_async()
  717. .await
  718. .expect("Failed to submit VAA")
  719. .await
  720. .unwrap()
  721. .failures()
  722. .is_empty());
  723. // Attempt to run the same VAA again.
  724. assert!(!contract
  725. .call("execute_governance_instruction")
  726. .gas(300_000_000_000_000)
  727. .deposit(300_000_000_000_000_000_000_000)
  728. .args_json(&json!({
  729. "vaa": vaa,
  730. }))
  731. .transact_async()
  732. .await
  733. .expect("Failed to submit VAA")
  734. .await
  735. .unwrap()
  736. .failures()
  737. .is_empty());
  738. }
  739. // A test that attempts to SetFee twice with the same governance action, the first should succeed,
  740. // the second should fail.
  741. #[tokio::test]
  742. async fn test_out_of_order_sequences_fail() {
  743. let (_, contract, _) = initialize_chain().await;
  744. // Set a high fee for the contract needed to submit a price.
  745. let vaa = wormhole::Vaa {
  746. emitter_chain: wormhole::Chain::Any,
  747. emitter_address: wormhole::Address([0; 32]),
  748. payload: (),
  749. sequence: 1,
  750. ..Default::default()
  751. };
  752. let vaa = {
  753. let mut cur = Cursor::new(Vec::new());
  754. serde_wormhole::to_writer(&mut cur, &vaa).unwrap();
  755. cur.write_all(
  756. &GovernanceInstruction {
  757. target: Chain::from(WormholeChain::Near),
  758. module: GovernanceModule::Target,
  759. action: GovernanceAction::SetFee { base: 128, expo: 8 },
  760. }
  761. .serialize()
  762. .unwrap(),
  763. )
  764. .unwrap();
  765. hex::encode(cur.into_inner())
  766. };
  767. // Attempt our first SetFee.
  768. assert!(contract
  769. .call("execute_governance_instruction")
  770. .gas(300_000_000_000_000)
  771. .deposit(300_000_000_000_000_000_000_000)
  772. .args_json(&json!({
  773. "vaa": vaa,
  774. }))
  775. .transact_async()
  776. .await
  777. .expect("Failed to submit VAA")
  778. .await
  779. .unwrap()
  780. .failures()
  781. .is_empty());
  782. // Generate another VAA with sequence 3.
  783. let vaa = wormhole::Vaa {
  784. emitter_chain: wormhole::Chain::Any,
  785. emitter_address: wormhole::Address([0; 32]),
  786. payload: (),
  787. sequence: 3,
  788. ..Default::default()
  789. };
  790. let vaa = {
  791. let mut cur = Cursor::new(Vec::new());
  792. serde_wormhole::to_writer(&mut cur, &vaa).unwrap();
  793. cur.write_all(
  794. &GovernanceInstruction {
  795. target: Chain::from(WormholeChain::Near),
  796. module: GovernanceModule::Target,
  797. action: GovernanceAction::SetFee { base: 128, expo: 8 },
  798. }
  799. .serialize()
  800. .unwrap(),
  801. )
  802. .unwrap();
  803. hex::encode(cur.into_inner())
  804. };
  805. // This should succeed.
  806. assert!(contract
  807. .call("execute_governance_instruction")
  808. .gas(300_000_000_000_000)
  809. .deposit(300_000_000_000_000_000_000_000)
  810. .args_json(&json!({
  811. "vaa": vaa,
  812. }))
  813. .transact_async()
  814. .await
  815. .expect("Failed to submit VAA")
  816. .await
  817. .unwrap()
  818. .failures()
  819. .is_empty());
  820. // Generate another VAA with sequence 2.
  821. let vaa = wormhole::Vaa {
  822. emitter_chain: wormhole::Chain::Any,
  823. emitter_address: wormhole::Address([0; 32]),
  824. payload: (),
  825. sequence: 2,
  826. ..Default::default()
  827. };
  828. let vaa = {
  829. let mut cur = Cursor::new(Vec::new());
  830. serde_wormhole::to_writer(&mut cur, &vaa).unwrap();
  831. cur.write_all(
  832. &GovernanceInstruction {
  833. target: Chain::from(WormholeChain::Near),
  834. module: GovernanceModule::Target,
  835. action: GovernanceAction::SetFee { base: 128, expo: 8 },
  836. }
  837. .serialize()
  838. .unwrap(),
  839. )
  840. .unwrap();
  841. hex::encode(cur.into_inner())
  842. };
  843. // This should fail due to being out of order.
  844. assert!(!contract
  845. .call("execute_governance_instruction")
  846. .gas(300_000_000_000_000)
  847. .deposit(300_000_000_000_000_000_000_000)
  848. .args_json(&json!({
  849. "vaa": vaa,
  850. }))
  851. .transact_async()
  852. .await
  853. .expect("Failed to submit VAA")
  854. .await
  855. .unwrap()
  856. .failures()
  857. .is_empty());
  858. }
  859. // A test that fails if the governance action payload target is not NEAR.
  860. #[tokio::test]
  861. async fn test_governance_target_fails_if_not_near() {
  862. let (_, contract, _) = initialize_chain().await;
  863. let vaa = wormhole::Vaa {
  864. emitter_chain: wormhole::Chain::Any,
  865. emitter_address: wormhole::Address([0; 32]),
  866. payload: (),
  867. sequence: 1,
  868. ..Default::default()
  869. };
  870. let vaa = {
  871. let mut cur = Cursor::new(Vec::new());
  872. serde_wormhole::to_writer(&mut cur, &vaa).unwrap();
  873. cur.write_all(
  874. &GovernanceInstruction {
  875. target: Chain::from(WormholeChain::Solana),
  876. module: GovernanceModule::Target,
  877. action: GovernanceAction::SetFee { base: 128, expo: 8 },
  878. }
  879. .serialize()
  880. .unwrap(),
  881. )
  882. .unwrap();
  883. hex::encode(cur.into_inner())
  884. };
  885. // This should fail as the target is Solana, when Near is expected.
  886. assert!(!contract
  887. .call("execute_governance_instruction")
  888. .gas(300_000_000_000_000)
  889. .deposit(300_000_000_000_000_000_000_000)
  890. .args_json(&json!({
  891. "vaa": vaa,
  892. }))
  893. .transact_async()
  894. .await
  895. .expect("Failed to submit VAA")
  896. .await
  897. .unwrap()
  898. .failures()
  899. .is_empty());
  900. }
  901. // A test to check accumulator style updates work as intended.
  902. #[tokio::test]
  903. async fn test_accumulator_updates() {
  904. fn create_dummy_price_feed_message(value: i64) -> Message {
  905. let mut dummy_id = [0; 32];
  906. dummy_id[0] = value as u8;
  907. let msg = PriceFeedMessage {
  908. feed_id: dummy_id,
  909. price: value,
  910. conf: value as u64,
  911. exponent: value as i32,
  912. publish_time: value,
  913. prev_publish_time: value,
  914. ema_price: value,
  915. ema_conf: value as u64,
  916. };
  917. Message::PriceFeedMessage(msg)
  918. }
  919. fn create_accumulator_message_from_updates(
  920. price_updates: Vec<MerklePriceUpdate>,
  921. tree: MerkleTree<Keccak160>,
  922. corrupt_wormhole_message: bool,
  923. emitter_address: [u8; 32],
  924. emitter_chain: u16,
  925. ) -> Vec<u8> {
  926. let mut root_hash = [0u8; 20];
  927. root_hash.copy_from_slice(&to_vec::<_, BigEndian>(&tree.root).unwrap()[..20]);
  928. let wormhole_message = WormholeMessage::new(WormholePayload::Merkle(WormholeMerkleRoot {
  929. slot: 0,
  930. ring_size: 0,
  931. root: root_hash,
  932. }));
  933. let vaa = wormhole::Vaa {
  934. emitter_chain: emitter_chain.into(),
  935. emitter_address: wormhole::Address(emitter_address),
  936. sequence: 2,
  937. payload: (),
  938. ..Default::default()
  939. };
  940. let vaa = {
  941. let mut cur = Cursor::new(Vec::new());
  942. serde_wormhole::to_writer(&mut cur, &vaa).expect("Failed to serialize VAA");
  943. cur.write_all(&to_vec::<_, BigEndian>(&wormhole_message).unwrap())
  944. .expect("Failed to write Payload");
  945. cur.into_inner()
  946. };
  947. let accumulator_update_data = AccumulatorUpdateData::new(Proof::WormholeMerkle {
  948. vaa: PrefixedVec::from(vaa),
  949. updates: price_updates,
  950. });
  951. to_vec::<_, BigEndian>(&accumulator_update_data).unwrap()
  952. }
  953. fn create_accumulator_message(
  954. all_feeds: &[Message],
  955. updates: &[Message],
  956. corrupt_wormhole_message: bool,
  957. ) -> Vec<u8> {
  958. let all_feeds_bytes: Vec<_> = all_feeds
  959. .iter()
  960. .map(|f| to_vec::<_, BigEndian>(f).unwrap())
  961. .collect();
  962. let all_feeds_bytes_refs: Vec<_> = all_feeds_bytes.iter().map(|f| f.as_ref()).collect();
  963. let tree = MerkleTree::<Keccak160>::new(all_feeds_bytes_refs.as_slice()).unwrap();
  964. let mut price_updates: Vec<MerklePriceUpdate> = vec![];
  965. for update in updates {
  966. let proof = tree
  967. .prove(&to_vec::<_, BigEndian>(update).unwrap())
  968. .unwrap();
  969. price_updates.push(MerklePriceUpdate {
  970. message: PrefixedVec::from(to_vec::<_, BigEndian>(update).unwrap()),
  971. proof,
  972. });
  973. }
  974. create_accumulator_message_from_updates(
  975. price_updates,
  976. tree,
  977. corrupt_wormhole_message,
  978. [1; 32],
  979. wormhole::Chain::Any.into(),
  980. )
  981. }
  982. let (_, contract, _) = initialize_chain().await;
  983. // Submit a new Source to the contract, this will trigger a cross-contract call to wormhole
  984. let vaa = wormhole::Vaa {
  985. emitter_chain: wormhole::Chain::Any,
  986. emitter_address: wormhole::Address([0; 32]),
  987. sequence: 1,
  988. payload: (),
  989. ..Default::default()
  990. };
  991. let vaa = {
  992. let mut cur = Cursor::new(Vec::new());
  993. serde_wormhole::to_writer(&mut cur, &vaa).expect("Failed to serialize VAA");
  994. cur.write_all(
  995. &GovernanceInstruction {
  996. target: Chain::from(WormholeChain::Any),
  997. module: GovernanceModule::Target,
  998. action: GovernanceAction::SetDataSources {
  999. data_sources: vec![
  1000. Source::default(),
  1001. Source {
  1002. emitter: [1; 32],
  1003. chain: Chain::from(WormholeChain::Any),
  1004. },
  1005. ],
  1006. },
  1007. }
  1008. .serialize()
  1009. .unwrap(),
  1010. )
  1011. .expect("Failed to write Payload");
  1012. hex::encode(cur.into_inner())
  1013. };
  1014. assert!(contract
  1015. .call("execute_governance_instruction")
  1016. .gas(300_000_000_000_000)
  1017. .deposit(300_000_000_000_000_000_000_000)
  1018. .args_json(&json!({
  1019. "vaa": vaa,
  1020. }))
  1021. .transact_async()
  1022. .await
  1023. .expect("Failed to submit VAA")
  1024. .await
  1025. .unwrap()
  1026. .failures()
  1027. .is_empty());
  1028. // Create a couple of test feeds.
  1029. let feed_1 = create_dummy_price_feed_message(100);
  1030. let feed_2 = create_dummy_price_feed_message(200);
  1031. let message = create_accumulator_message(&[feed_1, feed_2], &[feed_1], false);
  1032. let message = hex::encode(message);
  1033. // Call the usual UpdatePriceFeed function.
  1034. assert!(contract
  1035. .call("update_price_feed")
  1036. .gas(300_000_000_000_000)
  1037. .deposit(300_000_000_000_000_000_000_000)
  1038. .args_json(&json!({
  1039. "data": message,
  1040. }))
  1041. .transact_async()
  1042. .await
  1043. .expect("Failed to submit VAA")
  1044. .await
  1045. .unwrap()
  1046. .failures()
  1047. .is_empty());
  1048. }