Skip to main content

breez_sdk_spark/issuer/
sdk.rs

1use std::sync::Arc;
2
3use spark_wallet::{MAX_TOKEN_EXTRA_METADATA_BYTES, SparkAddress, SparkWallet};
4
5use crate::{
6    BurnIssuerTokenRequest, CreateIssuerTokenRequest, FreezeIssuerTokenRequest,
7    FreezeIssuerTokenResponse, MintIssuerTokenRequest, Payment, SdkError, Storage, TokenBalance,
8    TokenMetadata, UnfreezeIssuerTokenRequest, UnfreezeIssuerTokenResponse,
9    utils::token::map_and_persist_token_transaction,
10};
11
12#[cfg_attr(feature = "uniffi", derive(uniffi::Object))]
13pub struct TokenIssuer {
14    spark_wallet: Arc<SparkWallet>,
15    storage: Arc<dyn Storage>,
16}
17
18impl TokenIssuer {
19    pub fn new(spark_wallet: Arc<SparkWallet>, storage: Arc<dyn Storage>) -> Self {
20        Self {
21            spark_wallet,
22            storage,
23        }
24    }
25}
26
27#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
28impl TokenIssuer {
29    /// Gets the issuer token balance
30    ///
31    /// # Returns
32    ///
33    /// Result containing either:
34    /// * `TokenBalance` - The balance of the issuer token
35    /// * `SdkError` - If there was an error during the retrieval or no issuer token exists
36    pub async fn get_issuer_token_balance(&self) -> Result<TokenBalance, SdkError> {
37        Ok(self.spark_wallet.get_issuer_token_balance().await?.into())
38    }
39
40    /// Gets the issuer token metadata
41    ///
42    /// # Returns
43    ///
44    /// Result containing either:
45    /// * `TokenMetadata` - The metadata of the issuer token
46    /// * `SdkError` - If there was an error during the retrieval or no issuer token exists
47    pub async fn get_issuer_token_metadata(&self) -> Result<TokenMetadata, SdkError> {
48        Ok(self.spark_wallet.get_issuer_token_metadata().await?.into())
49    }
50
51    /// Creates a new issuer token
52    ///
53    /// # Arguments
54    ///
55    /// * `request`: The request containing the token parameters
56    ///
57    /// # Returns
58    ///
59    /// Result containing either:
60    /// * `TokenMetadata` - The metadata of the created token
61    /// * `SdkError` - If there was an error during the token creation
62    pub async fn create_issuer_token(
63        &self,
64        request: CreateIssuerTokenRequest,
65    ) -> Result<TokenMetadata, SdkError> {
66        if request
67            .extra_metadata
68            .as_ref()
69            .is_some_and(|m| m.len() > MAX_TOKEN_EXTRA_METADATA_BYTES)
70        {
71            return Err(SdkError::InvalidInput(format!(
72                "Token extra metadata must be at most {MAX_TOKEN_EXTRA_METADATA_BYTES} bytes"
73            )));
74        }
75        self.spark_wallet
76            .create_issuer_token(
77                &request.name,
78                &request.ticker,
79                request.decimals,
80                request.is_freezable,
81                request.max_supply,
82                request.extra_metadata,
83            )
84            .await?;
85        self.get_issuer_token_metadata().await
86    }
87
88    /// Mints supply for the issuer token
89    ///
90    /// # Arguments
91    ///
92    /// * `request`: The request contiaining the amount of the supply to mint
93    ///
94    /// # Returns
95    ///
96    /// Result containing either:
97    /// * `Payment` - The payment representing the minting transaction
98    /// * `SdkError` - If there was an error during the minting process
99    pub async fn mint_issuer_token(
100        &self,
101        request: MintIssuerTokenRequest,
102    ) -> Result<Payment, SdkError> {
103        let token_transaction = self.spark_wallet.mint_issuer_token(request.amount).await?;
104        map_and_persist_token_transaction(&self.spark_wallet, &self.storage, &token_transaction)
105            .await
106    }
107
108    /// Burns supply of the issuer token
109    ///
110    /// # Arguments
111    ///
112    /// * `request`: The request containing the amount of the supply to burn
113    ///
114    /// # Returns
115    ///
116    /// Result containing either:
117    /// * `Payment` - The payment representing the burn transaction
118    /// * `SdkError` - If there was an error during the burn process
119    pub async fn burn_issuer_token(
120        &self,
121        request: BurnIssuerTokenRequest,
122    ) -> Result<Payment, SdkError> {
123        let token_transaction = self
124            .spark_wallet
125            .burn_issuer_token(request.amount, None)
126            .await?;
127        map_and_persist_token_transaction(&self.spark_wallet, &self.storage, &token_transaction)
128            .await
129    }
130
131    /// Freezes tokens held at the specified address
132    ///
133    /// # Arguments
134    ///
135    /// * `request`: The request containing the spark address where the tokens to be frozen are held
136    ///
137    /// # Returns
138    ///
139    /// Result containing either:
140    /// * `FreezeIssuerTokenResponse` - The response containing details of the freeze operation
141    /// * `SdkError` - If there was an error during the freeze process
142    pub async fn freeze_issuer_token(
143        &self,
144        request: FreezeIssuerTokenRequest,
145    ) -> Result<FreezeIssuerTokenResponse, SdkError> {
146        let spark_address = request
147            .address
148            .parse::<SparkAddress>()
149            .map_err(|_| SdkError::InvalidInput("Invalid spark address".to_string()))?;
150        Ok(self
151            .spark_wallet
152            .freeze_issuer_token(&spark_address)
153            .await?
154            .into())
155    }
156
157    /// Unfreezes tokens held at the specified address
158    ///
159    /// # Arguments
160    ///
161    /// * `request`: The request containing the spark address where the tokens to be unfrozen are held
162    ///
163    /// # Returns
164    ///
165    /// Result containing either:
166    /// * `UnfreezeIssuerTokenResponse` - The response containing details of the unfreeze operation
167    /// * `SdkError` - If there was an error during the unfreeze process
168    pub async fn unfreeze_issuer_token(
169        &self,
170        request: UnfreezeIssuerTokenRequest,
171    ) -> Result<UnfreezeIssuerTokenResponse, SdkError> {
172        let spark_address = request
173            .address
174            .parse::<SparkAddress>()
175            .map_err(|_| SdkError::InvalidInput("Invalid spark address".to_string()))?;
176        Ok(self
177            .spark_wallet
178            .unfreeze_issuer_token(&spark_address)
179            .await?
180            .into())
181    }
182}