iota_graphql_rpc/types/
move_object.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use async_graphql::{connection::Connection, *};
6use iota_names::config::IotaNamesConfig;
7use iota_types::{
8    TypeTag,
9    object::{Data, MoveObject as NativeMoveObject},
10};
11
12use crate::{
13    connection::ScanConnection,
14    data::Db,
15    error::Error,
16    types::{
17        balance::{self, Balance},
18        base64::Base64,
19        big_int::BigInt,
20        coin::{Coin, CoinDowncastError},
21        coin_metadata::{CoinMetadata, CoinMetadataDowncastError},
22        cursor::Page,
23        display::DisplayEntry,
24        dynamic_field::{DynamicField, DynamicFieldName},
25        iota_address::IotaAddress,
26        iota_names_registration::{NameFormat, NameRegistration, NameRegistrationDowncastError},
27        move_type::MoveType,
28        move_value::MoveValue,
29        object::{self, Object, ObjectFilter, ObjectImpl, ObjectLookup, ObjectOwner, ObjectStatus},
30        owner::OwnerImpl,
31        stake::{StakedIota, StakedIotaDowncastError},
32        transaction_block::{self, TransactionBlock, TransactionBlockFilter},
33        type_filter::ExactTypeFilter,
34        uint53::UInt53,
35    },
36};
37
38#[derive(Clone)]
39pub(crate) struct MoveObject {
40    /// Representation of this Move Object as a generic Object.
41    pub super_: Object,
42
43    /// Move-object-specific data, extracted from the native representation at
44    /// `graphql_object.native_object.data`.
45    pub native: NativeMoveObject,
46}
47
48/// Type to implement GraphQL fields that are shared by all MoveObjects.
49pub(crate) struct MoveObjectImpl<'o>(pub &'o MoveObject);
50
51pub(crate) enum MoveObjectDowncastError {
52    WrappedOrDeleted,
53    NotAMoveObject,
54}
55
56/// This interface is implemented by types that represent a Move object on-chain
57/// (A Move value whose type has `key`).
58#[expect(clippy::duplicated_attributes)]
59#[derive(Interface)]
60#[graphql(
61    name = "IMoveObject",
62    field(
63        name = "contents",
64        ty = "Option<MoveValue>",
65        desc = "Displays the contents of the Move object in a JSON string and through GraphQL \
66                types. Also provides the flat representation of the type signature, and the BCS of \
67                the corresponding data."
68    ),
69    field(
70        name = "display",
71        ty = "Option<Vec<DisplayEntry>>",
72        desc = "The set of named templates defined on-chain for the type of this object, to be \
73                handled off-chain. The server substitutes data from the object into these \
74                templates to generate a display string per template."
75    ),
76    field(
77        name = "dynamic_field",
78        arg(name = "name", ty = "DynamicFieldName"),
79        ty = "Option<DynamicField>",
80        desc = "Access a dynamic field on an object using its name. Names are arbitrary Move \
81                values whose type have `copy`, `drop`, and `store`, and are specified using their \
82                type, and their BCS contents, Base64 encoded.\n\n\
83                Dynamic fields on wrapped objects can be accessed by using the same API under the \
84                Ownertype."
85    ),
86    field(
87        name = "dynamic_object_field",
88        arg(name = "name", ty = "DynamicFieldName"),
89        ty = "Option<DynamicField>",
90        desc = "Access a dynamic object field on an object using its name. Names are arbitrary \
91                Move values whose type have `copy`, `drop`, and `store`, and are specified using \
92                their type, and their BCS contents, Base64 encoded. The value of a dynamic object \
93                field can also be accessed off-chain directly via its address (e.g. using \
94                `Query.object`).\n\n\
95                Dynamic fields on wrapped objects can be accessed by using the same API under the \
96                Owner type."
97    ),
98    field(
99        name = "dynamic_fields",
100        arg(name = "first", ty = "Option<u64>"),
101        arg(name = "after", ty = "Option<object::Cursor>"),
102        arg(name = "last", ty = "Option<u64>"),
103        arg(name = "before", ty = "Option<object::Cursor>"),
104        ty = "Connection<String, DynamicField>",
105        desc = "The dynamic fields and dynamic object fields on an object.\n\n\
106                Dynamic fields on wrapped objects can be accessed by using the same API under the \
107                Owner type."
108    )
109)]
110pub(crate) enum IMoveObject {
111    MoveObject(MoveObject),
112    Coin(Coin),
113    CoinMetadata(CoinMetadata),
114    StakedIota(StakedIota),
115    NameRegistration(NameRegistration),
116}
117
118/// The representation of an object as a Move Object, which exposes additional
119/// information (content, module that governs it, version, is transferrable,
120/// etc.) about this object.
121#[Object]
122impl MoveObject {
123    pub(crate) async fn address(&self) -> IotaAddress {
124        OwnerImpl::from(&self.super_).address().await
125    }
126
127    /// Objects owned by this object, optionally `filter`-ed.
128    pub(crate) async fn objects(
129        &self,
130        ctx: &Context<'_>,
131        first: Option<u64>,
132        after: Option<object::Cursor>,
133        last: Option<u64>,
134        before: Option<object::Cursor>,
135        filter: Option<ObjectFilter>,
136    ) -> Result<Connection<String, MoveObject>> {
137        OwnerImpl::from(&self.super_)
138            .objects(ctx, first, after, last, before, filter)
139            .await
140    }
141
142    /// Total balance of all coins with marker type owned by this object. If
143    /// type is not supplied, it defaults to `0x2::iota::IOTA`.
144    pub(crate) async fn balance(
145        &self,
146        ctx: &Context<'_>,
147        type_: Option<ExactTypeFilter>,
148    ) -> Result<Option<Balance>> {
149        OwnerImpl::from(&self.super_).balance(ctx, type_).await
150    }
151
152    /// The balances of all coin types owned by this object.
153    pub(crate) async fn balances(
154        &self,
155        ctx: &Context<'_>,
156        first: Option<u64>,
157        after: Option<balance::Cursor>,
158        last: Option<u64>,
159        before: Option<balance::Cursor>,
160    ) -> Result<Connection<String, Balance>> {
161        OwnerImpl::from(&self.super_)
162            .balances(ctx, first, after, last, before)
163            .await
164    }
165
166    /// The coin objects for this object.
167    ///
168    /// `type` is a filter on the coin's type parameter, defaulting to
169    /// `0x2::iota::IOTA`.
170    pub(crate) async fn coins(
171        &self,
172        ctx: &Context<'_>,
173        first: Option<u64>,
174        after: Option<object::Cursor>,
175        last: Option<u64>,
176        before: Option<object::Cursor>,
177        type_: Option<ExactTypeFilter>,
178    ) -> Result<Connection<String, Coin>> {
179        OwnerImpl::from(&self.super_)
180            .coins(ctx, first, after, last, before, type_)
181            .await
182    }
183
184    /// The `0x3::staking_pool::StakedIota` objects owned by this object.
185    pub(crate) async fn staked_iotas(
186        &self,
187        ctx: &Context<'_>,
188        first: Option<u64>,
189        after: Option<object::Cursor>,
190        last: Option<u64>,
191        before: Option<object::Cursor>,
192    ) -> Result<Connection<String, StakedIota>> {
193        OwnerImpl::from(&self.super_)
194            .staked_iotas(ctx, first, after, last, before)
195            .await
196    }
197
198    /// The name explicitly configured as the default name pointing to this
199    /// object.
200    pub(crate) async fn iota_names_default_name(
201        &self,
202        ctx: &Context<'_>,
203        format: Option<NameFormat>,
204    ) -> Result<Option<String>> {
205        OwnerImpl::from(&self.super_)
206            .iota_names_default_name(ctx, format)
207            .await
208    }
209
210    /// The NameRegistration NFTs owned by this object. These grant the
211    /// owner the capability to manage the associated name.
212    pub(crate) async fn iota_names_registrations(
213        &self,
214        ctx: &Context<'_>,
215        first: Option<u64>,
216        after: Option<object::Cursor>,
217        last: Option<u64>,
218        before: Option<object::Cursor>,
219    ) -> Result<Connection<String, NameRegistration>> {
220        OwnerImpl::from(&self.super_)
221            .iota_names_registrations(ctx, first, after, last, before)
222            .await
223    }
224
225    pub(crate) async fn version(&self) -> UInt53 {
226        ObjectImpl(&self.super_).version().await
227    }
228
229    /// The current status of the object as read from the off-chain store. The
230    /// possible states are:
231    /// - NOT_INDEXED: The object is loaded from serialized data, such as the
232    ///   contents of a genesis or system package upgrade transaction.
233    /// - INDEXED: The object is retrieved from the off-chain index and
234    ///   represents the most recent or historical state of the object.
235    /// - WRAPPED_OR_DELETED: The object is deleted or wrapped and only partial
236    ///   information can be loaded.
237    pub(crate) async fn status(&self) -> ObjectStatus {
238        ObjectImpl(&self.super_).status().await
239    }
240
241    /// 32-byte hash that identifies the object's contents, encoded as a Base58
242    /// string.
243    pub(crate) async fn digest(&self) -> Option<String> {
244        ObjectImpl(&self.super_).digest().await
245    }
246
247    /// The owner type of this object: Immutable, Shared, Parent, Address
248    pub(crate) async fn owner(&self, ctx: &Context<'_>) -> Option<ObjectOwner> {
249        ObjectImpl(&self.super_).owner(ctx).await
250    }
251
252    /// The transaction block that created this version of the object.
253    pub(crate) async fn previous_transaction_block(
254        &self,
255        ctx: &Context<'_>,
256    ) -> Result<Option<TransactionBlock>> {
257        ObjectImpl(&self.super_)
258            .previous_transaction_block(ctx)
259            .await
260    }
261
262    /// The amount of IOTA we would rebate if this object gets deleted or
263    /// mutated. This number is recalculated based on the present storage
264    /// gas price.
265    pub(crate) async fn storage_rebate(&self) -> Option<BigInt> {
266        ObjectImpl(&self.super_).storage_rebate().await
267    }
268
269    /// The transaction blocks that sent objects to this object.
270    ///
271    /// `scanLimit` restricts the number of candidate transactions scanned when
272    /// gathering a page of results. It is required for queries that apply
273    /// more than two complex filters (on function, kind, sender, recipient,
274    /// input object, changed object, or ids), and can be at most
275    /// `serviceConfig.maxScanLimit`.
276    ///
277    /// When the scan limit is reached the page will be returned even if it has
278    /// fewer than `first` results when paginating forward (`last` when
279    /// paginating backwards). If there are more transactions to scan,
280    /// `pageInfo.hasNextPage` (or `pageInfo.hasPreviousPage`) will be set to
281    /// `true`, and `PageInfo.endCursor` (or `PageInfo.startCursor`) will be set
282    /// to the last transaction that was scanned as opposed to the last (or
283    /// first) transaction in the page.
284    ///
285    /// Requesting the next (or previous) page after this cursor will resume the
286    /// search, scanning the next `scanLimit` many transactions in the
287    /// direction of pagination, and so on until all transactions in the
288    /// scanning range have been visited.
289    ///
290    /// By default, the scanning range includes all transactions known to
291    /// GraphQL, but it can be restricted by the `after` and `before`
292    /// cursors, and the `beforeCheckpoint`, `afterCheckpoint` and
293    /// `atCheckpoint` filters.
294    pub(crate) async fn received_transaction_blocks(
295        &self,
296        ctx: &Context<'_>,
297        first: Option<u64>,
298        after: Option<transaction_block::Cursor>,
299        last: Option<u64>,
300        before: Option<transaction_block::Cursor>,
301        filter: Option<TransactionBlockFilter>,
302        scan_limit: Option<u64>,
303    ) -> Result<ScanConnection<String, TransactionBlock>> {
304        ObjectImpl(&self.super_)
305            .received_transaction_blocks(ctx, first, after, last, before, filter, scan_limit)
306            .await
307    }
308
309    /// The Base64-encoded BCS serialization of the object's content.
310    pub(crate) async fn bcs(&self) -> Result<Option<Base64>> {
311        ObjectImpl(&self.super_).bcs().await
312    }
313
314    /// Displays the contents of the Move object in a JSON string and through
315    /// GraphQL types. Also provides the flat representation of the type
316    /// signature, and the BCS of the corresponding data.
317    pub(crate) async fn contents(&self) -> Option<MoveValue> {
318        MoveObjectImpl(self).contents().await
319    }
320
321    /// The set of named templates defined on-chain for the type of this object,
322    /// to be handled off-chain. The server substitutes data from the object
323    /// into these templates to generate a display string per template.
324    pub(crate) async fn display(&self, ctx: &Context<'_>) -> Result<Option<Vec<DisplayEntry>>> {
325        ObjectImpl(&self.super_).display(ctx).await
326    }
327
328    /// Access a dynamic field on an object using its name. Names are arbitrary
329    /// Move values whose type have `copy`, `drop`, and `store`, and are
330    /// specified using their type, and their BCS contents, Base64 encoded.
331    ///
332    /// Dynamic fields on wrapped objects can be accessed by using the same API
333    /// under the Owner type.
334    pub(crate) async fn dynamic_field(
335        &self,
336        ctx: &Context<'_>,
337        name: DynamicFieldName,
338    ) -> Result<Option<DynamicField>> {
339        OwnerImpl::from(&self.super_)
340            .dynamic_field(ctx, name, Some(self.root_version()))
341            .await
342    }
343
344    /// Access a dynamic object field on an object using its name. Names are
345    /// arbitrary Move values whose type have `copy`, `drop`, and `store`,
346    /// and are specified using their type, and their BCS contents, Base64
347    /// encoded. The value of a dynamic object field can also be accessed
348    /// off-chain directly via its address (e.g. using `Query.object`).
349    ///
350    /// Dynamic fields on wrapped objects can be accessed by using the same API
351    /// under the Owner type.
352    pub(crate) async fn dynamic_object_field(
353        &self,
354        ctx: &Context<'_>,
355        name: DynamicFieldName,
356    ) -> Result<Option<DynamicField>> {
357        OwnerImpl::from(&self.super_)
358            .dynamic_object_field(ctx, name, Some(self.root_version()))
359            .await
360    }
361
362    /// The dynamic fields and dynamic object fields on an object.
363    ///
364    /// Dynamic fields on wrapped objects can be accessed by using the same API
365    /// under the Owner type.
366    pub(crate) async fn dynamic_fields(
367        &self,
368        ctx: &Context<'_>,
369        first: Option<u64>,
370        after: Option<object::Cursor>,
371        last: Option<u64>,
372        before: Option<object::Cursor>,
373    ) -> Result<Connection<String, DynamicField>> {
374        OwnerImpl::from(&self.super_)
375            .dynamic_fields(ctx, first, after, last, before, Some(self.root_version()))
376            .await
377    }
378
379    /// Attempts to convert the Move object into a `0x2::coin::Coin`.
380    async fn as_coin(&self) -> Result<Option<Coin>> {
381        match Coin::try_from(self) {
382            Ok(coin) => Ok(Some(coin)),
383            Err(CoinDowncastError::NotACoin) => Ok(None),
384            Err(CoinDowncastError::Bcs(e)) => {
385                Err(Error::Internal(format!("Failed to deserialize Coin: {e}"))).extend()
386            }
387        }
388    }
389
390    /// Attempts to convert the Move object into a
391    /// `0x3::staking_pool::StakedIota`.
392    async fn as_staked_iota(&self) -> Result<Option<StakedIota>> {
393        match StakedIota::try_from(self) {
394            Ok(coin) => Ok(Some(coin)),
395            Err(StakedIotaDowncastError::NotAStakedIota) => Ok(None),
396            Err(StakedIotaDowncastError::Bcs(e)) => Err(Error::Internal(format!(
397                "Failed to deserialize StakedIota: {e}"
398            )))
399            .extend(),
400        }
401    }
402
403    /// Attempts to convert the Move object into a `0x2::coin::CoinMetadata`.
404    async fn as_coin_metadata(&self) -> Result<Option<CoinMetadata>> {
405        match CoinMetadata::try_from(self) {
406            Ok(metadata) => Ok(Some(metadata)),
407            Err(CoinMetadataDowncastError::NotCoinMetadata) => Ok(None),
408            Err(CoinMetadataDowncastError::Bcs(e)) => Err(Error::Internal(format!(
409                "Failed to deserialize CoinMetadata: {e}"
410            )))
411            .extend(),
412        }
413    }
414
415    // Attempts to convert the Move object into a `NameRegistration` object.
416    async fn as_iota_names_registration(
417        &self,
418        ctx: &Context<'_>,
419    ) -> Result<Option<NameRegistration>> {
420        let cfg: &IotaNamesConfig = ctx.data_unchecked();
421        let tag = NameRegistration::type_(cfg.package_address.into());
422
423        match NameRegistration::try_from(self, &tag) {
424            Ok(registration) => Ok(Some(registration)),
425            Err(NameRegistrationDowncastError::NotAnNameRegistration) => Ok(None),
426            Err(NameRegistrationDowncastError::Bcs(e)) => Err(Error::Internal(format!(
427                "Failed to deserialize
428     NameRegistration: {e}",
429            )))
430            .extend(),
431        }
432    }
433}
434
435impl MoveObjectImpl<'_> {
436    pub(crate) async fn contents(&self) -> Option<MoveValue> {
437        let type_ = TypeTag::from(self.0.native.type_().clone());
438        Some(MoveValue::new(type_, self.0.native.contents().into()))
439    }
440    pub(crate) async fn has_public_transfer(&self, ctx: &Context<'_>) -> Result<bool> {
441        let type_: MoveType = self.0.native.type_().clone().into();
442        let set = type_.abilities_impl(ctx.data_unchecked()).await.extend()?;
443        Ok(set.is_some_and(|s| s.has_key() && s.has_store()))
444    }
445}
446
447impl MoveObject {
448    pub(crate) async fn query(
449        ctx: &Context<'_>,
450        address: IotaAddress,
451        key: ObjectLookup,
452    ) -> Result<Option<Self>, Error> {
453        let Some(object) = Object::query(ctx, address, key).await? else {
454            return Ok(None);
455        };
456
457        match MoveObject::try_from(&object) {
458            Ok(object) => Ok(Some(object)),
459            Err(MoveObjectDowncastError::WrappedOrDeleted) => Ok(None),
460            Err(MoveObjectDowncastError::NotAMoveObject) => {
461                Err(Error::Internal(format!("{address} is not a Move object")))?
462            }
463        }
464    }
465
466    /// Query the database for a `page` of Move objects, optionally `filter`-ed.
467    ///
468    /// `checkpoint_viewed_at` represents the checkpoint sequence number at
469    /// which this page was queried for. Each entity returned in the
470    /// connection will inherit this checkpoint, so that when viewing that
471    /// entity's state, it will be as if it was read at the same checkpoint.
472    pub(crate) async fn paginate(
473        db: &Db,
474        page: Page<object::Cursor>,
475        filter: ObjectFilter,
476        checkpoint_viewed_at: u64,
477    ) -> Result<Connection<String, MoveObject>, Error> {
478        Object::paginate_subtype(db, page, filter, checkpoint_viewed_at, |object| {
479            let address = object.address;
480            MoveObject::try_from(&object).map_err(|_| {
481                Error::Internal(format!(
482                    "Expected {address} to be a Move object, but it's not."
483                ))
484            })
485        })
486        .await
487    }
488
489    /// Root parent object version for dynamic fields.
490    ///
491    /// Check [`Object::root_version`] for details.
492    pub(crate) fn root_version(&self) -> u64 {
493        self.super_.root_version()
494    }
495}
496
497impl TryFrom<&Object> for MoveObject {
498    type Error = MoveObjectDowncastError;
499
500    fn try_from(object: &Object) -> Result<Self, Self::Error> {
501        let Some(native) = object.native_impl() else {
502            return Err(MoveObjectDowncastError::WrappedOrDeleted);
503        };
504
505        if let Data::Move(move_object) = &native.data {
506            Ok(Self {
507                super_: object.clone(),
508                native: move_object.clone(),
509            })
510        } else {
511            Err(MoveObjectDowncastError::NotAMoveObject)
512        }
513    }
514}