iota_graphql_rpc/types/
coin_metadata.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_types::{
7    TypeTag,
8    coin::{CoinMetadata as NativeCoinMetadata, TreasuryCap},
9    gas_coin::GAS,
10};
11
12use crate::{
13    connection::ScanConnection,
14    context_data::db_data_provider::PgManager,
15    data::Db,
16    error::Error,
17    types::{
18        balance::{self, Balance},
19        base64::Base64,
20        big_int::BigInt,
21        coin::Coin,
22        display::DisplayEntry,
23        dynamic_field::{DynamicField, DynamicFieldName},
24        iota_address::IotaAddress,
25        iota_names_registration::{NameFormat, NameRegistration},
26        move_object::{MoveObject, MoveObjectImpl},
27        move_value::MoveValue,
28        object::{self, Object, ObjectFilter, ObjectImpl, ObjectOwner, ObjectStatus},
29        owner::OwnerImpl,
30        stake::StakedIota,
31        system_state_summary::SystemStateSummaryView,
32        transaction_block::{self, TransactionBlock, TransactionBlockFilter},
33        type_filter::ExactTypeFilter,
34        uint53::UInt53,
35    },
36};
37
38pub(crate) struct CoinMetadata {
39    pub super_: MoveObject,
40    pub native: NativeCoinMetadata,
41}
42
43pub(crate) enum CoinMetadataDowncastError {
44    NotCoinMetadata,
45    Bcs(bcs::Error),
46}
47
48/// The metadata for a coin type.
49#[Object]
50impl CoinMetadata {
51    pub(crate) async fn address(&self) -> IotaAddress {
52        OwnerImpl::from(&self.super_.super_).address().await
53    }
54
55    /// Objects owned by this object, optionally `filter`-ed.
56    pub(crate) async fn objects(
57        &self,
58        ctx: &Context<'_>,
59        first: Option<u64>,
60        after: Option<object::Cursor>,
61        last: Option<u64>,
62        before: Option<object::Cursor>,
63        filter: Option<ObjectFilter>,
64    ) -> Result<Connection<String, MoveObject>> {
65        OwnerImpl::from(&self.super_.super_)
66            .objects(ctx, first, after, last, before, filter)
67            .await
68    }
69
70    /// Total balance of all coins with marker type owned by this object. If
71    /// type is not supplied, it defaults to `0x2::iota::IOTA`.
72    pub(crate) async fn balance(
73        &self,
74        ctx: &Context<'_>,
75        type_: Option<ExactTypeFilter>,
76    ) -> Result<Option<Balance>> {
77        OwnerImpl::from(&self.super_.super_)
78            .balance(ctx, type_)
79            .await
80    }
81
82    /// The balances of all coin types owned by this object.
83    pub(crate) async fn balances(
84        &self,
85        ctx: &Context<'_>,
86        first: Option<u64>,
87        after: Option<balance::Cursor>,
88        last: Option<u64>,
89        before: Option<balance::Cursor>,
90    ) -> Result<Connection<String, Balance>> {
91        OwnerImpl::from(&self.super_.super_)
92            .balances(ctx, first, after, last, before)
93            .await
94    }
95
96    /// The coin objects for this object.
97    ///
98    /// `type` is a filter on the coin's type parameter, defaulting to
99    /// `0x2::iota::IOTA`.
100    pub(crate) async fn coins(
101        &self,
102        ctx: &Context<'_>,
103        first: Option<u64>,
104        after: Option<object::Cursor>,
105        last: Option<u64>,
106        before: Option<object::Cursor>,
107        type_: Option<ExactTypeFilter>,
108    ) -> Result<Connection<String, Coin>> {
109        OwnerImpl::from(&self.super_.super_)
110            .coins(ctx, first, after, last, before, type_)
111            .await
112    }
113
114    /// The `0x3::staking_pool::StakedIota` objects owned by this object.
115    pub(crate) async fn staked_iotas(
116        &self,
117        ctx: &Context<'_>,
118        first: Option<u64>,
119        after: Option<object::Cursor>,
120        last: Option<u64>,
121        before: Option<object::Cursor>,
122    ) -> Result<Connection<String, StakedIota>> {
123        OwnerImpl::from(&self.super_.super_)
124            .staked_iotas(ctx, first, after, last, before)
125            .await
126    }
127
128    /// The name explicitly configured as the default name pointing to this
129    /// object.
130    pub(crate) async fn iota_names_default_name(
131        &self,
132        ctx: &Context<'_>,
133        format: Option<NameFormat>,
134    ) -> Result<Option<String>> {
135        OwnerImpl::from(&self.super_.super_)
136            .iota_names_default_name(ctx, format)
137            .await
138    }
139
140    /// The NameRegistration NFTs owned by this object. These grant the
141    /// owner the capability to manage the associated name.
142    pub(crate) async fn iota_names_registrations(
143        &self,
144        ctx: &Context<'_>,
145        first: Option<u64>,
146        after: Option<object::Cursor>,
147        last: Option<u64>,
148        before: Option<object::Cursor>,
149    ) -> Result<Connection<String, NameRegistration>> {
150        OwnerImpl::from(&self.super_.super_)
151            .iota_names_registrations(ctx, first, after, last, before)
152            .await
153    }
154
155    pub(crate) async fn version(&self) -> UInt53 {
156        ObjectImpl(&self.super_.super_).version().await
157    }
158
159    /// The current status of the object as read from the off-chain store. The
160    /// possible states are:
161    /// - NOT_INDEXED: The object is loaded from serialized data, such as the
162    ///   contents of a genesis or system package upgrade transaction.
163    /// - INDEXED: The object is retrieved from the off-chain index and
164    ///   represents the most recent or historical state of the object.
165    /// - WRAPPED_OR_DELETED: The object is deleted or wrapped and only partial
166    ///   information can be loaded.
167    pub(crate) async fn status(&self) -> ObjectStatus {
168        ObjectImpl(&self.super_.super_).status().await
169    }
170
171    /// 32-byte hash that identifies the object's contents, encoded as a Base58
172    /// string.
173    pub(crate) async fn digest(&self) -> Option<String> {
174        ObjectImpl(&self.super_.super_).digest().await
175    }
176
177    /// The owner type of this object: Immutable, Shared, Parent, Address
178    pub(crate) async fn owner(&self, ctx: &Context<'_>) -> Option<ObjectOwner> {
179        ObjectImpl(&self.super_.super_).owner(ctx).await
180    }
181
182    /// The transaction block that created this version of the object.
183    pub(crate) async fn previous_transaction_block(
184        &self,
185        ctx: &Context<'_>,
186    ) -> Result<Option<TransactionBlock>> {
187        ObjectImpl(&self.super_.super_)
188            .previous_transaction_block(ctx)
189            .await
190    }
191
192    /// The amount of IOTA we would rebate if this object gets deleted or
193    /// mutated. This number is recalculated based on the present storage
194    /// gas price.
195    pub(crate) async fn storage_rebate(&self) -> Option<BigInt> {
196        ObjectImpl(&self.super_.super_).storage_rebate().await
197    }
198
199    /// The transaction blocks that sent objects to this object.
200    ///
201    /// `scanLimit` restricts the number of candidate transactions scanned when
202    /// gathering a page of results. It is required for queries that apply
203    /// more than two complex filters (on function, kind, sender, recipient,
204    /// input object, changed object, or ids), and can be at most
205    /// `serviceConfig.maxScanLimit`.
206    ///
207    /// When the scan limit is reached the page will be returned even if it has
208    /// fewer than `first` results when paginating forward (`last` when
209    /// paginating backwards). If there are more transactions to scan,
210    /// `pageInfo.hasNextPage` (or `pageInfo.hasPreviousPage`) will be set to
211    /// `true`, and `PageInfo.endCursor` (or `PageInfo.startCursor`) will be set
212    /// to the last transaction that was scanned as opposed to the last (or
213    /// first) transaction in the page.
214    ///
215    /// Requesting the next (or previous) page after this cursor will resume the
216    /// search, scanning the next `scanLimit` many transactions in the
217    /// direction of pagination, and so on until all transactions in the
218    /// scanning range have been visited.
219    ///
220    /// By default, the scanning range includes all transactions known to
221    /// GraphQL, but it can be restricted by the `after` and `before`
222    /// cursors, and the `beforeCheckpoint`, `afterCheckpoint` and
223    /// `atCheckpoint` filters.
224    pub(crate) async fn received_transaction_blocks(
225        &self,
226        ctx: &Context<'_>,
227        first: Option<u64>,
228        after: Option<transaction_block::Cursor>,
229        last: Option<u64>,
230        before: Option<transaction_block::Cursor>,
231        filter: Option<TransactionBlockFilter>,
232        scan_limit: Option<u64>,
233    ) -> Result<ScanConnection<String, TransactionBlock>> {
234        ObjectImpl(&self.super_.super_)
235            .received_transaction_blocks(ctx, first, after, last, before, filter, scan_limit)
236            .await
237    }
238
239    /// The Base64-encoded BCS serialization of the object's content.
240    pub(crate) async fn bcs(&self) -> Result<Option<Base64>> {
241        ObjectImpl(&self.super_.super_).bcs().await
242    }
243
244    /// Displays the contents of the Move object in a JSON string and through
245    /// GraphQL types. Also provides the flat representation of the type
246    /// signature, and the BCS of the corresponding data.
247    pub(crate) async fn contents(&self) -> Option<MoveValue> {
248        MoveObjectImpl(&self.super_).contents().await
249    }
250
251    /// The set of named templates defined on-chain for the type of this object,
252    /// to be handled off-chain. The server substitutes data from the object
253    /// into these templates to generate a display string per template.
254    pub(crate) async fn display(&self, ctx: &Context<'_>) -> Result<Option<Vec<DisplayEntry>>> {
255        ObjectImpl(&self.super_.super_).display(ctx).await
256    }
257
258    /// Access a dynamic field on an object using its name. Names are arbitrary
259    /// Move values whose type have `copy`, `drop`, and `store`, and are
260    /// specified using their type, and their BCS contents, Base64 encoded.
261    ///
262    /// Dynamic fields on wrapped objects can be accessed by using the same API
263    /// under the Owner type.
264    pub(crate) async fn dynamic_field(
265        &self,
266        ctx: &Context<'_>,
267        name: DynamicFieldName,
268    ) -> Result<Option<DynamicField>> {
269        OwnerImpl::from(&self.super_.super_)
270            .dynamic_field(ctx, name, Some(self.super_.root_version()))
271            .await
272    }
273
274    /// Access a dynamic object field on an object using its name. Names are
275    /// arbitrary Move values whose type have `copy`, `drop`, and `store`,
276    /// and are specified using their type, and their BCS contents, Base64
277    /// encoded. The value of a dynamic object field can also be accessed
278    /// off-chain directly via its address (e.g. using `Query.object`).
279    ///
280    /// Dynamic fields on wrapped objects can be accessed by using the same API
281    /// under the Owner type.
282    pub(crate) async fn dynamic_object_field(
283        &self,
284        ctx: &Context<'_>,
285        name: DynamicFieldName,
286    ) -> Result<Option<DynamicField>> {
287        OwnerImpl::from(&self.super_.super_)
288            .dynamic_object_field(ctx, name, Some(self.super_.root_version()))
289            .await
290    }
291
292    /// The dynamic fields and dynamic object fields on an object.
293    ///
294    /// Dynamic fields on wrapped objects can be accessed by using the same API
295    /// under the Owner type.
296    pub(crate) async fn dynamic_fields(
297        &self,
298        ctx: &Context<'_>,
299        first: Option<u64>,
300        after: Option<object::Cursor>,
301        last: Option<u64>,
302        before: Option<object::Cursor>,
303    ) -> Result<Connection<String, DynamicField>> {
304        OwnerImpl::from(&self.super_.super_)
305            .dynamic_fields(
306                ctx,
307                first,
308                after,
309                last,
310                before,
311                Some(self.super_.root_version()),
312            )
313            .await
314    }
315
316    /// The number of decimal places used to represent the token.
317    async fn decimals(&self) -> Option<u8> {
318        Some(self.native.decimals)
319    }
320
321    /// Full, official name of the token.
322    async fn name(&self) -> Option<&str> {
323        Some(&self.native.name)
324    }
325
326    /// The token's identifying abbreviation.
327    async fn symbol(&self) -> Option<&str> {
328        Some(&self.native.symbol)
329    }
330
331    /// Optional description of the token, provided by the creator of the token.
332    async fn description(&self) -> Option<&str> {
333        Some(&self.native.description)
334    }
335
336    async fn icon_url(&self) -> Option<&str> {
337        self.native.icon_url.as_deref()
338    }
339
340    /// The overall quantity of tokens that will be issued.
341    async fn supply(&self, ctx: &Context<'_>) -> Result<Option<BigInt>> {
342        let mut type_params = self.super_.native.type_().type_params();
343        let Some(coin_type) = type_params.pop() else {
344            return Ok(None);
345        };
346
347        let supply = CoinMetadata::query_total_supply(
348            ctx,
349            coin_type,
350            self.super_.super_.checkpoint_viewed_at,
351        )
352        .await
353        .extend()?;
354
355        Ok(supply.map(BigInt::from))
356    }
357}
358
359impl CoinMetadata {
360    /// Read a `CoinMetadata` from the `db` for the coin whose inner type is
361    /// `coin_type`.
362    pub(crate) async fn query(
363        db: &Db,
364        coin_type: TypeTag,
365        checkpoint_viewed_at: u64,
366    ) -> Result<Option<CoinMetadata>, Error> {
367        let TypeTag::Struct(coin_struct) = coin_type else {
368            // If the type supplied is not metadata, we know it's not a valid coin type, so
369            // there won't be CoinMetadata for it.
370            return Ok(None);
371        };
372
373        let metadata_type = NativeCoinMetadata::type_(*coin_struct);
374        let Some(object) = Object::query_singleton(db, metadata_type, checkpoint_viewed_at).await?
375        else {
376            return Ok(None);
377        };
378
379        let move_object = MoveObject::try_from(&object).map_err(|_| {
380            Error::Internal(format!(
381                "Expected {} to be CoinMetadata, but it is not an object.",
382                object.address,
383            ))
384        })?;
385
386        let coin_metadata = CoinMetadata::try_from(&move_object).map_err(|_| {
387            Error::Internal(format!(
388                "Expected {} to be CoinMetadata, but it is not.",
389                object.address,
390            ))
391        })?;
392
393        Ok(Some(coin_metadata))
394    }
395
396    pub(crate) async fn query_total_supply(
397        ctx: &Context<'_>,
398        coin_type: TypeTag,
399        checkpoint_viewed_at: u64,
400    ) -> Result<Option<u64>, Error> {
401        let TypeTag::Struct(coin_struct) = coin_type else {
402            // If the type supplied is not metadata, we know it's not a valid coin type, so
403            // there won't be CoinMetadata for it.
404            return Ok(None);
405        };
406
407        Ok(Some(if GAS::is_gas(coin_struct.as_ref()) {
408            let pg_manager = ctx.data_unchecked::<PgManager>();
409
410            let state = pg_manager.fetch_iota_system_state(None).await?;
411
412            state.iota_total_supply()
413        } else {
414            let cap_type = TreasuryCap::type_(*coin_struct);
415
416            let db = ctx.data_unchecked();
417
418            let Some(object) = Object::query_singleton(db, cap_type, checkpoint_viewed_at).await?
419            else {
420                return Ok(None);
421            };
422
423            let Some(native) = object.native_impl() else {
424                return Ok(None);
425            };
426
427            let treasury_cap = TreasuryCap::try_from(native.clone()).map_err(|e| {
428                Error::Internal(format!(
429                    "Error while deserializing treasury cap {}: {e}",
430                    object.address,
431                ))
432            })?;
433
434            treasury_cap.total_supply.value
435        }))
436    }
437}
438
439impl TryFrom<&MoveObject> for CoinMetadata {
440    type Error = CoinMetadataDowncastError;
441
442    fn try_from(move_object: &MoveObject) -> Result<Self, Self::Error> {
443        if !move_object.native.type_().is_coin_metadata() {
444            return Err(CoinMetadataDowncastError::NotCoinMetadata);
445        }
446
447        Ok(Self {
448            super_: move_object.clone(),
449            native: bcs::from_bytes(move_object.native.contents())
450                .map_err(CoinMetadataDowncastError::Bcs)?,
451        })
452    }
453}