Skip to main content

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