governance_instruction.move 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. module pyth::governance_instruction {
  2. use wormhole::cursor;
  3. use pyth::deserialize;
  4. use pyth::error;
  5. use pyth::governance_action::{Self, GovernanceAction};
  6. use wormhole::u16;
  7. const MAGIC: vector<u8> = x"5054474d"; // "PTGM": Pyth Governance Message
  8. const MODULE: u8 = 1;
  9. struct GovernanceInstruction {
  10. module_: u8,
  11. action: GovernanceAction,
  12. target_chain_id: u64,
  13. payload: vector<u8>,
  14. }
  15. fun validate(instruction: &GovernanceInstruction) {
  16. assert!(instruction.module_ == MODULE, error::invalid_governance_module());
  17. let target_chain_id = instruction.target_chain_id;
  18. assert!(target_chain_id == u16::to_u64(wormhole::state::get_chain_id()) || target_chain_id == 0, error::invalid_governance_target_chain_id());
  19. }
  20. public fun from_byte_vec(bytes: vector<u8>): GovernanceInstruction {
  21. let cursor = cursor::init(bytes);
  22. let magic = deserialize::deserialize_vector(&mut cursor, 4);
  23. assert!(magic == MAGIC, error::invalid_governance_magic_value());
  24. let module_ = deserialize::deserialize_u8(&mut cursor);
  25. let action = governance_action::from_u8(deserialize::deserialize_u8(&mut cursor));
  26. let target_chain_id = deserialize::deserialize_u16(&mut cursor);
  27. let payload = cursor::rest(cursor);
  28. let instruction = GovernanceInstruction {
  29. module_,
  30. action,
  31. target_chain_id,
  32. payload
  33. };
  34. validate(&instruction);
  35. instruction
  36. }
  37. public fun get_module(instruction: &GovernanceInstruction): u8 {
  38. instruction.module_
  39. }
  40. public fun get_action(instruction: &GovernanceInstruction): GovernanceAction {
  41. instruction.action
  42. }
  43. public fun get_target_chain_id(instruction: &GovernanceInstruction): u64 {
  44. instruction.target_chain_id
  45. }
  46. public fun destroy(instruction: GovernanceInstruction): vector<u8> {
  47. let GovernanceInstruction {
  48. module_: _,
  49. action: _,
  50. target_chain_id: _,
  51. payload: payload
  52. } = instruction;
  53. payload
  54. }
  55. #[test]
  56. #[expected_failure(abort_code = 65556)]
  57. fun test_from_byte_vec_invalid_magic() {
  58. let bytes = x"5054474eb01087a85361f738f19454e66664d3c9";
  59. destroy(from_byte_vec(bytes));
  60. }
  61. #[test]
  62. #[expected_failure(abort_code = 65548)]
  63. fun test_from_byte_vec_invalid_module() {
  64. let bytes = x"5054474db00187a85361f738f19454e66664d3c9";
  65. destroy(from_byte_vec(bytes));
  66. }
  67. #[test]
  68. #[expected_failure(abort_code = 65548)]
  69. fun test_from_byte_vec_invalid_target_chain_id() {
  70. let bytes = x"5054474db00187a85361f738f19454e66664d3c9";
  71. destroy(from_byte_vec(bytes));
  72. }
  73. }