hedera 0.43.0

The SDK for interacting with Hedera Hashgraph.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
mod associate;
mod burn;
mod create;
mod delete;
mod dissociate;
mod fee_schedule_update;
mod freeze;
mod grant_kyc;
mod info;
mod mint;
mod nft_info;
mod nft_transfer;
mod nft_update;
mod pause;
mod reject;
mod reject_flow;

mod airdrop;
mod cancel_airdrop;
mod claim_airdrop;
mod revoke_kyc;
mod transfer;
mod unfreeze;
mod unpause;
mod update;
mod wipe;

use hedera::{
    Client,
    PublicKey,
    TokenBurnTransaction,
    TokenCreateTransaction,
    TokenDeleteTransaction,
    TokenId,
    TokenMintTransaction,
    TransactionResponse,
};
use time::{
    Duration,
    OffsetDateTime,
};
use tokio::task::JoinSet;

use crate::account::Account;
use crate::common::{
    setup_global,
    Operator,
    TestEnvironment,
};

pub(crate) enum Key {
    Owner,
    Custom(PublicKey),
}

pub(crate) struct TokenKeys {
    pub(crate) admin: Option<Key>,
    pub(crate) freeze: Option<Key>,
    pub(crate) wipe: Option<Key>,
    pub(crate) kyc: Option<Key>,
    pub(crate) supply: Option<Key>,
    pub(crate) fee_schedule: Option<Key>,
    pub(crate) pause: Option<Key>,
}

impl TokenKeys {
    const NONE: Self = Self {
        admin: None,
        freeze: None,
        wipe: None,
        kyc: None,
        supply: None,
        fee_schedule: None,
        pause: None,
    };

    const DEFAULT: Self = Self { admin: Some(Key::Owner), ..Self::NONE };

    const ALL_OWNER: Self = Self {
        admin: Some(Key::Owner),
        freeze: Some(Key::Owner),
        wipe: Some(Key::Owner),
        kyc: Some(Key::Owner),
        supply: Some(Key::Owner),
        fee_schedule: Some(Key::Owner),
        pause: Some(Key::Owner),
    };
}

impl Default for TokenKeys {
    fn default() -> Self {
        Self::DEFAULT
    }
}

#[derive(Default)]
pub(crate) struct CreateFungibleToken {
    initial_supply: u64,
    keys: TokenKeys,
}

pub(crate) struct FungibleToken {
    pub(crate) id: TokenId,
    pub(crate) owner: Account,
}

pub(crate) const TEST_FUNGIBLE_INITIAL_BALANCE: &u64 = &1_000_000;
pub(crate) const TEST_MINTED_NFTS: &u64 = &10;
pub(crate) const TEST_AMOUNT: i64 = 100;

impl FungibleToken {
    pub(crate) async fn create(
        client: &Client,
        owner: &Account,
        params: CreateFungibleToken,
    ) -> hedera::Result<Self> {
        let owner_public_key = owner.key.public_key();

        let token_id = {
            let mut tx = TokenCreateTransaction::new();
            tx.name("ffff")
                .symbol("F")
                .decimals(3)
                .treasury_account_id(owner.id)
                .initial_supply(params.initial_supply);

            let keys = params.keys;

            if let Some(it) = keys.admin {
                tx.admin_key(match it {
                    Key::Owner => owner_public_key,
                    Key::Custom(key) => key,
                });
            }

            if let Some(it) = keys.freeze {
                tx.freeze_key(match it {
                    Key::Owner => owner_public_key,
                    Key::Custom(key) => key,
                });
            }

            if let Some(it) = keys.wipe {
                tx.wipe_key(match it {
                    Key::Owner => owner_public_key,
                    Key::Custom(key) => key,
                });
            }

            if let Some(it) = keys.kyc {
                tx.kyc_key(match it {
                    Key::Owner => owner_public_key,
                    Key::Custom(key) => key,
                });
            }

            if let Some(it) = keys.supply {
                tx.supply_key(match it {
                    Key::Owner => owner_public_key,
                    Key::Custom(key) => key,
                });
            }

            if let Some(it) = keys.fee_schedule {
                tx.fee_schedule_key(match it {
                    Key::Owner => owner_public_key,
                    Key::Custom(key) => key,
                });
            }

            if let Some(it) = keys.pause {
                tx.pause_key(match it {
                    Key::Owner => owner_public_key,
                    Key::Custom(key) => key,
                });
            }

            tx.freeze_default(false)
                .expiration_time(OffsetDateTime::now_utc() + Duration::minutes(5))
                .sign(owner.key.clone())
                .execute(client)
                .await?
                .get_receipt(client)
                .await?
                .token_id
                .unwrap()
        };

        Ok(Self { id: token_id, owner: owner.clone() })
    }

