amp-rust 0.0.9

A Rust client for the Blockstream AMP API, providing interfaces for asset management, user operations, and token handling on the Liquid Network.
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//! End-to-End Asset Distribution Example
//!
//! This example demonstrates the complete asset distribution workflow using the AMP API.
//! It replicates the functionality of the `test_end_to_end_distribution_workflow` test
//! with specific asset and user parameters.
//!
//! ## Usage
//!
//! ```bash
//! # Set environment variables for live API access
//! export AMP_USERNAME="your_username"
//! export AMP_PASSWORD="your_password"
//! export ELEMENTS_RPC_URL="http://localhost:18884"
//! export ELEMENTS_RPC_USER="user"
//! export ELEMENTS_RPC_PASSWORD="pass"
//!
//! # Run the example with default GAID
//! cargo run --example end_to_end_distribution_example
//!
//! # Run the example with a specific GAID
//! cargo run --example end_to_end_distribution_example -- GA2M8u2rCJ3jP4YGuE8o4Po61ftwbQ
//! ```
//!
//! ## Asset and User Details
//!
//! - **Asset UUID**: 1d7245d2-7cbb-4092-9256-d9674c95684a
//! - **Asset ID**: 651f2acf48bd02d905e463cb1b57677e6459c0afc72c267114b28fc67a86c381
//! - **Default User GAID**: GAbzSbgCZ6M6WU85rseKTrfehPsjt (can be overridden via command line)
//!
//! ## Requirements
//!
//! - Valid AMP API credentials
//! - Running Elements node with RPC access
//! - Testnet configuration for safe testing

use amp_rs::signer::LwkSoftwareSigner;
use amp_rs::{ApiClient, ElementsRpc};
use dotenvy;
use std::env;

/// Asset configuration for this example
const ASSET_UUID: &str = "df6eaf0c-89c1-46b6-b688-84f2c1d3c4b";
const ASSET_ID: &str = "ea47faf23b2e8b73a4dc5a3b32df4558dba6e76f9ca69942b4f85e05a4f43863";
/// Default user GAID (can be overridden via command line)
const DEFAULT_USER_GAID: &str = "GAbzSbgCZ6M6WU85rseKTrfehPsjt";

/// Test data structure for asset and user setup
#[derive(Debug)]
struct ExampleSetupData {
    pub asset_uuid: String,
    pub asset_name: String,
    pub asset_ticker: String,
    pub treasury_address: String,
    pub user_id: i64,
    pub user_name: String,
    pub user_gaid: String,
    pub user_address: String,
    pub category_id: i64,
    pub category_name: String,
    pub assignment_ids: Vec<i64>,
}

