1use 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#[Object]
48impl CoinMetadata {
49 pub(crate) async fn address(&self) -> IotaAddress {
50 OwnerImpl::from(&self.super_.super_).address().await
51 }
52
53 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 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 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 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 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 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 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 pub(crate) async fn status(&self) -> ObjectStatus {
164 ObjectImpl(&self.super_.super_).status().await
165 }
166
167 pub(crate) async fn digest(&self) -> Option<String> {
170 ObjectImpl(&self.super_.super_).digest().await
171 }
172
173 pub(crate) async fn owner(&self, ctx: &Context<'_>) -> Result<Option<ObjectOwner>> {
175 ObjectImpl(&self.super_.super_).owner(ctx).await
176 }
177
178 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 pub(crate) async fn storage_rebate(&self) -> Option<BigInt> {
192 ObjectImpl(&self.super_.super_).storage_rebate().await
193 }
194
195 #[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 pub(crate) async fn bcs(&self) -> Result<Option<Base64>> {
215 ObjectImpl(&self.super_.super_).bcs().await
216 }
217
218 pub(crate) async fn contents(&self) -> Option<MoveValue> {
222 MoveObjectImpl(&self.super_).contents().await
223 }
224
225 pub(crate) async fn display(&self, ctx: &Context<'_>) -> Result<Option<Vec<DisplayEntry>>> {
229 ObjectImpl(&self.super_.super_).display(ctx).await
230 }
231
232 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 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 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 async fn decimals(&self) -> Option<u8> {
292 Some(self.native.decimals)
293 }
294
295 async fn name(&self) -> Option<&str> {
297 Some(&self.native.name)
298 }
299
300 async fn symbol(&self) -> Option<&str> {
302 Some(&self.native.symbol)
303 }
304
305 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 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 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 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 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}