    async fn create_ft(
        client: &Client,
        owner: &Account,
        decimals: u32,
    ) -> anyhow::Result<FungibleToken> {
        let id = TokenCreateTransaction::new()
            .name("ffff".to_string())
            .symbol("F".to_string())
            .token_memo("memo".to_string())
            .decimals(decimals)
            .initial_supply(1_000_000)
            .max_supply(1_000_000)
            .treasury_account_id(owner.id)
            .token_supply_type(hedera::TokenSupplyType::Finite)
            .admin_key(owner.key.public_key())
            .freeze_key(owner.key.public_key())
            .wipe_key(owner.key.public_key())
            .supply_key(owner.key.public_key())
            .metadata_key(owner.key.public_key())
            .pause_key(owner.key.public_key())
            .execute(&client)
            .await?
            .get_receipt(&client)
            .await?
            .token_id
            .unwrap();

        Ok(FungibleToken { id, owner: owner.clone() })
    }

    async fn burn(&self, client: &Client, supply: u64) -> hedera::Result<()> {
        hedera::TokenBurnTransaction::new()
            .token_id(self.id)
            .amount(supply)
            .sign(self.owner.key.clone())
            .execute(client)
            .await?
            .get_receipt(client)
            .await?;

        Ok(())
    }

    async fn delete(self, client: &Client) -> hedera::Result<()> {
        TokenDeleteTransaction::new()
            .token_id(self.id)
            .sign(self.owner.key)
            .execute(client)
            .await?
            .get_receipt(client)
            .await?;

        Ok(())
    }
}

pub(crate) struct Nft {
    pub(crate) id: TokenId,
    pub(crate) owner: Account,
}

impl Nft {
    pub(crate) async fn create(client: &Client, owner: &Account) -> hedera::Result<Self> {
        let owner_public_key = owner.key.public_key();
        let token_id = TokenCreateTransaction::new()
            .name("ffff")
            .symbol("F")
            .token_type(hedera::TokenType::NonFungibleUnique)
            .treasury_account_id(owner.id)
            .admin_key(owner_public_key)
            .freeze_key(owner_public_key)
            .wipe_key(owner_public_key)
            .pause_key(owner_public_key)
            .supply_key(owner_public_key)
            .fee_schedule_key(owner_public_key)
            .freeze_default(false)
            .expiration_time(OffsetDateTime::now_utc() + Duration::minutes(5))
            .sign(owner.key.clone())
            .execute(client)
            .await?
            .get_receipt(client)
            .await?
            .token_id
            .unwrap();

        Ok(Self { id: token_id, owner: owner.clone() })
    }

    // fixme: find a better name
    async fn mint_incremental(
        &self,
        client: &Client,
        nfts_to_mint: u8,
    ) -> hedera::Result<Vec<i64>> {
        self.mint(client, (0..nfts_to_mint).map(|it| [it])).await
    }

    pub(crate) async fn mint<Bytes: AsRef<[u8]>>(
        &self,
        client: &Client,
        metadata: impl IntoIterator<Item = Bytes>,
    ) -> hedera::Result<Vec<i64>> {
        async fn inner(
            nft: &Nft,
            client: &Client,
            mut tx: TokenMintTransaction,
        ) -> hedera::Result<Vec<i64>> {
            let serials = tx
                .token_id(nft.id)
                .sign(nft.owner.key.clone())
                .execute(client)
                .await?
                .get_receipt(client)
                .await?
                .serials;

            Ok(serials)
        }

        let mut tx = TokenMintTransaction::new();

        tx.metadata(metadata);

        inner(self, client, tx).await
    }