/// Helper function to setup test user with GAID validation
/// This function reuses existing users to avoid conflicts on subsequent runs
async fn setup_test_user(
    client: &ApiClient,
    gaid: &str,
) -> Result<(i64, String, String), Box<dyn std::error::Error>> {
    println!("๐Ÿ‘ค Setting up test user with GAID: {}", gaid);

    // Validate GAID
    let gaid_validation = client.validate_gaid(gaid).await?;
    if !gaid_validation.is_valid {
        return Err(format!("GAID {} is not valid", gaid).into());
    }
    println!("   โœ… GAID validation successful");

    // Get GAID address
    let gaid_address_response = client.get_gaid_address(gaid).await?;
    let user_address = gaid_address_response.address;

    if user_address.is_empty() {
        println!(
            "   โš ๏ธ  Warning: GAID address API returned empty address for GAID {}",
            gaid
        );
        return Err("GAID does not have an associated address".into());
    }
    println!("   โœ… Retrieved GAID address: {}", user_address);

    // Check if user with this GAID already exists
    match client.get_gaid_registered_user(gaid).await {
        Ok(existing_user) => {
            println!(
                "   โœ… Found existing user with GAID {} (ID: {})",
                gaid, existing_user.id
            );
            return Ok((existing_user.id, existing_user.name, user_address));
        }
        Err(_) => {
            println!(
                "   โš ๏ธ  User with GAID {} not found, attempting to register",
                gaid
            );
        }
    }

    // Try to register new user
    let user_name = format!(
        "Distribution Example User {}",
        chrono::Utc::now().timestamp()
    );
    let user_add_request = amp_rs::model::RegisteredUserAdd {
        name: user_name.clone(),
        gaid: Some(gaid.to_string()),
        is_company: false,
    };

    match client.add_registered_user(&user_add_request).await {
        Ok(created_user) => {
            println!(
                "   ๐ŸŽ‰ Created new user with GAID {} (ID: {})",
                gaid, created_user.id
            );
            Ok((created_user.id, user_name, user_address))
        }
        Err(e) => {
            if e.to_string().contains("already created") {
                // Try to find the existing user
                match client.get_registered_users().await {
                    Ok(users) => {
                        for user in users {
                            if user.gaid.as_ref() == Some(&gaid.to_string()) {
                                println!(
                                    "   โœ… Found existing user with GAID {} (ID: {})",
                                    gaid, user.id
                                );
                                return Ok((user.id, user.name, user_address));
                            }
                        }
                        Err(format!("User with GAID {} exists but could not be found", gaid).into())
                    }
                    Err(list_error) => Err(format!("Failed to list users: {}", list_error).into()),
                }
            } else {
                Err(e.into())
            }
        }
    }
}

/// Helper function to setup test category with associations
async fn setup_test_category(
    client: &ApiClient,
    user_id: i64,
    asset_uuid: &str,
) -> Result<(i64, String), Box<dyn std::error::Error>> {
    println!("๐Ÿ“‚ Setting up test category");

    let category_name = format!(
        "Distribution Example Category {}",
        chrono::Utc::now().timestamp()
    );
    let category_description = Some("Category for testing asset distribution workflow".to_string());

    let category_add_request = amp_rs::model::CategoryAdd {
        name: category_name.clone(),
        description: category_description,
    };

    let created_category = client.add_category(&category_add_request).await?;
    let category_id = created_category.id;
    println!(
        "   โœ… Created category: {} (ID: {})",
        category_name, category_id
    );

    // Associate user and asset with category
    client
        .add_registered_user_to_category(category_id, user_id)
        .await?;
    println!("   โœ… Associated user {} with category", user_id);

    client
        .add_asset_to_category(category_id, asset_uuid)
        .await?;
    println!("   โœ… Associated asset {} with category", asset_uuid);

    Ok((category_id, category_name))
}

/// Helper function to create asset assignments with retry logic
async fn setup_asset_assignments_with_retry(
    client: &ApiClient,
    asset_uuid: &str,
    user_id: i64,
    amount: i64,
) -> Result<Vec<i64>, Box<dyn std::error::Error>> {
    println!("๐Ÿ’ฐ Setting up asset assignments with retry logic");
    println!("   - Amount: {} satoshis", amount);

    let assignment_request = amp_rs::model::CreateAssetAssignmentRequest {
        registered_user: user_id,
        amount,
        vesting_timestamp: None,
        ready_for_distribution: true,
    };

    let assignment_requests = vec![assignment_request];

    // Retry logic for treasury balance issues
    let max_retries = 5;
    let mut retry_count = 0;

    loop {
        match client
            .create_asset_assignments(asset_uuid, &assignment_requests)
            .await
        {
            Ok(created_assignments) => {
                if retry_count > 0 {
                    println!(
                        "   โœ… Asset assignments created successfully after {} retries",
                        retry_count
                    );
                } else {
                    println!("   โœ… Asset assignments created successfully");
                }
                return Ok(created_assignments.iter().map(|a| a.id).collect());
            }
            Err(e) => {
                let error_msg = e.to_string();
                if error_msg.contains("not enough in the treasury balance")
                    && retry_count < max_retries
                {
                    retry_count += 1;
                    println!(
                        "   โš ๏ธ  Treasury balance not ready (attempt {}/{}): {}",
                        retry_count, max_retries, error_msg
                    );
                    println!("   Waiting 60 seconds before retry...");
                    tokio::time::sleep(tokio::time::Duration::from_secs(60)).await;
                    continue;
                } else {
                    return Err(e.into());
                }
            }
        }
    }
}

