1use std::fmt::{self, Display, Formatter, Write};
6
7use enum_dispatch::enum_dispatch;
8use fastcrypto::encoding::{Base64, Encoding};
9use futures::{Stream, StreamExt, stream::FuturesOrdered};
10use iota_json::{IotaJsonValue, primitive_type};
11use iota_package_resolver::{CleverError, ErrorConstants, PackageStore, Resolver};
12use iota_sdk_types::{
13 AccountClaimKind, Address, Argument, CanceledTransaction, ChangeEpoch, ChangeEpochV2,
14 ChangeEpochV3, ChangeEpochV4, Command, ConsensusCommitDigest,
15 ConsensusDeterminedVersionAssignments, EndOfEpochTransactionKind,
16 ExecutionError as ExecutionFailureStatus, ExecutionStatus, GasCostSummary, GenesisObject,
17 Identifier, MoveCall, ObjectDigest, ObjectId, ObjectReference, OwnedObjectReference, Owner,
18 ProgrammableTransaction, SenderSignedTransaction, SharedObjectReference, Transaction,
19 TransactionDigest, TransactionEffects, TransactionEvents, TransactionEventsDigest,
20 TransactionKind, TransferObjects, TypeTag, UserSignature, Version, VersionAssignment,
21 WriteKind,
22};
23use iota_types::{
24 base_types::EpochId,
25 effects::TransactionEffectsAPI,
26 error::{ExecutionError, IotaError, IotaResult},
27 event::EventID,
28 iota_sdk_types_conversions::{identifier_sdk_to_core, type_tag_core_to_sdk},
29 iota_serde::BigInt,
30 layout_resolver::{LayoutResolver, get_layout_from_struct_tag},
31 messages_checkpoint::CheckpointSequenceNumber,
32 object::bounded_visitor::BoundedVisitor,
33 parse_iota_type_tag,
34 quorum_driver_types::ExecuteTransactionRequestType as NativeExecuteTransactionRequestType,
35 storage::DeleteKind,
36 transaction::{CallArg, InputObjectKind, TransactionAPI},
37};
38use move_binary_format::CompiledModule;
39use move_bytecode_utils::module_cache::GetModule;
40use move_core_types::{
41 account_address::AccountAddress, annotated_value::MoveTypeLayout, language_storage::ModuleId,
42};
43use schemars::JsonSchema;
44use serde::{Deserialize, Serialize};
45use serde_with::{DisplayFromStr, serde_as};
46use strum::{Display, EnumString};
47use tabled::{
48 builder::Builder as TableBuilder,
49 settings::{Panel as TablePanel, Style as TableStyle, style::HorizontalLine},
50};
51
52use crate::{
53 IotaEvent, IotaEventID, IotaMoveValue, ObjectRefSchema, Page,
54 balance_changes::BalanceChange,
55 iota_gas_cost_summary::IotaGasCostSummary,
56 iota_owner::OwnerSchema,
57 iota_primitives::{
58 Address as AddressSchema, Base58 as Base58Schema, Base64 as Base64Schema,
59 ObjectId as ObjectIdSchema, SequenceNumberString as SequenceNumberStringSchema,
60 SequenceNumberU64, TypeTag as TypeTagSchema, UserSignature as UserSignatureSchema,
61 },
62 object_changes::ObjectChange,
63};
64
65pub type IotaEpochId = BigInt<u64>;
67
68#[derive(Debug, Serialize, Deserialize, JsonSchema)]
69pub enum ExecuteTransactionRequestType {
70 WaitForEffectsCert,
71 WaitForLocalExecution,
72}
73
74impl From<NativeExecuteTransactionRequestType> for ExecuteTransactionRequestType {
75 fn from(request_type: NativeExecuteTransactionRequestType) -> Self {
76 match request_type {
77 NativeExecuteTransactionRequestType::WaitForEffectsCert => Self::WaitForEffectsCert,
78 NativeExecuteTransactionRequestType::WaitForLocalExecution => {
79 Self::WaitForLocalExecution
80 }
81 }
82 }
83}
84
85impl From<ExecuteTransactionRequestType> for NativeExecuteTransactionRequestType {
86 fn from(request_type: ExecuteTransactionRequestType) -> Self {
87 match request_type {
88 ExecuteTransactionRequestType::WaitForEffectsCert => Self::WaitForEffectsCert,
89 ExecuteTransactionRequestType::WaitForLocalExecution => Self::WaitForLocalExecution,
90 }
91 }
92}
93
94#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, Default)]
95#[serde(
96 rename_all = "camelCase",
97 rename = "TransactionBlockResponseQuery",
98 default
99)]
100pub struct IotaTransactionBlockResponseQuery {
101 pub filter: Option<TransactionFilter>,
103 pub options: Option<IotaTransactionBlockResponseOptions>,
106}
107
108impl IotaTransactionBlockResponseQuery {
109 pub fn new(
110 filter: Option<TransactionFilter>,
111 options: Option<IotaTransactionBlockResponseOptions>,
112 ) -> Self {
113 Self { filter, options }
114 }
115
116 pub fn new_with_filter(filter: TransactionFilter) -> Self {
117 Self {
118 filter: Some(filter),
119 options: None,
120 }
121 }
122}
123
124#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, Default)]
125#[serde(
126 rename_all = "camelCase",
127 rename = "TransactionBlockResponseQuery",
128 default
129)]
130pub struct IotaTransactionBlockResponseQueryV2 {
131 pub filter: Option<TransactionFilterV2>,
133 pub options: Option<IotaTransactionBlockResponseOptions>,
136}
137
138impl IotaTransactionBlockResponseQueryV2 {
139 pub fn new(
140 filter: Option<TransactionFilterV2>,
141 options: Option<IotaTransactionBlockResponseOptions>,
142 ) -> Self {
143 Self { filter, options }
144 }
145
146 pub fn new_with_filter(filter: TransactionFilterV2) -> Self {
147 Self {
148 filter: Some(filter),
149 options: None,
150 }
151 }
152}
153
154pub type TransactionBlocksPage = Page<IotaTransactionBlockResponse, TransactionDigest>;
155
156#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, Eq, PartialEq, Default)]
157#[serde(
158 rename_all = "camelCase",
159 rename = "TransactionBlockResponseOptions",
160 default
161)]
162pub struct IotaTransactionBlockResponseOptions {
163 pub show_input: bool,
165 pub show_raw_input: bool,
167 pub show_effects: bool,
169 pub show_events: bool,
171 pub show_object_changes: bool,
173 pub show_balance_changes: bool,
175 pub show_raw_effects: bool,
177}
178
179impl IotaTransactionBlockResponseOptions {
180 pub fn new() -> Self {
181 Self::default()
182 }
183
184 pub fn full_content() -> Self {
185 Self {
186 show_effects: true,
187 show_input: true,
188 show_raw_input: true,
189 show_events: true,
190 show_object_changes: true,
191 show_balance_changes: true,
192 show_raw_effects: false,
195 }
196 }
197
198 pub fn with_input(mut self) -> Self {
199 self.show_input = true;
200 self
201 }
202
203 pub fn with_raw_input(mut self) -> Self {
204 self.show_raw_input = true;
205 self
206 }
207
208 pub fn with_effects(mut self) -> Self {
209 self.show_effects = true;
210 self
211 }
212
213 pub fn with_events(mut self) -> Self {
214 self.show_events = true;
215 self
216 }
217
218 pub fn with_balance_changes(mut self) -> Self {
219 self.show_balance_changes = true;
220 self
221 }
222
223 pub fn with_object_changes(mut self) -> Self {
224 self.show_object_changes = true;
225 self
226 }
227
228 pub fn with_raw_effects(mut self) -> Self {
229 self.show_raw_effects = true;
230 self
231 }
232
233 pub fn default_execution_request_type(&self) -> NativeExecuteTransactionRequestType {
236 if self.require_effects() {
239 NativeExecuteTransactionRequestType::WaitForLocalExecution
240 } else {
241 NativeExecuteTransactionRequestType::WaitForEffectsCert
242 }
243 }
244
245 pub fn require_input(&self) -> bool {
246 self.show_input || self.show_raw_input || self.show_object_changes
247 }
248
249 pub fn require_effects(&self) -> bool {
250 self.show_effects
251 || self.show_events
252 || self.show_balance_changes
253 || self.show_object_changes
254 || self.show_raw_effects
255 }
256
257 pub fn only_digest(&self) -> bool {
258 self == &Self::default()
259 }
260}
261
262#[serde_as]
263#[derive(Serialize, Deserialize, Debug, JsonSchema, Clone, Default)]
264#[serde(rename_all = "camelCase", rename = "TransactionBlockResponse")]
265pub struct IotaTransactionBlockResponse {
266 #[serde_as(as = "Base58Schema")]
267 #[schemars(with = "Base58Schema")]
268 pub digest: TransactionDigest,
269 #[serde(skip_serializing_if = "Option::is_none")]
271 pub transaction: Option<IotaTransactionBlock>,
272 #[serde_as(as = "Base64")]
275 #[schemars(with = "Base64Schema")]
276 #[serde(skip_serializing_if = "Vec::is_empty", default)]
277 pub raw_transaction: Vec<u8>,
278 #[serde(skip_serializing_if = "Option::is_none")]
279 pub effects: Option<IotaTransactionBlockEffects>,
280 #[serde(skip_serializing_if = "Option::is_none")]
281 pub events: Option<IotaTransactionBlockEvents>,
282 #[serde(skip_serializing_if = "Option::is_none")]
283 pub object_changes: Option<Vec<ObjectChange>>,
284 #[serde(skip_serializing_if = "Option::is_none")]
285 pub balance_changes: Option<Vec<BalanceChange>>,
286 #[serde(default, skip_serializing_if = "Option::is_none")]
287 #[schemars(with = "Option<String>")]
288 #[serde_as(as = "Option<DisplayFromStr>")]
289 pub timestamp_ms: Option<u64>,
290 #[serde(default, skip_serializing_if = "Option::is_none")]
291 pub confirmed_local_execution: Option<bool>,
292 #[schemars(with = "Option<String>")]
296 #[serde_as(as = "Option<DisplayFromStr>")]
297 #[serde(skip_serializing_if = "Option::is_none")]
298 pub checkpoint: Option<CheckpointSequenceNumber>,
299 #[serde(skip_serializing_if = "Vec::is_empty", default)]
302 pub errors: Vec<String>,
303 #[serde(skip_serializing_if = "Vec::is_empty", default)]
304 pub raw_effects: Vec<u8>,
305}
306
307impl IotaTransactionBlockResponse {
308 pub fn new(digest: TransactionDigest) -> Self {
309 Self {
310 digest,
311 ..Default::default()
312 }
313 }
314
315 pub fn status_ok(&self) -> Option<bool> {
316 self.effects.as_ref().map(|e| e.status().is_ok())
317 }
318
319 pub fn mutated_objects(&self) -> impl Iterator<Item = ObjectReference> + '_ {
321 self.object_changes.iter().flat_map(|obj_changes| {
322 obj_changes
323 .iter()
324 .filter(|change| matches!(change, ObjectChange::Mutated { .. }))
325 .map(|change| change.object_ref())
326 })
327 }
328}
329
330impl PartialEq for IotaTransactionBlockResponse {
332 fn eq(&self, other: &Self) -> bool {
333 self.transaction == other.transaction
334 && self.effects == other.effects
335 && self.timestamp_ms == other.timestamp_ms
336 && self.confirmed_local_execution == other.confirmed_local_execution
337 && self.checkpoint == other.checkpoint
338 }
339}
340
341impl Display for IotaTransactionBlockResponse {
342 fn fmt(&self, writer: &mut Formatter<'_>) -> fmt::Result {
343 writeln!(writer, "Transaction Digest: {}", self.digest)?;
344
345 if let Some(t) = &self.transaction {
346 writeln!(writer, "{t}")?;
347 }
348
349 if let Some(e) = &self.effects {
350 writeln!(writer, "{e}")?;
351 }
352
353 if let Some(e) = &self.events {
354 writeln!(writer, "{e}")?;
355 }
356
357 if let Some(object_changes) = &self.object_changes {
358 let mut builder = TableBuilder::default();
359 let (
360 mut created,
361 mut deleted,
362 mut mutated,
363 mut published,
364 mut transferred,
365 mut wrapped,
366 mut unwrapped,
367 ) = (vec![], vec![], vec![], vec![], vec![], vec![], vec![]);
368
369 for obj in object_changes {
370 match obj {
371 ObjectChange::Created { .. } => created.push(obj),
372 ObjectChange::Deleted { .. } => deleted.push(obj),
373 ObjectChange::Mutated { .. } => mutated.push(obj),
374 ObjectChange::Published { .. } => published.push(obj),
375 ObjectChange::Transferred { .. } => transferred.push(obj),
376 ObjectChange::Wrapped { .. } => wrapped.push(obj),
377 ObjectChange::Unwrapped { .. } => unwrapped.push(obj),
378 };
379 }
380
381 write_obj_changes(created, "Created", &mut builder)?;
382 write_obj_changes(deleted, "Deleted", &mut builder)?;
383 write_obj_changes(mutated, "Mutated", &mut builder)?;
384 write_obj_changes(published, "Published", &mut builder)?;
385 write_obj_changes(transferred, "Transferred", &mut builder)?;
386 write_obj_changes(wrapped, "Wrapped", &mut builder)?;
387 write_obj_changes(unwrapped, "Unwrapped", &mut builder)?;
388
389 let mut table = builder.build();
390 table.with(TablePanel::header("Object Changes"));
391 table.with(TableStyle::rounded().horizontals([HorizontalLine::new(
392 1,
393 TableStyle::modern().get_horizontal(),
394 )]));
395 writeln!(writer, "{table}")?;
396 }
397
398 if let Some(balance_changes) = &self.balance_changes {
399 if !balance_changes.is_empty() {
403 let mut builder = TableBuilder::default();
404 for balance in balance_changes {
405 builder.push_record(vec![format!("{balance}")]);
406 }
407 let mut table = builder.build();
408 table.with(TablePanel::header("Balance Changes"));
409 table.with(TableStyle::rounded().horizontals([HorizontalLine::new(
410 1,
411 TableStyle::modern().get_horizontal(),
412 )]));
413 writeln!(writer, "{table}")?;
414 } else {
415 writeln!(writer, "╭────────────────────╮")?;
416 writeln!(writer, "│ No balance changes │")?;
417 writeln!(writer, "╰────────────────────╯")?;
418 }
419 }
420 Ok(())
421 }
422}
423
424fn write_obj_changes<T: Display>(
425 values: Vec<T>,
426 output_string: &str,
427 builder: &mut TableBuilder,
428) -> std::fmt::Result {
429 if !values.is_empty() {
430 builder.push_record(vec![format!("{output_string} Objects: ")]);
431 for obj in values {
432 builder.push_record(vec![format!("{obj}")]);
433 }
434 }
435 Ok(())
436}
437
438pub fn get_new_package_obj_from_response(
439 response: &IotaTransactionBlockResponse,
440) -> Option<ObjectReference> {
441 response.object_changes.as_ref().and_then(|changes| {
442 changes
443 .iter()
444 .find(|change| matches!(change, ObjectChange::Published { .. }))
445 .map(|change| change.object_ref())
446 })
447}
448
449pub fn get_new_package_upgrade_cap_from_response(
450 response: &IotaTransactionBlockResponse,
451) -> Option<ObjectReference> {
452 response.object_changes.as_ref().and_then(|changes| {
453 changes
454 .iter()
455 .find(|change| {
456 matches!(change, ObjectChange::Created {
457 owner: Owner::Address(_),
458 object_type,
459 ..
460 } if object_type.is_upgrade_cap())
461 })
462 .map(|change| change.object_ref())
463 })
464}
465
466#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
467#[serde(rename = "TransactionBlockKind", tag = "kind")]
468pub enum IotaTransactionBlockKind {
469 Genesis(IotaGenesisTransaction),
472 ConsensusCommitPrologueV1(IotaConsensusCommitPrologueV1),
475 ProgrammableTransaction(IotaProgrammableTransactionBlock),
478 RandomnessStateUpdate(IotaRandomnessStateUpdate),
480 TransactionDenyRulesUpdate(IotaTransactionDenyRulesUpdate),
483 EndOfEpochTransaction(IotaEndOfEpochTransaction),
485 ClaimAccount(IotaClaimAccountTransaction),
487 }
489
490impl Display for IotaTransactionBlockKind {
491 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
492 let mut writer = String::new();
493 match &self {
494 Self::Genesis(_) => {
495 writeln!(writer, "Transaction Kind: Genesis Transaction")?;
496 }
497 Self::ConsensusCommitPrologueV1(p) => {
498 writeln!(writer, "Transaction Kind: Consensus Commit Prologue V1")?;
499 writeln!(
500 writer,
501 "Epoch: {}, Round: {}, SubDagIndex: {:?}, Timestamp: {}, ConsensusCommitDigest: {}",
502 p.epoch,
503 p.round,
504 p.sub_dag_index,
505 p.commit_timestamp_ms,
506 p.consensus_commit_digest
507 )?;
508 }
509 Self::ProgrammableTransaction(p) => {
510 write!(writer, "Transaction Kind: Programmable")?;
511 write!(writer, "{}", crate::displays::Pretty(p))?;
512 }
513 Self::RandomnessStateUpdate(_) => {
514 writeln!(writer, "Transaction Kind: Randomness State Update")?;
515 }
516 Self::TransactionDenyRulesUpdate(_) => {
517 writeln!(writer, "Transaction Kind: Transaction Deny Rules Update")?;
518 }
519 Self::EndOfEpochTransaction(_) => {
520 writeln!(writer, "Transaction Kind: End of Epoch Transaction")?;
521 }
522 Self::ClaimAccount(claim) => {
523 writeln!(writer, "Transaction Kind: Claim Account")?;
524 match &claim.account_kind {
525 IotaAccountClaimKind::SmartAccount(smart) => {
526 writeln!(
527 writer,
528 "Account Kind: Smart Account, Public Key Scheme Flag: {}, Public Key: {}",
529 smart.public_key_scheme,
530 Base64::encode(&smart.public_key_raw_bytes)
531 )?;
532 }
533 }
534 }
535 }
536 write!(f, "{writer}")
537 }
538}
539
540impl IotaTransactionBlockKind {
541 fn try_from_inner(
542 tx: TransactionKind,
543 tx_digest: TransactionDigest,
544 ) -> Result<Self, anyhow::Error> {
545 match tx {
546 TransactionKind::Genesis(g) => Ok(Self::Genesis(IotaGenesisTransaction {
547 objects: g.objects.iter().map(GenesisObject::id).collect(),
548 events: g
549 .events
550 .into_iter()
551 .enumerate()
552 .map(|(seq, _event)| EventID::from((tx_digest, seq as u64)))
553 .collect(),
554 })),
555 TransactionKind::ConsensusCommitPrologueV1(p) => Ok(Self::ConsensusCommitPrologueV1(
556 IotaConsensusCommitPrologueV1 {
557 epoch: p.epoch,
558 round: p.round,
559 sub_dag_index: p.sub_dag_index,
560 commit_timestamp_ms: p.commit_timestamp_ms,
561 consensus_commit_digest: p.consensus_commit_digest,
562 consensus_determined_version_assignments: p
563 .consensus_determined_version_assignments
564 .try_into()?,
565 },
566 )),
567 TransactionKind::Programmable(_) => {
568 Err(anyhow::anyhow!(
570 "ProgrammableTransaction must be handled by the caller, not try_from_inner"
571 ))
572 }
573 #[allow(deprecated)]
574 TransactionKind::AuthenticatorStateUpdateV1Deprecated => {
575 Err(anyhow::anyhow!(
579 "AuthenticatorStateUpdateV1 transactions are deprecated and were never created on IOTA"
580 ))
581 }
582 TransactionKind::RandomnessStateUpdate(update) => {
583 Ok(Self::RandomnessStateUpdate(IotaRandomnessStateUpdate {
584 epoch: update.epoch,
585 randomness_round: update.randomness_round.value(),
586 random_bytes: update.random_bytes,
587 }))
588 }
589 TransactionKind::TransactionDenyRulesUpdate(update) => Ok(
590 Self::TransactionDenyRulesUpdate(IotaTransactionDenyRulesUpdate {
591 epoch: update.epoch,
592 round: update.round,
593 added_addresses: update.added_addresses.into_iter().collect(),
594 removed_addresses: update.removed_addresses.into_iter().collect(),
595 added_objects: update.added_objects.into_iter().collect(),
596 removed_objects: update.removed_objects.into_iter().collect(),
597 added_packages: update.added_packages.into_iter().collect(),
598 removed_packages: update.removed_packages.into_iter().collect(),
599 package_publish_disabled: update.package_publish_disabled,
600 package_upgrade_disabled: update.package_upgrade_disabled,
601 shared_object_disabled: update.shared_object_disabled,
602 user_transaction_disabled: update.user_transaction_disabled,
603 receiving_objects_disabled: update.receiving_objects_disabled,
604 move_authenticator_disabled: update.move_authenticator_disabled,
605 }),
606 ),
607 TransactionKind::EndOfEpoch(end_of_epoch_tx) => {
608 Ok(Self::EndOfEpochTransaction(IotaEndOfEpochTransaction {
609 transactions: end_of_epoch_tx
610 .into_iter()
611 .map(|tx| {
612 Ok(match tx {
613 EndOfEpochTransactionKind::ChangeEpoch(e) => {
614 IotaEndOfEpochTransactionKind::ChangeEpoch(e.into())
615 }
616 EndOfEpochTransactionKind::ChangeEpochV2(e) => {
617 IotaEndOfEpochTransactionKind::ChangeEpochV2(e.into())
618 }
619 EndOfEpochTransactionKind::ChangeEpochV3(e) => {
620 IotaEndOfEpochTransactionKind::ChangeEpochV2(e.into())
621 }
622 EndOfEpochTransactionKind::ChangeEpochV4(e) => {
623 IotaEndOfEpochTransactionKind::ChangeEpochV2(e.into())
624 }
625 EndOfEpochTransactionKind::TransactionDenyRulesCreate => {
626 IotaEndOfEpochTransactionKind::TransactionDenyRulesCreate
627 }
628 _ => anyhow::bail!("unknown EndOfEpochTransactionKind variant"),
629 })
630 })
631 .collect::<Result<_, anyhow::Error>>()?,
632 }))
633 }
634 TransactionKind::ClaimAccount(claim_tx) => {
635 let kind = match claim_tx.kind {
636 AccountClaimKind::SmartAccount(smart) => {
637 IotaAccountClaimKind::SmartAccount(IotaSmartAccountClaim {
638 public_key_scheme: smart.public_key_scheme,
639 public_key_raw_bytes: smart.public_key_raw_bytes,
640 })
641 }
642 _ => {
643 return Err(anyhow::anyhow!("unsupported AccountClaimKind variant"));
644 }
645 };
646 Ok(Self::ClaimAccount(IotaClaimAccountTransaction {
647 account_kind: kind,
648 }))
649 }
650 _ => Err(anyhow::anyhow!("unknown TransactionKind variant")),
651 }
652 }
653
654 fn try_from_with_module_cache(
655 tx: TransactionKind,
656 module_cache: &impl GetModule,
657 tx_digest: TransactionDigest,
658 ) -> Result<Self, anyhow::Error> {
659 match tx {
660 TransactionKind::Programmable(p) => Ok(Self::ProgrammableTransaction(
661 IotaProgrammableTransactionBlock::try_from_with_module_cache(p, module_cache)?,
662 )),
663 tx => Self::try_from_inner(tx, tx_digest),
664 }
665 }
666
667 async fn try_from_with_package_resolver(
668 tx: TransactionKind,
669 package_resolver: &Resolver<impl PackageStore>,
670 tx_digest: TransactionDigest,
671 ) -> Result<Self, anyhow::Error> {
672 match tx {
673 TransactionKind::Programmable(p) => Ok(Self::ProgrammableTransaction(
674 IotaProgrammableTransactionBlock::try_from_with_package_resolver(
675 p,
676 package_resolver,
677 )
678 .await?,
679 )),
680 tx => Self::try_from_inner(tx, tx_digest),
681 }
682 }
683
684 pub fn transaction_count(&self) -> usize {
685 match self {
686 Self::ProgrammableTransaction(p) => p.commands.len(),
687 _ => 1,
688 }
689 }
690
691 pub fn name(&self) -> &'static str {
692 match self {
693 Self::Genesis(_) => "Genesis",
694 Self::ConsensusCommitPrologueV1(_) => "ConsensusCommitPrologueV1",
695 Self::ProgrammableTransaction(_) => "ProgrammableTransaction",
696 Self::RandomnessStateUpdate(_) => "RandomnessStateUpdate",
697 Self::TransactionDenyRulesUpdate(_) => "TransactionDenyRulesUpdate",
698 Self::EndOfEpochTransaction(_) => "EndOfEpochTransaction",
699 Self::ClaimAccount(_) => "ClaimAccount",
700 }
701 }
702}
703
704#[serde_as]
705#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
706pub struct IotaChangeEpoch {
707 #[schemars(with = "String")]
708 #[serde_as(as = "DisplayFromStr")]
709 pub epoch: EpochId,
710 #[schemars(with = "String")]
711 #[serde_as(as = "DisplayFromStr")]
712 pub storage_charge: u64,
713 #[schemars(with = "String")]
714 #[serde_as(as = "DisplayFromStr")]
715 pub computation_charge: u64,
716 #[schemars(with = "String")]
717 #[serde_as(as = "DisplayFromStr")]
718 pub storage_rebate: u64,
719 #[schemars(with = "String")]
720 #[serde_as(as = "DisplayFromStr")]
721 pub epoch_start_timestamp_ms: u64,
722}
723
724impl From<ChangeEpoch> for IotaChangeEpoch {
725 fn from(e: ChangeEpoch) -> Self {
726 Self {
727 epoch: e.epoch,
728 storage_charge: e.storage_charge,
729 computation_charge: e.computation_charge,
730 storage_rebate: e.storage_rebate,
731 epoch_start_timestamp_ms: e.epoch_start_timestamp_ms,
732 }
733 }
734}
735
736#[serde_as]
737#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
738pub struct IotaChangeEpochV2 {
739 #[schemars(with = "String")]
740 #[serde_as(as = "DisplayFromStr")]
741 pub epoch: EpochId,
742 #[schemars(with = "String")]
743 #[serde_as(as = "DisplayFromStr")]
744 pub storage_charge: u64,
745 #[schemars(with = "String")]
746 #[serde_as(as = "DisplayFromStr")]
747 pub computation_charge: u64,
748 #[schemars(with = "String")]
749 #[serde_as(as = "DisplayFromStr")]
750 pub computation_charge_burned: u64,
751 #[schemars(with = "String")]
752 #[serde_as(as = "DisplayFromStr")]
753 pub storage_rebate: u64,
754 #[schemars(with = "String")]
755 #[serde_as(as = "DisplayFromStr")]
756 pub epoch_start_timestamp_ms: u64,
757 #[schemars(with = "Option<Vec<String>>")]
758 #[serde_as(as = "Option<Vec<DisplayFromStr>>")]
759 #[serde(skip_serializing_if = "Option::is_none", default)]
760 pub eligible_active_validators: Option<Vec<u64>>,
761 #[schemars(with = "Option<Vec<String>>")]
762 #[serde_as(as = "Option<Vec<DisplayFromStr>>")]
763 #[serde(skip_serializing_if = "Option::is_none", default)]
764 pub scores: Option<Vec<u64>>,
765}
766
767impl From<ChangeEpochV2> for IotaChangeEpochV2 {
768 fn from(e: ChangeEpochV2) -> Self {
769 Self {
770 epoch: e.epoch,
771 storage_charge: e.storage_charge,
772 computation_charge: e.computation_charge,
773 computation_charge_burned: e.computation_charge_burned,
774 storage_rebate: e.storage_rebate,
775 epoch_start_timestamp_ms: e.epoch_start_timestamp_ms,
776 eligible_active_validators: None,
777 scores: None,
778 }
779 }
780}
781
782impl From<ChangeEpochV3> for IotaChangeEpochV2 {
783 fn from(e: ChangeEpochV3) -> Self {
784 Self {
785 epoch: e.epoch,
786 storage_charge: e.storage_charge,
787 computation_charge: e.computation_charge,
788 computation_charge_burned: e.computation_charge_burned,
789 storage_rebate: e.storage_rebate,
790 epoch_start_timestamp_ms: e.epoch_start_timestamp_ms,
791 eligible_active_validators: Some(e.eligible_active_validators),
792 scores: None,
793 }
794 }
795}
796
797impl From<ChangeEpochV4> for IotaChangeEpochV2 {
798 fn from(e: ChangeEpochV4) -> Self {
799 Self {
800 epoch: e.epoch,
801 storage_charge: e.storage_charge,
802 computation_charge: e.computation_charge,
803 computation_charge_burned: e.computation_charge_burned,
804 storage_rebate: e.storage_rebate,
805 epoch_start_timestamp_ms: e.epoch_start_timestamp_ms,
806 eligible_active_validators: Some(e.eligible_active_validators),
807 scores: Some(e.scores),
808 }
809 }
810}
811
812#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, PartialEq, Eq)]
813#[enum_dispatch(IotaTransactionBlockEffectsAPI)]
814#[serde(
815 rename = "TransactionBlockEffects",
816 rename_all = "camelCase",
817 tag = "messageVersion"
818)]
819pub enum IotaTransactionBlockEffects {
820 V1(IotaTransactionBlockEffectsV1),
821}
822
823#[enum_dispatch]
824pub trait IotaTransactionBlockEffectsAPI {
825 fn status(&self) -> &IotaExecutionStatus;
826 fn into_status(self) -> IotaExecutionStatus;
827 fn shared_objects(&self) -> &[ObjectReference];
828 fn created(&self) -> &[OwnedObjectRef];
829 fn mutated(&self) -> &[OwnedObjectRef];
830 fn unwrapped(&self) -> &[OwnedObjectRef];
831 fn deleted(&self) -> &[ObjectReference];
832 fn unwrapped_then_deleted(&self) -> &[ObjectReference];
833 fn wrapped(&self) -> &[ObjectReference];
834 fn gas_object(&self) -> &OwnedObjectRef;
835 fn events_digest(&self) -> Option<&TransactionEventsDigest>;
836 fn dependencies(&self) -> &[TransactionDigest];
837 fn executed_epoch(&self) -> EpochId;
838 fn transaction_digest(&self) -> &TransactionDigest;
839 fn gas_cost_summary(&self) -> &GasCostSummary;
840
841 fn mutated_excluding_gas(&self) -> Vec<OwnedObjectRef>;
843 fn modified_at_versions(&self) -> Vec<(ObjectId, Version)>;
844 fn all_changed_objects(&self) -> Vec<(&OwnedObjectRef, WriteKind)>;
845 fn all_deleted_objects(&self) -> Vec<(&ObjectReference, DeleteKind)>;
846}
847
848#[serde_as]
849#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, JsonSchema)]
850#[serde(
851 rename = "TransactionBlockEffectsModifiedAtVersions",
852 rename_all = "camelCase"
853)]
854pub struct IotaTransactionBlockEffectsModifiedAtVersions {
855 #[serde_as(as = "ObjectIdSchema")]
856 #[schemars(with = "ObjectIdSchema")]
857 object_id: ObjectId,
858 #[schemars(with = "SequenceNumberStringSchema")]
859 #[serde_as(as = "SequenceNumberStringSchema")]
860 sequence_number: Version,
861}
862
863#[serde_as]
865#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, JsonSchema)]
866#[serde(rename = "TransactionBlockEffectsV1", rename_all = "camelCase")]
867pub struct IotaTransactionBlockEffectsV1 {
868 pub status: IotaExecutionStatus,
870 #[schemars(with = "String")]
872 #[serde_as(as = "DisplayFromStr")]
873 pub executed_epoch: EpochId,
874 #[schemars(with = "IotaGasCostSummary")]
875 #[serde_as(as = "IotaGasCostSummary")]
876 pub gas_used: GasCostSummary,
877 #[serde(default, skip_serializing_if = "Vec::is_empty")]
880 pub modified_at_versions: Vec<IotaTransactionBlockEffectsModifiedAtVersions>,
881 #[serde(default, skip_serializing_if = "Vec::is_empty")]
884 #[schemars(with = "Vec<ObjectRefSchema>")]
885 #[serde_as(as = "Vec<ObjectRefSchema>")]
886 pub shared_objects: Vec<ObjectReference>,
887 #[serde_as(as = "Base58Schema")]
889 #[schemars(with = "Base58Schema")]
890 pub transaction_digest: TransactionDigest,
891 #[serde(default, skip_serializing_if = "Vec::is_empty")]
893 pub created: Vec<OwnedObjectRef>,
894 #[serde(default, skip_serializing_if = "Vec::is_empty")]
896 pub mutated: Vec<OwnedObjectRef>,
897 #[serde(default, skip_serializing_if = "Vec::is_empty")]
901 pub unwrapped: Vec<OwnedObjectRef>,
902 #[serde(default, skip_serializing_if = "Vec::is_empty")]
904 #[schemars(with = "Vec<ObjectRefSchema>")]
905 #[serde_as(as = "Vec<ObjectRefSchema>")]
906 pub deleted: Vec<ObjectReference>,
907 #[serde(default, skip_serializing_if = "Vec::is_empty")]
910 #[schemars(with = "Vec<ObjectRefSchema>")]
911 #[serde_as(as = "Vec<ObjectRefSchema>")]
912 pub unwrapped_then_deleted: Vec<ObjectReference>,
913 #[serde(default, skip_serializing_if = "Vec::is_empty")]
915 #[schemars(with = "Vec<ObjectRefSchema>")]
916 #[serde_as(as = "Vec<ObjectRefSchema>")]
917 pub wrapped: Vec<ObjectReference>,
918 pub gas_object: OwnedObjectRef,
921 #[serde(skip_serializing_if = "Option::is_none")]
924 #[serde_as(as = "Option<Base58Schema>")]
925 #[schemars(with = "Option<Base58Schema>")]
926 pub events_digest: Option<TransactionEventsDigest>,
927 #[serde(default, skip_serializing_if = "Vec::is_empty")]
929 #[serde_as(as = "Vec<Base58Schema>")]
930 #[schemars(with = "Vec<Base58Schema>")]
931 pub dependencies: Vec<TransactionDigest>,
932}
933
934impl IotaTransactionBlockEffectsAPI for IotaTransactionBlockEffectsV1 {
935 fn status(&self) -> &IotaExecutionStatus {
936 &self.status
937 }
938 fn into_status(self) -> IotaExecutionStatus {
939 self.status
940 }
941 fn shared_objects(&self) -> &[ObjectReference] {
942 &self.shared_objects
943 }
944 fn created(&self) -> &[OwnedObjectRef] {
945 &self.created
946 }
947 fn mutated(&self) -> &[OwnedObjectRef] {
948 &self.mutated
949 }
950 fn unwrapped(&self) -> &[OwnedObjectRef] {
951 &self.unwrapped
952 }
953 fn deleted(&self) -> &[ObjectReference] {
954 &self.deleted
955 }
956 fn unwrapped_then_deleted(&self) -> &[ObjectReference] {
957 &self.unwrapped_then_deleted
958 }
959 fn wrapped(&self) -> &[ObjectReference] {
960 &self.wrapped
961 }
962 fn gas_object(&self) -> &OwnedObjectRef {
963 &self.gas_object
964 }
965 fn events_digest(&self) -> Option<&TransactionEventsDigest> {
966 self.events_digest.as_ref()
967 }
968 fn dependencies(&self) -> &[TransactionDigest] {
969 &self.dependencies
970 }
971
972 fn executed_epoch(&self) -> EpochId {
973 self.executed_epoch
974 }
975
976 fn transaction_digest(&self) -> &TransactionDigest {
977 &self.transaction_digest
978 }
979
980 fn gas_cost_summary(&self) -> &GasCostSummary {
981 &self.gas_used
982 }
983
984 fn mutated_excluding_gas(&self) -> Vec<OwnedObjectRef> {
985 self.mutated
986 .iter()
987 .filter(|o| *o != &self.gas_object)
988 .cloned()
989 .collect()
990 }
991
992 fn modified_at_versions(&self) -> Vec<(ObjectId, Version)> {
993 self.modified_at_versions
994 .iter()
995 .map(|v| (v.object_id, v.sequence_number))
996 .collect::<Vec<_>>()
997 }
998
999 fn all_changed_objects(&self) -> Vec<(&OwnedObjectRef, WriteKind)> {
1000 self.mutated
1001 .iter()
1002 .map(|owner_ref| (owner_ref, WriteKind::Mutate))
1003 .chain(
1004 self.created
1005 .iter()
1006 .map(|owner_ref| (owner_ref, WriteKind::Create)),
1007 )
1008 .chain(
1009 self.unwrapped
1010 .iter()
1011 .map(|owner_ref| (owner_ref, WriteKind::Unwrap)),
1012 )
1013 .collect()
1014 }
1015
1016 fn all_deleted_objects(&self) -> Vec<(&ObjectReference, DeleteKind)> {
1017 self.deleted
1018 .iter()
1019 .map(|r| (r, DeleteKind::Normal))
1020 .chain(
1021 self.unwrapped_then_deleted
1022 .iter()
1023 .map(|r| (r, DeleteKind::UnwrapThenDelete)),
1024 )
1025 .chain(self.wrapped.iter().map(|r| (r, DeleteKind::Wrap)))
1026 .collect()
1027 }
1028}
1029
1030impl IotaTransactionBlockEffects {
1031 pub fn new_for_testing(
1032 transaction_digest: TransactionDigest,
1033 status: IotaExecutionStatus,
1034 ) -> Self {
1035 Self::V1(IotaTransactionBlockEffectsV1 {
1036 transaction_digest,
1037 status,
1038 gas_object: OwnedObjectRef {
1039 owner: Owner::Address(Address::random()),
1040 reference: iota_types::base_types::random_object_ref(),
1041 },
1042 executed_epoch: 0,
1043 modified_at_versions: vec![],
1044 gas_used: GasCostSummary::default(),
1045 shared_objects: vec![],
1046 created: vec![],
1047 mutated: vec![],
1048 unwrapped: vec![],
1049 deleted: vec![],
1050 unwrapped_then_deleted: vec![],
1051 wrapped: vec![],
1052 events_digest: None,
1053 dependencies: vec![],
1054 })
1055 }
1056
1057 pub async fn from_native_with_clever_error<S: PackageStore>(
1063 native: TransactionEffects,
1064 resolver: &Resolver<S>,
1065 ) -> Result<Self, anyhow::Error> {
1066 let clever_status =
1067 IotaExecutionStatus::from_native_with_clever_error(native.status().clone(), resolver)
1068 .await?;
1069 match native {
1070 TransactionEffects::V1(inner) => {
1071 let mut inner =
1072 IotaTransactionBlockEffectsV1::try_from(TransactionEffects::V1(inner))?;
1073 inner.status = clever_status;
1074 Ok(inner.into())
1075 }
1076 _ => Err(anyhow::anyhow!("unknown TransactionEffects variant")),
1077 }
1078 }
1079}
1080
1081impl TryFrom<TransactionEffects> for IotaTransactionBlockEffects {
1082 type Error = IotaError;
1083
1084 fn try_from(native: TransactionEffects) -> Result<Self, Self::Error> {
1085 let effects = IotaTransactionBlockEffectsV1::try_from(native)
1086 .map_err(|e| IotaError::Unknown(e.to_string()))?;
1087 Ok(IotaTransactionBlockEffects::V1(effects))
1088 }
1089}
1090
1091impl TryFrom<TransactionEffects> for IotaTransactionBlockEffectsV1 {
1092 type Error = anyhow::Error;
1093
1094 fn try_from(native: TransactionEffects) -> Result<Self, Self::Error> {
1095 Ok(Self {
1096 status: native.status().clone().try_into()?,
1097 executed_epoch: native.epoch(),
1098 modified_at_versions: native
1099 .modified_at_versions()
1100 .into_iter()
1101 .map(|modified| IotaTransactionBlockEffectsModifiedAtVersions {
1102 object_id: *modified.object_id(),
1103 sequence_number: modified.version(),
1104 })
1105 .collect(),
1106 gas_used: native.gas_cost_summary().clone(),
1107 shared_objects: native
1108 .input_shared_objects()
1109 .into_iter()
1110 .map(|shared| shared.object_reference())
1111 .collect(),
1112 transaction_digest: *native.transaction_digest(),
1113 created: to_owned_ref(native.created()),
1114 mutated: to_owned_ref(native.mutated().to_vec()),
1115 unwrapped: to_owned_ref(native.unwrapped().to_vec()),
1116 deleted: native.deleted().to_vec(),
1117 unwrapped_then_deleted: native.unwrapped_then_deleted().to_vec(),
1118 wrapped: native.wrapped().to_vec(),
1119 gas_object: OwnedObjectRef {
1120 owner: *native.gas_object().owner(),
1121 reference: *native.gas_object().reference(),
1122 },
1123 events_digest: native.events_digest().copied(),
1124 dependencies: native.dependencies().to_vec(),
1125 })
1126 }
1127}
1128
1129fn owned_objref_string(obj: &OwnedObjectRef) -> String {
1130 format!(
1131 " ┌──\n │ ID: {} \n │ Owner: {} \n │ Version: {} \n │ Digest: {}\n └──",
1132 obj.reference.object_id, obj.owner, obj.reference.version, obj.reference.digest
1133 )
1134}
1135
1136fn objref_string(obj: &ObjectReference) -> String {
1137 format!(
1138 " ┌──\n │ ID: {} \n │ Version: {} \n │ Digest: {}\n └──",
1139 obj.object_id, obj.version, obj.digest
1140 )
1141}
1142
1143impl Display for IotaTransactionBlockEffects {
1144 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1145 let mut builder = TableBuilder::default();
1146
1147 builder.push_record(vec![format!("Digest: {}", self.transaction_digest())]);
1148 builder.push_record(vec![format!("Status: {:?}", self.status())]);
1149 builder.push_record(vec![format!("Executed Epoch: {}", self.executed_epoch())]);
1150
1151 if !self.created().is_empty() {
1152 builder.push_record(vec!["\nCreated Objects: ".to_string()]);
1153
1154 for oref in self.created() {
1155 builder.push_record(vec![owned_objref_string(oref)]);
1156 }
1157 }
1158
1159 if !self.mutated().is_empty() {
1160 builder.push_record(vec!["Mutated Objects: ".to_string()]);
1161 for oref in self.mutated() {
1162 builder.push_record(vec![owned_objref_string(oref)]);
1163 }
1164 }
1165
1166 if !self.shared_objects().is_empty() {
1167 builder.push_record(vec!["Shared Objects: ".to_string()]);
1168 for oref in self.shared_objects() {
1169 builder.push_record(vec![objref_string(oref)]);
1170 }
1171 }
1172
1173 if !self.deleted().is_empty() {
1174 builder.push_record(vec!["Deleted Objects: ".to_string()]);
1175
1176 for oref in self.deleted() {
1177 builder.push_record(vec![objref_string(oref)]);
1178 }
1179 }
1180
1181 if !self.wrapped().is_empty() {
1182 builder.push_record(vec!["Wrapped Objects: ".to_string()]);
1183
1184 for oref in self.wrapped() {
1185 builder.push_record(vec![objref_string(oref)]);
1186 }
1187 }
1188
1189 if !self.unwrapped().is_empty() {
1190 builder.push_record(vec!["Unwrapped Objects: ".to_string()]);
1191 for oref in self.unwrapped() {
1192 builder.push_record(vec![owned_objref_string(oref)]);
1193 }
1194 }
1195
1196 builder.push_record(vec![format!(
1197 "Gas Object: \n{}",
1198 owned_objref_string(self.gas_object())
1199 )]);
1200
1201 let gas_cost_summary = self.gas_cost_summary();
1202 builder.push_record(vec![format!(
1203 "Gas Cost Summary:\n \
1204 Storage Cost: {} NANOS\n \
1205 Computation Cost: {} NANOS\n \
1206 Computation Cost Burned: {} NANOS\n \
1207 Storage Rebate: {} NANOS\n \
1208 Non-refundable Storage Fee: {} NANOS",
1209 gas_cost_summary.storage_cost,
1210 gas_cost_summary.computation_cost,
1211 gas_cost_summary.computation_cost_burned,
1212 gas_cost_summary.storage_rebate,
1213 gas_cost_summary.non_refundable_storage_fee,
1214 )]);
1215
1216 let dependencies = self.dependencies();
1217 if !dependencies.is_empty() {
1218 builder.push_record(vec!["\nTransaction Dependencies:".to_string()]);
1219 for dependency in dependencies {
1220 builder.push_record(vec![format!(" {dependency}")]);
1221 }
1222 }
1223
1224 let mut table = builder.build();
1225 table.with(TablePanel::header("Transaction Effects"));
1226 table.with(TableStyle::rounded().horizontals([HorizontalLine::new(
1227 1,
1228 TableStyle::modern().get_horizontal(),
1229 )]));
1230 write!(f, "{table}")
1231 }
1232}
1233
1234#[serde_as]
1235#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, JsonSchema)]
1236#[serde(rename_all = "camelCase")]
1237pub struct DryRunTransactionBlockResponse {
1238 pub effects: IotaTransactionBlockEffects,
1239 pub events: IotaTransactionBlockEvents,
1240 pub object_changes: Vec<ObjectChange>,
1241 pub balance_changes: Vec<BalanceChange>,
1242 pub input: IotaTransactionBlockData,
1243 #[serde(default, skip_serializing_if = "Option::is_none")]
1245 #[schemars(with = "Option<String>")]
1246 #[serde_as(as = "Option<DisplayFromStr>")]
1247 pub suggested_gas_price: Option<u64>,
1248 pub execution_error_source: Option<String>,
1249}
1250
1251#[derive(Eq, PartialEq, Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1252#[serde(rename = "TransactionBlockEvents", transparent)]
1253pub struct IotaTransactionBlockEvents {
1254 pub data: Vec<IotaEvent>,
1255}
1256
1257impl IotaTransactionBlockEvents {
1258 pub fn try_from(
1259 mut events: TransactionEvents,
1260 tx_digest: TransactionDigest,
1261 timestamp_ms: Option<u64>,
1262 resolver: &mut dyn LayoutResolver,
1263 ) -> IotaResult<Self> {
1264 Ok(Self {
1265 data: events
1266 .drain(..)
1267 .enumerate()
1268 .map(|(seq, event)| {
1269 let layout = resolver.get_annotated_layout(&event.struct_tag)?;
1270 IotaEvent::try_from(event, tx_digest, seq as u64, timestamp_ms, layout)
1271 })
1272 .collect::<Result<_, _>>()?,
1273 })
1274 }
1275
1276 pub fn try_from_using_module_resolver(
1279 mut events: TransactionEvents,
1280 tx_digest: TransactionDigest,
1281 timestamp_ms: Option<u64>,
1282 resolver: &impl GetModule,
1283 ) -> IotaResult<Self> {
1284 Ok(Self {
1285 data: events
1286 .drain(..)
1287 .enumerate()
1288 .map(|(seq, event)| {
1289 let layout = get_layout_from_struct_tag(event.struct_tag.clone(), resolver)?;
1290 IotaEvent::try_from(event, tx_digest, seq as u64, timestamp_ms, layout)
1291 })
1292 .collect::<Result<_, _>>()?,
1293 })
1294 }
1295}
1296
1297impl Display for IotaTransactionBlockEvents {
1298 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1299 if self.data.is_empty() {
1300 writeln!(f, "╭─────────────────────────────╮")?;
1301 writeln!(f, "│ No transaction block events │")?;
1302 writeln!(f, "╰─────────────────────────────╯")
1303 } else {
1304 let mut builder = TableBuilder::default();
1305
1306 for event in &self.data {
1307 builder.push_record(vec![format!("{event}")]);
1308 }
1309
1310 let mut table = builder.build();
1311 table.with(TablePanel::header("Transaction Block Events"));
1312 table.with(TableStyle::rounded().horizontals([HorizontalLine::new(
1313 1,
1314 TableStyle::modern().get_horizontal(),
1315 )]));
1316 write!(f, "{table}")
1317 }
1318 }
1319}
1320
1321#[serde_as]
1325#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)]
1326#[serde(rename = "DevInspectArgs", rename_all = "camelCase")]
1327pub struct DevInspectArgs {
1328 #[serde_as(as = "Option<AddressSchema>")]
1331 #[schemars(with = "Option<AddressSchema>")]
1332 pub gas_sponsor: Option<Address>,
1333 #[schemars(with = "Option<String>")]
1335 #[serde_as(as = "Option<DisplayFromStr>")]
1336 pub gas_budget: Option<u64>,
1337 #[schemars(with = "Option<Vec<ObjectRefSchema>>")]
1339 #[serde_as(as = "Option<Vec<ObjectRefSchema>>")]
1340 pub gas_objects: Option<Vec<ObjectReference>>,
1341 pub skip_checks: Option<bool>,
1343 pub show_raw_txn_data_and_effects: Option<bool>,
1345}
1346
1347#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1349#[serde(rename = "DevInspectResults", rename_all = "camelCase")]
1350pub struct DevInspectResults {
1351 pub effects: IotaTransactionBlockEffects,
1356 pub events: IotaTransactionBlockEvents,
1359 #[serde(skip_serializing_if = "Option::is_none")]
1362 pub results: Option<Vec<IotaExecutionResult>>,
1363 #[serde(skip_serializing_if = "Option::is_none")]
1365 pub error: Option<String>,
1366 #[serde(skip_serializing_if = "Vec::is_empty", default)]
1368 pub raw_txn_data: Vec<u8>,
1369 #[serde(skip_serializing_if = "Vec::is_empty", default)]
1371 pub raw_effects: Vec<u8>,
1372}
1373
1374#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1375#[serde(rename = "IotaExecutionResult", rename_all = "camelCase")]
1376pub struct IotaExecutionResult {
1377 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1380 #[schemars(with = "Vec<(IotaArgument, Vec<u8>, TypeTagSchema)>")]
1381 pub mutable_reference_outputs: Vec<(IotaArgument, Vec<u8>, IotaTypeTag)>,
1382 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1384 #[schemars(with = "Vec<(Vec<u8>, TypeTagSchema)>")]
1385 pub return_values: Vec<(Vec<u8>, IotaTypeTag)>,
1386}
1387
1388impl IotaExecutionResult {
1389 fn into_stream_return_value_layouts<S: PackageStore>(
1390 self,
1391 package_resolver: &Resolver<S>,
1392 ) -> impl Stream<Item = anyhow::Result<(Vec<u8>, MoveTypeLayout)>> + use<'_, S> {
1393 self.return_values
1394 .into_iter()
1395 .map(|(bytes, iota_type_tag)| async {
1396 let type_tag = TypeTag::try_from(iota_type_tag)?;
1397 let move_type_layout = package_resolver.type_layout(type_tag).await?;
1398 Ok((bytes, move_type_layout))
1399 })
1400 .collect::<FuturesOrdered<_>>()
1401 }
1402}
1403
1404#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1405pub enum IotaMoveViewCallResults {
1406 #[serde(rename = "executionError")]
1408 Error(String),
1409 #[serde(rename = "functionReturnValues")]
1411 Results(Vec<IotaMoveValue>),
1412}
1413
1414impl IotaMoveViewCallResults {
1415 pub async fn from_dev_inspect_results<S: PackageStore>(
1418 package_store: S,
1419 dev_inspect_results: DevInspectResults,
1420 ) -> anyhow::Result<Self> {
1421 if let Some(error) = dev_inspect_results.error {
1422 return Ok(Self::Error(error));
1423 }
1424 let Some(mut tx_execution_results) = dev_inspect_results.results else {
1425 return Ok(Self::Error("function call returned no values".into()));
1426 };
1427 let Some(execution_results) = tx_execution_results.pop() else {
1428 return Ok(Self::Error(
1429 "no results from move view function call".into(),
1430 ));
1431 };
1432 if !tx_execution_results.is_empty() {
1433 return Ok(Self::Error("multiple transactions executed".into()));
1434 }
1435 let mut move_call_results = Vec::with_capacity(execution_results.return_values.len());
1436 let package_resolver = Resolver::new(package_store);
1437 let mut execution_results =
1438 execution_results.into_stream_return_value_layouts(&package_resolver);
1439 while let Some(result) = execution_results.next().await {
1440 let (bytes, move_type_layout) = result?;
1441 let move_value = BoundedVisitor::deserialize_value(&bytes, &move_type_layout)?;
1442 move_call_results.push(IotaMoveValue::from(move_value));
1443 }
1444 Ok(Self::Results(move_call_results))
1445 }
1446
1447 pub fn into_return_values(self) -> Vec<IotaMoveValue> {
1448 match self {
1449 IotaMoveViewCallResults::Error(_) => Default::default(),
1450 IotaMoveViewCallResults::Results(values) => values,
1451 }
1452 }
1453
1454 pub fn error(&self) -> Option<&str> {
1455 match self {
1456 IotaMoveViewCallResults::Error(e) => Some(e.as_str()),
1457 IotaMoveViewCallResults::Results(_) => None,
1458 }
1459 }
1460}
1461
1462type ExecutionResult = (
1463 Vec<(Argument, Vec<u8>, TypeTag)>,
1465 Vec<(Vec<u8>, TypeTag)>,
1467);
1468
1469impl DevInspectResults {
1470 pub fn new(
1471 effects: TransactionEffects,
1472 events: TransactionEvents,
1473 return_values: Result<Vec<ExecutionResult>, ExecutionError>,
1474 raw_txn_data: Vec<u8>,
1475 raw_effects: Vec<u8>,
1476 resolver: &mut dyn LayoutResolver,
1477 ) -> IotaResult<Self> {
1478 let tx_digest = *effects.transaction_digest();
1479 let mut error = None;
1480 let mut results = None;
1481 match return_values {
1482 Err(e) => error = Some(e.to_string()),
1483 Ok(srvs) => {
1484 results = Some(
1485 srvs.into_iter()
1486 .map(|srv| {
1487 let (mutable_reference_outputs, return_values) = srv;
1488 let mutable_reference_outputs = mutable_reference_outputs
1489 .into_iter()
1490 .map(|(a, bytes, tag)| {
1491 Ok((IotaArgument::try_from(a)?, bytes, IotaTypeTag::from(tag)))
1492 })
1493 .collect::<Result<_, anyhow::Error>>()?;
1494 let return_values = return_values
1495 .into_iter()
1496 .map(|(bytes, tag)| (bytes, IotaTypeTag::from(tag)))
1497 .collect();
1498 Ok(IotaExecutionResult {
1499 mutable_reference_outputs,
1500 return_values,
1501 })
1502 })
1503 .collect::<Result<_, anyhow::Error>>()
1504 .map_err(|e| IotaError::Unknown(e.to_string()))?,
1505 )
1506 }
1507 };
1508 Ok(Self {
1509 effects: effects.try_into()?,
1510 events: IotaTransactionBlockEvents::try_from(events, tx_digest, None, resolver)?,
1511 results,
1512 error,
1513 raw_txn_data,
1514 raw_effects,
1515 })
1516 }
1517}
1518
1519#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, JsonSchema)]
1520pub enum IotaTransactionBlockBuilderMode {
1521 Commit,
1523 DevInspect,
1526}
1527
1528#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, JsonSchema)]
1529#[serde(rename = "ExecutionStatus", rename_all = "camelCase", tag = "status")]
1530pub enum IotaExecutionStatus {
1531 Success,
1533 Failure { error: String },
1535}
1536
1537impl IotaExecutionStatus {
1538 pub async fn from_native_with_clever_error<S: PackageStore>(
1544 native: ExecutionStatus,
1545 resolver: &Resolver<S>,
1546 ) -> Result<Self, anyhow::Error> {
1547 match native {
1548 ExecutionStatus::Failure {
1549 error,
1550 command: Some(mut command_index),
1551 } => {
1552 let error = 'error: {
1553 let ExecutionFailureStatus::MoveAbort { location, code } = &error else {
1554 break 'error error.to_string();
1555 };
1556 let fname_string = if let Some(fname) = &location.function_name {
1557 format!("::{fname}'")
1558 } else {
1559 "'".to_string()
1560 };
1561
1562 let module_id = ModuleId::new(
1563 AccountAddress::from(location.package.into_bytes()),
1564 identifier_sdk_to_core(&location.module),
1565 );
1566
1567 let Some(CleverError {
1568 module_id,
1569 source_line_number,
1570 error_info,
1571 error_code,
1572 }) = resolver
1573 .resolve_clever_error(module_id.clone(), *code)
1574 .await
1575 else {
1576 break 'error format!(
1577 "from '{}{fname_string} (instruction {}), abort code: {code}",
1578 module_id.to_canonical_display(true),
1579 location.instruction,
1580 );
1581 };
1582
1583 let error_code_str = match error_code {
1584 Some(code) => format!("(code = {code})"),
1585 None => String::new(),
1586 };
1587
1588 match error_info {
1589 ErrorConstants::Rendered {
1590 identifier,
1591 constant,
1592 } => {
1593 format!(
1594 "from '{}{fname_string} (line {source_line_number}), abort{error_code_str} '{identifier}': {constant}",
1595 module_id.to_canonical_display(true)
1596 )
1597 }
1598 ErrorConstants::Raw { identifier, bytes } => {
1599 let const_str = Base64::encode(bytes);
1600 format!(
1601 "from '{}{fname_string} (line {source_line_number}), abort{error_code_str} '{identifier}': {const_str}",
1602 module_id.to_canonical_display(true)
1603 )
1604 }
1605 ErrorConstants::None => {
1606 format!(
1607 "from '{}{fname_string} (line {source_line_number}){}",
1608 module_id.to_canonical_display(true),
1609 match error_code {
1610 Some(code) => format!(" abort(code = {code})"),
1611 None => String::new(),
1612 }
1613 )
1614 }
1615 }
1616 };
1617 command_index += 1;
1619 let suffix = match command_index % 10 {
1620 1 if command_index % 100 != 11 => "st",
1621 2 if command_index % 100 != 12 => "nd",
1622 3 if command_index % 100 != 13 => "rd",
1623 _ => "th",
1624 };
1625 Ok(IotaExecutionStatus::Failure {
1626 error: format!("Error in {command_index}{suffix} command, {error}"),
1627 })
1628 }
1629 _ => native.try_into(),
1630 }
1631 }
1632}
1633
1634impl Display for IotaExecutionStatus {
1635 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1636 match self {
1637 Self::Success => write!(f, "success"),
1638 Self::Failure { error } => write!(f, "failure due to {error}"),
1639 }
1640 }
1641}
1642
1643impl IotaExecutionStatus {
1644 pub fn is_ok(&self) -> bool {
1645 matches!(self, IotaExecutionStatus::Success)
1646 }
1647 pub fn is_err(&self) -> bool {
1648 matches!(self, IotaExecutionStatus::Failure { .. })
1649 }
1650}
1651
1652impl TryFrom<ExecutionStatus> for IotaExecutionStatus {
1653 type Error = anyhow::Error;
1654
1655 fn try_from(status: ExecutionStatus) -> Result<Self, Self::Error> {
1656 Ok(match status {
1657 ExecutionStatus::Success => Self::Success,
1658 ExecutionStatus::Failure {
1659 error,
1660 command: None,
1661 } => Self::Failure {
1662 error: error.to_string(),
1663 },
1664 ExecutionStatus::Failure {
1665 error,
1666 command: Some(idx),
1667 } => Self::Failure {
1668 error: format!("{error} in command {idx}"),
1669 },
1670 _ => anyhow::bail!("unknown ExecutionStatus variant"),
1671 })
1672 }
1673}
1674
1675fn to_owned_ref(owned_refs: Vec<OwnedObjectReference>) -> Vec<OwnedObjectRef> {
1676 owned_refs
1677 .into_iter()
1678 .map(|owned| OwnedObjectRef {
1679 owner: *owned.owner(),
1680 reference: *owned.reference(),
1681 })
1682 .collect()
1683}
1684
1685#[serde_as]
1686#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, PartialEq, Eq)]
1687#[serde(rename = "GasData", rename_all = "camelCase")]
1688pub struct IotaGasData {
1689 #[schemars(with = "Vec<ObjectRefSchema>")]
1690 #[serde_as(as = "Vec<ObjectRefSchema>")]
1691 pub payment: Vec<ObjectReference>,
1692 #[serde_as(as = "AddressSchema")]
1693 #[schemars(with = "AddressSchema")]
1694 pub owner: Address,
1695 #[schemars(with = "String")]
1696 #[serde_as(as = "DisplayFromStr")]
1697 pub price: u64,
1698 #[schemars(with = "String")]
1699 #[serde_as(as = "DisplayFromStr")]
1700 pub budget: u64,
1701}
1702
1703impl Display for IotaGasData {
1704 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1705 writeln!(f, "Gas Owner: {}", self.owner)?;
1706 writeln!(f, "Gas Budget: {} NANOS", self.budget)?;
1707 writeln!(f, "Gas Price: {} NANOS", self.price)?;
1708 writeln!(f, "Gas Payment:")?;
1709 for payment in &self.payment {
1710 write!(f, "{} ", objref_string(payment))?;
1711 }
1712 writeln!(f)
1713 }
1714}
1715
1716#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, PartialEq, Eq)]
1717#[enum_dispatch(IotaTransactionBlockDataAPI)]
1718#[serde(
1719 rename = "TransactionBlockData",
1720 rename_all = "camelCase",
1721 tag = "messageVersion"
1722)]
1723pub enum IotaTransactionBlockData {
1724 V1(IotaTransactionBlockDataV1),
1725}
1726
1727#[enum_dispatch]
1728pub trait IotaTransactionBlockDataAPI {
1729 fn transaction(&self) -> &IotaTransactionBlockKind;
1730 fn sender(&self) -> &Address;
1731 fn gas_data(&self) -> &IotaGasData;
1732}
1733
1734#[serde_as]
1735#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, PartialEq, Eq)]
1736#[serde(rename = "TransactionBlockDataV1", rename_all = "camelCase")]
1737pub struct IotaTransactionBlockDataV1 {
1738 pub transaction: IotaTransactionBlockKind,
1739 #[serde_as(as = "AddressSchema")]
1740 #[schemars(with = "AddressSchema")]
1741 pub sender: Address,
1742 pub gas_data: IotaGasData,
1743}
1744
1745impl IotaTransactionBlockDataAPI for IotaTransactionBlockDataV1 {
1746 fn transaction(&self) -> &IotaTransactionBlockKind {
1747 &self.transaction
1748 }
1749 fn sender(&self) -> &Address {
1750 &self.sender
1751 }
1752 fn gas_data(&self) -> &IotaGasData {
1753 &self.gas_data
1754 }
1755}
1756
1757impl IotaTransactionBlockData {
1758 pub fn move_calls(&self) -> Vec<&IotaProgrammableMoveCall> {
1759 match self {
1760 Self::V1(data) => match &data.transaction {
1761 IotaTransactionBlockKind::ProgrammableTransaction(pt) => pt
1762 .commands
1763 .iter()
1764 .filter_map(|command| match command {
1765 IotaCommand::MoveCall(c) => Some(&**c),
1766 _ => None,
1767 })
1768 .collect(),
1769 _ => vec![],
1770 },
1771 }
1772 }
1773
1774 fn try_from_inner(
1775 tx: Transaction,
1776 transaction: IotaTransactionBlockKind,
1777 ) -> Result<Self, anyhow::Error> {
1778 let message_version = tx.message_version();
1779 let sender = tx.sender();
1780 let gas_data = IotaGasData {
1781 payment: tx.gas().to_vec(),
1782 owner: tx.gas_owner(),
1783 price: tx.gas_price(),
1784 budget: tx.gas_budget(),
1785 };
1786
1787 match message_version {
1788 1 => Ok(IotaTransactionBlockData::V1(IotaTransactionBlockDataV1 {
1789 transaction,
1790 sender,
1791 gas_data,
1792 })),
1793 _ => Err(anyhow::anyhow!(
1794 "Support for Transaction version {message_version} not implemented"
1795 )),
1796 }
1797 }
1798
1799 pub fn try_from_with_module_cache(
1800 tx: Transaction,
1801 module_cache: &impl GetModule,
1802 tx_digest: TransactionDigest,
1803 ) -> Result<Self, anyhow::Error> {
1804 let transaction = IotaTransactionBlockKind::try_from_with_module_cache(
1805 tx.kind().clone(),
1806 module_cache,
1807 tx_digest,
1808 )?;
1809 Self::try_from_inner(tx, transaction)
1810 }
1811
1812 pub async fn try_from_with_package_resolver(
1813 tx: Transaction,
1814 package_resolver: &Resolver<impl PackageStore>,
1815 tx_digest: TransactionDigest,
1816 ) -> Result<Self, anyhow::Error> {
1817 let transaction = IotaTransactionBlockKind::try_from_with_package_resolver(
1818 tx.kind().clone(),
1819 package_resolver,
1820 tx_digest,
1821 )
1822 .await?;
1823 Self::try_from_inner(tx, transaction)
1824 }
1825}
1826
1827impl Display for IotaTransactionBlockData {
1828 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1829 match self {
1830 Self::V1(data) => {
1831 writeln!(f, "Sender: {}", data.sender)?;
1832 writeln!(f, "{}", self.gas_data())?;
1833 writeln!(f, "{}", data.transaction)
1834 }
1835 }
1836 }
1837}
1838
1839#[serde_as]
1840#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, PartialEq, Eq)]
1841#[serde(rename = "TransactionBlock", rename_all = "camelCase")]
1842pub struct IotaTransactionBlock {
1843 pub data: IotaTransactionBlockData,
1844 #[serde_as(as = "Vec<UserSignatureSchema>")]
1845 #[schemars(with = "Vec<UserSignatureSchema>")]
1846 pub tx_signatures: Vec<UserSignature>,
1847}
1848
1849impl IotaTransactionBlock {
1850 pub fn try_from(
1851 tx: SenderSignedTransaction,
1852 module_cache: &impl GetModule,
1853 tx_digest: TransactionDigest,
1854 ) -> Result<Self, anyhow::Error> {
1855 Ok(Self {
1856 data: IotaTransactionBlockData::try_from_with_module_cache(
1857 tx.transaction().clone(),
1858 module_cache,
1859 tx_digest,
1860 )?,
1861 tx_signatures: tx.signatures().to_vec(),
1862 })
1863 }
1864
1865 pub async fn try_from_with_package_resolver(
1869 tx: SenderSignedTransaction,
1870 package_resolver: &Resolver<impl PackageStore>,
1871 tx_digest: TransactionDigest,
1872 ) -> Result<Self, anyhow::Error> {
1873 Ok(Self {
1874 data: IotaTransactionBlockData::try_from_with_package_resolver(
1875 tx.transaction().clone(),
1876 package_resolver,
1877 tx_digest,
1878 )
1879 .await?,
1880 tx_signatures: tx.signatures().to_vec(),
1881 })
1882 }
1883}
1884
1885impl Display for IotaTransactionBlock {
1886 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1887 let mut builder = TableBuilder::default();
1888
1889 builder.push_record(vec![format!("{}", self.data)]);
1890 builder.push_record(vec!["Signatures:".to_string()]);
1891 for tx_sig in &self.tx_signatures {
1892 builder.push_record(vec![format!(
1893 " {}\n",
1894 match tx_sig {
1895 UserSignature::Simple(sig) =>
1896 Base64::from_bytes(sig.signature_bytes()).encoded(),
1897 _ => Base64::from_bytes(&tx_sig.to_bytes()).encoded(),
1901 }
1902 )]);
1903 }
1904
1905 let mut table = builder.build();
1906 table.with(TablePanel::header("Transaction Data"));
1907 table.with(TableStyle::rounded().horizontals([HorizontalLine::new(
1908 1,
1909 TableStyle::modern().get_horizontal(),
1910 )]));
1911 write!(f, "{table}")
1912 }
1913}
1914
1915#[serde_as]
1916#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
1917pub struct IotaGenesisTransaction {
1918 #[serde_as(as = "Vec<ObjectIdSchema>")]
1919 #[schemars(with = "Vec<ObjectIdSchema>")]
1920 pub objects: Vec<ObjectId>,
1921 #[schemars(with = "Vec<IotaEventID>")]
1922 pub events: Vec<EventID>,
1923}
1924
1925#[serde_as]
1926#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
1927pub struct IotaConsensusCommitPrologueV1 {
1928 #[schemars(with = "String")]
1929 #[serde_as(as = "DisplayFromStr")]
1930 pub epoch: u64,
1931 #[schemars(with = "String")]
1932 #[serde_as(as = "DisplayFromStr")]
1933 pub round: u64,
1934 #[schemars(with = "Option<String>")]
1935 #[serde_as(as = "Option<DisplayFromStr>")]
1936 pub sub_dag_index: Option<u64>,
1937 #[schemars(with = "String")]
1938 #[serde_as(as = "DisplayFromStr")]
1939 pub commit_timestamp_ms: u64,
1940 #[serde_as(as = "Base58Schema")]
1941 #[schemars(with = "Base58Schema")]
1942 pub consensus_commit_digest: ConsensusCommitDigest,
1943 pub consensus_determined_version_assignments: IotaConsensusDeterminedVersionAssignments,
1944}
1945
1946#[serde_as]
1949#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, JsonSchema)]
1950#[schemars(rename = "ConsensusDeterminedVersionAssignments")]
1951pub enum IotaConsensusDeterminedVersionAssignments {
1952 CancelledTransactions(
1954 #[serde_as(as = "Vec<(Base58Schema, Vec<(ObjectIdSchema, serde_with::Same)>)>")]
1955 #[schemars(with = "Vec<(Base58Schema, Vec<(ObjectIdSchema, SequenceNumberU64)>)>")]
1956 Vec<(TransactionDigest, Vec<(ObjectId, SequenceNumberU64)>)>,
1957 ),
1958}
1959
1960impl TryFrom<ConsensusDeterminedVersionAssignments> for IotaConsensusDeterminedVersionAssignments {
1961 type Error = anyhow::Error;
1962
1963 fn try_from(
1964 consensus_determined_version_assignments: ConsensusDeterminedVersionAssignments,
1965 ) -> Result<Self, Self::Error> {
1966 Ok(match consensus_determined_version_assignments {
1967 ConsensusDeterminedVersionAssignments::CanceledTransactions {
1968 canceled_transactions,
1969 } => IotaConsensusDeterminedVersionAssignments::CancelledTransactions(
1970 canceled_transactions
1971 .into_iter()
1972 .map(|cancelled| {
1973 (
1974 cancelled.digest,
1975 cancelled
1976 .version_assignments
1977 .into_iter()
1978 .map(|va| (va.object_id, va.version.into()))
1979 .collect(),
1980 )
1981 })
1982 .collect(),
1983 ),
1984 _ => anyhow::bail!("unknown ConsensusDeterminedVersionAssignments variant"),
1985 })
1986 }
1987}
1988
1989impl From<IotaConsensusDeterminedVersionAssignments> for ConsensusDeterminedVersionAssignments {
1990 fn from(
1991 iota_consensus_determined_version_assignments: IotaConsensusDeterminedVersionAssignments,
1992 ) -> Self {
1993 match iota_consensus_determined_version_assignments {
1994 IotaConsensusDeterminedVersionAssignments::CancelledTransactions(assignments) => {
1995 ConsensusDeterminedVersionAssignments::CanceledTransactions {
1996 canceled_transactions: assignments
1997 .into_iter()
1998 .map(|(digest, version_assignments)| CanceledTransaction {
1999 digest,
2000 version_assignments: version_assignments
2001 .into_iter()
2002 .map(|(object_id, version)| VersionAssignment {
2003 object_id,
2004 version: version.into(),
2005 })
2006 .collect(),
2007 })
2008 .collect(),
2009 }
2010 }
2011 }
2012 }
2013}
2014
2015#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
2017pub struct IotaClaimAccountTransaction {
2018 pub account_kind: IotaAccountClaimKind,
2020}
2021
2022#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
2024#[serde(tag = "type", rename_all = "camelCase")]
2025pub enum IotaAccountClaimKind {
2026 SmartAccount(IotaSmartAccountClaim),
2027}
2028
2029#[serde_as]
2031#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
2032pub struct IotaSmartAccountClaim {
2033 pub public_key_scheme: u8,
2036 #[serde_as(as = "Base64")]
2039 #[schemars(with = "Base64Schema")]
2040 pub public_key_raw_bytes: Vec<u8>,
2041}
2042
2043#[serde_as]
2044#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
2045pub struct IotaRandomnessStateUpdate {
2046 #[schemars(with = "String")]
2047 #[serde_as(as = "DisplayFromStr")]
2048 pub epoch: u64,
2049
2050 #[schemars(with = "String")]
2051 #[serde_as(as = "DisplayFromStr")]
2052 pub randomness_round: u64,
2053 pub random_bytes: Vec<u8>,
2054}
2055
2056#[serde_as]
2060#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
2061pub struct IotaTransactionDenyRulesUpdate {
2062 #[schemars(with = "String")]
2063 #[serde_as(as = "DisplayFromStr")]
2064 pub epoch: u64,
2065
2066 #[schemars(with = "String")]
2067 #[serde_as(as = "DisplayFromStr")]
2068 pub round: u64,
2069 #[schemars(with = "Vec<AddressSchema>")]
2070 #[serde_as(as = "Vec<AddressSchema>")]
2071 pub added_addresses: Vec<Address>,
2072 #[schemars(with = "Vec<AddressSchema>")]
2073 #[serde_as(as = "Vec<AddressSchema>")]
2074 pub removed_addresses: Vec<Address>,
2075 #[schemars(with = "Vec<ObjectIdSchema>")]
2076 #[serde_as(as = "Vec<ObjectIdSchema>")]
2077 pub added_objects: Vec<ObjectId>,
2078 #[schemars(with = "Vec<ObjectIdSchema>")]
2079 #[serde_as(as = "Vec<ObjectIdSchema>")]
2080 pub removed_objects: Vec<ObjectId>,
2081 #[schemars(with = "Vec<ObjectIdSchema>")]
2082 #[serde_as(as = "Vec<ObjectIdSchema>")]
2083 pub added_packages: Vec<ObjectId>,
2084 #[schemars(with = "Vec<ObjectIdSchema>")]
2085 #[serde_as(as = "Vec<ObjectIdSchema>")]
2086 pub removed_packages: Vec<ObjectId>,
2087 pub package_publish_disabled: bool,
2088 pub package_upgrade_disabled: bool,
2089 pub shared_object_disabled: bool,
2090 pub user_transaction_disabled: bool,
2091 pub receiving_objects_disabled: bool,
2092 pub move_authenticator_disabled: bool,
2093}
2094
2095#[serde_as]
2096#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
2097pub struct IotaEndOfEpochTransaction {
2098 pub transactions: Vec<IotaEndOfEpochTransactionKind>,
2099}
2100
2101#[serde_as]
2102#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
2103pub enum IotaEndOfEpochTransactionKind {
2104 ChangeEpoch(IotaChangeEpoch),
2105 ChangeEpochV2(IotaChangeEpochV2),
2106 TransactionDenyRulesCreate,
2107}
2108
2109#[serde_as]
2110#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, JsonSchema)]
2111#[serde(rename = "InputObjectKind")]
2112pub enum IotaInputObjectKind {
2113 MovePackage(
2115 #[serde_as(as = "ObjectIdSchema")]
2116 #[schemars(with = "ObjectIdSchema")]
2117 ObjectId,
2118 ),
2119 ImmOrOwnedMoveObject(
2121 #[schemars(with = "ObjectRefSchema")]
2122 #[serde_as(as = "ObjectRefSchema")]
2123 ObjectReference,
2124 ),
2125 SharedMoveObject {
2127 #[serde_as(as = "ObjectIdSchema")]
2128 #[schemars(with = "ObjectIdSchema")]
2129 id: ObjectId,
2130 #[schemars(with = "SequenceNumberStringSchema")]
2131 #[serde_as(as = "SequenceNumberStringSchema")]
2132 initial_shared_version: Version,
2133 #[serde(default = "default_shared_object_mutability")]
2134 mutable: bool,
2135 },
2136}
2137
2138#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
2141pub struct IotaProgrammableTransactionBlock {
2142 pub inputs: Vec<IotaCallArg>,
2144 #[serde(rename = "transactions")]
2145 pub commands: Vec<IotaCommand>,
2149}
2150
2151impl Display for IotaProgrammableTransactionBlock {
2152 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2153 let Self { inputs, commands } = self;
2154 writeln!(f, "Inputs: {inputs:?}")?;
2155 writeln!(f, "Commands: [")?;
2156 for c in commands {
2157 writeln!(f, " {c},")?;
2158 }
2159 writeln!(f, "]")
2160 }
2161}
2162
2163impl IotaProgrammableTransactionBlock {
2164 fn try_from_with_module_cache(
2165 value: ProgrammableTransaction,
2166 module_cache: &impl GetModule,
2167 ) -> Result<Self, anyhow::Error> {
2168 let ProgrammableTransaction { inputs, commands } = value;
2169 let input_types = Self::resolve_input_type(&inputs, &commands, module_cache);
2170 Ok(IotaProgrammableTransactionBlock {
2171 inputs: inputs
2172 .into_iter()
2173 .zip(input_types)
2174 .map(|(arg, layout)| IotaCallArg::try_from(arg, layout.as_ref()))
2175 .collect::<Result<_, _>>()?,
2176 commands: commands
2177 .into_iter()
2178 .map(IotaCommand::try_from)
2179 .collect::<Result<_, _>>()?,
2180 })
2181 }
2182
2183 async fn try_from_with_package_resolver(
2184 value: ProgrammableTransaction,
2185 package_resolver: &Resolver<impl PackageStore>,
2186 ) -> Result<Self, anyhow::Error> {
2187 let input_types = package_resolver
2190 .pure_input_layouts(&value)
2191 .await
2192 .unwrap_or_else(|e| {
2193 tracing::warn!("pure_input_layouts failed: {:?}", e);
2194 vec![None; value.inputs.len()]
2195 });
2196
2197 let ProgrammableTransaction { inputs, commands } = value;
2198 Ok(IotaProgrammableTransactionBlock {
2199 inputs: inputs
2200 .into_iter()
2201 .zip(input_types)
2202 .map(|(arg, layout)| IotaCallArg::try_from(arg, layout.as_ref()))
2203 .collect::<Result<_, _>>()?,
2204 commands: commands
2205 .into_iter()
2206 .map(IotaCommand::try_from)
2207 .collect::<Result<_, _>>()?,
2208 })
2209 }
2210
2211 fn resolve_input_type(
2212 inputs: &[CallArg],
2213 commands: &[Command],
2214 module_cache: &impl GetModule,
2215 ) -> Vec<Option<MoveTypeLayout>> {
2216 let mut result_types = vec![None; inputs.len()];
2217 for command in commands.iter() {
2218 match command {
2219 Command::MoveCall(cmd) => {
2220 let module = identifier_sdk_to_core(&cmd.module);
2221 let id = ModuleId::new(AccountAddress::new(cmd.package.into_bytes()), module);
2222 let Some(types) = get_signature_types(id, &cmd.function, module_cache) else {
2223 return result_types;
2224 };
2225 for (arg, type_) in cmd.arguments.iter().zip(types) {
2226 if let (&Argument::Input(i), Some(type_)) = (arg, type_) {
2227 if let Some(x) = result_types.get_mut(i as usize) {
2228 x.replace(type_);
2229 }
2230 }
2231 }
2232 }
2233 Command::SplitCoins(cmd) => {
2234 for arg in &cmd.amounts {
2235 if let &Argument::Input(i) = arg {
2236 if let Some(x) = result_types.get_mut(i as usize) {
2237 x.replace(MoveTypeLayout::U64);
2238 }
2239 }
2240 }
2241 }
2242 Command::TransferObjects(TransferObjects {
2243 address: Argument::Input(i),
2244 ..
2245 }) => {
2246 if let Some(x) = result_types.get_mut((*i) as usize) {
2247 x.replace(MoveTypeLayout::Address);
2248 }
2249 }
2250 _ => {}
2251 }
2252 }
2253 result_types
2254 }
2255}
2256
2257fn get_signature_types(
2258 id: ModuleId,
2259 function: &Identifier,
2260 module_cache: &impl GetModule,
2261) -> Option<Vec<Option<MoveTypeLayout>>> {
2262 use std::borrow::Borrow;
2263 if let Ok(Some(module)) = module_cache.get_module_by_id(&id) {
2264 let module: &CompiledModule = module.borrow();
2265 let func = module
2266 .function_handles
2267 .iter()
2268 .find(|f| module.identifier_at(f.name).as_str() == function.as_str())?;
2269 Some(
2270 module
2271 .signature_at(func.parameters)
2272 .0
2273 .iter()
2274 .map(|s| primitive_type(module, &[], s))
2275 .collect(),
2276 )
2277 } else {
2278 None
2279 }
2280}
2281
2282#[serde_as]
2284#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
2285#[serde(rename = "IotaTransaction")]
2286pub enum IotaCommand {
2287 MoveCall(Box<IotaProgrammableMoveCall>),
2289 TransferObjects(Vec<IotaArgument>, IotaArgument),
2294 SplitCoins(IotaArgument, Vec<IotaArgument>),
2297 MergeCoins(IotaArgument, Vec<IotaArgument>),
2300 Publish(
2303 #[serde_as(as = "Vec<ObjectIdSchema>")]
2304 #[schemars(with = "Vec<ObjectIdSchema>")]
2305 Vec<ObjectId>,
2306 ),
2307 Upgrade(
2309 #[serde_as(as = "Vec<ObjectIdSchema>")]
2310 #[schemars(with = "Vec<ObjectIdSchema>")]
2311 Vec<ObjectId>,
2312 #[serde_as(as = "ObjectIdSchema")]
2313 #[schemars(with = "ObjectIdSchema")]
2314 ObjectId,
2315 IotaArgument,
2316 ),
2317 MakeMoveVec(Option<String>, Vec<IotaArgument>),
2321}
2322
2323impl Display for IotaCommand {
2324 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2325 match self {
2326 Self::MoveCall(p) => {
2327 write!(f, "MoveCall({p})")
2328 }
2329 Self::MakeMoveVec(ty_opt, elems) => {
2330 write!(f, "MakeMoveVec(")?;
2331 if let Some(ty) = ty_opt {
2332 write!(f, "Some{ty}")?;
2333 } else {
2334 write!(f, "None")?;
2335 }
2336 write!(f, ",[")?;
2337 write_sep(f, elems, None, ",")?;
2338 write!(f, "])")
2339 }
2340 Self::TransferObjects(objs, addr) => {
2341 write!(f, "TransferObjects([")?;
2342 write_sep(f, objs, None, ",")?;
2343 write!(f, "],{addr})")
2344 }
2345 Self::SplitCoins(coin, amounts) => {
2346 write!(f, "SplitCoins({coin},")?;
2347 write_sep(f, amounts, None, ",")?;
2348 write!(f, ")")
2349 }
2350 Self::MergeCoins(target, coins) => {
2351 write!(f, "MergeCoins({target},")?;
2352 write_sep(f, coins, None, ",")?;
2353 write!(f, ")")
2354 }
2355 Self::Publish(deps) => {
2356 write!(f, "Publish(<modules>,")?;
2357 write_sep(f, deps, None, ",")?;
2358 write!(f, ")")
2359 }
2360 Self::Upgrade(deps, current_package_id, ticket) => {
2361 write!(f, "Upgrade(<modules>, {ticket},")?;
2362 write_sep(f, deps, None, ",")?;
2363 write!(f, ", {current_package_id}")?;
2364 write!(f, ")")
2365 }
2366 }
2367 }
2368}
2369
2370impl TryFrom<Command> for IotaCommand {
2371 type Error = anyhow::Error;
2372
2373 fn try_from(value: Command) -> Result<Self, Self::Error> {
2374 Ok(match value {
2375 Command::MoveCall(cmd) => IotaCommand::MoveCall(Box::new(cmd.try_into()?)),
2376 Command::TransferObjects(cmd) => IotaCommand::TransferObjects(
2377 cmd.objects
2378 .into_iter()
2379 .map(IotaArgument::try_from)
2380 .collect::<Result<_, _>>()?,
2381 cmd.address.try_into()?,
2382 ),
2383 Command::SplitCoins(cmd) => IotaCommand::SplitCoins(
2384 cmd.coin.try_into()?,
2385 cmd.amounts
2386 .into_iter()
2387 .map(IotaArgument::try_from)
2388 .collect::<Result<_, _>>()?,
2389 ),
2390 Command::MergeCoins(cmd) => IotaCommand::MergeCoins(
2391 cmd.coin.try_into()?,
2392 cmd.coins_to_merge
2393 .into_iter()
2394 .map(IotaArgument::try_from)
2395 .collect::<Result<_, _>>()?,
2396 ),
2397 Command::Publish(cmd) => IotaCommand::Publish(cmd.dependencies),
2398 Command::MakeMoveVector(cmd) => IotaCommand::MakeMoveVec(
2399 cmd.type_tag.map(|tag| tag.to_string()),
2400 cmd.elements
2401 .into_iter()
2402 .map(IotaArgument::try_from)
2403 .collect::<Result<_, _>>()?,
2404 ),
2405 Command::Upgrade(cmd) => IotaCommand::Upgrade(
2406 cmd.dependencies,
2407 cmd.package,
2408 IotaArgument::try_from(cmd.ticket)?,
2409 ),
2410 _ => anyhow::bail!("unknown Command variant"),
2411 })
2412 }
2413}
2414
2415#[derive(Debug, Copy, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
2417pub enum IotaArgument {
2418 GasCoin,
2421 Input(u16),
2424 Result(u16),
2427 NestedResult(u16, u16),
2431}
2432
2433impl Display for IotaArgument {
2434 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2435 match self {
2436 Self::GasCoin => write!(f, "GasCoin"),
2437 Self::Input(i) => write!(f, "Input({i})"),
2438 Self::Result(i) => write!(f, "Result({i})"),
2439 Self::NestedResult(i, j) => write!(f, "NestedResult({i},{j})"),
2440 }
2441 }
2442}
2443
2444impl TryFrom<Argument> for IotaArgument {
2445 type Error = anyhow::Error;
2446
2447 fn try_from(value: Argument) -> Result<Self, Self::Error> {
2448 Ok(match value {
2449 Argument::Gas => Self::GasCoin,
2450 Argument::Input(i) => Self::Input(i),
2451 Argument::Result(i) => Self::Result(i),
2452 Argument::NestedResult(i, j) => Self::NestedResult(i, j),
2453 _ => anyhow::bail!("unknown Argument variant"),
2454 })
2455 }
2456}
2457
2458#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
2459#[serde(untagged)]
2460pub enum PtbInput {
2461 PtbRef(IotaArgument),
2462 CallArg(IotaJsonValue),
2463}
2464
2465#[serde_as]
2468#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
2469pub struct IotaProgrammableMoveCall {
2470 #[serde_as(as = "ObjectIdSchema")]
2472 #[schemars(with = "ObjectIdSchema")]
2473 pub package: ObjectId,
2474 pub module: String,
2476 pub function: String,
2478 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2479 pub type_arguments: Vec<String>,
2481 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2482 pub arguments: Vec<IotaArgument>,
2484}
2485
2486pub(crate) fn write_sep<T: Display>(
2491 f: &mut Formatter<'_>,
2492 items: impl IntoIterator<Item = T>,
2493 delimiters: Option<(&str, &str)>,
2494 separator: &str,
2495) -> std::fmt::Result {
2496 let mut xs = items.into_iter();
2497 let Some(x) = xs.next() else {
2498 return Ok(());
2499 };
2500 if let Some((left, _)) = delimiters {
2501 write!(f, "{left}")?;
2502 }
2503 write!(f, "{x}")?;
2504 for x in xs {
2505 write!(f, "{separator}{x}")?;
2506 }
2507 if let Some((_, right)) = delimiters {
2508 write!(f, "{right}")?;
2509 }
2510 Ok(())
2511}
2512
2513impl Display for IotaProgrammableMoveCall {
2514 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2515 let Self {
2516 package,
2517 module,
2518 function,
2519 type_arguments,
2520 arguments,
2521 } = self;
2522 write!(f, "{package}::{module}::{function}")?;
2523 if !type_arguments.is_empty() {
2524 write!(f, "<")?;
2525 write_sep(f, type_arguments, None, ",")?;
2526 write!(f, ">")?;
2527 }
2528 write!(f, "(")?;
2529 write_sep(f, arguments, None, ",")?;
2530 write!(f, ")")
2531 }
2532}
2533
2534impl TryFrom<MoveCall> for IotaProgrammableMoveCall {
2535 type Error = anyhow::Error;
2536
2537 fn try_from(value: MoveCall) -> Result<Self, Self::Error> {
2538 let MoveCall {
2539 package,
2540 module,
2541 function,
2542 type_arguments,
2543 arguments,
2544 } = value;
2545 Ok(Self {
2546 package,
2547 module: module.to_string(),
2548 function: function.to_string(),
2549 type_arguments: type_arguments.into_iter().map(|t| t.to_string()).collect(),
2550 arguments: arguments
2551 .into_iter()
2552 .map(IotaArgument::try_from)
2553 .collect::<Result<_, _>>()?,
2554 })
2555 }
2556}
2557
2558const fn default_shared_object_mutability() -> bool {
2559 true
2560}
2561
2562impl From<InputObjectKind> for IotaInputObjectKind {
2563 fn from(input: InputObjectKind) -> Self {
2564 match input {
2565 InputObjectKind::MovePackage(id) => Self::MovePackage(id),
2566 InputObjectKind::ImmOrOwnedMoveObject(oref) => Self::ImmOrOwnedMoveObject(oref),
2567 InputObjectKind::SharedMoveObject {
2568 id,
2569 initial_shared_version,
2570 mutable,
2571 } => Self::SharedMoveObject {
2572 id,
2573 initial_shared_version,
2574 mutable,
2575 },
2576 }
2577 }
2578}
2579
2580#[derive(Debug, Serialize, Deserialize, Clone)]
2581#[serde(rename = "TypeTag", rename_all = "camelCase")]
2582pub struct IotaTypeTag(String);
2583
2584impl IotaTypeTag {
2585 pub fn new(tag: String) -> Self {
2586 Self(tag)
2587 }
2588}
2589
2590impl AsRef<str> for IotaTypeTag {
2591 fn as_ref(&self) -> &str {
2592 &self.0
2593 }
2594}
2595
2596impl TryFrom<IotaTypeTag> for TypeTag {
2597 type Error = anyhow::Error;
2598 fn try_from(tag: IotaTypeTag) -> Result<Self, Self::Error> {
2599 parse_iota_type_tag(&tag.0)
2600 }
2601}
2602
2603impl From<TypeTag> for IotaTypeTag {
2604 fn from(tag: TypeTag) -> Self {
2605 Self(format!("{tag}"))
2606 }
2607}
2608
2609#[derive(Serialize, Deserialize, JsonSchema)]
2610#[serde(rename_all = "camelCase")]
2611pub enum RPCTransactionRequestParams {
2612 TransferObjectRequestParams(TransferObjectParams),
2613 MoveCallRequestParams(MoveCallParams),
2614}
2615
2616#[serde_as]
2617#[derive(Serialize, Deserialize, JsonSchema)]
2618#[serde(rename_all = "camelCase")]
2619pub struct TransferObjectParams {
2620 #[serde_as(as = "AddressSchema")]
2621 #[schemars(with = "AddressSchema")]
2622 pub recipient: Address,
2623 #[serde_as(as = "ObjectIdSchema")]
2624 #[schemars(with = "ObjectIdSchema")]
2625 pub object_id: ObjectId,
2626}
2627
2628#[serde_as]
2629#[derive(Serialize, Deserialize, JsonSchema)]
2630#[serde(rename_all = "camelCase")]
2631pub struct MoveCallParams {
2632 #[serde_as(as = "ObjectIdSchema")]
2633 #[schemars(with = "ObjectIdSchema")]
2634 pub package_object_id: ObjectId,
2635 pub module: String,
2636 pub function: String,
2637 #[serde(default)]
2638 #[schemars(with = "Vec<TypeTagSchema>")]
2639 pub type_arguments: Vec<IotaTypeTag>,
2640 pub arguments: Vec<PtbInput>,
2641}
2642
2643#[serde_as]
2644#[derive(Serialize, Deserialize, Clone, JsonSchema)]
2645#[serde(rename_all = "camelCase")]
2646pub struct TransactionBlockBytes {
2647 #[schemars(with = "Base64Schema")]
2650 pub tx_bytes: Base64,
2651 #[schemars(with = "Vec<ObjectRefSchema>")]
2653 #[serde_as(as = "Vec<ObjectRefSchema>")]
2654 pub gas: Vec<ObjectReference>,
2655 pub input_objects: Vec<IotaInputObjectKind>,
2657}
2658
2659impl TransactionBlockBytes {
2660 pub fn from_data(tx: Transaction) -> Result<Self, anyhow::Error> {
2661 Ok(Self {
2662 tx_bytes: Base64::from_bytes(&tx.to_bcs()),
2663 gas: tx.gas().to_vec(),
2664 input_objects: tx
2665 .input_objects()?
2666 .into_iter()
2667 .map(IotaInputObjectKind::from)
2668 .collect(),
2669 })
2670 }
2671
2672 pub fn to_data(self) -> Result<Transaction, anyhow::Error> {
2673 bcs::from_bytes::<Transaction>(&self.tx_bytes.to_vec().map_err(|e| anyhow::anyhow!(e))?)
2674 .map_err(|e| anyhow::anyhow!(e))
2675 }
2676}
2677
2678#[serde_as]
2679#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, JsonSchema)]
2680#[serde(rename = "OwnedObjectRef")]
2681pub struct OwnedObjectRef {
2682 #[schemars(with = "OwnerSchema")]
2683 #[serde_as(as = "OwnerSchema")]
2684 pub owner: Owner,
2685 #[schemars(with = "ObjectRefSchema")]
2686 #[serde_as(as = "ObjectRefSchema")]
2687 pub reference: ObjectReference,
2688}
2689
2690impl OwnedObjectRef {
2691 pub fn object_id(&self) -> ObjectId {
2692 self.reference.object_id
2693 }
2694 pub fn version(&self) -> Version {
2695 self.reference.version
2696 }
2697}
2698
2699#[serde_as]
2700#[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize, JsonSchema)]
2701#[serde(tag = "type", rename_all = "camelCase")]
2702pub enum IotaCallArg {
2703 Object(IotaObjectArg),
2705 Pure(IotaPureValue),
2707 TransactionDependency {
2710 #[serde_as(as = "Base58Schema")]
2711 #[schemars(with = "Base58Schema")]
2712 digest: TransactionDigest,
2713 },
2714}
2715
2716impl IotaCallArg {
2717 pub fn try_from(
2718 value: CallArg,
2719 layout: Option<&MoveTypeLayout>,
2720 ) -> Result<Self, anyhow::Error> {
2721 Ok(match value {
2722 CallArg::Pure(p) => IotaCallArg::Pure(IotaPureValue {
2723 value_type: layout.map(|l| type_tag_core_to_sdk(&l.into())),
2724 value: IotaJsonValue::from_bcs_bytes(layout, &p)?,
2725 }),
2726 CallArg::ImmutableOrOwned(object_ref) => {
2727 IotaCallArg::Object(IotaObjectArg::ImmOrOwnedObject {
2728 object_id: object_ref.object_id,
2729 version: object_ref.version,
2730 digest: object_ref.digest,
2731 })
2732 }
2733 CallArg::Shared(SharedObjectReference {
2734 object_id: id,
2735 initial_shared_version,
2736 mutable,
2737 }) => IotaCallArg::Object(IotaObjectArg::SharedObject {
2738 object_id: id,
2739 initial_shared_version,
2740 mutable,
2741 }),
2742 CallArg::Receiving(object_ref) => IotaCallArg::Object(IotaObjectArg::Receiving {
2743 object_id: object_ref.object_id,
2744 version: object_ref.version,
2745 digest: object_ref.digest,
2746 }),
2747 CallArg::TransactionDependency(digest) => IotaCallArg::TransactionDependency { digest },
2748 _ => anyhow::bail!("unknown CallArg variant"),
2749 })
2750 }
2751
2752 pub fn pure(&self) -> Option<&IotaJsonValue> {
2753 match self {
2754 IotaCallArg::Pure(v) => Some(&v.value),
2755 _ => None,
2756 }
2757 }
2758
2759 pub fn object(&self) -> Option<&ObjectId> {
2760 match self {
2761 IotaCallArg::Object(IotaObjectArg::SharedObject { object_id, .. })
2762 | IotaCallArg::Object(IotaObjectArg::ImmOrOwnedObject { object_id, .. })
2763 | IotaCallArg::Object(IotaObjectArg::Receiving { object_id, .. }) => Some(object_id),
2764 _ => None,
2765 }
2766 }
2767}
2768
2769#[serde_as]
2770#[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize, JsonSchema)]
2771#[serde(rename_all = "camelCase")]
2772pub struct IotaPureValue {
2773 #[schemars(with = "Option<TypeTagSchema>")]
2774 #[serde_as(as = "Option<TypeTagSchema>")]
2775 value_type: Option<TypeTag>,
2776 value: IotaJsonValue,
2777}
2778
2779impl IotaPureValue {
2780 pub fn value(&self) -> IotaJsonValue {
2781 self.value.clone()
2782 }
2783
2784 pub fn value_type(&self) -> Option<TypeTag> {
2785 self.value_type.clone()
2786 }
2787}
2788
2789#[serde_as]
2790#[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize, JsonSchema)]
2791#[serde(tag = "objectType", rename_all = "camelCase")]
2792pub enum IotaObjectArg {
2793 #[serde(rename_all = "camelCase")]
2795 ImmOrOwnedObject {
2796 #[serde_as(as = "ObjectIdSchema")]
2797 #[schemars(with = "ObjectIdSchema")]
2798 object_id: ObjectId,
2799 #[schemars(with = "SequenceNumberStringSchema")]
2800 #[serde_as(as = "SequenceNumberStringSchema")]
2801 version: Version,
2802 #[serde_as(as = "Base58Schema")]
2803 #[schemars(with = "Base58Schema")]
2804 digest: ObjectDigest,
2805 },
2806 #[serde(rename_all = "camelCase")]
2810 SharedObject {
2811 #[serde_as(as = "ObjectIdSchema")]
2812 #[schemars(with = "ObjectIdSchema")]
2813 object_id: ObjectId,
2814 #[schemars(with = "SequenceNumberStringSchema")]
2815 #[serde_as(as = "SequenceNumberStringSchema")]
2816 initial_shared_version: Version,
2817 mutable: bool,
2818 },
2819 #[serde(rename_all = "camelCase")]
2821 Receiving {
2822 #[serde_as(as = "ObjectIdSchema")]
2823 #[schemars(with = "ObjectIdSchema")]
2824 object_id: ObjectId,
2825 #[schemars(with = "SequenceNumberStringSchema")]
2826 #[serde_as(as = "SequenceNumberStringSchema")]
2827 version: Version,
2828 #[serde_as(as = "Base58Schema")]
2829 #[schemars(with = "Base58Schema")]
2830 digest: ObjectDigest,
2831 },
2832}
2833
2834#[serde_as]
2835#[derive(Clone, Debug, JsonSchema, Serialize, Deserialize)]
2836pub enum TransactionFilter {
2837 Checkpoint(
2839 #[schemars(with = "String")]
2840 #[serde_as(as = "DisplayFromStr")]
2841 CheckpointSequenceNumber,
2842 ),
2843 MoveFunction {
2845 #[serde_as(as = "ObjectIdSchema")]
2846 #[schemars(with = "ObjectIdSchema")]
2847 package: ObjectId,
2848 module: Option<String>,
2849 function: Option<String>,
2850 },
2851 InputObject(
2853 #[serde_as(as = "ObjectIdSchema")]
2854 #[schemars(with = "ObjectIdSchema")]
2855 ObjectId,
2856 ),
2857 ChangedObject(
2860 #[serde_as(as = "ObjectIdSchema")]
2861 #[schemars(with = "ObjectIdSchema")]
2862 ObjectId,
2863 ),
2864 FromAddress(
2866 #[serde_as(as = "AddressSchema")]
2867 #[schemars(with = "AddressSchema")]
2868 Address,
2869 ),
2870 ToAddress(
2872 #[serde_as(as = "AddressSchema")]
2873 #[schemars(with = "AddressSchema")]
2874 Address,
2875 ),
2876 FromAndToAddress {
2878 #[serde_as(as = "AddressSchema")]
2879 #[schemars(with = "AddressSchema")]
2880 from: Address,
2881 #[serde_as(as = "AddressSchema")]
2882 #[schemars(with = "AddressSchema")]
2883 to: Address,
2884 },
2885 FromOrToAddress {
2887 #[serde_as(as = "AddressSchema")]
2888 #[schemars(with = "AddressSchema")]
2889 addr: Address,
2890 },
2891 TransactionKind(IotaTransactionKind),
2893 TransactionKindIn(Vec<IotaTransactionKind>),
2895}
2896
2897impl TransactionFilter {
2898 pub fn as_v2(&self) -> TransactionFilterV2 {
2899 match self {
2900 TransactionFilter::InputObject(o) => TransactionFilterV2::InputObject(*o),
2901 TransactionFilter::ChangedObject(o) => TransactionFilterV2::ChangedObject(*o),
2902 TransactionFilter::FromAddress(a) => TransactionFilterV2::FromAddress(*a),
2903 TransactionFilter::ToAddress(a) => TransactionFilterV2::ToAddress(*a),
2904 TransactionFilter::FromAndToAddress { from, to } => {
2905 TransactionFilterV2::FromAndToAddress {
2906 from: *from,
2907 to: *to,
2908 }
2909 }
2910 TransactionFilter::FromOrToAddress { addr } => {
2911 TransactionFilterV2::FromOrToAddress { addr: *addr }
2912 }
2913 TransactionFilter::MoveFunction {
2914 package,
2915 module,
2916 function,
2917 } => TransactionFilterV2::MoveFunction {
2918 package: *package,
2919 module: module.clone(),
2920 function: function.clone(),
2921 },
2922 TransactionFilter::TransactionKind(kind) => TransactionFilterV2::TransactionKind(*kind),
2923 TransactionFilter::TransactionKindIn(kinds) => {
2924 TransactionFilterV2::TransactionKindIn(kinds.clone())
2925 }
2926 TransactionFilter::Checkpoint(checkpoint) => {
2927 TransactionFilterV2::Checkpoint(*checkpoint)
2928 }
2929 }
2930 }
2931}
2932
2933#[serde_as]
2934#[derive(Clone, Debug, JsonSchema, Serialize, Deserialize)]
2935#[non_exhaustive]
2936pub enum TransactionFilterV2 {
2937 Checkpoint(
2939 #[schemars(with = "String")]
2940 #[serde_as(as = "DisplayFromStr")]
2941 CheckpointSequenceNumber,
2942 ),
2943 MoveFunction {
2945 #[serde_as(as = "ObjectIdSchema")]
2946 #[schemars(with = "ObjectIdSchema")]
2947 package: ObjectId,
2948 module: Option<String>,
2949 function: Option<String>,
2950 },
2951 InputObject(
2953 #[serde_as(as = "ObjectIdSchema")]
2954 #[schemars(with = "ObjectIdSchema")]
2955 ObjectId,
2956 ),
2957 ChangedObject(
2960 #[serde_as(as = "ObjectIdSchema")]
2961 #[schemars(with = "ObjectIdSchema")]
2962 ObjectId,
2963 ),
2964 WrappedOrDeletedObject(
2968 #[serde_as(as = "ObjectIdSchema")]
2969 #[schemars(with = "ObjectIdSchema")]
2970 ObjectId,
2971 ),
2972 FromAddress(
2974 #[serde_as(as = "AddressSchema")]
2975 #[schemars(with = "AddressSchema")]
2976 Address,
2977 ),
2978 ToAddress(
2980 #[serde_as(as = "AddressSchema")]
2981 #[schemars(with = "AddressSchema")]
2982 Address,
2983 ),
2984 FromAndToAddress {
2986 #[serde_as(as = "AddressSchema")]
2987 #[schemars(with = "AddressSchema")]
2988 from: Address,
2989 #[serde_as(as = "AddressSchema")]
2990 #[schemars(with = "AddressSchema")]
2991 to: Address,
2992 },
2993 FromOrToAddress {
2995 #[serde_as(as = "AddressSchema")]
2996 #[schemars(with = "AddressSchema")]
2997 addr: Address,
2998 },
2999 TransactionKind(IotaTransactionKind),
3001 TransactionKindIn(Vec<IotaTransactionKind>),
3003}
3004
3005impl TransactionFilterV2 {
3006 pub fn as_v1(&self) -> Option<TransactionFilter> {
3007 match self {
3008 TransactionFilterV2::InputObject(o) => Some(TransactionFilter::InputObject(*o)),
3009 TransactionFilterV2::ChangedObject(o) => Some(TransactionFilter::ChangedObject(*o)),
3010 TransactionFilterV2::FromAddress(a) => Some(TransactionFilter::FromAddress(*a)),
3011 TransactionFilterV2::ToAddress(a) => Some(TransactionFilter::ToAddress(*a)),
3012 TransactionFilterV2::FromAndToAddress { from, to } => {
3013 Some(TransactionFilter::FromAndToAddress {
3014 from: *from,
3015 to: *to,
3016 })
3017 }
3018 TransactionFilterV2::FromOrToAddress { addr } => {
3019 Some(TransactionFilter::FromOrToAddress { addr: *addr })
3020 }
3021 TransactionFilterV2::MoveFunction {
3022 package,
3023 module,
3024 function,
3025 } => Some(TransactionFilter::MoveFunction {
3026 package: *package,
3027 module: module.clone(),
3028 function: function.clone(),
3029 }),
3030 TransactionFilterV2::TransactionKind(kind) => {
3031 Some(TransactionFilter::TransactionKind(*kind))
3032 }
3033 TransactionFilterV2::TransactionKindIn(kinds) => {
3034 Some(TransactionFilter::TransactionKindIn(kinds.clone()))
3035 }
3036 TransactionFilterV2::Checkpoint(checkpoint) => {
3037 Some(TransactionFilter::Checkpoint(*checkpoint))
3038 }
3039 TransactionFilterV2::WrappedOrDeletedObject(_) => None,
3041 }
3042 }
3043}
3044
3045#[derive(
3049 Debug, Clone, Copy, PartialEq, Eq, EnumString, Display, Serialize, Deserialize, JsonSchema,
3050)]
3051#[non_exhaustive]
3052pub enum IotaTransactionKind {
3053 SystemTransaction = 0,
3056 ProgrammableTransaction = 1,
3057 Genesis = 2,
3058 ConsensusCommitPrologueV1 = 3,
3059 RandomnessStateUpdate = 5,
3060 EndOfEpochTransaction = 6,
3061 TransactionDenyRulesUpdate = 7,
3062 ClaimAccount = 8,
3063}
3064
3065impl IotaTransactionKind {
3066 pub const NON_SYSTEM_KINDS: [Self; 2] = [Self::ProgrammableTransaction, Self::ClaimAccount];
3068
3069 pub fn is_system_transaction(&self) -> bool {
3071 !Self::NON_SYSTEM_KINDS.contains(self)
3072 }
3073}
3074
3075impl TryFrom<&TransactionKind> for IotaTransactionKind {
3076 type Error = anyhow::Error;
3077
3078 fn try_from(kind: &TransactionKind) -> Result<Self, Self::Error> {
3079 Ok(match kind {
3080 TransactionKind::Genesis(_) => Self::Genesis,
3081 TransactionKind::ConsensusCommitPrologueV1(_) => Self::ConsensusCommitPrologueV1,
3082 #[allow(deprecated)]
3083 TransactionKind::AuthenticatorStateUpdateV1Deprecated => Self::SystemTransaction,
3084 TransactionKind::RandomnessStateUpdate(_) => Self::RandomnessStateUpdate,
3085 TransactionKind::TransactionDenyRulesUpdate(_) => Self::TransactionDenyRulesUpdate,
3086 TransactionKind::EndOfEpoch(_) => Self::EndOfEpochTransaction,
3087 TransactionKind::Programmable(_) => Self::ProgrammableTransaction,
3088 TransactionKind::ClaimAccount(_) => Self::ClaimAccount,
3089 _ => anyhow::bail!("unknown TransactionKind variant"),
3090 })
3091 }
3092}