    pub(crate) async fn burn(
        &self,
        client: &Client,
        serials: impl IntoIterator<Item = i64>,
    ) -> hedera::Result<()> {
        // non generic inner function to save generic instantiations... Not that that's a huge concern here.
        async fn inner(
            nft: &Nft,
            client: &Client,
            mut tx: TokenBurnTransaction,
        ) -> hedera::Result<()> {
            tx.token_id(nft.id)
                .sign(nft.owner.key.clone())
                .execute(client)
                .await?
                .get_receipt(client)
                .await
                .map(drop)
        }

        let mut tx = TokenBurnTransaction::new();

        tx.serials(serials);

        inner(self, client, tx).await
    }

    pub(crate) async fn delete(self, client: &Client) -> hedera::Result<()> {
        TokenDeleteTransaction::new()
            .token_id(self.id)
            .sign(self.owner.key)
            .execute(client)
            .await?
            .get_receipt(client)
            .await?;

        Ok(())
    }
}

#[tokio::test]
async fn mint_several_nfts_at_once() -> anyhow::Result<()> {
    async fn setup(op: &Operator, client: &Client) -> anyhow::Result<TokenId> {
        let token_id = TokenCreateTransaction::new()
            .name("sdk::rust::e2e::mint_many")
            .symbol("ยต")
            .token_type(hedera::TokenType::NonFungibleUnique)
            .treasury_account_id(op.account_id)
            .admin_key(op.private_key.clone().public_key())
            .supply_key(op.private_key.clone().public_key())
            .expiration_time(OffsetDateTime::now_utc() + Duration::minutes(5))
            .freeze_default(false)
            .execute(client)
            .await?
            .get_receipt(client)
            .await?
            .token_id
            .ok_or_else(|| anyhow::anyhow!("Token creation failed"))?;

        log::info!("successfully created token {token_id}");

        Ok(token_id)
    }

    async fn teardown(client: &Client, token_id: TokenId) -> anyhow::Result<()> {
        TokenDeleteTransaction::new()
            .token_id(token_id)
            .execute(client)
            .await?
            .get_receipt(client)
            .await?;

        Ok(())
    }

    const MINT_TRANSACTIONS: usize = 5;
    // mint faster by using less transactions.
    const MAX_MINTS_PER_TX: usize = 10;

    let TestEnvironment { config, client } = setup_global();

    let Some(op) = &config.operator else {
        log::debug!("skipping test due to lack of operator");
        return Ok(());
    };

    if !config.run_nonfree_tests {
        log::debug!("skipping non-free test");
        return Ok(());
    }

    let token_id = setup(op, &client).await?;

    let mut tasks = JoinSet::new();

    for _ in 0..MINT_TRANSACTIONS {
        // give the tasks a bit of time between spawning to avoid hammering the network.
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        tasks.spawn({
            let client = client.clone();
            async move { create_nft(&client, token_id, MAX_MINTS_PER_TX).await }
        });
    }

    let mut responses = Vec::with_capacity(MINT_TRANSACTIONS);

    // note: we collect the responses to test simultaniously waiting for multiple receipts next.
    while let Some(response) = tasks.join_next().await {
        let response = response??;

        responses.push(response);
    }

    let mut tasks = JoinSet::new();

    for response in responses {
        // give the tasks a bit of time between spawning to avoid hammering the network.
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;

        let client = client.clone();
        tasks.spawn(async move { response.get_receipt(&client).await });
    }

    while let Some(receipt) = tasks.join_next().await {
        // we error for status here.
        let _receipt = receipt??;
    }

    teardown(&client, token_id).await?;

    Ok(())
}

async fn create_nft(
    client: &Client,
    token_id: TokenId,
    nfts: usize,
) -> hedera::Result<TransactionResponse> {
    TokenMintTransaction::default()
        .token_id(token_id)
        .metadata(vec![Vec::from([0x12, 0x34]); nfts])
        .execute(client)
        .await
}