1use std::{
6 cmp::Ordering,
7 collections::BTreeMap,
8 fmt,
9 fmt::{Display, Formatter, Write},
10};
11
12use anyhow::anyhow;
13use colored::Colorize;
14use fastcrypto::encoding::Base64;
15use iota_protocol_config::ProtocolConfig;
16use iota_types::{
17 base_types::{
18 IotaAddress, ObjectDigest, ObjectID, ObjectInfo, ObjectRef, ObjectType, SequenceNumber,
19 TransactionDigest,
20 },
21 error::{
22 ExecutionError, IotaError, IotaObjectResponseError, IotaResult, UserInputError,
23 UserInputResult,
24 },
25 gas_coin::GasCoin,
26 iota_serde::{BigInt, IotaStructTag, SequenceNumber as AsSequenceNumber},
27 messages_checkpoint::CheckpointSequenceNumber,
28 move_package::{MovePackage, TypeOrigin, UpgradeInfo},
29 object::{Data, MoveObject, Object, ObjectInner, ObjectRead, Owner},
30};
31use move_bytecode_utils::module_cache::GetModule;
32use move_core_types::{
33 annotated_value::{MoveStructLayout, MoveValue},
34 identifier::Identifier,
35 language_storage::StructTag,
36};
37use schemars::JsonSchema;
38use serde::{Deserialize, Serialize};
39use serde_json::Value;
40use serde_with::{DisplayFromStr, serde_as};
41
42use crate::{IotaMoveStruct, IotaMoveValue, Page};
43
44#[derive(Serialize, Deserialize, Debug, JsonSchema, Clone, PartialEq, Eq)]
45pub struct IotaObjectResponse {
46 #[serde(skip_serializing_if = "Option::is_none")]
47 pub data: Option<IotaObjectData>,
48 #[serde(skip_serializing_if = "Option::is_none")]
49 pub error: Option<IotaObjectResponseError>,
50}
51
52impl IotaObjectResponse {
53 pub fn new(data: Option<IotaObjectData>, error: Option<IotaObjectResponseError>) -> Self {
54 Self { data, error }
55 }
56
57 pub fn new_with_data(data: IotaObjectData) -> Self {
58 Self {
59 data: Some(data),
60 error: None,
61 }
62 }
63
64 pub fn new_with_error(error: IotaObjectResponseError) -> Self {
65 Self {
66 data: None,
67 error: Some(error),
68 }
69 }
70}
71
72impl Ord for IotaObjectResponse {
73 fn cmp(&self, other: &Self) -> Ordering {
74 match (&self.data, &other.data) {
75 (Some(data), Some(data_2)) => {
76 if data.object_id.cmp(&data_2.object_id).eq(&Ordering::Greater) {
77 return Ordering::Greater;
78 } else if data.object_id.cmp(&data_2.object_id).eq(&Ordering::Less) {
79 return Ordering::Less;
80 }
81 Ordering::Equal
82 }
83 (Some(_), None) => Ordering::Less,
86 (None, Some(_)) => Ordering::Greater,
87 _ => Ordering::Equal,
89 }
90 }
91}
92
93impl PartialOrd for IotaObjectResponse {
94 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
95 Some(self.cmp(other))
96 }
97}
98
99impl IotaObjectResponse {
100 pub fn move_object_bcs(&self) -> Option<&Vec<u8>> {
101 match &self.data {
102 Some(IotaObjectData {
103 bcs: Some(IotaRawData::MoveObject(obj)),
104 ..
105 }) => Some(&obj.bcs_bytes),
106 _ => None,
107 }
108 }
109
110 pub fn owner(&self) -> Option<Owner> {
111 if let Some(data) = &self.data {
112 return data.owner;
113 }
114 None
115 }
116
117 pub fn object_id(&self) -> Result<ObjectID, anyhow::Error> {
118 match (&self.data, &self.error) {
119 (Some(obj_data), None) => Ok(obj_data.object_id),
120 (None, Some(IotaObjectResponseError::NotExists { object_id })) => Ok(*object_id),
121 (
122 None,
123 Some(IotaObjectResponseError::Deleted {
124 object_id,
125 version: _,
126 digest: _,
127 }),
128 ) => Ok(*object_id),
129 _ => Err(anyhow!(
130 "Could not get object_id, something went wrong with IotaObjectResponse construction."
131 )),
132 }
133 }
134
135 pub fn object_ref_if_exists(&self) -> Option<ObjectRef> {
136 match (&self.data, &self.error) {
137 (Some(obj_data), None) => Some(obj_data.object_ref()),
138 _ => None,
139 }
140 }
141}
142
143impl TryFrom<IotaObjectResponse> for ObjectInfo {
144 type Error = anyhow::Error;
145
146 fn try_from(value: IotaObjectResponse) -> Result<Self, Self::Error> {
147 let IotaObjectData {
148 object_id,
149 version,
150 digest,
151 type_,
152 owner,
153 previous_transaction,
154 ..
155 } = value.into_object()?;
156
157 Ok(ObjectInfo {
158 object_id,
159 version,
160 digest,
161 type_: type_.ok_or_else(|| anyhow!("Object type not found for object."))?,
162 owner: owner.ok_or_else(|| anyhow!("Owner not found for object."))?,
163 previous_transaction: previous_transaction
164 .ok_or_else(|| anyhow!("Transaction digest not found for object."))?,
165 })
166 }
167}
168
169#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, Eq, PartialEq)]
170pub struct DisplayFieldsResponse {
171 pub data: Option<BTreeMap<String, String>>,
172 pub error: Option<IotaObjectResponseError>,
173}
174
175#[serde_as]
176#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, Eq, PartialEq)]
177#[serde(rename_all = "camelCase", rename = "ObjectData")]
178pub struct IotaObjectData {
179 pub object_id: ObjectID,
180 #[schemars(with = "AsSequenceNumber")]
182 #[serde_as(as = "AsSequenceNumber")]
183 pub version: SequenceNumber,
184 pub digest: ObjectDigest,
186 #[schemars(with = "Option<String>")]
189 #[serde_as(as = "Option<DisplayFromStr>")]
190 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
191 pub type_: Option<ObjectType>,
192 #[serde(skip_serializing_if = "Option::is_none")]
196 pub owner: Option<Owner>,
197 #[serde(skip_serializing_if = "Option::is_none")]
201 pub previous_transaction: Option<TransactionDigest>,
202 #[schemars(with = "Option<BigInt<u64>>")]
206 #[serde_as(as = "Option<BigInt<u64>>")]
207 #[serde(skip_serializing_if = "Option::is_none")]
208 pub storage_rebate: Option<u64>,
209 #[serde(skip_serializing_if = "Option::is_none")]
213 pub display: Option<DisplayFieldsResponse>,
214 #[serde(skip_serializing_if = "Option::is_none")]
217 pub content: Option<IotaParsedData>,
218 #[serde(skip_serializing_if = "Option::is_none")]
221 pub bcs: Option<IotaRawData>,
222}
223
224impl IotaObjectData {
225 pub fn new(
226 object_ref: ObjectRef,
227 obj: Object,
228 layout: impl Into<Option<MoveStructLayout>>,
229 options: IotaObjectDataOptions,
230 display_fields: impl Into<Option<DisplayFieldsResponse>>,
231 ) -> anyhow::Result<Self> {
232 let layout = layout.into();
233 let display_fields = display_fields.into();
234 let show_display = options.show_display;
235 let IotaObjectDataOptions {
236 show_type,
237 show_owner,
238 show_previous_transaction,
239 show_content,
240 show_bcs,
241 show_storage_rebate,
242 ..
243 } = options;
244
245 let (object_id, version, digest) = object_ref;
246 let type_ = if show_type {
247 Some(Into::<ObjectType>::into(&obj))
248 } else {
249 None
250 };
251
252 let bcs: Option<IotaRawData> = if show_bcs {
253 let data = match obj.data.clone() {
254 Data::Move(m) => {
255 let layout = layout.clone().ok_or_else(|| {
256 anyhow!("Layout is required to convert Move object to json")
257 })?;
258 IotaRawData::try_from_object(m, layout)?
259 }
260 Data::Package(p) => IotaRawData::try_from_package(p)
261 .map_err(|e| anyhow!("Error getting raw data from package: {e:#?}"))?,
262 };
263 Some(data)
264 } else {
265 None
266 };
267
268 let obj = obj.into_inner();
269
270 let content: Option<IotaParsedData> = if show_content {
271 let data = match obj.data {
272 Data::Move(m) => {
273 let layout = layout.ok_or_else(|| {
274 anyhow!("Layout is required to convert Move object to json")
275 })?;
276 IotaParsedData::try_from_object(m, layout)?
277 }
278 Data::Package(p) => IotaParsedData::try_from_package(p)?,
279 };
280 Some(data)
281 } else {
282 None
283 };
284
285 Ok(IotaObjectData {
286 object_id,
287 version,
288 digest,
289 type_,
290 owner: if show_owner { Some(obj.owner) } else { None },
291 storage_rebate: if show_storage_rebate {
292 Some(obj.storage_rebate)
293 } else {
294 None
295 },
296 previous_transaction: if show_previous_transaction {
297 Some(obj.previous_transaction)
298 } else {
299 None
300 },
301 content,
302 bcs,
303 display: if show_display { display_fields } else { None },
304 })
305 }
306
307 pub fn object_ref(&self) -> ObjectRef {
308 (self.object_id, self.version, self.digest)
309 }
310
311 pub fn object_type(&self) -> anyhow::Result<ObjectType> {
312 self.type_
313 .as_ref()
314 .ok_or_else(|| anyhow!("type is missing for object {:?}", self.object_id))
315 .cloned()
316 }
317
318 pub fn is_gas_coin(&self) -> bool {
319 match self.type_.as_ref() {
320 Some(ObjectType::Struct(ty)) if ty.is_gas_coin() => true,
321 Some(_) => false,
322 None => false,
323 }
324 }
325}
326
327impl Display for IotaObjectData {
328 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
329 let type_ = if let Some(type_) = &self.type_ {
330 type_.to_string()
331 } else {
332 "Unknown Type".into()
333 };
334 let mut writer = String::new();
335 writeln!(
336 writer,
337 "{}",
338 format!("----- {type_} ({}[{}]) -----", self.object_id, self.version).bold()
339 )?;
340 if let Some(owner) = self.owner {
341 writeln!(writer, "{}: {owner}", "Owner".bold().bright_black())?;
342 }
343
344 writeln!(
345 writer,
346 "{}: {}",
347 "Version".bold().bright_black(),
348 self.version
349 )?;
350 if let Some(storage_rebate) = self.storage_rebate {
351 writeln!(
352 writer,
353 "{}: {storage_rebate}",
354 "Storage Rebate".bold().bright_black(),
355 )?;
356 }
357
358 if let Some(previous_transaction) = self.previous_transaction {
359 writeln!(
360 writer,
361 "{}: {previous_transaction:?}",
362 "Previous Transaction".bold().bright_black(),
363 )?;
364 }
365 if let Some(content) = self.content.as_ref() {
366 writeln!(writer, "{}", "----- Data -----".bold())?;
367 write!(writer, "{content}")?;
368 }
369
370 write!(f, "{writer}")
371 }
372}
373
374impl TryFrom<&IotaObjectData> for GasCoin {
375 type Error = anyhow::Error;
376 fn try_from(object: &IotaObjectData) -> Result<Self, Self::Error> {
377 match &object
378 .content
379 .as_ref()
380 .ok_or_else(|| anyhow!("Expect object content to not be empty"))?
381 {
382 IotaParsedData::MoveObject(o) => {
383 if GasCoin::type_() == o.type_ {
384 return GasCoin::try_from(&o.fields);
385 }
386 }
387 IotaParsedData::Package(_) => {}
388 }
389
390 Err(anyhow!(
391 "Gas object type is not a gas coin: {:?}",
392 object.type_
393 ))
394 }
395}
396
397impl TryFrom<&IotaMoveStruct> for GasCoin {
398 type Error = anyhow::Error;
399 fn try_from(move_struct: &IotaMoveStruct) -> Result<Self, Self::Error> {
400 match move_struct {
401 IotaMoveStruct::WithFields(fields) | IotaMoveStruct::WithTypes { type_: _, fields } => {
402 if let Some(IotaMoveValue::String(balance)) = fields.get("balance") {
403 if let Ok(balance) = balance.parse::<u64>() {
404 if let Some(IotaMoveValue::UID { id }) = fields.get("id") {
405 return Ok(GasCoin::new(*id, balance));
406 }
407 }
408 }
409 }
410 _ => {}
411 }
412 Err(anyhow!("Struct is not a gas coin: {move_struct:?}"))
413 }
414}
415
416#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, Eq, PartialEq, Default)]
417#[serde(rename_all = "camelCase", rename = "ObjectDataOptions", default)]
418pub struct IotaObjectDataOptions {
419 pub show_type: bool,
421 pub show_owner: bool,
423 pub show_previous_transaction: bool,
426 pub show_display: bool,
429 pub show_content: bool,
432 pub show_bcs: bool,
434 pub show_storage_rebate: bool,
436}
437
438impl IotaObjectDataOptions {
439 pub fn new() -> Self {
440 Self::default()
441 }
442
443 pub fn bcs_lossless() -> Self {
445 Self {
446 show_bcs: true,
447 show_type: true,
448 show_owner: true,
449 show_previous_transaction: true,
450 show_display: false,
451 show_content: false,
452 show_storage_rebate: true,
453 }
454 }
455
456 pub fn full_content() -> Self {
458 Self {
459 show_bcs: false,
460 show_type: true,
461 show_owner: true,
462 show_previous_transaction: true,
463 show_display: false,
464 show_content: true,
465 show_storage_rebate: true,
466 }
467 }
468
469 pub fn with_content(mut self) -> Self {
470 self.show_content = true;
471 self
472 }
473
474 pub fn with_owner(mut self) -> Self {
475 self.show_owner = true;
476 self
477 }
478
479 pub fn with_type(mut self) -> Self {
480 self.show_type = true;
481 self
482 }
483
484 pub fn with_display(mut self) -> Self {
485 self.show_display = true;
486 self
487 }
488
489 pub fn with_bcs(mut self) -> Self {
490 self.show_bcs = true;
491 self
492 }
493
494 pub fn with_previous_transaction(mut self) -> Self {
495 self.show_previous_transaction = true;
496 self
497 }
498
499 pub fn is_not_in_object_info(&self) -> bool {
500 self.show_bcs || self.show_content || self.show_display || self.show_storage_rebate
501 }
502}
503
504impl TryFrom<(ObjectRead, IotaObjectDataOptions)> for IotaObjectResponse {
505 type Error = anyhow::Error;
506
507 fn try_from(
508 (object_read, options): (ObjectRead, IotaObjectDataOptions),
509 ) -> Result<Self, Self::Error> {
510 match object_read {
511 ObjectRead::NotExists(id) => Ok(IotaObjectResponse::new_with_error(
512 IotaObjectResponseError::NotExists { object_id: id },
513 )),
514 ObjectRead::Exists(object_ref, o, layout) => Ok(IotaObjectResponse::new_with_data(
515 IotaObjectData::new(object_ref, o, layout, options, None)?,
516 )),
517 ObjectRead::Deleted((object_id, version, digest)) => Ok(
518 IotaObjectResponse::new_with_error(IotaObjectResponseError::Deleted {
519 object_id,
520 version,
521 digest,
522 }),
523 ),
524 }
525 }
526}
527
528impl TryFrom<(ObjectInfo, IotaObjectDataOptions)> for IotaObjectResponse {
529 type Error = anyhow::Error;
530
531 fn try_from(
532 (object_info, options): (ObjectInfo, IotaObjectDataOptions),
533 ) -> Result<Self, Self::Error> {
534 let IotaObjectDataOptions {
535 show_type,
536 show_owner,
537 show_previous_transaction,
538 ..
539 } = options;
540
541 Ok(Self::new_with_data(IotaObjectData {
542 object_id: object_info.object_id,
543 version: object_info.version,
544 digest: object_info.digest,
545 type_: show_type.then_some(object_info.type_),
546 owner: show_owner.then_some(object_info.owner),
547 previous_transaction: show_previous_transaction
548 .then_some(object_info.previous_transaction),
549 storage_rebate: None,
550 display: None,
551 content: None,
552 bcs: None,
553 }))
554 }
555}
556
557impl IotaObjectResponse {
558 pub fn object(&self) -> Result<&IotaObjectData, IotaObjectResponseError> {
561 if let Some(data) = &self.data {
562 Ok(data)
563 } else if let Some(error) = &self.error {
564 Err(error.clone())
565 } else {
566 Err(IotaObjectResponseError::Unknown)
569 }
570 }
571
572 pub fn into_object(self) -> Result<IotaObjectData, IotaObjectResponseError> {
575 match self.object() {
576 Ok(data) => Ok(data.clone()),
577 Err(error) => Err(error),
578 }
579 }
580}
581
582impl TryInto<Object> for IotaObjectData {
583 type Error = anyhow::Error;
584
585 fn try_into(self) -> Result<Object, Self::Error> {
586 let protocol_config = ProtocolConfig::get_for_min_version();
587 let data = match self.bcs {
588 Some(IotaRawData::MoveObject(o)) => Data::Move({
589 MoveObject::new_from_execution(
590 o.type_().clone().into(),
591 o.version,
592 o.bcs_bytes,
593 &protocol_config,
594 )?
595 }),
596 Some(IotaRawData::Package(p)) => Data::Package(MovePackage::new(
597 p.id,
598 self.version,
599 p.module_map,
600 protocol_config.max_move_package_size(),
601 p.type_origin_table,
602 p.linkage_table,
603 )?),
604 _ => Err(anyhow!(
605 "BCS data is required to convert IotaObjectData to Object"
606 ))?,
607 };
608 Ok(ObjectInner {
609 data,
610 owner: self
611 .owner
612 .ok_or_else(|| anyhow!("Owner is required to convert IotaObjectData to Object"))?,
613 previous_transaction: self.previous_transaction.ok_or_else(|| {
614 anyhow!("previous_transaction is required to convert IotaObjectData to Object")
615 })?,
616 storage_rebate: self.storage_rebate.ok_or_else(|| {
617 anyhow!("storage_rebate is required to convert IotaObjectData to Object")
618 })?,
619 }
620 .into())
621 }
622}
623
624#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, Eq, PartialEq, Ord, PartialOrd)]
625#[serde(rename_all = "camelCase", rename = "ObjectRef")]
626pub struct IotaObjectRef {
627 pub object_id: ObjectID,
629 pub version: SequenceNumber,
631 pub digest: ObjectDigest,
633}
634
635impl IotaObjectRef {
636 pub fn to_object_ref(&self) -> ObjectRef {
637 (self.object_id, self.version, self.digest)
638 }
639}
640
641impl Display for IotaObjectRef {
642 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
643 write!(
644 f,
645 "Object ID: {}, version: {}, digest: {}",
646 self.object_id, self.version, self.digest
647 )
648 }
649}
650
651impl From<ObjectRef> for IotaObjectRef {
652 fn from(oref: ObjectRef) -> Self {
653 Self {
654 object_id: oref.0,
655 version: oref.1,
656 digest: oref.2,
657 }
658 }
659}
660
661pub trait IotaData: Sized {
662 type ObjectType;
663 type PackageType;
664 fn try_from_object(object: MoveObject, layout: MoveStructLayout)
665 -> Result<Self, anyhow::Error>;
666 fn try_from_package(package: MovePackage) -> Result<Self, anyhow::Error>;
667 fn try_as_move(&self) -> Option<&Self::ObjectType>;
668 fn try_into_move(self) -> Option<Self::ObjectType>;
669 fn try_as_package(&self) -> Option<&Self::PackageType>;
670 fn type_(&self) -> Option<&StructTag>;
671}
672
673#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Eq, PartialEq)]
674#[serde(tag = "dataType", rename_all = "camelCase", rename = "RawData")]
675pub enum IotaRawData {
676 MoveObject(IotaRawMoveObject),
678 Package(IotaRawMovePackage),
679}
680
681impl IotaData for IotaRawData {
682 type ObjectType = IotaRawMoveObject;
683 type PackageType = IotaRawMovePackage;
684
685 fn try_from_object(object: MoveObject, _: MoveStructLayout) -> Result<Self, anyhow::Error> {
686 Ok(Self::MoveObject(object.into()))
687 }
688
689 fn try_from_package(package: MovePackage) -> Result<Self, anyhow::Error> {
690 Ok(Self::Package(package.into()))
691 }
692
693 fn try_as_move(&self) -> Option<&Self::ObjectType> {
694 match self {
695 Self::MoveObject(o) => Some(o),
696 Self::Package(_) => None,
697 }
698 }
699
700 fn try_into_move(self) -> Option<Self::ObjectType> {
701 match self {
702 Self::MoveObject(o) => Some(o),
703 Self::Package(_) => None,
704 }
705 }
706
707 fn try_as_package(&self) -> Option<&Self::PackageType> {
708 match self {
709 Self::MoveObject(_) => None,
710 Self::Package(p) => Some(p),
711 }
712 }
713
714 fn type_(&self) -> Option<&StructTag> {
715 match self {
716 Self::MoveObject(o) => Some(&o.type_),
717 Self::Package(_) => None,
718 }
719 }
720}
721
722#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Eq, PartialEq)]
723#[serde(tag = "dataType", rename_all = "camelCase", rename = "Data")]
724pub enum IotaParsedData {
725 MoveObject(IotaParsedMoveObject),
727 Package(IotaMovePackage),
728}
729
730impl IotaData for IotaParsedData {
731 type ObjectType = IotaParsedMoveObject;
732 type PackageType = IotaMovePackage;
733
734 fn try_from_object(
735 object: MoveObject,
736 layout: MoveStructLayout,
737 ) -> Result<Self, anyhow::Error> {
738 Ok(Self::MoveObject(IotaParsedMoveObject::try_from_layout(
739 object, layout,
740 )?))
741 }
742
743 fn try_from_package(package: MovePackage) -> Result<Self, anyhow::Error> {
744 Ok(Self::Package(IotaMovePackage {
745 disassembled: package.disassemble()?,
746 }))
747 }
748
749 fn try_as_move(&self) -> Option<&Self::ObjectType> {
750 match self {
751 Self::MoveObject(o) => Some(o),
752 Self::Package(_) => None,
753 }
754 }
755
756 fn try_into_move(self) -> Option<Self::ObjectType> {
757 match self {
758 Self::MoveObject(o) => Some(o),
759 Self::Package(_) => None,
760 }
761 }
762
763 fn try_as_package(&self) -> Option<&Self::PackageType> {
764 match self {
765 Self::MoveObject(_) => None,
766 Self::Package(p) => Some(p),
767 }
768 }
769
770 fn type_(&self) -> Option<&StructTag> {
771 match self {
772 Self::MoveObject(o) => Some(&o.type_),
773 Self::Package(_) => None,
774 }
775 }
776}
777
778impl Display for IotaParsedData {
779 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
780 let mut writer = String::new();
781 match self {
782 IotaParsedData::MoveObject(o) => {
783 writeln!(writer, "{}: {}", "type".bold().bright_black(), o.type_)?;
784 write!(writer, "{}", &o.fields)?;
785 }
786 IotaParsedData::Package(p) => {
787 write!(
788 writer,
789 "{}: {:?}",
790 "Modules".bold().bright_black(),
791 p.disassembled.keys()
792 )?;
793 }
794 }
795 write!(f, "{writer}")
796 }
797}
798
799impl IotaParsedData {
800 pub fn try_from_object_read(object_read: ObjectRead) -> Result<Self, anyhow::Error> {
801 match object_read {
802 ObjectRead::NotExists(id) => Err(anyhow::anyhow!("Object {id} does not exist")),
803 ObjectRead::Exists(_object_ref, o, layout) => {
804 let data = match o.into_inner().data {
805 Data::Move(m) => {
806 let layout = layout.ok_or_else(|| {
807 anyhow!("Layout is required to convert Move object to json")
808 })?;
809 IotaParsedData::try_from_object(m, layout)?
810 }
811 Data::Package(p) => IotaParsedData::try_from_package(p)?,
812 };
813 Ok(data)
814 }
815 ObjectRead::Deleted((object_id, version, digest)) => Err(anyhow::anyhow!(
816 "Object {object_id} was deleted at version {version} with digest {digest}"
817 )),
818 }
819 }
820}
821
822pub trait IotaMoveObject: Sized {
823 fn try_from_layout(object: MoveObject, layout: MoveStructLayout)
824 -> Result<Self, anyhow::Error>;
825
826 fn try_from(o: MoveObject, resolver: &impl GetModule) -> Result<Self, anyhow::Error> {
827 let layout = o.get_layout(resolver)?;
828 Self::try_from_layout(o, layout)
829 }
830
831 fn type_(&self) -> &StructTag;
832}
833
834#[serde_as]
835#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Eq, PartialEq)]
836#[serde(rename = "MoveObject", rename_all = "camelCase")]
837pub struct IotaParsedMoveObject {
838 #[serde(rename = "type")]
839 #[serde_as(as = "IotaStructTag")]
840 #[schemars(with = "String")]
841 pub type_: StructTag,
842 pub fields: IotaMoveStruct,
843}
844
845impl IotaMoveObject for IotaParsedMoveObject {
846 fn try_from_layout(
847 object: MoveObject,
848 layout: MoveStructLayout,
849 ) -> Result<Self, anyhow::Error> {
850 let move_struct = object.to_move_struct(&layout)?.into();
851
852 Ok(
853 if let IotaMoveStruct::WithTypes { type_, fields } = move_struct {
854 IotaParsedMoveObject {
855 type_,
856 fields: IotaMoveStruct::WithFields(fields),
857 }
858 } else {
859 IotaParsedMoveObject {
860 type_: object.type_().clone().into(),
861 fields: move_struct,
862 }
863 },
864 )
865 }
866
867 fn type_(&self) -> &StructTag {
868 &self.type_
869 }
870}
871
872impl IotaParsedMoveObject {
873 pub fn try_from_object_read(object_read: ObjectRead) -> Result<Self, anyhow::Error> {
874 let parsed_data = IotaParsedData::try_from_object_read(object_read)?;
875 match parsed_data {
876 IotaParsedData::MoveObject(o) => Ok(o),
877 IotaParsedData::Package(_) => Err(anyhow::anyhow!("Object is not a Move object")),
878 }
879 }
880
881 pub fn read_dynamic_field_value(&self, field_name: &str) -> Option<IotaMoveValue> {
882 match &self.fields {
883 IotaMoveStruct::WithFields(fields) => fields.get(field_name).cloned(),
884 IotaMoveStruct::WithTypes { fields, .. } => fields.get(field_name).cloned(),
885 _ => None,
886 }
887 }
888}
889
890pub fn type_and_fields_from_move_event_data(
891 event_data: MoveValue,
892) -> IotaResult<(StructTag, serde_json::Value)> {
893 match event_data.into() {
894 IotaMoveValue::Struct(move_struct) => match &move_struct {
895 IotaMoveStruct::WithTypes { type_, .. } => {
896 Ok((type_.clone(), move_struct.clone().to_json_value()))
897 }
898 _ => Err(IotaError::ObjectDeserialization {
899 error: "Found non-type IotaMoveStruct in MoveValue event".to_string(),
900 }),
901 },
902 IotaMoveValue::Variant(v) => Ok((v.type_.clone(), v.clone().to_json_value())),
903 IotaMoveValue::Vector(_)
904 | IotaMoveValue::Number(_)
905 | IotaMoveValue::Bool(_)
906 | IotaMoveValue::Address(_)
907 | IotaMoveValue::String(_)
908 | IotaMoveValue::UID { .. }
909 | IotaMoveValue::Option(_) => Err(IotaError::ObjectDeserialization {
910 error: "Invalid MoveValue event type -- this should not be possible".to_string(),
911 }),
912 }
913}
914
915#[serde_as]
916#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Eq, PartialEq)]
917#[serde(rename = "RawMoveObject", rename_all = "camelCase")]
918pub struct IotaRawMoveObject {
919 #[schemars(with = "String")]
920 #[serde(rename = "type")]
921 #[serde_as(as = "IotaStructTag")]
922 pub type_: StructTag,
923 pub version: SequenceNumber,
924 #[serde_as(as = "Base64")]
925 #[schemars(with = "Base64")]
926 pub bcs_bytes: Vec<u8>,
927}
928
929impl From<MoveObject> for IotaRawMoveObject {
930 fn from(o: MoveObject) -> Self {
931 Self {
932 type_: o.type_().clone().into(),
933 version: o.version(),
934 bcs_bytes: o.into_contents(),
935 }
936 }
937}
938
939impl IotaMoveObject for IotaRawMoveObject {
940 fn try_from_layout(
941 object: MoveObject,
942 _layout: MoveStructLayout,
943 ) -> Result<Self, anyhow::Error> {
944 Ok(Self {
945 type_: object.type_().clone().into(),
946 version: object.version(),
947 bcs_bytes: object.into_contents(),
948 })
949 }
950
951 fn type_(&self) -> &StructTag {
952 &self.type_
953 }
954}
955
956impl IotaRawMoveObject {
957 pub fn deserialize<'a, T: Deserialize<'a>>(&'a self) -> Result<T, anyhow::Error> {
958 Ok(bcs::from_bytes(self.bcs_bytes.as_slice())?)
959 }
960}
961
962#[serde_as]
963#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Eq, PartialEq)]
964#[serde(rename = "RawMovePackage", rename_all = "camelCase")]
965pub struct IotaRawMovePackage {
966 pub id: ObjectID,
967 pub version: SequenceNumber,
968 #[schemars(with = "BTreeMap<String, Base64>")]
969 #[serde_as(as = "BTreeMap<_, Base64>")]
970 pub module_map: BTreeMap<String, Vec<u8>>,
971 pub type_origin_table: Vec<TypeOrigin>,
972 pub linkage_table: BTreeMap<ObjectID, UpgradeInfo>,
973}
974
975impl From<MovePackage> for IotaRawMovePackage {
976 fn from(p: MovePackage) -> Self {
977 Self {
978 id: p.id(),
979 version: p.version(),
980 module_map: p.serialized_module_map().clone(),
981 type_origin_table: p.type_origin_table().clone(),
982 linkage_table: p.linkage_table().clone(),
983 }
984 }
985}
986
987impl IotaRawMovePackage {
988 pub fn to_move_package(
989 &self,
990 max_move_package_size: u64,
991 ) -> Result<MovePackage, ExecutionError> {
992 MovePackage::new(
993 self.id,
994 self.version,
995 self.module_map.clone(),
996 max_move_package_size,
997 self.type_origin_table.clone(),
998 self.linkage_table.clone(),
999 )
1000 }
1001}
1002
1003#[derive(Serialize, Deserialize, Debug, JsonSchema, Clone, PartialEq, Eq)]
1004#[serde(tag = "status", content = "details", rename = "ObjectRead")]
1005pub enum IotaPastObjectResponse {
1006 VersionFound(IotaObjectData),
1008 ObjectNotExists(ObjectID),
1010 ObjectDeleted(IotaObjectRef),
1012 VersionNotFound(ObjectID, SequenceNumber),
1014 VersionTooHigh {
1016 object_id: ObjectID,
1017 asked_version: SequenceNumber,
1018 latest_version: SequenceNumber,
1019 },
1020}
1021
1022impl IotaPastObjectResponse {
1023 pub fn object(&self) -> UserInputResult<&IotaObjectData> {
1025 match &self {
1026 Self::ObjectDeleted(oref) => Err(UserInputError::ObjectDeleted {
1027 object_ref: oref.to_object_ref(),
1028 }),
1029 Self::ObjectNotExists(id) => Err(UserInputError::ObjectNotFound {
1030 object_id: *id,
1031 version: None,
1032 }),
1033 Self::VersionFound(o) => Ok(o),
1034 Self::VersionNotFound(id, seq_num) => Err(UserInputError::ObjectNotFound {
1035 object_id: *id,
1036 version: Some(*seq_num),
1037 }),
1038 Self::VersionTooHigh {
1039 object_id,
1040 asked_version,
1041 latest_version,
1042 } => Err(UserInputError::ObjectSequenceNumberTooHigh {
1043 object_id: *object_id,
1044 asked_version: *asked_version,
1045 latest_version: *latest_version,
1046 }),
1047 }
1048 }
1049
1050 pub fn into_object(self) -> UserInputResult<IotaObjectData> {
1052 match self {
1053 Self::ObjectDeleted(oref) => Err(UserInputError::ObjectDeleted {
1054 object_ref: oref.to_object_ref(),
1055 }),
1056 Self::ObjectNotExists(id) => Err(UserInputError::ObjectNotFound {
1057 object_id: id,
1058 version: None,
1059 }),
1060 Self::VersionFound(o) => Ok(o),
1061 Self::VersionNotFound(object_id, version) => Err(UserInputError::ObjectNotFound {
1062 object_id,
1063 version: Some(version),
1064 }),
1065 Self::VersionTooHigh {
1066 object_id,
1067 asked_version,
1068 latest_version,
1069 } => Err(UserInputError::ObjectSequenceNumberTooHigh {
1070 object_id,
1071 asked_version,
1072 latest_version,
1073 }),
1074 }
1075 }
1076}
1077
1078#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Eq, PartialEq)]
1079#[serde(rename = "MovePackage", rename_all = "camelCase")]
1080pub struct IotaMovePackage {
1081 pub disassembled: BTreeMap<String, Value>,
1082}
1083
1084pub type QueryObjectsPage = Page<IotaObjectResponse, CheckpointedObjectID>;
1085pub type ObjectsPage = Page<IotaObjectResponse, ObjectID>;
1086
1087#[serde_as]
1088#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Copy, Eq, PartialEq)]
1089#[serde(rename_all = "camelCase")]
1090pub struct CheckpointedObjectID {
1091 pub object_id: ObjectID,
1092 #[schemars(with = "Option<BigInt<u64>>")]
1093 #[serde_as(as = "Option<BigInt<u64>>")]
1094 #[serde(skip_serializing_if = "Option::is_none")]
1095 pub at_checkpoint: Option<CheckpointSequenceNumber>,
1096}
1097
1098#[serde_as]
1099#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Eq, PartialEq)]
1100#[serde(rename = "GetPastObjectRequest", rename_all = "camelCase")]
1101pub struct IotaGetPastObjectRequest {
1102 pub object_id: ObjectID,
1104 #[schemars(with = "AsSequenceNumber")]
1106 #[serde_as(as = "AsSequenceNumber")]
1107 pub version: SequenceNumber,
1108}
1109
1110#[serde_as]
1111#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1112pub enum IotaObjectDataFilter {
1113 MatchAll(Vec<IotaObjectDataFilter>),
1114 MatchAny(Vec<IotaObjectDataFilter>),
1115 MatchNone(Vec<IotaObjectDataFilter>),
1116 Package(ObjectID),
1118 MoveModule {
1120 package: ObjectID,
1122 #[schemars(with = "String")]
1124 #[serde_as(as = "DisplayFromStr")]
1125 module: Identifier,
1126 },
1127 StructType(
1129 #[schemars(with = "String")]
1130 #[serde_as(as = "IotaStructTag")]
1131 StructTag,
1132 ),
1133 AddressOwner(IotaAddress),
1134 ObjectOwner(ObjectID),
1135 ObjectId(ObjectID),
1136 ObjectIds(Vec<ObjectID>),
1138 Version(
1139 #[schemars(with = "BigInt<u64>")]
1140 #[serde_as(as = "BigInt<u64>")]
1141 u64,
1142 ),
1143}
1144
1145impl IotaObjectDataFilter {
1146 pub fn gas_coin() -> Self {
1147 Self::StructType(GasCoin::type_())
1148 }
1149
1150 pub fn and(self, other: Self) -> Self {
1151 Self::MatchAll(vec![self, other])
1152 }
1153 pub fn or(self, other: Self) -> Self {
1154 Self::MatchAny(vec![self, other])
1155 }
1156 pub fn not(self, other: Self) -> Self {
1157 Self::MatchNone(vec![self, other])
1158 }
1159
1160 pub fn matches(&self, object: &ObjectInfo) -> bool {
1161 match self {
1162 IotaObjectDataFilter::MatchAll(filters) => !filters.iter().any(|f| !f.matches(object)),
1163 IotaObjectDataFilter::MatchAny(filters) => filters.iter().any(|f| f.matches(object)),
1164 IotaObjectDataFilter::MatchNone(filters) => !filters.iter().any(|f| f.matches(object)),
1165 IotaObjectDataFilter::StructType(s) => {
1166 let obj_tag: StructTag = match &object.type_ {
1167 ObjectType::Package => return false,
1168 ObjectType::Struct(s) => s.clone().into(),
1169 };
1170 if !s.type_params.is_empty() && s.type_params != obj_tag.type_params {
1173 false
1174 } else {
1175 obj_tag.address == s.address
1176 && obj_tag.module == s.module
1177 && obj_tag.name == s.name
1178 }
1179 }
1180 IotaObjectDataFilter::MoveModule { package, module } => {
1181 matches!(&object.type_, ObjectType::Struct(s) if &ObjectID::from(s.address()) == package
1182 && s.module() == module.as_ident_str())
1183 }
1184 IotaObjectDataFilter::Package(p) => {
1185 matches!(&object.type_, ObjectType::Struct(s) if &ObjectID::from(s.address()) == p)
1186 }
1187 IotaObjectDataFilter::AddressOwner(a) => {
1188 matches!(object.owner, Owner::AddressOwner(addr) if &addr == a)
1189 }
1190 IotaObjectDataFilter::ObjectOwner(o) => {
1191 matches!(object.owner, Owner::ObjectOwner(addr) if addr == IotaAddress::from(*o))
1192 }
1193 IotaObjectDataFilter::ObjectId(id) => &object.object_id == id,
1194 IotaObjectDataFilter::ObjectIds(ids) => ids.contains(&object.object_id),
1195 IotaObjectDataFilter::Version(v) => object.version.value() == *v,
1196 }
1197 }
1198}
1199
1200#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, Default)]
1201#[serde(rename_all = "camelCase", rename = "ObjectResponseQuery", default)]
1202pub struct IotaObjectResponseQuery {
1203 pub filter: Option<IotaObjectDataFilter>,
1205 pub options: Option<IotaObjectDataOptions>,
1208}
1209
1210impl IotaObjectResponseQuery {
1211 pub fn new(
1212 filter: Option<IotaObjectDataFilter>,
1213 options: Option<IotaObjectDataOptions>,
1214 ) -> Self {
1215 Self { filter, options }
1216 }
1217
1218 pub fn new_with_filter(filter: IotaObjectDataFilter) -> Self {
1219 Self {
1220 filter: Some(filter),
1221 options: None,
1222 }
1223 }
1224
1225 pub fn new_with_options(options: IotaObjectDataOptions) -> Self {
1226 Self {
1227 filter: None,
1228 options: Some(options),
1229 }
1230 }
1231}