1use std::collections::BTreeMap;
5use std::convert::TryFrom;
6use std::fmt::{Debug, Display, Formatter};
7use std::sync::Arc;
8
9use move_binary_format::CompiledModule;
10use move_bytecode_utils::layout::TypeLayoutBuilder;
11use move_bytecode_utils::module_cache::GetModule;
12use move_core_types::annotated_value::{MoveStruct, MoveStructLayout, MoveTypeLayout, MoveValue};
13use move_core_types::language_storage::StructTag;
14use move_core_types::language_storage::TypeTag;
15use mysten_common::debug_fatal;
16use once_cell::sync::Lazy;
17use schemars::JsonSchema;
18use serde::{Deserialize, Serialize};
19use serde_with::Bytes;
20use serde_with::serde_as;
21
22use crate::accumulator_root::AccumulatorValue;
23use crate::base_types::{FullObjectID, FullObjectRef, MoveObjectType, ObjectIDParseError};
24use crate::coin::{Coin, CoinMetadata, TreasuryCap};
25use crate::crypto::{default_hash, deterministic_random_account_key};
26use crate::error::{
27 ExecutionError, SuiError, SuiErrorKind, SuiResult, UserInputError, UserInputResult,
28};
29use crate::execution_status::ExecutionErrorKind;
30use crate::gas_coin::GAS;
31use crate::is_system_package;
32use crate::layout_resolver::LayoutResolver;
33use crate::move_package::MovePackage;
34use crate::{
35 base_types::{
36 ObjectDigest, ObjectID, ObjectRef, SequenceNumber, SuiAddress, TransactionDigest,
37 },
38 gas_coin::GasCoin,
39};
40use sui_protocol_config::ProtocolConfig;
41
42use self::balance_traversal::BalanceTraversal;
43use self::bounded_visitor::BoundedVisitor;
44
45mod balance_traversal;
46pub mod bounded_visitor;
47pub mod option_visitor;
48pub mod rpc_visitor;
49
50pub const GAS_VALUE_FOR_TESTING: u64 = 300_000_000_000_000;
51pub const OBJECT_START_VERSION: SequenceNumber = SequenceNumber::from_u64(1);
52
53#[serde_as]
54#[derive(Eq, PartialEq, Debug, Clone, Deserialize, Serialize, Hash)]
55pub struct MoveObject {
56 type_: MoveObjectType,
58 has_public_transfer: bool,
61 version: SequenceNumber,
64 #[serde_as(as = "Bytes")]
66 contents: Vec<u8>,
67}
68
69pub const ID_END_INDEX: usize = ObjectID::LENGTH;
71
72impl MoveObject {
73 pub unsafe fn new_from_execution(
84 type_: MoveObjectType,
85 has_public_transfer: bool,
86 version: SequenceNumber,
87 contents: Vec<u8>,
88 protocol_config: &ProtocolConfig,
89 system_mutation: bool,
90 ) -> Result<Self, ExecutionError> {
91 let bound = if protocol_config.allow_unbounded_system_objects() && system_mutation {
92 if contents.len() as u64 > protocol_config.max_move_object_size() {
93 debug_fatal!(
94 "System created object (ID = {:?}) of type {:?} and size {} exceeds normal max size {}",
95 MoveObject::id_opt(&contents).ok(),
96 type_,
97 contents.len(),
98 protocol_config.max_move_object_size()
99 );
100 }
101 u64::MAX
102 } else {
103 protocol_config.max_move_object_size()
104 };
105 unsafe {
106 Self::new_from_execution_with_limit(
107 type_,
108 has_public_transfer,
109 version,
110 contents,
111 bound,
112 )
113 }
114 }
115
116 pub unsafe fn new_from_execution_with_limit(
119 type_: MoveObjectType,
120 has_public_transfer: bool,
121 version: SequenceNumber,
122 contents: Vec<u8>,
123 max_move_object_size: u64,
124 ) -> Result<Self, ExecutionError> {
125 debug_assert!(!type_.is_gas_coin() || has_public_transfer);
129 if contents.len() as u64 > max_move_object_size {
130 return Err(ExecutionError::from_kind(
131 ExecutionErrorKind::MoveObjectTooBig {
132 object_size: contents.len() as u64,
133 max_object_size: max_move_object_size,
134 },
135 ));
136 }
137 Ok(Self {
138 type_,
139 has_public_transfer,
140 version,
141 contents,
142 })
143 }
144
145 pub fn new_gas_coin(version: SequenceNumber, id: ObjectID, value: u64) -> Self {
146 unsafe {
148 Self::new_from_execution_with_limit(
149 GasCoin::type_().into(),
150 true,
151 version,
152 GasCoin::new(id, value).to_bcs_bytes(),
153 256,
154 )
155 .unwrap()
156 }
157 }
158
159 pub fn new_coin(coin_type: TypeTag, version: SequenceNumber, id: ObjectID, value: u64) -> Self {
160 unsafe {
162 Self::new_from_execution_with_limit(
163 MoveObjectType::coin(coin_type),
164 true,
165 version,
166 Coin::new(id, value).to_bcs_bytes(),
167 256,
168 )
169 .unwrap()
170 }
171 }
172
173 pub fn type_(&self) -> &MoveObjectType {
174 &self.type_
175 }
176
177 pub fn is_type(&self, s: &StructTag) -> bool {
178 self.type_.is(s)
179 }
180
181 pub fn has_public_transfer(&self) -> bool {
182 self.has_public_transfer
183 }
184
185 pub fn id(&self) -> ObjectID {
186 Self::id_opt(&self.contents).unwrap()
187 }
188
189 pub fn id_opt(contents: &[u8]) -> Result<ObjectID, ObjectIDParseError> {
190 if ID_END_INDEX > contents.len() {
191 return Err(ObjectIDParseError::TryFromSliceError);
192 }
193 ObjectID::try_from(&contents[0..ID_END_INDEX])
194 }
195
196 pub fn get_coin_value_unsafe(&self) -> u64 {
201 debug_assert!(self.type_.is_coin());
202 debug_assert!(self.contents.len() == 40);
204
205 u64::from_le_bytes(<[u8; 8]>::try_from(&self.contents[ID_END_INDEX..]).unwrap())
207 }
208
209 pub fn set_coin_value_unsafe(&mut self, value: u64) {
214 debug_assert!(self.type_.is_coin());
215 debug_assert!(self.contents.len() == 40);
217
218 self.contents.splice(ID_END_INDEX.., value.to_le_bytes());
219 }
220
221 pub fn set_clock_timestamp_ms_unsafe(&mut self, timestamp_ms: u64) {
225 assert!(self.is_clock());
226 assert!(self.contents.len() == 40);
228
229 self.contents
230 .splice(ID_END_INDEX.., timestamp_ms.to_le_bytes());
231 }
232
233 pub fn set_contents_unsafe(&mut self, contents: Vec<u8>) {
234 self.contents = contents;
235 }
236
237 pub fn is_coin(&self) -> bool {
238 self.type_.is_coin()
239 }
240
241 pub fn is_staked_sui(&self) -> bool {
242 self.type_.is_staked_sui()
243 }
244
245 pub fn is_clock(&self) -> bool {
246 self.type_.is(&crate::clock::Clock::type_())
247 }
248
249 pub fn version(&self) -> SequenceNumber {
250 self.version
251 }
252
253 pub fn contents_and_type_equal(&self, other: &Self) -> bool {
254 self.contents == other.contents && self.type_ == other.type_
255 }
256
257 #[cfg(test)]
261 pub fn type_specific_contents(&self) -> &[u8] {
262 &self.contents[ID_END_INDEX..]
263 }
264
265 pub(crate) fn update_contents_advance_epoch_safe_mode(
268 &mut self,
269 new_contents: Vec<u8>,
270 protocol_config: &ProtocolConfig,
271 ) -> Result<(), ExecutionError> {
272 if new_contents.len() as u64 > protocol_config.max_move_object_size() {
273 if protocol_config.allow_unbounded_system_objects() {
274 debug_fatal!(
275 "Safe mode object update (ID = {}) of size {} exceeds normal max size {}",
276 self.id(),
277 new_contents.len(),
278 protocol_config.max_move_object_size()
279 )
280 } else {
281 return Err(ExecutionError::from_kind(
282 ExecutionErrorKind::MoveObjectTooBig {
283 object_size: new_contents.len() as u64,
284 max_object_size: protocol_config.max_move_object_size(),
285 },
286 ));
287 }
288 }
289
290 #[cfg(debug_assertions)]
291 let old_id = self.id();
292 self.contents = new_contents;
293
294 #[cfg(debug_assertions)]
296 debug_assert_eq!(self.id(), old_id);
297
298 Ok(())
299 }
300
301 pub fn increment_version_to(&mut self, next: SequenceNumber) {
304 self.version.increment_to(next);
305 }
306
307 pub fn decrement_version_to(&mut self, prev: SequenceNumber) {
308 self.version.decrement_to(prev);
309 }
310
311 pub fn contents(&self) -> &[u8] {
312 &self.contents
313 }
314
315 pub fn into_contents(self) -> Vec<u8> {
316 self.contents
317 }
318
319 pub fn into_type(self) -> MoveObjectType {
320 self.type_
321 }
322
323 pub fn into_inner(self) -> (MoveObjectType, Vec<u8>) {
324 (self.type_, self.contents)
325 }
326
327 pub fn get_layout(&self, resolver: &impl GetModule) -> Result<MoveStructLayout, SuiError> {
331 Self::get_struct_layout_from_struct_tag(self.type_().clone().into(), resolver)
332 }
333
334 pub fn get_struct_layout_from_struct_tag(
335 struct_tag: StructTag,
336 resolver: &impl GetModule,
337 ) -> Result<MoveStructLayout, SuiError> {
338 let type_ = TypeTag::Struct(Box::new(struct_tag));
339 let layout = TypeLayoutBuilder::build_with_types(&type_, resolver).map_err(|e| {
340 SuiErrorKind::ObjectSerializationError {
341 error: e.to_string(),
342 }
343 })?;
344 match layout {
345 MoveTypeLayout::Struct(l) => Ok(*l),
346 _ => unreachable!(
347 "We called build_with_types on Struct type, should get a struct layout"
348 ),
349 }
350 }
351
352 pub fn to_move_struct(&self, layout: &MoveStructLayout) -> Result<MoveStruct, SuiError> {
354 BoundedVisitor::deserialize_struct(&self.contents, layout).map_err(|e| {
355 SuiErrorKind::ObjectSerializationError {
356 error: e.to_string(),
357 }
358 .into()
359 })
360 }
361
362 pub fn to_move_struct_with_resolver(
364 &self,
365 resolver: &impl GetModule,
366 ) -> Result<MoveStruct, SuiError> {
367 self.to_move_struct(&self.get_layout(resolver)?)
368 }
369
370 pub fn to_rust<'de, T: Deserialize<'de>>(&'de self) -> Option<T> {
371 bcs::from_bytes(self.contents()).ok()
372 }
373
374 pub fn object_size_for_gas_metering(&self) -> usize {
379 let serialized_type_tag_size =
380 bcs::serialized_size(&self.type_).expect("Serializing type tag should not fail");
381 self.contents.len() + serialized_type_tag_size + 1 + 8
384 }
385
386 pub fn get_total_sui(&self, layout_resolver: &mut dyn LayoutResolver) -> Result<u64, SuiError> {
388 if self.type_.is_gas_coin() {
389 let balance = self.get_coin_value_unsafe();
390 Ok(balance)
391 } else if self.type_.coin_type_maybe().is_some() {
392 Ok(0)
394 } else if self.type_.is_sui_balance_accumulator_field() {
395 let value = AccumulatorValue::try_from(self)?;
396 let AccumulatorValue::U128(v) = value;
397 assert!(
400 v.value <= u64::MAX as u128,
401 "SUI balance cannot exceed u64::MAX"
402 );
403 Ok(v.value as u64)
404 } else {
405 let layout = layout_resolver.get_annotated_layout(&self.type_().clone().into())?;
406
407 let mut traversal = BalanceTraversal::default();
408 MoveValue::visit_deserialize(&self.contents, &layout.into_layout(), &mut traversal)
409 .map_err(|e| SuiErrorKind::ObjectSerializationError {
410 error: e.to_string(),
411 })?;
412
413 Ok(traversal
414 .finish()
415 .get(&GAS::type_tag())
416 .copied()
417 .unwrap_or(0))
418 }
419 }
420}
421
422#[derive(Eq, PartialEq, Debug, Clone, Deserialize, Serialize, Hash)]
423#[allow(clippy::large_enum_variant)]
424pub enum Data {
425 Move(MoveObject),
427 Package(MovePackage),
429 }
431
432impl Data {
433 pub fn try_as_move(&self) -> Option<&MoveObject> {
434 use Data::*;
435 match self {
436 Move(m) => Some(m),
437 Package(_) => None,
438 }
439 }
440
441 pub fn try_as_move_mut(&mut self) -> Option<&mut MoveObject> {
442 use Data::*;
443 match self {
444 Move(m) => Some(m),
445 Package(_) => None,
446 }
447 }
448
449 pub fn try_as_package(&self) -> Option<&MovePackage> {
450 use Data::*;
451 match self {
452 Move(_) => None,
453 Package(p) => Some(p),
454 }
455 }
456
457 pub fn try_as_package_mut(&mut self) -> Option<&mut MovePackage> {
458 use Data::*;
459 match self {
460 Move(_) => None,
461 Package(p) => Some(p),
462 }
463 }
464
465 pub fn try_into_package(self) -> Option<MovePackage> {
466 use Data::*;
467 match self {
468 Move(_) => None,
469 Package(p) => Some(p),
470 }
471 }
472
473 pub fn type_(&self) -> Option<&MoveObjectType> {
474 use Data::*;
475 match self {
476 Move(m) => Some(m.type_()),
477 Package(_) => None,
478 }
479 }
480
481 pub fn struct_tag(&self) -> Option<StructTag> {
482 use Data::*;
483 match self {
484 Move(m) => Some(m.type_().clone().into()),
485 Package(_) => None,
486 }
487 }
488
489 pub fn id(&self) -> ObjectID {
490 match self {
491 Self::Move(v) => v.id(),
492 Self::Package(m) => m.id(),
493 }
494 }
495}
496
497#[repr(u8)]
515#[derive(Debug, Clone, Eq, Copy, Hash, Ord, PartialEq, PartialOrd)]
516pub enum ObjectPermission {
517 ImmutableUsage = 1 << 0,
518 MutableUsage = 1 << 1,
519 Write = 1 << 2,
520 Delete = 1 << 3,
521 InternalTransfer = 1 << 4,
522 PublicTransfer = 1 << 5,
523 Wrap = 1 << 6,
524}
525
526impl ObjectPermission {
527 pub fn from_u64(bits: u64) -> Option<Self> {
528 match bits {
529 b if b == Self::Write as u64 => Some(Self::Write),
530 b if b == Self::Delete as u64 => Some(Self::Delete),
531 b if b == Self::InternalTransfer as u64 => Some(Self::InternalTransfer),
532 b if b == Self::PublicTransfer as u64 => Some(Self::PublicTransfer),
533 b if b == Self::Wrap as u64 => Some(Self::Wrap),
534 b if b == Self::MutableUsage as u64 => Some(Self::MutableUsage),
535 b if b == Self::ImmutableUsage as u64 => Some(Self::ImmutableUsage),
536 _ => {
537 debug_assert!(false, "Invalid ObjectPermission bit pattern: {bits}.");
538 None
539 }
540 }
541 }
542}
543
544impl Display for ObjectPermission {
545 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
546 match self {
547 Self::Write => write!(f, "Write"),
548 Self::Delete => write!(f, "Delete"),
549 Self::InternalTransfer => write!(f, "InternalTransfer"),
550 Self::PublicTransfer => write!(f, "PublicTransfer"),
551 Self::Wrap => write!(f, "Wrap"),
552 Self::MutableUsage => write!(f, "MutableUsage"),
553 Self::ImmutableUsage => write!(f, "ImmutableUsage"),
554 }
555 }
556}
557
558#[derive(
560 Eq, PartialEq, Debug, Clone, Copy, Deserialize, Serialize, Hash, JsonSchema, Ord, PartialOrd,
561)]
562#[serde(try_from = "u64", into = "u64")]
563pub struct ObjectPermissions(u64);
564
565#[cfg(feature = "fuzzing")]
566impl proptest::arbitrary::Arbitrary for ObjectPermissions {
567 type Parameters = ();
568 type Strategy = proptest::strategy::BoxedStrategy<Self>;
569 fn arbitrary_with(_: ()) -> Self::Strategy {
570 use proptest::prelude::*;
571 any::<u8>()
572 .prop_map(|bits| {
573 let mut bits = bits as u64 & Self::ALL_BITS;
574 if bits & Self::MUTABLE_PERMISSION_BITS != 0 {
575 bits |= ObjectPermission::MutableUsage as u64;
576 }
577 Self(bits)
578 })
579 .boxed()
580 }
581}
582
583impl ObjectPermissions {
584 const MUTABLE_PERMISSION_BITS: u64 = (ObjectPermission::Write as u64)
587 | (ObjectPermission::Delete as u64)
588 | (ObjectPermission::InternalTransfer as u64)
589 | (ObjectPermission::PublicTransfer as u64)
590 | (ObjectPermission::Wrap as u64);
591
592 const ALL_BITS: u64 = Self::MUTABLE_PERMISSION_BITS
594 | (ObjectPermission::MutableUsage as u64)
595 | (ObjectPermission::ImmutableUsage as u64);
596
597 pub const NONE: Self = Self(0);
598 pub const IMMUTABLE_USAGE: Self = Self::from_bits(ObjectPermission::ImmutableUsage as u64);
599 pub const MUTABLE_USAGE: Self = Self::from_bits(ObjectPermission::MutableUsage as u64);
600 pub const WRITE: Self =
601 Self::from_bits(ObjectPermission::Write as u64 | ObjectPermission::MutableUsage as u64);
602 pub const DELETE: Self =
603 Self::from_bits(ObjectPermission::Delete as u64 | ObjectPermission::MutableUsage as u64);
604 pub const INTERNAL_TRANSFER: Self = Self::from_bits(
605 ObjectPermission::InternalTransfer as u64 | ObjectPermission::MutableUsage as u64,
606 );
607 pub const PUBLIC_TRANSFER: Self = Self::from_bits(
608 ObjectPermission::PublicTransfer as u64 | ObjectPermission::MutableUsage as u64,
609 );
610 pub const WRAP: Self =
611 Self::from_bits(ObjectPermission::Wrap as u64 | ObjectPermission::MutableUsage as u64);
612 pub const ALL: Self = Self::from_bits(Self::ALL_BITS);
613
614 pub const LEGACY_SHARED_OBJECT: Self = Self::from_bits(
615 (ObjectPermission::Write as u64)
616 | (ObjectPermission::Delete as u64)
617 | (ObjectPermission::MutableUsage as u64)
618 | (ObjectPermission::ImmutableUsage as u64),
619 );
620
621 const fn from_bits(bits: u64) -> Self {
625 assert!(bits & !Self::ALL_BITS == 0, "unknown permission bit");
626 let has_mutable_perm = bits & Self::MUTABLE_PERMISSION_BITS != 0;
627 let has_mutable_usage = bits & (ObjectPermission::MutableUsage as u64) != 0;
628 assert!(
629 !has_mutable_perm || has_mutable_usage,
630 "a mutable permission requires MutableUsage"
631 );
632 Self(bits)
633 }
634
635 pub const fn new(bits: u64) -> Option<Self> {
638 if bits & !Self::ALL_BITS != 0 {
639 return None;
640 }
641 let has_mutable_perm = bits & Self::MUTABLE_PERMISSION_BITS != 0;
642 let has_mutable_usage = bits & (ObjectPermission::MutableUsage as u64) != 0;
643 if has_mutable_perm && !has_mutable_usage {
644 return None;
645 }
646 Some(Self(bits))
647 }
648
649 pub fn can(&self, permission: ObjectPermission) -> bool {
650 let p = permission as u64;
651 (self.0 & p) == p
652 }
653
654 pub fn can_write(&self) -> bool {
656 self.can(ObjectPermission::Write)
657 }
658
659 pub fn can_delete(&self) -> bool {
662 self.can(ObjectPermission::Delete)
663 }
664
665 pub fn can_internal_transfer(&self) -> bool {
667 self.can(ObjectPermission::InternalTransfer)
668 }
669
670 pub fn can_public_transfer(&self) -> bool {
672 self.can(ObjectPermission::PublicTransfer)
673 }
674
675 pub fn can_wrap(&self) -> bool {
679 self.can(ObjectPermission::Wrap)
680 }
681
682 pub fn can_use_mutably(&self) -> bool {
685 self.can(ObjectPermission::MutableUsage)
686 }
687
688 pub fn can_use_immutably(&self) -> bool {
690 self.can(ObjectPermission::ImmutableUsage)
691 }
692
693 #[inline(always)]
694 const fn is_subset_bits(sub: u64, sup: u64) -> bool {
695 (sub & sup) == sub
696 }
697
698 pub const fn is_subset(&self, other: Self) -> bool {
699 Self::is_subset_bits(self.0, other.0)
700 }
701}
702
703impl std::ops::BitOr<ObjectPermissions> for ObjectPermissions {
704 type Output = Self;
705 fn bitor(self, rhs: Self) -> Self {
706 Self(self.0 | rhs.0)
709 }
710}
711
712impl TryFrom<u64> for ObjectPermissions {
713 type Error = &'static str;
714 fn try_from(bits: u64) -> Result<Self, Self::Error> {
715 Self::new(bits).ok_or("invalid ObjectPermissions bits")
716 }
717}
718
719impl From<ObjectPermissions> for u64 {
720 fn from(p: ObjectPermissions) -> u64 {
721 p.0
722 }
723}
724
725pub struct ObjectPermissionsIterator {
726 set: ObjectPermissions,
727 idx: usize,
728 #[cfg(debug_assertions)]
729 emitted: u64,
730}
731
732impl ObjectPermissionsIterator {
733 const ORDER: &'static [ObjectPermission] = &[
734 ObjectPermission::ImmutableUsage,
735 ObjectPermission::MutableUsage,
736 ObjectPermission::Write,
737 ObjectPermission::Delete,
738 ObjectPermission::InternalTransfer,
739 ObjectPermission::PublicTransfer,
740 ObjectPermission::Wrap,
741 ];
742}
743
744impl Iterator for ObjectPermissionsIterator {
745 type Item = ObjectPermission;
746
747 fn next(&mut self) -> Option<Self::Item> {
748 while self.idx < Self::ORDER.len() {
749 let p = Self::ORDER[self.idx];
750 self.idx += 1;
751 if self.set.can(p) {
752 #[cfg(debug_assertions)]
753 {
754 self.emitted |= p as u64;
755 }
756 return Some(p);
757 }
758 }
759 #[cfg(debug_assertions)]
760 debug_assert_eq!(
761 self.emitted, self.set.0,
762 "ObjectPermissionsIterator did not iterate over every permission in the set",
763 );
764 None
765 }
766}
767
768impl IntoIterator for ObjectPermissions {
769 type Item = ObjectPermission;
770 type IntoIter = ObjectPermissionsIterator;
771 fn into_iter(self) -> Self::IntoIter {
772 debug_assert_eq!(
773 ObjectPermissionsIterator::ORDER
774 .iter()
775 .copied()
776 .fold(0u64, |a, p| {
777 let bit = p as u64;
778 debug_assert_eq!(
779 a & bit,
780 0,
781 "duplicate ObjectPermission in ObjectPermissionsIterator::ORDER: {p:?}",
782 );
783 a | bit
784 }),
785 ObjectPermissions::ALL.0,
786 "ObjectPermissionsIterator::ORDER must contain every ObjectPermission",
787 );
788 ObjectPermissionsIterator {
789 idx: 0,
790 set: self,
791 #[cfg(debug_assertions)]
792 emitted: 0,
793 }
794 }
795}
796
797impl Display for ObjectPermissions {
798 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
799 write!(f, "{{")?;
800 let mut first = true;
801 for permission in *self {
802 if !first {
803 write!(f, ",")?;
804 }
805 write!(f, "{}", permission)?;
806 first = false;
807 }
808 write!(f, "}}")
809 }
810}
811
812#[derive(
815 Eq, PartialEq, Debug, Clone, Deserialize, Serialize, Hash, JsonSchema, Ord, PartialOrd,
816)]
817#[serde(try_from = "RawPartySerde", into = "RawPartySerde")]
818pub struct Party {
819 default_permissions: ObjectPermissions,
821 members: BTreeMap<SuiAddress, ObjectPermissions>,
823}
824
825impl Party {
826 pub fn new(
828 default_permissions: ObjectPermissions,
829 members: BTreeMap<SuiAddress, ObjectPermissions>,
830 ) -> Option<Self> {
831 if Self::is_consensus_address_owner(default_permissions, &members) {
832 return None;
833 }
834 Some(Self {
835 default_permissions,
836 members,
837 })
838 }
839
840 pub fn is_consensus_address_owner(
841 default_permissions: ObjectPermissions,
842 members: &BTreeMap<SuiAddress, ObjectPermissions>,
843 ) -> bool {
844 default_permissions == ObjectPermissions::NONE
845 && members.len() == 1
846 && members.values().next() == Some(&ObjectPermissions::ALL)
847 }
848
849 pub fn members(&self) -> impl Iterator<Item = &SuiAddress> {
850 self.members.keys()
851 }
852
853 pub fn permissions_for(&self, address: &SuiAddress) -> ObjectPermissions {
854 self.members
855 .get(address)
856 .copied()
857 .unwrap_or(self.default_permissions)
858 }
859}
860
861impl Display for Party {
862 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
863 write!(
864 f,
865 "Party {{ default_permissions: {}, members: {{",
866 self.default_permissions.0
867 )?;
868 let mut first = true;
869 for (address, permissions) in &self.members {
870 if !first {
871 write!(f, ", ")?;
872 }
873 write!(f, "{} => {}", address, permissions.0)?;
874 first = false;
875 }
876 write!(f, "}} }}")
877 }
878}
879
880#[derive(Deserialize, Serialize)]
881struct RawPartySerde {
882 default_permissions: ObjectPermissions,
883 members: Vec<(SuiAddress, ObjectPermissions)>,
884}
885
886impl TryFrom<RawPartySerde> for Party {
887 type Error = &'static str;
888 fn try_from(raw: RawPartySerde) -> Result<Self, Self::Error> {
889 for window in raw.members.windows(2) {
890 match window[0].0.cmp(&window[1].0) {
891 std::cmp::Ordering::Less => continue,
892 std::cmp::Ordering::Equal => return Err("duplicate Party member address"),
893 std::cmp::Ordering::Greater => return Err("Party members must be sorted"),
894 }
895 }
896 let members: BTreeMap<SuiAddress, ObjectPermissions> = raw.members.into_iter().collect();
897 Self::new(raw.default_permissions, members)
901 .ok_or("invalid Party: violates canonical representation")
902 }
903}
904
905impl From<Party> for RawPartySerde {
906 fn from(p: Party) -> Self {
907 Self {
908 default_permissions: p.default_permissions,
909 members: p.members.into_iter().collect(),
910 }
911 }
912}
913
914#[cfg(feature = "fuzzing")]
915impl proptest::arbitrary::Arbitrary for Party {
916 type Parameters = ();
917 type Strategy = proptest::strategy::BoxedStrategy<Self>;
918 fn arbitrary_with(_: ()) -> Self::Strategy {
919 use proptest::prelude::*;
920 (
921 any::<ObjectPermissions>(),
922 any::<BTreeMap<SuiAddress, ObjectPermissions>>(),
923 )
924 .prop_filter_map(
925 "Party representable as ConsensusAddressOwner",
926 |(default_permissions, members)| Self::new(default_permissions, members),
927 )
928 .boxed()
929 }
930}
931
932#[derive(
933 Eq, PartialEq, Debug, Clone, Deserialize, Serialize, Hash, JsonSchema, Ord, PartialOrd,
934)]
935#[cfg_attr(feature = "fuzzing", derive(proptest_derive::Arbitrary))]
936pub enum Owner {
937 AddressOwner(SuiAddress),
939 ObjectOwner(SuiAddress),
942 Shared {
944 initial_shared_version: SequenceNumber,
946 },
947 Immutable,
949 ConsensusAddressOwner {
951 start_version: SequenceNumber,
955 owner: SuiAddress,
957 },
958 Party {
962 start_version: SequenceNumber,
966 permissions: Party,
968 },
969}
970
971impl Owner {
972 pub fn get_address_owner_address(&self) -> SuiResult<SuiAddress> {
975 match self {
976 Self::AddressOwner(address) => Ok(*address),
977 Self::Shared { .. }
978 | Self::Immutable
979 | Self::ObjectOwner(_)
980 | Self::ConsensusAddressOwner { .. }
981 | Self::Party { .. } => Err(SuiErrorKind::UnexpectedOwnerType.into()),
982 }
983 }
984
985 pub fn get_owner_address(&self) -> SuiResult<SuiAddress> {
989 match self {
990 Self::AddressOwner(address)
991 | Self::ObjectOwner(address)
992 | Self::ConsensusAddressOwner { owner: address, .. } => Ok(*address),
993 Self::Shared { .. } | Self::Immutable | Self::Party { .. } => {
994 Err(SuiErrorKind::UnexpectedOwnerType.into())
995 }
996 }
997 }
998
999 pub fn start_version(&self) -> Option<SequenceNumber> {
1002 match self {
1003 Self::Shared {
1004 initial_shared_version,
1005 } => Some(*initial_shared_version),
1006 Self::ConsensusAddressOwner { start_version, .. }
1007 | Self::Party { start_version, .. } => Some(*start_version),
1008 Self::Immutable | Self::AddressOwner(_) | Self::ObjectOwner(_) => None,
1009 }
1010 }
1011
1012 pub fn is_immutable(&self) -> bool {
1013 matches!(self, Owner::Immutable)
1014 }
1015
1016 pub fn is_address_owned(&self) -> bool {
1017 matches!(self, Owner::AddressOwner(_))
1018 }
1019
1020 pub fn is_child_object(&self) -> bool {
1021 matches!(self, Owner::ObjectOwner(_))
1022 }
1023
1024 pub fn is_shared(&self) -> bool {
1025 matches!(self, Owner::Shared { .. })
1026 }
1027
1028 pub fn is_consensus(&self) -> bool {
1029 matches!(
1030 self,
1031 Owner::Shared { .. } | Owner::ConsensusAddressOwner { .. } | Owner::Party { .. }
1032 )
1033 }
1034}
1035
1036impl PartialEq<ObjectID> for Owner {
1037 fn eq(&self, other: &ObjectID) -> bool {
1038 let other_id: SuiAddress = (*other).into();
1039 match self {
1040 Self::ObjectOwner(id) => id == &other_id,
1041 Self::AddressOwner(_)
1042 | Self::Shared { .. }
1043 | Self::Immutable
1044 | Self::ConsensusAddressOwner { .. }
1045 | Self::Party { .. } => false,
1046 }
1047 }
1048}
1049
1050impl Display for Owner {
1051 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1052 match self {
1053 Self::AddressOwner(address) => {
1054 write!(f, "Account Address ( {} )", address)
1055 }
1056 Self::ObjectOwner(address) => {
1057 write!(f, "Object ID: ( {} )", address)
1058 }
1059 Self::Immutable => {
1060 write!(f, "Immutable")
1061 }
1062 Self::Shared {
1063 initial_shared_version,
1064 } => {
1065 write!(f, "Shared( {} )", initial_shared_version.value())
1066 }
1067 Self::ConsensusAddressOwner {
1068 start_version,
1069 owner,
1070 } => {
1071 write!(
1072 f,
1073 "ConsensusAddressOwner( {}, {} )",
1074 start_version.value(),
1075 owner
1076 )
1077 }
1078 Self::Party {
1079 start_version,
1080 permissions,
1081 } => {
1082 write!(f, "Party( {}, {} )", start_version.value(), permissions)
1083 }
1084 }
1085 }
1086}
1087
1088#[derive(Eq, PartialEq, Debug, Clone, Deserialize, Serialize, Hash)]
1089#[serde(rename = "Object")]
1090pub struct ObjectInner {
1091 pub data: Data,
1093 pub owner: Owner,
1095 pub previous_transaction: TransactionDigest,
1097 pub storage_rebate: u64,
1101}
1102
1103#[derive(Eq, PartialEq, Clone, Deserialize, Serialize, Hash)]
1104#[serde(from = "ObjectInner")]
1105pub struct Object(Arc<ObjectInner>);
1106
1107fn is_object_debug_verbose() -> bool {
1108 static SUI_OBJECT_DEBUG_VERBOSE: Lazy<bool> =
1109 Lazy::new(|| std::env::var("SUI_OBJECT_DEBUG_VERBOSE").is_ok());
1110 *SUI_OBJECT_DEBUG_VERBOSE
1111}
1112
1113impl std::fmt::Debug for Object {
1114 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1115 if is_object_debug_verbose() {
1116 (*self.0).fmt(f)
1118 } else {
1119 f.debug_struct("Object")
1120 .field("id", &self.id())
1121 .field("version", &self.version())
1122 .field("owner", &self.owner())
1123 .finish()
1124 }
1125 }
1126}
1127
1128impl From<ObjectInner> for Object {
1129 fn from(inner: ObjectInner) -> Self {
1130 Self(Arc::new(inner))
1131 }
1132}
1133
1134impl Object {
1135 pub fn into_inner(self) -> ObjectInner {
1136 match Arc::try_unwrap(self.0) {
1137 Ok(inner) => inner,
1138 Err(inner_arc) => (*inner_arc).clone(),
1139 }
1140 }
1141
1142 pub fn as_inner(&self) -> &ObjectInner {
1143 &self.0
1144 }
1145
1146 pub fn owner(&self) -> &Owner {
1147 &self.0.owner
1148 }
1149
1150 pub fn new_from_genesis(
1151 data: Data,
1152 owner: Owner,
1153 previous_transaction: TransactionDigest,
1154 ) -> Self {
1155 ObjectInner {
1156 data,
1157 owner,
1158 previous_transaction,
1159 storage_rebate: 0,
1160 }
1161 .into()
1162 }
1163
1164 pub fn new_move(o: MoveObject, owner: Owner, previous_transaction: TransactionDigest) -> Self {
1166 ObjectInner {
1167 data: Data::Move(o),
1168 owner,
1169 previous_transaction,
1170 storage_rebate: 0,
1171 }
1172 .into()
1173 }
1174
1175 pub fn new_package_from_data(data: Data, previous_transaction: TransactionDigest) -> Self {
1176 ObjectInner {
1177 data,
1178 owner: Owner::Immutable,
1179 previous_transaction,
1180 storage_rebate: 0,
1181 }
1182 .into()
1183 }
1184
1185 pub fn new_from_package(package: MovePackage, previous_transaction: TransactionDigest) -> Self {
1187 Self::new_package_from_data(Data::Package(package), previous_transaction)
1188 }
1189
1190 pub fn new_package<'p>(
1191 modules: &[CompiledModule],
1192 previous_transaction: TransactionDigest,
1193 protocol_config: &ProtocolConfig,
1194 dependencies: impl IntoIterator<Item = &'p MovePackage>,
1195 ) -> Result<Self, ExecutionError> {
1196 Ok(Self::new_package_from_data(
1197 Data::Package(MovePackage::new_initial(
1198 modules,
1199 protocol_config,
1200 dependencies,
1201 )?),
1202 previous_transaction,
1203 ))
1204 }
1205
1206 pub fn new_upgraded_package<'p>(
1207 previous_package: &MovePackage,
1208 new_package_id: ObjectID,
1209 modules: &[CompiledModule],
1210 previous_transaction: TransactionDigest,
1211 protocol_config: &ProtocolConfig,
1212 dependencies: impl IntoIterator<Item = &'p MovePackage>,
1213 ) -> Result<Self, ExecutionError> {
1214 Ok(Self::new_package_from_data(
1215 Data::Package(previous_package.new_upgraded(
1216 new_package_id,
1217 modules,
1218 protocol_config,
1219 dependencies,
1220 )?),
1221 previous_transaction,
1222 ))
1223 }
1224
1225 pub fn new_package_for_testing(
1226 modules: &[CompiledModule],
1227 previous_transaction: TransactionDigest,
1228 dependencies: impl IntoIterator<Item = MovePackage>,
1229 ) -> Result<Self, ExecutionError> {
1230 let dependencies: Vec<_> = dependencies.into_iter().collect();
1231 let config = ProtocolConfig::get_for_max_version_UNSAFE();
1232 Self::new_package(modules, previous_transaction, &config, &dependencies)
1233 }
1234
1235 pub fn new_system_package(
1238 modules: &[CompiledModule],
1239 version: SequenceNumber,
1240 dependencies: Vec<ObjectID>,
1241 previous_transaction: TransactionDigest,
1242 ) -> Self {
1243 let ret = Self::new_package_from_data(
1244 Data::Package(MovePackage::new_system(version, modules, dependencies)),
1245 previous_transaction,
1246 );
1247
1248 #[cfg(not(msim))]
1249 assert!(ret.is_system_package());
1250
1251 ret
1252 }
1253}
1254
1255impl std::ops::Deref for Object {
1256 type Target = ObjectInner;
1257 fn deref(&self) -> &Self::Target {
1258 &self.0
1259 }
1260}
1261
1262impl std::ops::DerefMut for Object {
1263 fn deref_mut(&mut self) -> &mut Self::Target {
1264 Arc::make_mut(&mut self.0)
1265 }
1266}
1267
1268impl ObjectInner {
1269 pub fn is_system_package(&self) -> bool {
1271 self.is_package() && is_system_package(self.id())
1272 }
1273
1274 pub fn is_immutable(&self) -> bool {
1275 self.owner.is_immutable()
1276 }
1277
1278 pub fn is_address_owned(&self) -> bool {
1279 self.owner.is_address_owned()
1280 }
1281
1282 pub fn is_child_object(&self) -> bool {
1283 self.owner.is_child_object()
1284 }
1285
1286 pub fn is_shared(&self) -> bool {
1287 self.owner.is_shared()
1288 }
1289
1290 pub fn is_consensus(&self) -> bool {
1291 self.owner.is_consensus()
1292 }
1293
1294 pub fn get_single_owner(&self) -> Option<SuiAddress> {
1295 self.owner.get_owner_address().ok()
1296 }
1297
1298 pub fn get_owner_and_id(&self) -> Option<(Owner, ObjectID)> {
1301 Some((self.owner.clone(), self.id()))
1302 }
1303
1304 pub fn is_package(&self) -> bool {
1306 matches!(&self.data, Data::Package(_))
1307 }
1308
1309 pub fn compute_object_reference(&self) -> ObjectRef {
1310 (self.id(), self.version(), self.digest())
1311 }
1312
1313 pub fn compute_full_object_reference(&self) -> FullObjectRef {
1314 FullObjectRef(self.full_id(), self.version(), self.digest())
1315 }
1316
1317 pub fn digest(&self) -> ObjectDigest {
1318 ObjectDigest::new(default_hash(self))
1319 }
1320
1321 pub fn id(&self) -> ObjectID {
1322 use Data::*;
1323
1324 match &self.data {
1325 Move(v) => v.id(),
1326 Package(m) => m.id(),
1327 }
1328 }
1329
1330 pub fn full_id(&self) -> FullObjectID {
1331 let id = self.id();
1332 if let Some(start_version) = self.owner.start_version() {
1333 FullObjectID::Consensus((id, start_version))
1334 } else {
1335 FullObjectID::Fastpath(id)
1336 }
1337 }
1338
1339 pub fn version(&self) -> SequenceNumber {
1340 use Data::*;
1341
1342 match &self.data {
1343 Move(o) => o.version(),
1344 Package(p) => p.version(),
1345 }
1346 }
1347
1348 pub fn type_(&self) -> Option<&MoveObjectType> {
1349 self.data.type_()
1350 }
1351
1352 pub fn struct_tag(&self) -> Option<StructTag> {
1353 self.data.struct_tag()
1354 }
1355
1356 pub fn is_coin(&self) -> bool {
1357 if let Some(move_object) = self.data.try_as_move() {
1358 move_object.type_().is_coin()
1359 } else {
1360 false
1361 }
1362 }
1363
1364 pub fn is_gas_coin(&self) -> bool {
1365 if let Some(move_object) = self.data.try_as_move() {
1366 move_object.type_().is_gas_coin()
1367 } else {
1368 false
1369 }
1370 }
1371
1372 pub fn as_coin_maybe(&self) -> Option<Coin> {
1375 if let Some(move_object) = self.data.try_as_move() {
1376 if move_object.type_().is_coin() {
1377 let coin: Coin = bcs::from_bytes(move_object.contents()).ok()?;
1378 Some(coin)
1379 } else {
1380 None
1381 }
1382 } else {
1383 None
1384 }
1385 }
1386
1387 pub fn coin_type_maybe(&self) -> Option<TypeTag> {
1388 if let Some(move_object) = self.data.try_as_move() {
1389 move_object.type_().coin_type_maybe()
1390 } else {
1391 None
1392 }
1393 }
1394
1395 pub fn get_coin_value_unsafe(&self) -> u64 {
1400 self.data.try_as_move().unwrap().get_coin_value_unsafe()
1401 }
1402
1403 pub fn object_size_for_gas_metering(&self) -> usize {
1408 const DEFAULT_OWNER_SIZE: usize = 40;
1409 const TRANSACTION_DIGEST_SIZE: usize = 32;
1410 const STORAGE_REBATE_SIZE: usize = 8;
1411
1412 let meta_data_size = DEFAULT_OWNER_SIZE + TRANSACTION_DIGEST_SIZE + STORAGE_REBATE_SIZE;
1413 let data_size = match &self.data {
1414 Data::Move(m) => m.object_size_for_gas_metering(),
1415 Data::Package(p) => p.object_size_for_gas_metering(),
1416 };
1417 meta_data_size + data_size
1418 }
1419
1420 pub fn transfer(&mut self, new_owner: SuiAddress) {
1422 self.owner = Owner::AddressOwner(new_owner);
1423 }
1424
1425 pub fn get_layout(
1429 &self,
1430 resolver: &impl GetModule,
1431 ) -> Result<Option<MoveStructLayout>, SuiError> {
1432 match &self.data {
1433 Data::Move(m) => Ok(Some(m.get_layout(resolver)?)),
1434 Data::Package(_) => Ok(None),
1435 }
1436 }
1437
1438 pub fn get_move_template_type(&self) -> SuiResult<TypeTag> {
1442 let move_struct = self
1443 .data
1444 .struct_tag()
1445 .ok_or_else(|| SuiErrorKind::TypeError {
1446 error: "Object must be a Move object".to_owned(),
1447 })?;
1448 fp_ensure!(
1449 move_struct.type_params.len() == 1,
1450 SuiErrorKind::TypeError {
1451 error: "Move object struct must have one type parameter".to_owned()
1452 }
1453 .into()
1454 );
1455 let type_tag = move_struct.type_params[0].clone();
1457 Ok(type_tag)
1458 }
1459
1460 pub fn to_rust<'de, T: Deserialize<'de>>(&'de self) -> Option<T> {
1461 self.data.try_as_move().and_then(|data| data.to_rust())
1462 }
1463}
1464
1465impl Object {
1467 pub fn get_total_sui(&self, layout_resolver: &mut dyn LayoutResolver) -> Result<u64, SuiError> {
1469 Ok(self.storage_rebate
1470 + match &self.data {
1471 Data::Move(m) => m.get_total_sui(layout_resolver)?,
1472 Data::Package(_) => 0,
1473 })
1474 }
1475
1476 pub fn immutable_with_id_for_testing(id: ObjectID) -> Self {
1477 let data = Data::Move(MoveObject {
1478 type_: GasCoin::type_().into(),
1479 has_public_transfer: true,
1480 version: OBJECT_START_VERSION,
1481 contents: GasCoin::new(id, GAS_VALUE_FOR_TESTING).to_bcs_bytes(),
1482 });
1483 ObjectInner {
1484 owner: Owner::Immutable,
1485 data,
1486 previous_transaction: TransactionDigest::genesis_marker(),
1487 storage_rebate: 0,
1488 }
1489 .into()
1490 }
1491
1492 pub fn immutable_for_testing() -> Self {
1493 thread_local! {
1494 static IMMUTABLE_OBJECT_ID: ObjectID = ObjectID::random();
1495 }
1496
1497 Self::immutable_with_id_for_testing(IMMUTABLE_OBJECT_ID.with(|id| *id))
1498 }
1499
1500 pub fn shared_for_testing() -> Object {
1502 let id = ObjectID::random();
1503 let obj = MoveObject::new_gas_coin(OBJECT_START_VERSION, id, 10);
1504 let owner = Owner::Shared {
1505 initial_shared_version: obj.version(),
1506 };
1507 Object::new_move(obj, owner, TransactionDigest::genesis_marker())
1508 }
1509
1510 pub fn with_id_owner_gas_for_testing(id: ObjectID, owner: SuiAddress, gas: u64) -> Self {
1511 let data = Data::Move(MoveObject {
1512 type_: GasCoin::type_().into(),
1513 has_public_transfer: true,
1514 version: OBJECT_START_VERSION,
1515 contents: GasCoin::new(id, gas).to_bcs_bytes(),
1516 });
1517 ObjectInner {
1518 owner: Owner::AddressOwner(owner),
1519 data,
1520 previous_transaction: TransactionDigest::genesis_marker(),
1521 storage_rebate: 0,
1522 }
1523 .into()
1524 }
1525
1526 pub fn treasury_cap_for_testing(struct_tag: StructTag, treasury_cap: TreasuryCap) -> Self {
1527 let data = Data::Move(MoveObject {
1528 type_: TreasuryCap::type_(struct_tag).into(),
1529 has_public_transfer: true,
1530 version: OBJECT_START_VERSION,
1531 contents: bcs::to_bytes(&treasury_cap).expect("Failed to serialize"),
1532 });
1533 ObjectInner {
1534 owner: Owner::Immutable,
1535 data,
1536 previous_transaction: TransactionDigest::genesis_marker(),
1537 storage_rebate: 0,
1538 }
1539 .into()
1540 }
1541
1542 pub fn coin_metadata_for_testing(struct_tag: StructTag, metadata: CoinMetadata) -> Self {
1543 let data = Data::Move(MoveObject {
1544 type_: CoinMetadata::type_(struct_tag).into(),
1545 has_public_transfer: true,
1546 version: OBJECT_START_VERSION,
1547 contents: bcs::to_bytes(&metadata).expect("Failed to serialize"),
1548 });
1549 ObjectInner {
1550 owner: Owner::Immutable,
1551 data,
1552 previous_transaction: TransactionDigest::genesis_marker(),
1553 storage_rebate: 0,
1554 }
1555 .into()
1556 }
1557
1558 pub fn with_object_owner_for_testing(id: ObjectID, owner: ObjectID) -> Self {
1559 let data = Data::Move(MoveObject {
1560 type_: GasCoin::type_().into(),
1561 has_public_transfer: true,
1562 version: OBJECT_START_VERSION,
1563 contents: GasCoin::new(id, GAS_VALUE_FOR_TESTING).to_bcs_bytes(),
1564 });
1565 ObjectInner {
1566 owner: Owner::ObjectOwner(owner.into()),
1567 data,
1568 previous_transaction: TransactionDigest::genesis_marker(),
1569 storage_rebate: 0,
1570 }
1571 .into()
1572 }
1573
1574 pub fn with_id_owner_for_testing(id: ObjectID, owner: SuiAddress) -> Self {
1575 Self::with_id_owner_gas_for_testing(id, owner, GAS_VALUE_FOR_TESTING)
1577 }
1578
1579 pub fn with_id_owner_version_for_testing(
1580 id: ObjectID,
1581 version: SequenceNumber,
1582 owner: Owner,
1583 ) -> Self {
1584 let data = Data::Move(MoveObject {
1585 type_: GasCoin::type_().into(),
1586 has_public_transfer: true,
1587 version,
1588 contents: GasCoin::new(id, GAS_VALUE_FOR_TESTING).to_bcs_bytes(),
1589 });
1590 ObjectInner {
1591 owner,
1592 data,
1593 previous_transaction: TransactionDigest::genesis_marker(),
1594 storage_rebate: 0,
1595 }
1596 .into()
1597 }
1598
1599 pub fn with_owner_for_testing(owner: SuiAddress) -> Self {
1600 Self::with_id_owner_for_testing(ObjectID::random(), owner)
1601 }
1602
1603 pub fn new_gas_with_balance_and_owner_for_testing(value: u64, owner: SuiAddress) -> Self {
1606 let obj = MoveObject::new_gas_coin(OBJECT_START_VERSION, ObjectID::random(), value);
1607 Object::new_move(
1608 obj,
1609 Owner::AddressOwner(owner),
1610 TransactionDigest::genesis_marker(),
1611 )
1612 }
1613
1614 pub fn new_gas_for_testing() -> Self {
1616 let gas_object_id = ObjectID::random();
1617 let (owner, _) = deterministic_random_account_key();
1618 Object::with_id_owner_for_testing(gas_object_id, owner)
1619 }
1620}
1621
1622pub fn generate_test_gas_objects() -> Vec<Object> {
1624 thread_local! {
1625 static GAS_OBJECTS: Vec<Object> = (0..50)
1626 .map(|_| {
1627 let gas_object_id = ObjectID::random();
1628 let (owner, _) = deterministic_random_account_key();
1629 Object::with_id_owner_for_testing(gas_object_id, owner)
1630 })
1631 .collect();
1632 }
1633
1634 GAS_OBJECTS.with(|v| v.clone())
1635}
1636
1637#[allow(clippy::large_enum_variant)]
1638#[derive(Serialize, Deserialize, Debug)]
1639#[serde(tag = "status", content = "details")]
1640pub enum ObjectRead {
1641 NotExists(ObjectID),
1642 Exists(ObjectRef, Object, Option<MoveStructLayout>),
1643 Deleted(ObjectRef),
1644}
1645
1646impl ObjectRead {
1647 pub fn into_object(self) -> UserInputResult<Object> {
1650 match self {
1651 Self::Deleted(oref) => Err(UserInputError::ObjectDeleted { object_ref: oref }),
1652 Self::NotExists(id) => Err(UserInputError::ObjectNotFound {
1653 object_id: id,
1654 version: None,
1655 }),
1656 Self::Exists(_, o, _) => Ok(o),
1657 }
1658 }
1659
1660 pub fn object(&self) -> UserInputResult<&Object> {
1661 match self {
1662 Self::Deleted(oref) => Err(UserInputError::ObjectDeleted { object_ref: *oref }),
1663 Self::NotExists(id) => Err(UserInputError::ObjectNotFound {
1664 object_id: *id,
1665 version: None,
1666 }),
1667 Self::Exists(_, o, _) => Ok(o),
1668 }
1669 }
1670
1671 pub fn object_id(&self) -> ObjectID {
1672 match self {
1673 Self::Deleted(oref) => oref.0,
1674 Self::NotExists(id) => *id,
1675 Self::Exists(oref, _, _) => oref.0,
1676 }
1677 }
1678}
1679
1680impl Display for ObjectRead {
1681 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1682 match self {
1683 Self::Deleted(oref) => {
1684 write!(f, "ObjectRead::Deleted ({:?})", oref)
1685 }
1686 Self::NotExists(id) => {
1687 write!(f, "ObjectRead::NotExists ({:?})", id)
1688 }
1689 Self::Exists(oref, _, _) => {
1690 write!(f, "ObjectRead::Exists ({:?})", oref)
1691 }
1692 }
1693 }
1694}
1695
1696#[allow(clippy::large_enum_variant)]
1697#[derive(Serialize, Deserialize, Debug)]
1698#[serde(tag = "status", content = "details")]
1699pub enum PastObjectRead {
1700 ObjectNotExists(ObjectID),
1702 ObjectDeleted(ObjectRef),
1704 VersionFound(ObjectRef, Object, Option<MoveStructLayout>),
1706 VersionNotFound(ObjectID, SequenceNumber),
1708 VersionTooHigh {
1710 object_id: ObjectID,
1711 asked_version: SequenceNumber,
1712 latest_version: SequenceNumber,
1713 },
1714}
1715
1716impl PastObjectRead {
1717 pub fn into_object(self) -> UserInputResult<Object> {
1719 match self {
1720 Self::ObjectDeleted(oref) => Err(UserInputError::ObjectDeleted { object_ref: oref }),
1721 Self::ObjectNotExists(id) => Err(UserInputError::ObjectNotFound {
1722 object_id: id,
1723 version: None,
1724 }),
1725 Self::VersionFound(_, o, _) => Ok(o),
1726 Self::VersionNotFound(object_id, version) => Err(UserInputError::ObjectNotFound {
1727 object_id,
1728 version: Some(version),
1729 }),
1730 Self::VersionTooHigh {
1731 object_id,
1732 asked_version,
1733 latest_version,
1734 } => Err(UserInputError::ObjectSequenceNumberTooHigh {
1735 object_id,
1736 asked_version,
1737 latest_version,
1738 }),
1739 }
1740 }
1741}
1742
1743impl Display for PastObjectRead {
1744 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1745 match self {
1746 Self::ObjectDeleted(oref) => {
1747 write!(f, "PastObjectRead::ObjectDeleted ({:?})", oref)
1748 }
1749 Self::ObjectNotExists(id) => {
1750 write!(f, "PastObjectRead::ObjectNotExists ({:?})", id)
1751 }
1752 Self::VersionFound(oref, _, _) => {
1753 write!(f, "PastObjectRead::VersionFound ({:?})", oref)
1754 }
1755 Self::VersionNotFound(object_id, version) => {
1756 write!(
1757 f,
1758 "PastObjectRead::VersionNotFound ({:?}, asked sequence number {:?})",
1759 object_id, version
1760 )
1761 }
1762 Self::VersionTooHigh {
1763 object_id,
1764 asked_version,
1765 latest_version,
1766 } => {
1767 write!(
1768 f,
1769 "PastObjectRead::VersionTooHigh ({:?}, asked sequence number {:?}, latest sequence number {:?})",
1770 object_id, asked_version, latest_version
1771 )
1772 }
1773 }
1774 }
1775}
1776
1777#[cfg(test)]
1778mod tests {
1779 use crate::object::{OBJECT_START_VERSION, Object, Owner};
1780 use crate::{
1781 base_types::{ObjectID, SuiAddress, TransactionDigest},
1782 gas_coin::GasCoin,
1783 };
1784
1785 #[test]
1787 fn test_object_digest_and_serialized_format() {
1788 let g =
1789 GasCoin::new_for_testing_with_id(ObjectID::ZERO, 123).to_object(OBJECT_START_VERSION);
1790 let o = Object::new_move(
1791 g,
1792 Owner::AddressOwner(SuiAddress::ZERO),
1793 TransactionDigest::ZERO,
1794 );
1795 let bytes = bcs::to_bytes(&o).unwrap();
1796
1797 assert_eq!(
1798 bytes,
1799 [
1800 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1801 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1802 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1803 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1804 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1805 ]
1806 );
1807
1808 let objref = format!("{:?}", o.compute_object_reference());
1809 assert_eq!(
1810 objref,
1811 "(0x0000000000000000000000000000000000000000000000000000000000000000, SequenceNumber(1), o#59tZq65HVqZjUyNtD7BCGLTD87N5cpayYwEFrtwR4aMz)"
1812 );
1813 }
1814
1815 #[test]
1816 fn test_get_coin_value_unsafe() {
1817 fn test_for_value(v: u64) {
1818 let g = GasCoin::new_for_testing(v).to_object(OBJECT_START_VERSION);
1819 assert_eq!(g.get_coin_value_unsafe(), v);
1820 assert_eq!(GasCoin::try_from(&g).unwrap().value(), v);
1821 }
1822
1823 test_for_value(0);
1824 test_for_value(1);
1825 test_for_value(8);
1826 test_for_value(9);
1827 test_for_value(u8::MAX as u64);
1828 test_for_value(u8::MAX as u64 + 1);
1829 test_for_value(u16::MAX as u64);
1830 test_for_value(u16::MAX as u64 + 1);
1831 test_for_value(u32::MAX as u64);
1832 test_for_value(u32::MAX as u64 + 1);
1833 test_for_value(u64::MAX);
1834 }
1835
1836 #[test]
1837 fn test_set_coin_value_unsafe() {
1838 fn test_for_value(v: u64) {
1839 let mut g = GasCoin::new_for_testing(u64::MAX).to_object(OBJECT_START_VERSION);
1840 g.set_coin_value_unsafe(v);
1841 assert_eq!(g.get_coin_value_unsafe(), v);
1842 assert_eq!(GasCoin::try_from(&g).unwrap().value(), v);
1843 assert_eq!(g.version(), OBJECT_START_VERSION);
1844 assert_eq!(g.contents().len(), 40);
1845 }
1846
1847 test_for_value(0);
1848 test_for_value(1);
1849 test_for_value(8);
1850 test_for_value(9);
1851 test_for_value(u8::MAX as u64);
1852 test_for_value(u8::MAX as u64 + 1);
1853 test_for_value(u16::MAX as u64);
1854 test_for_value(u16::MAX as u64 + 1);
1855 test_for_value(u32::MAX as u64);
1856 test_for_value(u32::MAX as u64 + 1);
1857 test_for_value(u64::MAX);
1858 }
1859
1860 #[test]
1861 fn test_owner_variant_sizes() {
1862 use super::{Party, SequenceNumber};
1863
1864 assert_eq!(std::mem::size_of::<SuiAddress>(), 32);
1866 assert_eq!(std::mem::size_of::<SequenceNumber>(), 8);
1868 assert_eq!(std::mem::size_of::<(SequenceNumber, SuiAddress)>(), 40);
1870 assert_eq!(std::mem::size_of::<(SequenceNumber, Party)>(), 40);
1872
1873 assert_eq!(std::mem::size_of::<Owner>(), 48);
1875 }
1876}