Skip to main content

hiero_sdk/token/
token_mint_transaction.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use hiero_sdk_proto::services;
4use hiero_sdk_proto::services::token_service_client::TokenServiceClient;
5use tonic::transport::Channel;
6
7use crate::ledger_id::RefLedgerId;
8use crate::protobuf::{
9    FromProtobuf,
10    ToProtobuf,
11};
12use crate::transaction::{
13    AnyTransactionData,
14    ChunkInfo,
15    ToSchedulableTransactionDataProtobuf,
16    ToTransactionDataProtobuf,
17    TransactionData,
18    TransactionExecute,
19};
20use crate::{
21    BoxGrpcFuture,
22    Error,
23    TokenId,
24    Transaction,
25    ValidateChecksums,
26};
27
28/// Mints tokens to the Token's treasury Account.
29///
30/// The operation increases the Total Supply of the Token. The maximum total supply a token can have
31/// is 2^63-1.
32///
33/// The amount provided must be in the lowest denomination possible. Example: Token A has 2 decimals.
34/// In order to mint 100 tokens, one must provide amount of 10000. In order to mint 100.55 tokens,
35/// one must provide amount of 10055.
36///
37/// - If no Supply Key is defined, the transaction will resolve to `TokenHasNoSupplyKey`.
38/// - If both amount and metadata list get filled, a `InvalidTransactionBody` response code will be
39/// returned.
40/// - If the metadata list contains metadata which is too large, a `MetadataTooLong` response code will
41/// be returned.
42/// - If neither the amount nor the metadata list get filled, a `InvalidTokenMintAmount` response code
43/// will be returned.
44/// - If the metadata list count is greater than the batch size limit global dynamic property, a
45/// `BatchSizeLimitExceeded` response code will be returned.
46pub type TokenMintTransaction = Transaction<TokenMintTransactionData>;
47
48#[derive(Debug, Clone, Default)]
49pub struct TokenMintTransactionData {
50    /// The token for which to mint tokens.
51    token_id: Option<TokenId>,
52
53    /// The amount of a fungible token to mint to the treasury account.
54    amount: u64,
55
56    /// The list of metadata for a non-fungible token to mint to the treasury account.
57    metadata: Vec<Vec<u8>>,
58}
59
60impl TokenMintTransaction {
61    /// Returns the token for which to mint tokens.
62    #[must_use]
63    pub fn get_token_id(&self) -> Option<TokenId> {
64        self.data().token_id
65    }
66
67    /// Sets the token for which to mint tokens.
68    pub fn token_id(&mut self, token_id: impl Into<TokenId>) -> &mut Self {
69        self.data_mut().token_id = Some(token_id.into());
70        self
71    }
72
73    /// Returns the amount of a fungible token to mint to the treasury account.
74    #[must_use]
75    pub fn get_amount(&self) -> u64 {
76        self.data().amount
77    }
78
79    /// Sets the amount of a fungible token to mint to the treasury account.
80    pub fn amount(&mut self, amount: u64) -> &mut Self {
81        self.data_mut().amount = amount;
82        self
83    }
84
85    /// Returns the list of metadata for a non-fungible token to mint to the treasury account.
86    #[must_use]
87    pub fn get_metadata(&self) -> &[Vec<u8>] {
88        &self.data().metadata
89    }
90
91    /// Sets the list of metadata for a non-fungible token to mint to the treasury account.
92    pub fn metadata<Bytes>(&mut self, metadata: impl IntoIterator<Item = Bytes>) -> &mut Self
93    where
94        Bytes: AsRef<[u8]>,
95    {
96        self.data_mut().metadata =
97            metadata.into_iter().map(|bytes| bytes.as_ref().to_vec()).collect();
98
99        self
100    }
101}
102
103impl TransactionData for TokenMintTransactionData {}
104
105impl TransactionExecute for TokenMintTransactionData {
106    fn execute(
107        &self,
108        channel: Channel,
109        request: services::Transaction,
110    ) -> BoxGrpcFuture<'_, services::TransactionResponse> {
111        Box::pin(async { TokenServiceClient::new(channel).mint_token(request).await })
112    }
113}
114
115impl ValidateChecksums for TokenMintTransactionData {
116    fn validate_checksums(&self, ledger_id: &RefLedgerId) -> Result<(), Error> {
117        self.token_id.validate_checksums(ledger_id)
118    }
119}
120
121impl ToTransactionDataProtobuf for TokenMintTransactionData {
122    fn to_transaction_data_protobuf(
123        &self,
124        chunk_info: &ChunkInfo,
125    ) -> services::transaction_body::Data {
126        let _ = chunk_info.assert_single_transaction();
127
128        services::transaction_body::Data::TokenMint(self.to_protobuf())
129    }
130}
131
132impl ToSchedulableTransactionDataProtobuf for TokenMintTransactionData {
133    fn to_schedulable_transaction_data_protobuf(
134        &self,
135    ) -> services::schedulable_transaction_body::Data {
136        services::schedulable_transaction_body::Data::TokenMint(self.to_protobuf())
137    }
138}
139
140impl From<TokenMintTransactionData> for AnyTransactionData {
141    fn from(transaction: TokenMintTransactionData) -> Self {
142        Self::TokenMint(transaction)
143    }
144}
145
146impl FromProtobuf<services::TokenMintTransactionBody> for TokenMintTransactionData {
147    fn from_protobuf(pb: services::TokenMintTransactionBody) -> crate::Result<Self> {
148        Ok(Self {
149            token_id: Option::from_protobuf(pb.token)?,
150            amount: pb.amount,
151            metadata: pb.metadata,
152        })
153    }
154}
155
156impl ToProtobuf for TokenMintTransactionData {
157    type Protobuf = services::TokenMintTransactionBody;
158
159    fn to_protobuf(&self) -> Self::Protobuf {
160        services::TokenMintTransactionBody {
161            token: self.token_id.to_protobuf(),
162            amount: self.amount,
163            metadata: self.metadata.clone(),
164        }
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use expect_test::expect;
171    use hiero_sdk_proto::services::TokenMintTransactionBody;
172
173    use crate::protobuf::{
174        FromProtobuf,
175        ToProtobuf,
176    };
177    use crate::token::TokenMintTransactionData;
178    use crate::transaction::test_helpers::{
179        check_body,
180        transaction_body,
181    };
182    use crate::{
183        AnyTransaction,
184        TokenId,
185        TokenMintTransaction,
186    };
187
188    const TEST_TOKEN_ID: TokenId = TokenId::new(4, 2, 0);
189    const TEST_AMOUNT: u64 = 10;
190
191    fn metadata() -> Vec<Vec<u8>> {
192        [[1, 2, 3, 4, 5].into()].into()
193    }
194
195    fn make_transaction() -> TokenMintTransaction {
196        let mut tx = TokenMintTransaction::new_for_tests();
197
198        tx.token_id(TEST_TOKEN_ID).amount(TEST_AMOUNT).freeze().unwrap();
199
200        tx
201    }
202
203    fn make_metadata_transaction() -> TokenMintTransaction {
204        let mut tx = TokenMintTransaction::new_for_tests();
205
206        tx.token_id(TEST_TOKEN_ID).metadata(metadata()).freeze().unwrap();
207
208        tx
209    }
210
211    #[test]
212    fn serialize() {
213        let tx = make_transaction();
214
215        let tx = transaction_body(tx);
216
217        let tx = check_body(tx);
218
219        expect![[r#"
220            TokenMint(
221                TokenMintTransactionBody {
222                    token: Some(
223                        TokenId {
224                            shard_num: 4,
225                            realm_num: 2,
226                            token_num: 0,
227                        },
228                    ),
229                    amount: 10,
230                    metadata: [],
231                },
232            )
233        "#]]
234        .assert_debug_eq(&tx)
235    }
236
237    #[test]
238    fn to_from_bytes() {
239        let tx = make_transaction();
240
241        let tx2 = AnyTransaction::from_bytes(&tx.to_bytes().unwrap()).unwrap();
242
243        let tx = transaction_body(tx);
244
245        let tx2 = transaction_body(tx2);
246
247        assert_eq!(tx, tx2);
248    }
249
250    #[test]
251    fn serialize_metadata() {
252        let tx = make_metadata_transaction();
253
254        let tx = transaction_body(tx);
255
256        let tx = check_body(tx);
257
258        expect![[r#"
259            TokenMint(
260                TokenMintTransactionBody {
261                    token: Some(
262                        TokenId {
263                            shard_num: 4,
264                            realm_num: 2,
265                            token_num: 0,
266                        },
267                    ),
268                    amount: 0,
269                    metadata: [
270                        [
271                            1,
272                            2,
273                            3,
274                            4,
275                            5,
276                        ],
277                    ],
278                },
279            )
280        "#]]
281        .assert_debug_eq(&tx)
282    }
283
284    #[test]
285    fn to_from_bytes_metadata() {
286        let tx = make_metadata_transaction();
287
288        let tx2 = AnyTransaction::from_bytes(&tx.to_bytes().unwrap()).unwrap();
289
290        let tx = transaction_body(tx);
291
292        let tx2 = transaction_body(tx2);
293
294        assert_eq!(tx, tx2);
295    }
296
297    #[test]
298    fn from_proto_body() {
299        let tx = TokenMintTransactionBody {
300            token: Some(TEST_TOKEN_ID.to_protobuf()),
301            amount: TEST_AMOUNT,
302            metadata: metadata(),
303        };
304
305        let data = TokenMintTransactionData::from_protobuf(tx).unwrap();
306
307        assert_eq!(data.token_id, Some(TEST_TOKEN_ID));
308        assert_eq!(data.amount, TEST_AMOUNT);
309        assert_eq!(data.metadata, metadata());
310    }
311
312    #[test]
313    fn get_set_token_id() {
314        let mut tx = TokenMintTransaction::new();
315        tx.token_id(TEST_TOKEN_ID);
316
317        assert_eq!(tx.get_token_id(), Some(TEST_TOKEN_ID));
318    }
319
320    #[test]
321    #[should_panic]
322    fn get_set_token_id_frozen_panic() {
323        let mut tx = make_transaction();
324
325        tx.token_id(TEST_TOKEN_ID);
326    }
327
328    #[test]
329    fn get_set_amount() {
330        let mut tx = TokenMintTransaction::new();
331        tx.amount(TEST_AMOUNT);
332
333        assert_eq!(tx.get_amount(), TEST_AMOUNT);
334    }
335
336    #[test]
337    #[should_panic]
338    fn get_set_amount_frozen_panic() {
339        let mut tx = make_transaction();
340        tx.amount(TEST_AMOUNT);
341    }
342
343    #[test]
344    fn get_set_metadata() {
345        let mut tx = TokenMintTransaction::new();
346        tx.metadata(metadata());
347
348        assert_eq!(tx.get_metadata(), &metadata());
349    }
350
351    #[test]
352    #[should_panic]
353    fn get_set_metadata_frozen_panic() {
354        let mut tx = make_transaction();
355        tx.metadata(metadata());
356    }
357}