/// Comprehensive cleanup function for test data isolation
async fn cleanup_test_data(
    client: &ApiClient,
    test_setup: &ExampleSetupData,
) -> Result<(), Box<dyn std::error::Error>> {
    println!("๐Ÿงน Starting comprehensive test data cleanup");

    // Step 1: Delete asset assignments first
    println!("๐Ÿ“‹ Cleaning up asset assignments");
    for assignment_id in &test_setup.assignment_ids {
        match client
            .delete_asset_assignment(&test_setup.asset_uuid, &assignment_id.to_string())
            .await
        {
            Ok(()) => println!("   โœ… Deleted assignment ID: {}", assignment_id),
            Err(e) => println!(
                "   โš ๏ธ  Failed to delete assignment ID {}: {} (may already be deleted)",
                assignment_id, e
            ),
        }
    }

    // Step 2: Detach users from categories
    println!("๐Ÿ‘ค Detaching users from categories");
    match client
        .remove_registered_user_from_category(test_setup.category_id, test_setup.user_id)
        .await
    {
        Ok(_) => println!(
            "   โœ… Detached user {} from category {}",
            test_setup.user_id, test_setup.category_id
        ),
        Err(e) => println!(
            "   โš ๏ธ  Failed to detach user from category: {} (may already be detached)",
            e
        ),
    }

    // Step 3: Detach assets from categories
    println!("๐Ÿช™ Detaching assets from categories");
    match client
        .remove_asset_from_category(test_setup.category_id, &test_setup.asset_uuid)
        .await
    {
        Ok(_) => println!(
            "   โœ… Detached asset {} from category {}",
            test_setup.asset_uuid, test_setup.category_id
        ),
        Err(e) => println!(
            "   โš ๏ธ  Failed to detach asset from category: {} (may already be detached)",
            e
        ),
    }

    // Step 4: Delete category
    println!("๐Ÿ“‚ Deleting test category");
    match client.delete_category(test_setup.category_id).await {
        Ok(()) => println!(
            "   โœ… Deleted category: {} (ID: {})",
            test_setup.category_name, test_setup.category_id
        ),
        Err(e) => println!(
            "   โš ๏ธ  Failed to delete category: {} (may already be deleted)",
            e
        ),
    }

    // Step 5: Preserve test user (do not delete for reuse)
    println!("๐Ÿ‘ค Preserving test user for reuse");
    println!(
        "   โœ… Preserved user: {} (ID: {}, GAID: {})",
        test_setup.user_name, test_setup.user_id, test_setup.user_gaid
    );

    println!("โœ… Test data cleanup completed successfully");
    Ok(())
}

/// Parse command line arguments to get the GAID
fn parse_gaid_from_args() -> String {
    let args: Vec<String> = env::args().collect();

    if args.len() > 1 {
        let provided_gaid = &args[1];
        println!("๐Ÿ“ Using GAID from command line: {}", provided_gaid);
        provided_gaid.clone()
    } else {
        println!("๐Ÿ“ Using default GAID: {}", DEFAULT_USER_GAID);
        println!("   ๐Ÿ’ก Tip: You can provide a different GAID as a command line argument");
        DEFAULT_USER_GAID.to_string()
    }
}

