Skip to main content

sui_indexer_alt_jsonrpc/api/
coin.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::collections::HashMap;
5use std::str::FromStr;
6
7use anyhow::Context as _;
8use futures::future;
9use jsonrpsee::core::RpcResult;
10use jsonrpsee::proc_macros::rpc;
11use move_core_types::language_storage::StructTag;
12use move_core_types::language_storage::TypeTag;
13use mysten_common::ZipDebugEqIteratorExt;
14use sui_indexer_alt_consistent_store::ObjectByOwnerKey;
15use sui_indexer_alt_reader::consistent_reader::proto::Balance as ProtoBalance;
16use sui_indexer_alt_reader::consistent_reader::proto::owner::OwnerKind;
17use sui_json_rpc_types::Balance;
18use sui_json_rpc_types::Coin;
19use sui_json_rpc_types::Page as PageResponse;
20use sui_json_rpc_types::SuiCoinMetadata;
21use sui_open_rpc::Module;
22use sui_open_rpc_macros::open_rpc;
23use sui_types::SUI_FRAMEWORK_ADDRESS;
24use sui_types::base_types::ObjectID;
25use sui_types::base_types::SuiAddress;
26use sui_types::coin::COIN_METADATA_STRUCT_NAME;
27use sui_types::coin::COIN_MODULE_NAME;
28use sui_types::coin::COIN_STRUCT_NAME;
29use sui_types::coin::CoinMetadata;
30use sui_types::coin_registry::Currency;
31use sui_types::gas_coin::GAS;
32use sui_types::object::Object;
33use sui_types::object::Owner;
34
35use crate::api::rpc_module::RpcModule;
36use crate::context::Context;
37use crate::data::AddressBalanceCoin;
38use crate::data::load_live;
39use crate::error::InternalContext;
40use crate::error::RpcError;
41use crate::error::invalid_params;
42use crate::paginate::BcsCursor;
43use crate::paginate::Cursor as _;
44use crate::paginate::Page;
45
46#[open_rpc(namespace = "suix", tag = "Coin API")]
47#[rpc(server, namespace = "suix")]
48trait CoinsApi {
49    /// Return Coin objects owned by an address with a specified coin type.
50    /// If no coin type is specified, SUI coins are returned.
51    #[method(name = "getCoins")]
52    async fn get_coins(
53        &self,
54        /// the owner's Sui address
55        owner: SuiAddress,
56        /// optional coin type
57        coin_type: Option<String>,
58        /// optional paging cursor
59        cursor: Option<String>,
60        /// maximum number of items per page
61        limit: Option<usize>,
62    ) -> RpcResult<PageResponse<Coin, String>>;
63
64    /// Return metadata (e.g., symbol, decimals) for a coin. Note that if the coin's metadata was
65    /// wrapped in the transaction that published its marker type, or the latest version of the
66    /// metadata object is wrapped or deleted, it will not be found.
67    #[method(name = "getCoinMetadata")]
68    async fn get_coin_metadata(
69        &self,
70        /// type name for the coin (e.g., 0x168da5bf1f48dafc111b0a488fa454aca95e0b5e::usdc::USDC)
71        coin_type: String,
72    ) -> RpcResult<Option<SuiCoinMetadata>>;
73
74    /// Return the total coin balance for all coin types, owned by the address owner.
75    #[method(name = "getAllBalances")]
76    async fn get_all_balances(
77        &self,
78        /// the owner's Sui address
79        owner: SuiAddress,
80    ) -> RpcResult<Vec<Balance>>;
81
82    /// Return the total coin balance for one coin type, owned by the address.
83    /// If no coin type is specified, SUI coin balance is returned.
84    #[method(name = "getBalance")]
85    async fn get_balance(
86        &self,
87        /// the owner's Sui address
88        owner: SuiAddress,
89        /// optional type names for the coin (e.g., 0x168da5bf1f48dafc111b0a488fa454aca95e0b5e::usdc::USDC), default to 0x2::sui::SUI if not specified.
90        coin_type: Option<String>,
91    ) -> RpcResult<Balance>;
92}
93
94pub(crate) struct Coins(pub Context);
95
96#[derive(thiserror::Error, Debug)]
97pub(crate) enum Error {
98    #[error("Pagination issue: {0}")]
99    Pagination(#[from] crate::paginate::Error),
100
101    #[error("Failed to parse type {0:?}: {1}")]
102    BadType(String, anyhow::Error),
103}
104
105type Cursor = BcsCursor<Vec<u8>>;
106
107#[async_trait::async_trait]
108impl CoinsApiServer for Coins {
109    async fn get_coins(
110        &self,
111        owner: SuiAddress,
112        coin_type: Option<String>,
113        cursor: Option<String>,
114        limit: Option<usize>,
115    ) -> RpcResult<PageResponse<Coin, String>> {
116        let inner = if let Some(coin_type) = coin_type {
117            TypeTag::from_str(&coin_type)
118                .map_err(|e| invalid_params(Error::BadType(coin_type, e)))?
119        } else {
120            GAS::type_tag()
121        };
122
123        let object_type = StructTag {
124            address: SUI_FRAMEWORK_ADDRESS,
125            module: COIN_MODULE_NAME.to_owned(),
126            name: COIN_STRUCT_NAME.to_owned(),
127            type_params: vec![inner.clone()],
128        };
129
130        let Self(ctx) = self;
131        let config = &ctx.config().coins;
132
133        let page: Page<Cursor> = Page::from_params::<Error>(
134            config.default_page_size,
135            config.max_page_size,
136            cursor,
137            limit,
138            None,
139        )?;
140
141        let consistent_reader = ctx.consistent_reader();
142
143        // Coin balances are stored as bitwise negation, so iterating in regular (forward) order
144        // yields highest balances first.
145        let results = consistent_reader
146            .list_owned_objects(
147                None, /* checkpoint */
148                OwnerKind::Address,
149                Some(owner.to_string()),
150                Some(object_type.to_canonical_string(/* with_prefix */ true)),
151                Some(page.limit as u32),
152                page.cursor.as_ref().map(|c| c.0.clone()),
153                None,
154                true,
155            )
156            .await
157            .context("Failed to list owned coin objects")
158            .map_err(RpcError::<Error>::from)?;
159
160        let coin_ids: Vec<_> = results
161            .results
162            .iter()
163            .map(|obj_ref| obj_ref.value.0)
164            .collect();
165
166        let coin_futures = coin_ids.iter().map(|id| coin_response(ctx, *id));
167
168        // Fetch real coins and address balance coin concurrently.
169        let (coin_results, address_balance_coin) = tokio::join!(
170            future::join_all(coin_futures),
171            AddressBalanceCoin::by_owner(ctx, owner, inner),
172        );
173
174        let address_balance_coin = address_balance_coin
175            .context("Failed to get address balance coin")
176            .map_err(RpcError::<Error>::from)?
177            .map(AddressBalanceCoin::into_coin)
178            .transpose()
179            .context("Failed to render address balance coin")
180            .map_err(RpcError::<Error>::from)?;
181
182        let mut has_next_page = results.has_next_page;
183
184        // Pair each coin with its cursor token so we can derive the final cursor from
185        // whichever coin ends up last on the page.
186        let mut coins: Vec<(Coin, Vec<u8>)> = coin_results
187            .into_iter()
188            .zip_debug_eq(&coin_ids)
189            .map(|(r, id)| r.with_internal_context(|| format!("Failed to get object {id}")))
190            .collect::<Result<Vec<_>, _>>()?
191            .into_iter()
192            .zip_debug_eq(results.results.into_iter().map(|e| e.token))
193            .collect();
194
195        if let Some(ab_coin) = address_balance_coin {
196            let ab_token = ObjectByOwnerKey::from_coin_parts(
197                &Owner::AddressOwner(owner),
198                object_type.clone(),
199                ab_coin.balance,
200                ab_coin.coin_object_id,
201            )
202            .encode();
203
204            let include_ab_coin = page
205                .cursor
206                .as_ref()
207                .is_none_or(|cursor| ab_token > cursor.0);
208
209            if include_ab_coin {
210                let pos = coins.partition_point(|(_, t)| t < &ab_token);
211                coins.insert(pos, (ab_coin, ab_token));
212            }
213        }
214
215        has_next_page = has_next_page || coins.len() > page.limit as usize;
216        coins.truncate(page.limit as usize);
217
218        let next_cursor = coins
219            .last()
220            .map(|(_, token)| BcsCursor(token.clone()).encode())
221            .transpose()
222            .context("Failed to encode cursor")
223            .map_err(RpcError::<Error>::from)?;
224
225        let data = coins.into_iter().map(|(coin, _)| coin).collect();
226
227        Ok(PageResponse {
228            data,
229            next_cursor,
230            has_next_page,
231        })
232    }
233
234    async fn get_coin_metadata(&self, coin_type: String) -> RpcResult<Option<SuiCoinMetadata>> {
235        let Self(ctx) = self;
236
237        if let Some(currency) = coin_registry_response(ctx, &coin_type)
238            .await
239            .with_internal_context(|| format!("Failed to fetch Currency for {coin_type:?}"))?
240        {
241            return Ok(Some(currency));
242        }
243
244        if let Some(metadata) = coin_metadata_response(ctx, &coin_type)
245            .await
246            .with_internal_context(|| format!("Failed to fetch CoinMetadata for {coin_type:?}"))?
247        {
248            return Ok(Some(metadata));
249        }
250
251        Ok(None)
252    }
253
254    async fn get_all_balances(&self, owner: SuiAddress) -> RpcResult<Vec<Balance>> {
255        let Self(ctx) = self;
256        let consistent_reader = ctx.consistent_reader();
257        let config = &ctx.config().coins;
258
259        let mut all_balances = Vec::new();
260        let mut after_token: Option<Vec<u8>> = None;
261
262        loop {
263            let page = consistent_reader
264                .list_balances(
265                    None,
266                    owner.to_string(),
267                    Some(config.max_page_size as u32),
268                    after_token.clone(),
269                    None,
270                    true,
271                )
272                .await
273                .context("Failed to get all balances")
274                .map_err(RpcError::<Error>::from)?;
275
276            for edge in &page.results {
277                all_balances.push(try_from_proto(edge.value.clone())?);
278            }
279
280            if page.has_next_page {
281                after_token = page.results.last().map(|edge| edge.token.clone());
282            } else {
283                break;
284            }
285        }
286
287        Ok(all_balances)
288    }
289
290    async fn get_balance(
291        &self,
292        owner: SuiAddress,
293        coin_type: Option<String>,
294    ) -> RpcResult<Balance> {
295        let Self(ctx) = self;
296        let consistent_reader = ctx.consistent_reader();
297
298        let inner_coin_type = if let Some(coin_type) = coin_type {
299            TypeTag::from_str(&coin_type)
300                .map_err(|e| invalid_params(Error::BadType(coin_type, e)))?
301        } else {
302            GAS::type_tag()
303        };
304
305        let response = consistent_reader
306            .get_balance(
307                None,
308                owner.to_string(),
309                inner_coin_type.to_canonical_string(/* with_prefix */ true),
310            )
311            .await
312            .context("Failed to get balance")
313            .map_err(RpcError::<Error>::from)?;
314
315        Ok(try_from_proto(response)?)
316    }
317}
318
319impl RpcModule for Coins {
320    fn schema(&self) -> Module {
321        CoinsApiOpenRpc::module_doc()
322    }
323
324    fn into_impl(self) -> jsonrpsee::RpcModule<Self> {
325        self.into_rpc()
326    }
327}
328
329fn try_from_proto(proto: ProtoBalance) -> Result<Balance, RpcError<Error>> {
330    let coin_type: TypeTag = proto
331        .coin_type
332        .context("coin type missing")?
333        .parse()
334        .context("invalid coin type")?;
335    Ok(Balance {
336        coin_type: coin_type.to_canonical_string(/* with_prefix */ true),
337        total_balance: proto.total_balance.unwrap_or(0) as u128,
338        // The Consistent Store does not track coin object counts, so the rpc will
339        // always return 1.
340        coin_object_count: 1,
341        locked_balance: HashMap::new(),
342        funds_in_address_balance: proto.address_balance.unwrap_or(0) as u128,
343    })
344}
345
346async fn coin_response(ctx: &Context, id: ObjectID) -> Result<Coin, RpcError<Error>> {
347    let (object, coin_type, balance) = object_with_coin_data(ctx, id).await?;
348
349    let coin_object_id = object.id();
350    let digest = object.digest();
351    let version = object.version();
352    let previous_transaction = object.as_inner().previous_transaction;
353
354    Ok(Coin {
355        coin_type,
356        coin_object_id,
357        version,
358        digest,
359        balance,
360        previous_transaction,
361    })
362}
363
364async fn coin_registry_response(
365    ctx: &Context,
366    coin_type: &str,
367) -> Result<Option<SuiCoinMetadata>, RpcError<Error>> {
368    let coin_type = TypeTag::from_str(coin_type)
369        .map_err(|e| invalid_params(Error::BadType(coin_type.to_owned(), e)))?;
370
371    let currency_id = Currency::derive_object_id(coin_type)
372        .context("Failed to derive object id for coin registry Currency")?;
373
374    let Some(object) = load_live(ctx, currency_id)
375        .await
376        .context("Failed to load Currency object")?
377    else {
378        return Ok(None);
379    };
380
381    let Some(move_object) = object.data.try_as_move() else {
382        return Ok(None);
383    };
384
385    let currency: Currency =
386        bcs::from_bytes(move_object.contents()).context("Failed to parse Currency object")?;
387
388    Ok(Some(currency.into()))
389}
390
391/// Given the inner coin type, i.e 0x2::sui::SUI, load the CoinMetadata object.
392async fn coin_metadata_response(
393    ctx: &Context,
394    coin_type: &str,
395) -> Result<Option<SuiCoinMetadata>, RpcError<Error>> {
396    let inner = TypeTag::from_str(coin_type)
397        .map_err(|e| invalid_params(Error::BadType(coin_type.to_owned(), e)))?;
398
399    let object_type = StructTag {
400        address: SUI_FRAMEWORK_ADDRESS,
401        module: COIN_MODULE_NAME.to_owned(),
402        name: COIN_METADATA_STRUCT_NAME.to_owned(),
403        type_params: vec![inner],
404    };
405
406    let Some(obj_ref) = ctx
407        .consistent_reader()
408        .list_objects_by_type(
409            None,
410            object_type.to_canonical_string(/* with_prefix */ true),
411            Some(1),
412            None,
413            None,
414            false,
415        )
416        .await
417        .context("Failed to load object reference for CoinMetadata")?
418        .results
419        .into_iter()
420        .next()
421    else {
422        return Ok(None);
423    };
424
425    let id = obj_ref.value.0;
426
427    let Some(object) = load_live(ctx, id)
428        .await
429        .context("Failed to load latest version of CoinMetadata")?
430    else {
431        return Ok(None);
432    };
433
434    let Some(move_object) = object.data.try_as_move() else {
435        return Ok(None);
436    };
437
438    let coin_metadata: CoinMetadata =
439        bcs::from_bytes(move_object.contents()).context("Failed to parse Currency object")?;
440
441    Ok(Some(coin_metadata.into()))
442}
443
444async fn object_with_coin_data(
445    ctx: &Context,
446    id: ObjectID,
447) -> Result<(Object, String, u64), RpcError<Error>> {
448    let object = load_live(ctx, id)
449        .await?
450        .with_context(|| format!("Failed to load latest object {id}"))?;
451
452    let coin = object
453        .as_coin_maybe()
454        .context("Object is expected to be a coin")?;
455    let coin_type = object
456        .coin_type_maybe()
457        .context("Object is expected to have a coin type")?
458        .to_canonical_string(/* with_prefix */ true);
459    Ok((object, coin_type, coin.balance.value()))
460}