Skip to main content

hiero_sdk/token/
token_burn_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::protobuf::{
8    FromProtobuf,
9    ToProtobuf,
10};
11use crate::transaction::{
12    AnyTransactionData,
13    ChunkInfo,
14    ToSchedulableTransactionDataProtobuf,
15    ToTransactionDataProtobuf,
16    TransactionData,
17    TransactionExecute,
18};
19use crate::{
20    BoxGrpcFuture,
21    Error,
22    TokenId,
23    Transaction,
24    ValidateChecksums,
25};
26
27/// Burns tokens from the Token's treasury Account.
28///
29/// The operation decreases the Total Supply of the Token. Total supply cannot go below zero.
30///
31/// The amount provided must be in the lowest denomination possible. Example:
32/// Token A has 2 decimals. In order to burn 100 tokens, one must provide amount of 10000. In order
33/// to burn 100.55 tokens, one must provide amount of 10055.
34///
35/// For non-fungible tokens the transaction body accepts a `serials` list of integers as a parameter.
36///
37/// - If no Supply Key is defined, the transaction will resolve to `TOKEN_HAS_NO_SUPPLY_KEY`.
38///
39/// - If neither the amount nor the `serials` get filled, a `INVALID_TOKEN_BURN_AMOUNT` response code
40/// will be returned.
41///
42/// - If both amount and `serials` get filled, a `INVALID_TRANSACTION_BODY` response code will be
43/// returned.
44///
45/// - If the `serials` list count is greater than the batch size limit global dynamic property, a
46/// `BATCH_SIZE_LIMIT_EXCEEDED` response code will be returned.
47///
48/// - If the `serials` list contains a non-positive integer as a serial number, a `INVALID_NFT_ID`
49/// response code will be returned.
50pub type TokenBurnTransaction = Transaction<TokenBurnTransactionData>;
51
52#[derive(Debug, Clone, Default)]
53pub struct TokenBurnTransactionData {
54    /// The token for which to burn tokens.
55    token_id: Option<TokenId>,
56
57    /// The amount of a fungible token to burn from the treasury account.
58    amount: u64,
59
60    /// The serial numbers of a non-fungible token to burn from the treasury account.
61    serials: Vec<i64>,
62}
63
64impl TokenBurnTransaction {
65    /// Returns the token for which to burn tokens.
66    #[must_use]
67    pub fn get_token_id(&self) -> Option<TokenId> {
68        self.data().token_id
69    }
70
71    /// Sets the token for which to burn tokens.
72    pub fn token_id(&mut self, token_id: impl Into<TokenId>) -> &mut Self {
73        self.data_mut().token_id = Some(token_id.into());
74        self
75    }
76
77    /// Returns the amount of a fungible token to burn from the treasury account.
78    #[must_use]
79    pub fn get_amount(&self) -> u64 {
80        self.data().amount
81    }
82
83    /// Sets the amount of a fungible token to burn from the treasury account.
84    pub fn amount(&mut self, amount: impl Into<u64>) -> &mut Self {
85        self.data_mut().amount = amount.into();
86        self
87    }
88
89    /// Returns the serial numbers of a non-fungible token to burn from the treasury account.
90    #[must_use]
91    pub fn get_serials(&self) -> &[i64] {
92        &self.data().serials
93    }
94
95    /// Sets the serial numbers of a non-fungible token to burn from the treasury account.
96    pub fn serials(&mut self, serials: impl IntoIterator<Item = i64>) -> &mut Self {
97        self.data_mut().serials = serials.into_iter().collect();
98        self
99    }
100}
101
102impl TransactionData for TokenBurnTransactionData {}
103
104impl TransactionExecute for TokenBurnTransactionData {
105    fn execute(
106        &self,
107        channel: Channel,
108        request: services::Transaction,
109    ) -> BoxGrpcFuture<'_, services::TransactionResponse> {
110        Box::pin(async { TokenServiceClient::new(channel).burn_token(request).await })
111    }
112}
113
114impl ValidateChecksums for TokenBurnTransactionData {
115    fn validate_checksums(&self, ledger_id: &crate::ledger_id::RefLedgerId) -> Result<(), Error> {
116        self.token_id.validate_checksums(ledger_id)
117    }
118}
119
120impl ToTransactionDataProtobuf for TokenBurnTransactionData {
121    fn to_transaction_data_protobuf(
122        &self,
123        chunk_info: &ChunkInfo,
124    ) -> services::transaction_body::Data {
125        let _ = chunk_info.assert_single_transaction();
126
127        services::transaction_body::Data::TokenBurn(self.to_protobuf())
128    }
129}
130
131impl ToSchedulableTransactionDataProtobuf for TokenBurnTransactionData {
132    fn to_schedulable_transaction_data_protobuf(
133        &self,
134    ) -> services::schedulable_transaction_body::Data {
135        services::schedulable_transaction_body::Data::TokenBurn(self.to_protobuf())
136    }
137}
138
139impl From<TokenBurnTransactionData> for AnyTransactionData {
140    fn from(transaction: TokenBurnTransactionData) -> Self {
141        Self::TokenBurn(transaction)
142    }
143}
144
145impl FromProtobuf<services::TokenBurnTransactionBody> for TokenBurnTransactionData {
146    fn from_protobuf(pb: services::TokenBurnTransactionBody) -> crate::Result<Self> {
147        Ok(Self {
148            token_id: Option::from_protobuf(pb.token)?,
149            amount: pb.amount,
150            serials: pb.serial_numbers,
151        })
152    }
153}
154
155impl ToProtobuf for TokenBurnTransactionData {
156    type Protobuf = services::TokenBurnTransactionBody;
157
158    fn to_protobuf(&self) -> Self::Protobuf {
159        let token = self.token_id.to_protobuf();
160        let amount = self.amount;
161        let serial_numbers = self.serials.clone();
162
163        services::TokenBurnTransactionBody { token, amount, serial_numbers }
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use expect_test::expect_file;
170    use hiero_sdk_proto::services;
171
172    use super::TokenBurnTransactionData;
173    use crate::protobuf::{
174        FromProtobuf,
175        ToProtobuf,
176    };
177    use crate::transaction::test_helpers::{
178        check_body,
179        transaction_body,
180        TEST_TOKEN_ID,
181    };
182    use crate::{
183        AnyTransaction,
184        TokenBurnTransaction,
185    };
186
187    fn make_transaction() -> TokenBurnTransaction {
188        let mut tx = TokenBurnTransaction::new_for_tests();
189
190        tx.token_id(TEST_TOKEN_ID).amount(6 as u64).freeze().unwrap();
191
192        tx
193    }
194
195    fn make_transaction_nft() -> TokenBurnTransaction {
196        let mut tx = TokenBurnTransaction::new_for_tests();
197
198        let vec1 = vec![1, 2, 64];
199
200        tx.token_id(TEST_TOKEN_ID).serials(vec1).freeze().unwrap();
201
202        tx
203    }
204
205    #[test]
206    fn serialize_fungible() {
207        let tx = make_transaction();
208
209        let tx = transaction_body(tx);
210
211        let tx = check_body(tx);
212
213        expect_file!["./snapshots/token_burn_transaction/serialize_fungible.txt"]
214            .assert_debug_eq(&tx);
215    }
216
217    #[test]
218    fn serialize_nft() {
219        let tx = make_transaction_nft();
220
221        let tx = transaction_body(tx);
222
223        let tx = check_body(tx);
224
225        expect_file!["./snapshots/token_burn_transaction/serialize_nft.txt"].assert_debug_eq(&tx);
226    }
227
228    #[test]
229    fn to_from_bytes() {
230        let tx = make_transaction();
231        let tx2 = AnyTransaction::from_bytes(&tx.to_bytes().unwrap()).unwrap();
232        let tx = transaction_body(tx);
233        let tx2 = transaction_body(tx2);
234
235        assert_eq!(tx, tx2);
236    }
237
238    #[test]
239    fn to_from_bytes_nft() {
240        let tx = make_transaction_nft();
241        let tx2 = AnyTransaction::from_bytes(&tx.to_bytes().unwrap()).unwrap();
242        let tx = transaction_body(tx);
243        let tx2 = transaction_body(tx2);
244
245        assert_eq!(tx, tx2);
246    }
247
248    #[test]
249    fn from_proto_body() {
250        let tx = services::TokenBurnTransactionBody {
251            token: Some(TEST_TOKEN_ID.to_protobuf()),
252            amount: 6,
253            serial_numbers: Vec::new(),
254        };
255
256        let tx = TokenBurnTransactionData::from_protobuf(tx).unwrap();
257
258        assert_eq!(tx.token_id, Some(TEST_TOKEN_ID));
259        assert_eq!(tx.amount, 6);
260    }
261
262    #[test]
263    fn get_set_token_id() {
264        let mut tx = TokenBurnTransaction::new();
265        tx.token_id(TEST_TOKEN_ID);
266
267        assert_eq!(tx.get_token_id(), Some(TEST_TOKEN_ID));
268    }
269
270    #[test]
271    fn get_set_amount() {
272        let mut tx = TokenBurnTransaction::new();
273        tx.amount(23_u64);
274
275        assert_eq!(tx.get_amount(), 23);
276    }
277
278    #[test]
279    fn get_set_serial() {
280        let serials = [1, 2, 64];
281
282        let mut tx = TokenBurnTransaction::new();
283        tx.serials(Vec::from(serials));
284
285        assert_eq!(tx.get_serials(), serials);
286    }
287}