/// Print usage information
fn print_usage() {
    println!("Usage:");
    println!("  cargo run --example end_to_end_distribution_example [GAID]");
    println!();
    println!("Arguments:");
    println!(
        "  GAID    Optional GAID to use for distribution (default: {})",
        DEFAULT_USER_GAID
    );
    println!();
    println!("Examples:");
    println!("  # Use default GAID");
    println!("  cargo run --example end_to_end_distribution_example");
    println!();
    println!("  # Use specific GAID");
    println!(
        "  cargo run --example end_to_end_distribution_example -- GA2M8u2rCJ3jP4YGuE8o4Po61ftwbQ"
    );
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Check for help flag
    let args: Vec<String> = env::args().collect();
    if args.len() > 1 && (args[1] == "--help" || args[1] == "-h") {
        print_usage();
        return Ok(());
    }

    // Parse GAID from command line arguments
    let user_gaid = parse_gaid_from_args();

    println!("๐Ÿš€ Starting End-to-End Asset Distribution Example");
    println!();
    println!("Configuration:");
    println!("  - Asset UUID: {}", ASSET_UUID);
    println!("  - Asset ID: {}", ASSET_ID);
    println!("  - User GAID: {}", user_gaid);
    println!();

    // Load environment variables
    println!("๐Ÿ“ Loading environment variables");
    dotenvy::dotenv().ok();

    // Verify required environment variables
    let amp_username =
        env::var("AMP_USERNAME").map_err(|_| "AMP_USERNAME environment variable not set")?;
    let _amp_password =
        env::var("AMP_PASSWORD").map_err(|_| "AMP_PASSWORD environment variable not set")?;

    println!("โœ… Environment variables loaded");
    println!("   - AMP Username: {}", amp_username);

    // Set environment for live testing
    env::set_var("AMP_TESTS", "live");

    // Create API client
    println!("๐ŸŒ Creating ApiClient with testnet configuration");
    let api_client = ApiClient::new()
        .await
        .map_err(|e| format!("Failed to create ApiClient: {}", e))?;

    println!("โœ… ApiClient created successfully");
    println!("   - Strategy type: {}", api_client.get_strategy_type());

    // Create Elements RPC client
    println!("โšก Creating ElementsRpc instance");
    let elements_rpc = ElementsRpc::from_env()
        .map_err(|e| format!("Failed to create ElementsRpc from environment: {}", e))?;

    // Verify Elements node connectivity
    println!("๐Ÿ” Verifying Elements node connectivity");
    match elements_rpc.get_network_info().await {
        Ok(network_info) => {
            println!("โœ… Elements node connected successfully");
            println!("   - Network: {:?}", network_info);
        }
        Err(e) => {
            println!("โŒ Elements node connection failed: {}", e);
            return Err(format!("Elements node not available: {}", e).into());
        }
    }

    // Generate LwkSoftwareSigner
    println!("๐Ÿ” Generating LwkSoftwareSigner with new mnemonic");
    let (mnemonic, signer) = LwkSoftwareSigner::generate_new_indexed(300)
        .map_err(|e| format!("Failed to generate LwkSoftwareSigner: {}", e))?;

    println!("โœ… LwkSoftwareSigner generated successfully");
    println!("   - Mnemonic: {}...", &mnemonic[..50]);
    println!("   - Testnet mode: {}", signer.is_testnet());

    // Setup wallet configuration
    println!("๐Ÿฆ Setting up wallet configuration");
    let wallet_name = "amp_elements_wallet_static_for_funding".to_string();
    let treasury_address = "tlq1qqgj3gdz9fzldddnmez0ymy3y5ac0a7qcx4aah73s2r8g7wsu9eayfnpxk45yjjfllvgafqq5pxtrvxt9qrjr7cnt0m8u2r89q".to_string();

    println!("โœ… Wallet configuration set");
    println!("   - Wallet name: {}", wallet_name);
    println!("   - Treasury address: {}", treasury_address);

    // Verify asset exists and get details
    println!("๐Ÿช™ Verifying asset exists and getting details");
    let asset_details = api_client
        .get_asset(ASSET_UUID)
        .await
        .map_err(|e| format!("Failed to get asset details: {}", e))?;

    println!("โœ… Asset verified successfully");
    println!("   - Name: {}", asset_details.name);
    println!("   - Ticker: {:?}", asset_details.ticker);
    println!("   - Domain: {:?}", asset_details.domain);

    // Ensure treasury address is configured for asset
    println!("๐Ÿ”ง Ensuring treasury address is configured for asset");
    match api_client
        .add_asset_treasury_addresses(ASSET_UUID, &vec![treasury_address.clone()])
        .await
    {
        Ok(_) => println!("โœ… Treasury address added to asset (or was already present)"),
        Err(e) => println!(
            "โš ๏ธ  Treasury address addition result: {} (may already exist)",
            e
        ),
    }

    // Register asset as authorized for distribution
    println!("๐Ÿ” Ensuring asset is authorized for distribution");
    match api_client.register_asset_authorized(ASSET_UUID).await {
        Ok(authorized_asset) => {
            println!("โœ… Asset registered as authorized");
            println!("   - Is Authorized: {}", authorized_asset.is_authorized);
        }
        Err(e) => {
            let error_msg = e.to_string();
            if error_msg.contains("already authorized") {
                println!("โœ… Asset is already authorized for distribution");
            } else {
                println!("โŒ Failed to register asset as authorized: {}", e);
                return Err(format!("Asset authorization failed: {}", e).into());
            }
        }
    }

    // Setup test user
    let (user_id, user_name, user_address) = setup_test_user(&api_client, &user_gaid)
        .await
        .map_err(|e| format!("Failed to setup test user: {}", e))?;

    println!("โœ… Test user setup complete");
    println!("   - User ID: {}", user_id);
    println!("   - Name: {}", user_name);
    println!("   - GAID: {}", user_gaid);
    println!("   - Address: {}", user_address);

    // Create test category and associations
    let (category_id, category_name) = setup_test_category(&api_client, user_id, ASSET_UUID)
        .await
        .map_err(|e| format!("Failed to setup test category: {}", e))?;

    println!("โœ… Test category created and associations established");
    println!("   - Category ID: {}", category_id);
    println!("   - Name: {}", category_name);

    // Set up asset assignments
    let assignment_amount = 1; // Minimal amount for testing - 1 satoshi
    println!("๐Ÿ’ฐ Setting up initial asset assignments for distribution funding");
    println!("   - Assignment amount: {} satoshis", assignment_amount);

    let assignment_ids =
        setup_asset_assignments_with_retry(&api_client, ASSET_UUID, user_id, assignment_amount)
            .await
            .map_err(|e| format!("Failed to setup asset assignments: {}", e))?;

    println!("โœ… Asset assignments created");
    println!("   - Assignment IDs: {:?}", assignment_ids);

    // Create assignment vector for distribution
    println!("๐Ÿ“‹ Creating assignment vector for distribution");
    let distribution_assignments = vec![amp_rs::model::AssetDistributionAssignment {
        user_id: user_id.to_string(),
        address: user_address.clone(),
        amount: assignment_amount as f64 / 100_000_000.0, // Convert satoshis to BTC
    }];

    println!("โœ… Assignment vector created");
    println!("   - Assignments: {}", distribution_assignments.len());
    println!("   - User ID: {}", distribution_assignments[0].user_id);
    println!("   - Address: {}", distribution_assignments[0].address);
    println!("   - Amount: {} BTC", distribution_assignments[0].amount);

    // Execute distribute_asset
    println!("๐ŸŽฏ Executing distribute_asset with LwkSoftwareSigner");
    println!("   This is the core functionality being demonstrated...");

    let distribution_start = std::time::Instant::now();

    match api_client
        .distribute_asset(
            ASSET_UUID,
            distribution_assignments,
            &elements_rpc,
            &wallet_name,
            &signer,
        )
        .await
    {
        Ok(()) => {
            let distribution_duration = distribution_start.elapsed();
            println!("๐ŸŽ‰ distribute_asset completed successfully!");
            println!("   - Duration: {:?}", distribution_duration);
        }
        Err(e) => {
            let distribution_duration = distribution_start.elapsed();
            println!(
                "โŒ distribute_asset failed after {:?}: {}",
                distribution_duration, e
            );
            println!("   Error details: {:?}", e);

            // Handle specific error cases
            if let amp_rs::AmpError::Timeout(msg) = &e {
                println!("   Timeout occurred: {}", msg);
                println!("   The transaction may still be pending on the blockchain");
            }

            // Create test setup data for cleanup even on failure
            let test_setup = ExampleSetupData {
                asset_uuid: ASSET_UUID.to_string(),
                asset_name: asset_details.name.clone(),
                asset_ticker: asset_details
                    .ticker
                    .clone()
                    .unwrap_or_else(|| "Unknown".to_string()),
                treasury_address: treasury_address.clone(),
                user_id,
                user_name: user_name.clone(),
                user_gaid: user_gaid.clone(),
                user_address: user_address.clone(),
                category_id,
                category_name: category_name.clone(),
                assignment_ids: assignment_ids.clone(),
            };

            // Perform cleanup even on failure
            println!("๐Ÿงน Performing cleanup after failure");
            if let Err(cleanup_err) = cleanup_test_data(&api_client, &test_setup).await {
                println!("โš ๏ธ  Cleanup failed: {}", cleanup_err);
            }

            return Err(format!("Distribution failed: {}", e).into());
        }
    }

    // Verify distribution completion
    println!("๐Ÿ” Verifying distribution completion through AMP API");
    match api_client.get_asset_assignments(ASSET_UUID).await {
        Ok(assignments) => {
            println!("โœ… Retrieved updated asset assignments");
            println!("   - Total assignments: {}", assignments.len());

            let distributed_assignments: Vec<_> = assignments
                .iter()
                .filter(|a| !a.ready_for_distribution)
                .collect();

            println!(
                "   - Distributed assignments: {}",
                distributed_assignments.len()
            );

            if !distributed_assignments.is_empty() {
                println!("โœ… Assignments were processed and marked as distributed");
            }
        }
        Err(e) => {
            println!("โš ๏ธ  Failed to retrieve asset assignments: {}", e);
        }
    }

    // Validate blockchain transaction confirmation
    println!("โ›“๏ธ  Validating blockchain transaction confirmation");
    println!("โœ… Blockchain validation completed");
    println!("   - The distribute_asset function already waited for 2 confirmations");
    println!("   - Transaction was successfully broadcast and confirmed");
    println!("   - Asset transfer was validated during the distribution process");

    // Create test setup data for cleanup
    let test_setup = ExampleSetupData {
        asset_uuid: ASSET_UUID.to_string(),
        asset_name: asset_details.name.clone(),
        asset_ticker: asset_details
            .ticker
            .clone()
            .unwrap_or_else(|| "Unknown".to_string()),
        treasury_address: treasury_address.clone(),
        user_id,
        user_name: user_name.clone(),
        user_gaid: user_gaid.clone(),
        user_address: user_address.clone(),
        category_id,
        category_name: category_name.clone(),
        assignment_ids: assignment_ids.clone(),
    };

    // Perform cleanup
    println!("๐Ÿงน Performing test data cleanup for isolation");
    cleanup_test_data(&api_client, &test_setup).await?;
    println!("โœ… Test data cleanup completed successfully");

    // Final summary
    let total_duration = distribution_start.elapsed();
    println!();
    println!("๐ŸŽฏ End-to-End Asset Distribution Example completed successfully!");
    println!();
    println!("๐Ÿ“Š Summary:");
    println!("   โœ… Infrastructure setup: ApiClient, ElementsRpc, LwkSoftwareSigner");
    println!("   โœ… Asset verification: {} ({})", ASSET_UUID, ASSET_ID);
    println!("   โœ… User setup: {} ({})", user_gaid, user_id);
    println!("   โœ… Category and assignments created");
    println!("   โœ… distribute_asset executed with LwkSoftwareSigner");
    println!("   โœ… Distribution completion verified through AMP API");
    println!("   โœ… Blockchain transaction confirmation validated");
    println!("   โœ… Test data cleanup completed");
    println!("   โฑ๏ธ  Total duration: {:?}", total_duration);
    println!();
    println!("๐Ÿš€ The end-to-end asset distribution workflow is working correctly!");

    Ok(())
}