1use crate::base_types::{ObjectID, SequenceNumber, TransactionDigest};
5use crate::crypto::{AuthoritySignInfo, AuthorityStrongQuorumSignInfo};
6use crate::effects::{
7 SignedTransactionEffects, TransactionEvents, VerifiedSignedTransactionEffects,
8};
9use crate::error::{SuiError, SuiErrorKind};
10use crate::object::Object;
11use crate::transaction::{CertifiedTransaction, SenderSignedData, SignedTransaction, Transaction};
12
13use bytes::Bytes;
14use move_core_types::annotated_value::MoveStructLayout;
15use serde::{Deserialize, Serialize};
16
17use mysten_metrics::TX_TYPE_SHARED_OBJ_TX;
18use mysten_metrics::TX_TYPE_SINGLE_WRITER_TX;
19
20use strum::EnumIter;
21
22#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
23pub enum ObjectInfoRequestKind {
24 LatestObjectInfo,
26 PastObjectInfoDebug(SequenceNumber),
31}
32
33#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
35pub enum LayoutGenerationOption {
36 Generate,
37 None,
38}
39
40#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
43pub struct ObjectInfoRequest {
44 pub object_id: ObjectID,
46 pub generate_layout: LayoutGenerationOption,
48 pub request_kind: ObjectInfoRequestKind,
50}
51
52impl ObjectInfoRequest {
53 pub fn past_object_info_debug_request(
54 object_id: ObjectID,
55 version: SequenceNumber,
56 generate_layout: LayoutGenerationOption,
57 ) -> Self {
58 ObjectInfoRequest {
59 object_id,
60 generate_layout,
61 request_kind: ObjectInfoRequestKind::PastObjectInfoDebug(version),
62 }
63 }
64
65 pub fn latest_object_info_request(
66 object_id: ObjectID,
67 generate_layout: LayoutGenerationOption,
68 ) -> Self {
69 ObjectInfoRequest {
70 object_id,
71 generate_layout,
72 request_kind: ObjectInfoRequestKind::LatestObjectInfo,
73 }
74 }
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
79pub struct ObjectInfoResponse {
80 pub object: Object,
82 pub layout: Option<MoveStructLayout>,
85 pub lock_for_debugging: Option<SignedTransaction>,
90}
91
92#[derive(Debug, Clone)]
95pub struct VerifiedObjectInfoResponse {
96 pub object: Object,
98}
99
100#[derive(Clone, Debug, Serialize, Deserialize)]
101pub struct TransactionInfoRequest {
102 pub transaction_digest: TransactionDigest,
103}
104
105#[derive(Clone, Debug, Serialize, Deserialize)]
106#[allow(clippy::large_enum_variant)]
107pub enum TransactionStatus {
108 Signed(AuthoritySignInfo),
110 Executed(
115 Option<AuthorityStrongQuorumSignInfo>,
116 SignedTransactionEffects,
117 TransactionEvents,
118 ),
119}
120
121impl TransactionStatus {
122 pub fn into_signed_for_testing(self) -> AuthoritySignInfo {
123 match self {
124 Self::Signed(s) => s,
125 _ => unreachable!("Incorrect response type"),
126 }
127 }
128
129 pub fn into_effects_for_testing(self) -> SignedTransactionEffects {
130 match self {
131 Self::Executed(_, e, _) => e,
132 _ => unreachable!("Incorrect response type"),
133 }
134 }
135}
136
137impl PartialEq for TransactionStatus {
138 fn eq(&self, other: &Self) -> bool {
139 match self {
140 Self::Signed(s1) => match other {
141 Self::Signed(s2) => s1.epoch == s2.epoch,
142 _ => false,
143 },
144 Self::Executed(c1, e1, ev1) => match other {
145 Self::Executed(c2, e2, ev2) => {
146 c1.as_ref().map(|a| a.epoch) == c2.as_ref().map(|a| a.epoch)
147 && e1.epoch() == e2.epoch()
148 && e1.digest() == e2.digest()
149 && ev1.digest() == ev2.digest()
150 }
151 _ => false,
152 },
153 }
154 }
155}
156
157#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
158pub struct HandleTransactionResponse {
159 pub status: TransactionStatus,
160}
161
162#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
163pub struct TransactionInfoResponse {
164 pub transaction: SenderSignedData,
165 pub status: TransactionStatus,
166}
167
168#[derive(Clone, Debug, Serialize, Deserialize)]
169pub struct HandleCertificateResponseV2 {
170 pub signed_effects: SignedTransactionEffects,
171 pub events: TransactionEvents,
172 pub fastpath_input_objects: Vec<Object>,
174}
175
176#[derive(Clone, Debug, Serialize, Deserialize)]
177pub struct SubmitCertificateResponse {
178 pub executed: Option<HandleCertificateResponseV2>,
180}
181
182#[derive(Clone, Debug)]
183pub struct VerifiedHandleCertificateResponse {
184 pub signed_effects: VerifiedSignedTransactionEffects,
185 pub events: TransactionEvents,
186}
187
188#[derive(Serialize, Deserialize, Clone, Debug)]
189pub struct SystemStateRequest {
190 pub _unused: bool,
192}
193
194#[derive(Clone, Debug, Serialize, Deserialize)]
202pub struct HandleCertificateResponseV3 {
203 pub effects: SignedTransactionEffects,
204 pub events: Option<TransactionEvents>,
205
206 pub input_objects: Option<Vec<Object>>,
213
214 pub output_objects: Option<Vec<Object>>,
218 pub auxiliary_data: Option<Vec<u8>>,
219}
220
221#[derive(Clone, Debug, Serialize, Deserialize)]
222pub struct HandleCertificateRequestV3 {
223 pub certificate: CertifiedTransaction,
224
225 pub include_events: bool,
226 pub include_input_objects: bool,
227 pub include_output_objects: bool,
228 pub include_auxiliary_data: bool,
229}
230
231impl From<HandleCertificateResponseV3> for HandleCertificateResponseV2 {
232 fn from(value: HandleCertificateResponseV3) -> Self {
233 Self {
234 signed_effects: value.effects,
235 events: value.events.unwrap_or_default(),
236 fastpath_input_objects: Vec::new(),
237 }
238 }
239}
240
241#[derive(Clone, Debug, Serialize, Deserialize)]
248pub struct HandleSoftBundleCertificatesResponseV3 {
249 pub responses: Vec<HandleCertificateResponseV3>,
250}
251
252#[derive(Clone, Debug, Serialize, Deserialize)]
254pub struct HandleSoftBundleCertificatesRequestV3 {
255 pub certificates: Vec<CertifiedTransaction>,
256
257 pub wait_for_effects: bool,
258 pub include_events: bool,
259 pub include_input_objects: bool,
260 pub include_output_objects: bool,
261 pub include_auxiliary_data: bool,
262}
263
264#[derive(Default, Clone)]
267pub struct ExecutedData {
268 pub effects: crate::effects::TransactionEffects,
269 pub events: Option<crate::effects::TransactionEvents>,
270 pub input_objects: Vec<crate::object::Object>,
271 pub output_objects: Vec<crate::object::Object>,
272}
273
274#[derive(Clone, prost::Message)]
275pub struct RawExecutedData {
276 #[prost(bytes = "bytes", tag = "1")]
277 pub effects: Bytes,
278 #[prost(bytes = "bytes", optional, tag = "2")]
279 pub events: Option<Bytes>,
280 #[prost(bytes = "bytes", repeated, tag = "3")]
281 pub input_objects: Vec<Bytes>,
282 #[prost(bytes = "bytes", repeated, tag = "4")]
283 pub output_objects: Vec<Bytes>,
284}
285
286#[derive(Clone, Debug)]
290pub struct SubmitTxRequest {
291 pub transaction: Option<Transaction>,
292 pub ping_type: Option<PingType>,
293}
294
295impl From<Transaction> for SubmitTxRequest {
296 fn from(transaction: Transaction) -> Self {
297 Self::new_transaction(transaction)
298 }
299}
300
301impl SubmitTxRequest {
302 pub fn new_transaction(transaction: Transaction) -> Self {
303 Self {
304 transaction: Some(transaction),
305 ping_type: None,
306 }
307 }
308
309 pub fn new_ping() -> Self {
310 Self {
311 transaction: None,
312 ping_type: Some(PingType::Consensus),
313 }
314 }
315
316 pub fn tx_type(&self) -> TxType {
317 if self.ping_type.is_some() {
318 return TxType::SharedObject;
319 }
320 let transaction = self.transaction.as_ref().unwrap();
321 if transaction.is_consensus_tx() {
322 TxType::SharedObject
323 } else {
324 TxType::SingleWriter
325 }
326 }
327
328 pub fn tx_digest(&self) -> Option<TransactionDigest> {
331 self.transaction.as_ref().map(|t| *t.digest())
332 }
333}
334
335#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, EnumIter)]
336pub enum TxType {
337 SingleWriter,
338 SharedObject,
339}
340
341impl TxType {
342 pub fn as_str(&self) -> &str {
343 match self {
344 TxType::SingleWriter => TX_TYPE_SINGLE_WRITER_TX,
345 TxType::SharedObject => TX_TYPE_SHARED_OBJ_TX,
346 }
347 }
348}
349
350impl SubmitTxRequest {
351 pub fn into_raw(&self) -> Result<RawSubmitTxRequest, SuiError> {
352 let transactions = if let Some(transaction) = &self.transaction {
353 vec![
354 bcs::to_bytes(&transaction)
355 .map_err(|e| SuiErrorKind::TransactionSerializationError {
356 error: e.to_string(),
357 })?
358 .into(),
359 ]
360 } else {
361 vec![]
362 };
363
364 let submit_type = if self.ping_type.is_some() {
365 SubmitTxType::Ping
366 } else {
367 SubmitTxType::Default
368 };
369
370 Ok(RawSubmitTxRequest {
371 transactions,
372 submit_type: submit_type.into(),
373 })
374 }
375}
376
377#[derive(Clone)]
378pub enum SubmitTxResult {
379 Submitted {
380 consensus_position: crate::messages_consensus::ConsensusPosition,
381 },
382 Executed {
383 effects_digest: crate::digests::TransactionEffectsDigest,
384 details: Option<Box<ExecutedData>>,
387 },
388 Rejected {
389 error: crate::error::SuiError,
390 },
391}
392
393impl std::fmt::Debug for SubmitTxResult {
394 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
395 match self {
396 Self::Submitted { consensus_position } => f
397 .debug_struct("Submitted")
398 .field("consensus_position", consensus_position)
399 .finish(),
400 Self::Executed { effects_digest, .. } => f
401 .debug_struct("Executed")
402 .field("effects_digest", &format_args!("{}", effects_digest))
403 .finish(),
404 Self::Rejected { error } => f.debug_struct("Rejected").field("error", &error).finish(),
405 }
406 }
407}
408
409#[derive(Clone, Debug)]
410pub struct SubmitTxResponse {
411 pub results: Vec<SubmitTxResult>,
412}
413
414#[derive(Clone, prost::Message)]
415pub struct RawSubmitTxRequest {
416 #[prost(bytes = "bytes", repeated, tag = "1")]
418 pub transactions: Vec<Bytes>,
419
420 #[prost(enumeration = "SubmitTxType", tag = "2")]
422 pub submit_type: i32,
423}
424
425#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, prost::Enumeration)]
426#[repr(i32)]
427pub enum SubmitTxType {
428 Default = 0,
432 Ping = 1,
434 SoftBundle = 2,
437}
438
439#[derive(Clone, prost::Message)]
440pub struct RawSubmitTxResponse {
441 #[prost(message, repeated, tag = "1")]
443 pub results: Vec<RawSubmitTxResult>,
444}
445
446#[derive(Clone, prost::Message)]
447pub struct RawSubmitTxResult {
448 #[prost(oneof = "RawValidatorSubmitStatus", tags = "1, 2, 3")]
449 pub inner: Option<RawValidatorSubmitStatus>,
450}
451
452#[derive(Clone, prost::Oneof)]
453pub enum RawValidatorSubmitStatus {
454 #[prost(bytes = "bytes", tag = "1")]
456 Submitted(Bytes),
457
458 #[prost(message, tag = "2")]
460 Executed(RawExecutedStatus),
461
462 #[prost(message, tag = "3")]
464 Rejected(RawRejectedStatus),
465}
466
467#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, prost::Enumeration)]
468#[repr(i32)]
469pub enum PingType {
470 Consensus = 0,
473}
474
475impl PingType {
476 pub fn as_str(&self) -> &str {
477 match self {
478 PingType::Consensus => "consensus",
479 }
480 }
481}
482
483pub struct WaitForEffectsRequest {
486 pub transaction_digest: Option<crate::digests::TransactionDigest>,
487 pub consensus_position: Option<crate::messages_consensus::ConsensusPosition>,
491 pub include_details: bool,
494 pub ping_type: Option<PingType>,
496}
497
498#[derive(Clone)]
499pub enum WaitForEffectsResponse {
500 Executed {
501 effects_digest: crate::digests::TransactionEffectsDigest,
502 details: Option<Box<ExecutedData>>,
503 },
504 Rejected {
506 error: Option<crate::error::SuiError>,
509 },
510 Expired {
513 epoch: u64,
514 round: Option<u32>,
515 },
516}
517
518impl std::fmt::Debug for WaitForEffectsResponse {
519 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
520 match self {
521 Self::Executed { effects_digest, .. } => f
522 .debug_struct("Executed")
523 .field("effects_digest", effects_digest)
524 .finish(),
525 Self::Rejected { error } => f.debug_struct("Rejected").field("error", error).finish(),
526 Self::Expired { epoch, round } => f
527 .debug_struct("Expired")
528 .field("epoch", epoch)
529 .field("round", round)
530 .finish(),
531 }
532 }
533}
534
535#[derive(Clone, prost::Message)]
536pub struct RawWaitForEffectsRequest {
537 #[prost(bytes = "bytes", optional, tag = "1")]
539 pub transaction_digest: Option<Bytes>,
540
541 #[prost(bytes = "bytes", optional, tag = "2")]
545 pub consensus_position: Option<Bytes>,
546
547 #[prost(bool, tag = "3")]
550 pub include_details: bool,
551
552 #[prost(enumeration = "PingType", optional, tag = "4")]
554 pub ping_type: Option<i32>,
555}
556
557impl RawWaitForEffectsRequest {
558 pub fn get_ping_type(&self) -> Option<PingType> {
559 self.ping_type
560 .map(|p| PingType::try_from(p).expect("Invalid ping type"))
561 }
562}
563
564#[derive(Clone, prost::Message)]
565pub struct RawWaitForEffectsResponse {
566 #[prost(oneof = "RawValidatorTransactionStatus", tags = "1, 2, 3")]
571 pub inner: Option<RawValidatorTransactionStatus>,
572}
573
574#[derive(Clone, prost::Oneof)]
575pub enum RawValidatorTransactionStatus {
576 #[prost(message, tag = "1")]
577 Executed(RawExecutedStatus),
578 #[prost(message, tag = "2")]
579 Rejected(RawRejectedStatus),
580 #[prost(message, tag = "3")]
581 Expired(RawExpiredStatus),
582}
583
584#[derive(Clone, prost::Message)]
585pub struct RawExecutedStatus {
586 #[prost(bytes = "bytes", tag = "1")]
587 pub effects_digest: Bytes,
588 #[prost(message, optional, tag = "2")]
589 pub details: Option<RawExecutedData>,
590}
591
592#[derive(Clone, prost::Message)]
593pub struct RawRejectedStatus {
594 #[prost(bytes = "bytes", optional, tag = "1")]
595 pub error: Option<Bytes>,
596}
597
598#[derive(Clone, prost::Message)]
599pub struct RawExpiredStatus {
600 #[prost(uint64, tag = "1")]
602 pub epoch: u64,
603 #[prost(uint32, optional, tag = "2")]
605 pub round: Option<u32>,
606}
607
608#[derive(Clone, Debug, Default)]
612pub struct ValidatorHealthRequest {}
613
614#[derive(Clone, Debug, Default)]
616pub struct ValidatorHealthResponse {
617 pub num_inflight_execution_transactions: u64,
619 pub num_inflight_consensus_transactions: u64,
621 pub last_committed_leader_round: u32,
623 pub last_locally_built_checkpoint: u64,
625 pub staggering_active: Option<bool>,
629}
630
631#[derive(Clone, prost::Message)]
633pub struct RawValidatorHealthRequest {}
634
635#[derive(Clone, prost::Message)]
637pub struct RawValidatorHealthResponse {
638 #[prost(uint64, optional, tag = "1")]
640 pub pending_certificates: Option<u64>,
641 #[prost(uint64, optional, tag = "2")]
643 pub inflight_consensus_messages: Option<u64>,
644 #[prost(uint64, optional, tag = "3")]
646 pub consensus_round: Option<u64>,
647 #[prost(uint64, optional, tag = "4")]
649 pub checkpoint_sequence: Option<u64>,
650 #[prost(bool, optional, tag = "5")]
653 pub staggering_active: Option<bool>,
654}
655
656impl TryFrom<ExecutedData> for RawExecutedData {
659 type Error = crate::error::SuiError;
660
661 fn try_from(value: ExecutedData) -> Result<Self, Self::Error> {
662 let effects = bcs::to_bytes(&value.effects)
663 .map_err(
664 |err| crate::error::SuiErrorKind::GrpcMessageSerializeError {
665 type_info: "ExecutedData.effects".to_string(),
666 error: err.to_string(),
667 },
668 )?
669 .into();
670 let events = if let Some(events) = &value.events {
671 Some(
672 bcs::to_bytes(events)
673 .map_err(
674 |err| crate::error::SuiErrorKind::GrpcMessageSerializeError {
675 type_info: "ExecutedData.events".to_string(),
676 error: err.to_string(),
677 },
678 )?
679 .into(),
680 )
681 } else {
682 None
683 };
684 let mut input_objects = Vec::with_capacity(value.input_objects.len());
685 for object in value.input_objects {
686 input_objects.push(
687 bcs::to_bytes(&object)
688 .map_err(
689 |err| crate::error::SuiErrorKind::GrpcMessageSerializeError {
690 type_info: "ExecutedData.input_objects".to_string(),
691 error: err.to_string(),
692 },
693 )?
694 .into(),
695 );
696 }
697 let mut output_objects = Vec::with_capacity(value.output_objects.len());
698 for object in value.output_objects {
699 output_objects.push(
700 bcs::to_bytes(&object)
701 .map_err(
702 |err| crate::error::SuiErrorKind::GrpcMessageSerializeError {
703 type_info: "ExecutedData.output_objects".to_string(),
704 error: err.to_string(),
705 },
706 )?
707 .into(),
708 );
709 }
710 Ok(RawExecutedData {
711 effects,
712 events,
713 input_objects,
714 output_objects,
715 })
716 }
717}
718
719impl TryFrom<RawExecutedData> for ExecutedData {
720 type Error = crate::error::SuiError;
721
722 fn try_from(value: RawExecutedData) -> Result<Self, Self::Error> {
723 let effects = bcs::from_bytes(&value.effects).map_err(|err| {
724 crate::error::SuiErrorKind::GrpcMessageDeserializeError {
725 type_info: "RawExecutedData.effects".to_string(),
726 error: err.to_string(),
727 }
728 })?;
729 let events = if let Some(events) = value.events {
730 Some(bcs::from_bytes(&events).map_err(|err| {
731 crate::error::SuiErrorKind::GrpcMessageDeserializeError {
732 type_info: "RawExecutedData.events".to_string(),
733 error: err.to_string(),
734 }
735 })?)
736 } else {
737 None
738 };
739 let mut input_objects = Vec::with_capacity(value.input_objects.len());
740 for object in value.input_objects {
741 input_objects.push(bcs::from_bytes(&object).map_err(|err| {
742 crate::error::SuiErrorKind::GrpcMessageDeserializeError {
743 type_info: "RawExecutedData.input_objects".to_string(),
744 error: err.to_string(),
745 }
746 })?);
747 }
748 let mut output_objects = Vec::with_capacity(value.output_objects.len());
749 for object in value.output_objects {
750 output_objects.push(bcs::from_bytes(&object).map_err(|err| {
751 crate::error::SuiErrorKind::GrpcMessageDeserializeError {
752 type_info: "RawExecutedData.output_objects".to_string(),
753 error: err.to_string(),
754 }
755 })?);
756 }
757 Ok(ExecutedData {
758 effects,
759 events,
760 input_objects,
761 output_objects,
762 })
763 }
764}
765
766impl TryFrom<SubmitTxResult> for RawSubmitTxResult {
767 type Error = crate::error::SuiError;
768
769 fn try_from(value: SubmitTxResult) -> Result<Self, Self::Error> {
770 let inner = match value {
771 SubmitTxResult::Submitted { consensus_position } => {
772 let consensus_position = consensus_position.into_raw()?;
773 RawValidatorSubmitStatus::Submitted(consensus_position)
774 }
775 SubmitTxResult::Executed {
776 effects_digest,
777 details,
778 } => {
779 let raw_executed = try_from_response_executed(effects_digest, details)?;
780 RawValidatorSubmitStatus::Executed(raw_executed)
781 }
782 SubmitTxResult::Rejected { error } => {
783 RawValidatorSubmitStatus::Rejected(try_from_response_rejected(Some(error))?)
784 }
785 };
786 Ok(RawSubmitTxResult { inner: Some(inner) })
787 }
788}
789
790impl TryFrom<RawSubmitTxResult> for SubmitTxResult {
791 type Error = crate::error::SuiError;
792
793 fn try_from(value: RawSubmitTxResult) -> Result<Self, Self::Error> {
794 match value.inner {
795 Some(RawValidatorSubmitStatus::Submitted(consensus_position)) => {
796 Ok(SubmitTxResult::Submitted {
797 consensus_position: consensus_position.as_ref().try_into()?,
798 })
799 }
800 Some(RawValidatorSubmitStatus::Executed(executed)) => {
801 let (effects_digest, details) = try_from_raw_executed_status(executed)?;
802 Ok(SubmitTxResult::Executed {
803 effects_digest,
804 details,
805 })
806 }
807 Some(RawValidatorSubmitStatus::Rejected(error)) => {
808 let error = try_from_raw_rejected_status(error)?.unwrap_or(
809 crate::error::SuiErrorKind::GrpcMessageDeserializeError {
810 type_info: "RawSubmitTxResult.inner.Error".to_string(),
811 error: "RawSubmitTxResult.inner.Error is None".to_string(),
812 }
813 .into(),
814 );
815 Ok(SubmitTxResult::Rejected { error })
816 }
817 None => Err(crate::error::SuiErrorKind::GrpcMessageDeserializeError {
818 type_info: "RawSubmitTxResult.inner".to_string(),
819 error: "RawSubmitTxResult.inner is None".to_string(),
820 }
821 .into()),
822 }
823 }
824}
825
826impl TryFrom<RawSubmitTxResponse> for SubmitTxResponse {
827 type Error = crate::error::SuiError;
828
829 fn try_from(value: RawSubmitTxResponse) -> Result<Self, Self::Error> {
830 if value.results.len() != 1 {
832 return Err(crate::error::SuiErrorKind::GrpcMessageDeserializeError {
833 type_info: "RawSubmitTxResponse.results".to_string(),
834 error: format!("Expected exactly 1 result, got {}", value.results.len()),
835 }
836 .into());
837 }
838
839 let results = value
840 .results
841 .into_iter()
842 .map(|result| result.try_into())
843 .collect::<Result<Vec<SubmitTxResult>, crate::error::SuiError>>()?;
844
845 Ok(Self { results })
846 }
847}
848
849fn try_from_raw_executed_status(
850 executed: RawExecutedStatus,
851) -> Result<
852 (
853 crate::digests::TransactionEffectsDigest,
854 Option<Box<ExecutedData>>,
855 ),
856 crate::error::SuiError,
857> {
858 let effects_digest = bcs::from_bytes(&executed.effects_digest).map_err(|err| {
859 crate::error::SuiErrorKind::GrpcMessageDeserializeError {
860 type_info: "RawWaitForEffectsResponse.effects_digest".to_string(),
861 error: err.to_string(),
862 }
863 })?;
864 let executed_data = if let Some(details) = executed.details {
865 Some(Box::new(details.try_into()?))
866 } else {
867 None
868 };
869 Ok((effects_digest, executed_data))
870}
871
872fn try_from_raw_rejected_status(
873 rejected: RawRejectedStatus,
874) -> Result<Option<crate::error::SuiError>, crate::error::SuiError> {
875 match rejected.error {
876 Some(error_bytes) => {
877 let error = bcs::from_bytes(&error_bytes).map_err(|err| {
878 crate::error::SuiErrorKind::GrpcMessageDeserializeError {
879 type_info: "RawWaitForEffectsResponse.rejected.reason".to_string(),
880 error: err.to_string(),
881 }
882 })?;
883 Ok(Some(error))
884 }
885 None => Ok(None),
886 }
887}
888
889fn try_from_response_rejected(
890 error: Option<crate::error::SuiError>,
891) -> Result<RawRejectedStatus, crate::error::SuiError> {
892 let error = match error {
893 Some(e) => Some(
894 bcs::to_bytes(&e)
895 .map_err(
896 |err| crate::error::SuiErrorKind::GrpcMessageSerializeError {
897 type_info: "RawRejectedStatus.error".to_string(),
898 error: err.to_string(),
899 },
900 )?
901 .into(),
902 ),
903 None => None,
904 };
905 Ok(RawRejectedStatus { error })
906}
907
908fn try_from_response_executed(
909 effects_digest: crate::digests::TransactionEffectsDigest,
910 details: Option<Box<ExecutedData>>,
911) -> Result<RawExecutedStatus, crate::error::SuiError> {
912 let effects_digest = bcs::to_bytes(&effects_digest)
913 .map_err(
914 |err| crate::error::SuiErrorKind::GrpcMessageSerializeError {
915 type_info: "RawWaitForEffectsResponse.effects_digest".to_string(),
916 error: err.to_string(),
917 },
918 )?
919 .into();
920 let details = if let Some(details) = details {
921 Some((*details).try_into()?)
922 } else {
923 None
924 };
925 Ok(RawExecutedStatus {
926 effects_digest,
927 details,
928 })
929}
930
931impl TryFrom<RawWaitForEffectsRequest> for WaitForEffectsRequest {
932 type Error = crate::error::SuiError;
933
934 fn try_from(value: RawWaitForEffectsRequest) -> Result<Self, Self::Error> {
935 let transaction_digest = match value.transaction_digest {
936 Some(digest) => Some(bcs::from_bytes(&digest).map_err(|err| {
937 crate::error::SuiErrorKind::GrpcMessageDeserializeError {
938 type_info: "RawWaitForEffectsRequest.transaction_digest".to_string(),
939 error: err.to_string(),
940 }
941 })?),
942 None => None,
943 };
944 let consensus_position = match value.consensus_position {
945 Some(cp) => Some(cp.as_ref().try_into()?),
946 None => None,
947 };
948 let ping_type = value
949 .ping_type
950 .map(|p| {
951 PingType::try_from(p).map_err(|e| SuiErrorKind::GrpcMessageDeserializeError {
952 type_info: "RawWaitForEffectsRequest.ping_type".to_string(),
953 error: e.to_string(),
954 })
955 })
956 .transpose()?;
957 Ok(Self {
958 consensus_position,
959 transaction_digest,
960 include_details: value.include_details,
961 ping_type,
962 })
963 }
964}
965
966impl TryFrom<WaitForEffectsRequest> for RawWaitForEffectsRequest {
967 type Error = crate::error::SuiError;
968
969 fn try_from(value: WaitForEffectsRequest) -> Result<Self, Self::Error> {
970 let transaction_digest = match value.transaction_digest {
971 Some(digest) => Some(
972 bcs::to_bytes(&digest)
973 .map_err(
974 |err| crate::error::SuiErrorKind::GrpcMessageSerializeError {
975 type_info: "RawWaitForEffectsRequest.transaction_digest".to_string(),
976 error: err.to_string(),
977 },
978 )?
979 .into(),
980 ),
981 None => None,
982 };
983 let consensus_position = match value.consensus_position {
984 Some(cp) => Some(cp.into_raw()?),
985 None => None,
986 };
987 let ping_type = value.ping_type.map(|p| p.into());
988 Ok(Self {
989 consensus_position,
990 transaction_digest,
991 include_details: value.include_details,
992 ping_type,
993 })
994 }
995}
996
997impl TryFrom<RawWaitForEffectsResponse> for WaitForEffectsResponse {
998 type Error = crate::error::SuiError;
999
1000 fn try_from(value: RawWaitForEffectsResponse) -> Result<Self, Self::Error> {
1001 match value.inner {
1002 Some(RawValidatorTransactionStatus::Executed(executed)) => {
1003 let (effects_digest, details) = try_from_raw_executed_status(executed)?;
1004 Ok(Self::Executed {
1005 effects_digest,
1006 details,
1007 })
1008 }
1009 Some(RawValidatorTransactionStatus::Rejected(rejected)) => {
1010 let error = try_from_raw_rejected_status(rejected)?;
1011 Ok(Self::Rejected { error })
1012 }
1013 Some(RawValidatorTransactionStatus::Expired(expired)) => Ok(Self::Expired {
1014 epoch: expired.epoch,
1015 round: expired.round,
1016 }),
1017 None => Err(crate::error::SuiErrorKind::GrpcMessageDeserializeError {
1018 type_info: "RawWaitForEffectsResponse.inner".to_string(),
1019 error: "RawWaitForEffectsResponse.inner is None".to_string(),
1020 }
1021 .into()),
1022 }
1023 }
1024}
1025
1026impl TryFrom<WaitForEffectsResponse> for RawWaitForEffectsResponse {
1027 type Error = crate::error::SuiError;
1028
1029 fn try_from(value: WaitForEffectsResponse) -> Result<Self, Self::Error> {
1030 let inner = match value {
1031 WaitForEffectsResponse::Executed {
1032 effects_digest,
1033 details,
1034 } => {
1035 let raw_executed = try_from_response_executed(effects_digest, details)?;
1036 RawValidatorTransactionStatus::Executed(raw_executed)
1037 }
1038 WaitForEffectsResponse::Rejected { error } => {
1039 let raw_rejected = try_from_response_rejected(error)?;
1040 RawValidatorTransactionStatus::Rejected(raw_rejected)
1041 }
1042 WaitForEffectsResponse::Expired { epoch, round } => {
1043 RawValidatorTransactionStatus::Expired(RawExpiredStatus { epoch, round })
1044 }
1045 };
1046 Ok(RawWaitForEffectsResponse { inner: Some(inner) })
1047 }
1048}
1049
1050impl TryFrom<ValidatorHealthRequest> for RawValidatorHealthRequest {
1051 type Error = crate::error::SuiError;
1052
1053 fn try_from(_value: ValidatorHealthRequest) -> Result<Self, Self::Error> {
1054 Ok(Self {})
1055 }
1056}
1057
1058impl TryFrom<RawValidatorHealthRequest> for ValidatorHealthRequest {
1059 type Error = crate::error::SuiError;
1060
1061 fn try_from(_value: RawValidatorHealthRequest) -> Result<Self, Self::Error> {
1062 Ok(Self {})
1064 }
1065}
1066
1067impl TryFrom<ValidatorHealthResponse> for RawValidatorHealthResponse {
1068 type Error = crate::error::SuiError;
1069
1070 fn try_from(value: ValidatorHealthResponse) -> Result<Self, Self::Error> {
1071 Ok(Self {
1072 pending_certificates: Some(value.num_inflight_execution_transactions),
1073 inflight_consensus_messages: Some(value.num_inflight_consensus_transactions),
1074 consensus_round: Some(value.last_committed_leader_round as u64),
1075 checkpoint_sequence: Some(value.last_locally_built_checkpoint),
1076 staggering_active: value.staggering_active,
1077 })
1078 }
1079}
1080
1081impl TryFrom<RawValidatorHealthResponse> for ValidatorHealthResponse {
1082 type Error = crate::error::SuiError;
1083
1084 fn try_from(value: RawValidatorHealthResponse) -> Result<Self, Self::Error> {
1085 Ok(Self {
1086 num_inflight_consensus_transactions: value.inflight_consensus_messages.unwrap_or(0),
1087 num_inflight_execution_transactions: value.pending_certificates.unwrap_or(0),
1088 last_locally_built_checkpoint: value.checkpoint_sequence.unwrap_or(0),
1089 last_committed_leader_round: value.consensus_round.unwrap_or(0) as u32,
1090 staggering_active: value.staggering_active,
1091 })
1092 }
1093}
1094
1095#[cfg(test)]
1096mod tests {
1097 use crate::{
1098 messages_grpc::{SubmitTxRequest, SubmitTxType},
1099 transaction::{Transaction, TransactionData},
1100 };
1101
1102 #[tokio::test]
1103 async fn test_submit_tx_request_into_raw() {
1104 println!(
1105 "Case 1. SubmitTxRequest::new_ping should be converted to RawSubmitTxRequest with submit_type set to Ping."
1106 );
1107 {
1108 let request = SubmitTxRequest::new_ping();
1109 let raw_request = request.into_raw().unwrap();
1110
1111 let submit_type = SubmitTxType::try_from(raw_request.submit_type).unwrap();
1112 assert_eq!(submit_type, SubmitTxType::Ping);
1113 }
1114
1115 println!(
1116 "Case 2. SubmitTxRequest::new_transaction should be converted to RawSubmitTxRequest with submit_type set to Default."
1117 );
1118 {
1119 let sender = crate::base_types::SuiAddress::random_for_testing_only();
1121 let recipient = crate::base_types::SuiAddress::random_for_testing_only();
1122 let gas_object_ref = crate::base_types::random_object_ref();
1123
1124 let tx_data = TransactionData::new_transfer_sui(
1125 recipient,
1126 sender,
1127 None,
1128 gas_object_ref,
1129 1000,
1130 1000,
1131 );
1132
1133 let (_, keypair) = crate::crypto::get_account_key_pair();
1134 let transaction = Transaction::from_data_and_signer(tx_data, vec![&keypair]);
1135
1136 let request = SubmitTxRequest::new_transaction(transaction);
1137 let raw_request = request.into_raw().unwrap();
1138
1139 let submit_type = SubmitTxType::try_from(raw_request.submit_type).unwrap();
1140 assert_eq!(submit_type, SubmitTxType::Default);
1141 assert_eq!(raw_request.transactions.len(), 1);
1142 }
1143 }
1144}