datalayer-driver 6.0.0

Native Chia DataLayer Driver for storing and retrieving data in Chia blockchain
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
#![allow(clippy::result_large_err)]

use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};

// Import proof types from our own crate's rust module
use crate::error::WalletError;
pub use crate::types::{coin_records_to_states, SuccessResponse, XchServerCoin};
use crate::types::{EveProof, LineageProof, Proof};
use crate::xch_server_coin::{urls_from_conditions, MirrorArgs, MirrorSolution, NewXchServerCoin};
use crate::{NetworkType, UnspentCoinStates};
use chia_bls::{sign, verify, PublicKey, SecretKey, Signature};
use chia_consensus::consensus_constants::ConsensusConstants;
use chia_consensus::flags::{DONT_VALIDATE_SIGNATURE, MEMPOOL_MODE};
use chia_consensus::owned_conditions::OwnedSpendBundleConditions;
use chia_consensus::run_block_generator::run_block_generator;
use chia_consensus::solution_generator::solution_generator;
use chia_protocol::{
    Bytes, Bytes32, Coin, CoinSpend, CoinState, CoinStateFilters, RejectHeaderRequest,
    RequestBlockHeader, RequestFeeEstimates, RespondBlockHeader, RespondFeeEstimates, SpendBundle,
    TransactionAck,
};
use chia_puzzle_types::{
    nft::NftMetadata,
    standard::{StandardArgs, StandardSolution},
    DeriveSynthetic,
};
use chia_puzzles::SINGLETON_LAUNCHER_HASH;
use chia_wallet_sdk::client::Peer;
use chia_wallet_sdk::driver::{
    get_merkle_tree, Datastore, DatastoreMetadata, DelegatedPuzzle, Did, DidInfo, DriverError,
    HashedPtr, IntermediateLauncher, Launcher, Layer, NftMint, OracleLayer, SpendContext,
    SpendWithConditions, StandardLayer, WriterLayer,
};
use chia_wallet_sdk::signer::{AggSigConstants, RequiredSignature, SignerError};
use chia_wallet_sdk::types::{
    announcement_id,
    conditions::{CreateCoin, MeltSingleton, Memos, UpdateDatastoreMerkleRoot},
    Condition, Conditions, MAINNET_CONSTANTS, TESTNET11_CONSTANTS,
};
use chia_wallet_sdk::utils::{self, CoinSelectionError};
use clvm_traits::{clvm_tuple, FromClvm, ToClvm};
use clvm_utils::tree_hash;
use clvmr::Allocator;
use hex_literal::hex;

/* echo -n 'datastore' | sha256sum */
pub const DATASTORE_LAUNCHER_HINT: Bytes32 = Bytes32::new(hex!(
    "
    aa7e5b234e1d55967bf0a316395a2eab6cb3370332c0f251f0e44a5afb84fc68
    "
));

pub const DIG_ASSET_ID: Bytes32 = Bytes32::new(hex!(
    "a406d3a9de984d03c9591c10d917593b434d5263cabe2b42f6b367df16832f81"
));

pub const MAX_CLVM_COST: u64 = 11_000_000_000;

pub async fn get_unspent_coin_states_by_hint(
    peer: &Peer,
    hint: Bytes32,
    network_type: NetworkType,
) -> Result<UnspentCoinStates, WalletError> {
    let header_hash = match network_type {
        NetworkType::Mainnet => MAINNET_CONSTANTS.genesis_challenge,
        NetworkType::Testnet11 => TESTNET11_CONSTANTS.genesis_challenge,
    };
    get_unspent_coin_states(peer, hint, None, header_hash, true).await
}

pub async fn get_unspent_coin_states(
    peer: &Peer,
    puzzle_hash: Bytes32,
    previous_height: Option<u32>,
    previous_header_hash: Bytes32,
    allow_hints: bool,
) -> Result<UnspentCoinStates, WalletError> {
    let mut coin_states = Vec::new();
    let mut last_height = previous_height.unwrap_or_default();

    let mut last_header_hash = previous_header_hash;

    loop {
        let response = peer
            .request_puzzle_state(
                vec![puzzle_hash],
                if last_height == 0 {
                    None
                } else {
                    Some(last_height)
                },
                last_header_hash,
                CoinStateFilters {
                    include_spent: false,
                    include_unspent: true,
                    include_hinted: allow_hints,
                    min_amount: 1,
                },
                false,
            )
            .await
            .map_err(WalletError::Client)?
            .map_err(|_| WalletError::RejectPuzzleState)?;

        last_height = response.height;
        last_header_hash = response.header_hash;
        coin_states.extend(
            response
                .coin_states
                .into_iter()
                .filter(|cs| cs.spent_height.is_none()),
        );

        if response.is_finished {
            break;
        }
    }

    Ok(UnspentCoinStates {
        coin_states,
        last_height,
        last_header_hash,
    })
}

pub fn select_coins(coins: Vec<Coin>, total_amount: u64) -> Result<Vec<Coin>, CoinSelectionError> {
    utils::select_coins(coins.into_iter().collect(), total_amount)
}

fn spend_coins_together(
    ctx: &mut SpendContext,
    synthetic_key: PublicKey,
    coins: &[Coin],
    extra_conditions: Conditions,
    output: i64,
    change_puzzle_hash: Bytes32,
) -> Result<(), WalletError> {
    let p2 = StandardLayer::new(synthetic_key);

    let change = i64::try_from(coins.iter().map(|coin| coin.amount).sum::<u64>()).unwrap() - output;
    assert!(change >= 0);
    let change = change as u64;

    let first_coin_id = coins[0].coin_id();

    for (i, &coin) in coins.iter().enumerate() {
        if i == 0 {
            let mut conditions = extra_conditions.clone();

            if change > 0 {
                conditions = conditions.create_coin(change_puzzle_hash, change, Memos::None);
            }

            p2.spend(ctx, coin, conditions)?;
        } else {
            p2.spend(
                ctx,
                coin,
                Conditions::new().assert_concurrent_spend(first_coin_id),
            )?;
        }
    }
    Ok(())
}

pub fn send_xch(
    synthetic_key: PublicKey,
    coins: &[Coin],
    outputs: &[(Bytes32, u64, Vec<Bytes>)],
    fee: u64,
) -> Result<Vec<CoinSpend>, WalletError> {
    let mut ctx = SpendContext::new();

    let mut conditions = Conditions::new().reserve_fee(fee);
    let mut total_amount = fee;

    for output in outputs {
        let memos = ctx.alloc(&output.2)?;
        conditions = conditions.create_coin(output.0, output.1, Memos::Some(memos));
        total_amount += output.1;
    }

    spend_coins_together(
        &mut ctx,
        synthetic_key,
        coins,
        conditions,
        total_amount.try_into().unwrap(),
        StandardArgs::curry_tree_hash(synthetic_key).into(),
    )?;

    Ok(ctx.take())
}

pub fn create_server_coin(
    synthetic_key: PublicKey,
    selected_coins: Vec<Coin>,
    hint: Bytes32,
    uris: Vec<String>,
    amount: u64,
    fee: u64,
) -> Result<NewXchServerCoin, WalletError> {
    let puzzle_hash = StandardArgs::curry_tree_hash(synthetic_key).into();

    let mut memos = Vec::with_capacity(uris.len() + 1);
    memos.push(hint.to_vec());

    for url in &uris {
        memos.push(url.as_bytes().to_vec());
    }

    let mut ctx = SpendContext::new();

    let memos = ctx.alloc(&memos)?;

    let conditions = Conditions::new()
        .create_coin(
            MirrorArgs::curry_tree_hash().into(),
            amount,
            Memos::Some(memos),
        )
        .reserve_fee(fee);

    spend_coins_together(
        &mut ctx,
        synthetic_key,
        &selected_coins,
        conditions,
        (amount + fee).try_into().unwrap(),
        puzzle_hash,
    )?;

    let server_coin = XchServerCoin {
        coin: Coin::new(
            selected_coins[0].coin_id(),
            MirrorArgs::curry_tree_hash().into(),
            amount,
        ),
        p2_puzzle_hash: puzzle_hash,
        memo_urls: uris,
    };

    Ok(NewXchServerCoin {
        coin_spends: ctx.take(),
        server_coin,
    })
}

pub async fn spend_xch_server_coins(
    peer: &Peer,
    synthetic_key: PublicKey,
    selected_coins: Vec<Coin>,
    total_fee: u64,
    network: TargetNetwork,
) -> Result<Vec<CoinSpend>, WalletError> {
    let puzzle_hash = StandardArgs::curry_tree_hash(synthetic_key).into();

    let mut fee_coins = Vec::new();
    let mut server_coins = Vec::new();

    for coin in selected_coins {
        if coin.puzzle_hash == puzzle_hash {
            fee_coins.push(coin);
        } else {
            server_coins.push(coin);
        }
    }

    if server_coins.is_empty() {
        return Ok(Vec::new());
    }

    assert!(!fee_coins.is_empty());

    let parent_coins = peer
        .request_coin_state(
            server_coins.iter().map(|sc| sc.parent_coin_info).collect(),
            None,
            match network {
                TargetNetwork::Mainnet => MAINNET_CONSTANTS.genesis_challenge,
                TargetNetwork::Testnet11 => TESTNET11_CONSTANTS.genesis_challenge,
            },
            false,
        )
        .await?
        .map_err(|_| WalletError::RejectCoinState)?
        .coin_states;

    let mut ctx = SpendContext::new();

    let puzzle_reveal = ctx.curry(MirrorArgs::default())?;

    let mut conditions = Conditions::new().reserve_fee(total_fee);
    let mut total_fee: i64 = total_fee.try_into().unwrap();

    for server_coin in server_coins {
        let parent_coin = parent_coins
            .iter()
            .find(|cs| cs.coin.coin_id() == server_coin.parent_coin_info)
            .copied()
            .ok_or(WalletError::UnknownCoin)?;

        if parent_coin.coin.puzzle_hash != puzzle_hash {
            return Err(WalletError::Permission);
        }

        let parent_inner_puzzle = ctx.curry(StandardArgs::new(synthetic_key))?;

        let puzzle_reveal = ctx.serialize(&puzzle_reveal)?;

        let solution = ctx.serialize(&MirrorSolution {
            parent_parent_id: parent_coin.coin.parent_coin_info,
            parent_inner_puzzle,
            parent_amount: parent_coin.coin.amount,
            parent_solution: StandardSolution {
                original_public_key: None,
                delegated_puzzle: (),
                solution: (),
            },
        })?;

        total_fee -= i64::try_from(server_coin.amount).unwrap();
        ctx.insert(CoinSpend::new(server_coin, puzzle_reveal, solution));

        conditions = conditions.assert_concurrent_spend(server_coin.coin_id());
    }

    spend_coins_together(
        &mut ctx,
        synthetic_key,
        &fee_coins,
        conditions,
        total_fee,
        puzzle_hash,
    )?;

    Ok(ctx.take())
}

pub async fn fetch_xch_server_coin(
    peer: &Peer,
    coin_state: CoinState,
    max_cost: u64,
) -> Result<XchServerCoin, WalletError> {
    let Some(created_height) = coin_state.created_height else {
        return Err(WalletError::UnknownCoin);
    };

    let spend = peer
        .request_puzzle_and_solution(coin_state.coin.parent_coin_info, created_height)
        .await?
        .map_err(|_| WalletError::RejectPuzzleSolution)?;

    let mut allocator = Allocator::new();

    let Ok(output) = spend
        .puzzle
        .run(&mut allocator, 0, max_cost, &spend.solution)
    else {
        return Err(WalletError::Clvm);
    };

    let Ok(conditions) = Vec::<Condition>::from_clvm(&allocator, output.1) else {
        return Err(WalletError::Parse(
            "Failed to get conditions from clvm allocator".to_string(),
        ));
    };

    let Some(urls) = urls_from_conditions(&allocator, &coin_state.coin, &conditions) else {
        return Err(WalletError::Parse(
            "Failed to get urls from conditions".to_string(),
        ));
    };

    let puzzle = spend
        .puzzle
        .to_clvm(&mut allocator)
        .map_err(DriverError::ToClvm)?;

    Ok(XchServerCoin {
        coin: coin_state.coin,
        p2_puzzle_hash: tree_hash(&allocator, puzzle).into(),
        memo_urls: urls,
    })
}

#[allow(clippy::too_many_arguments)]
pub fn mint_store(
    minter_synthetic_key: PublicKey,
    selected_coins: Vec<Coin>,
    root_hash: Bytes32,
    label: Option<String>,
    description: Option<String>,
    bytes: Option<u64>,
    size_proof: Option<String>,
    owner_puzzle_hash: Bytes32,
    delegated_puzzles: Vec<DelegatedPuzzle>,
    fee: u64,
) -> Result<SuccessResponse, WalletError> {
    let minter_puzzle_hash: Bytes32 = StandardArgs::curry_tree_hash(minter_synthetic_key).into();
    let total_amount_from_coins = selected_coins.iter().map(|c| c.amount).sum::<u64>();

    let total_amount = fee + 1;

    let mut ctx = SpendContext::new();

    let p2 = StandardLayer::new(minter_synthetic_key);

    let lead_coin = selected_coins[0];
    let lead_coin_name = lead_coin.coin_id();

    for coin in selected_coins.into_iter().skip(1) {
        p2.spend(
            &mut ctx,
            coin,
            Conditions::new().assert_concurrent_spend(lead_coin_name),
        )?;
    }

    let (launch_singleton, datastore) = Launcher::new(lead_coin_name, 1).mint_datastore(
        &mut ctx,
        DatastoreMetadata {
            root_hash,
            label,
            description,
            bytes,
            size_proof,
        },
        owner_puzzle_hash.into(),
        delegated_puzzles,
    )?;

    let launch_singleton = Conditions::new().extend(
        launch_singleton
            .into_iter()
            .map(|cond| {
                if let Condition::CreateCoin(cc) = cond {
                    if cc.puzzle_hash == SINGLETON_LAUNCHER_HASH.into() {
                        let hint = ctx.hint(DATASTORE_LAUNCHER_HINT)?;

                        return Ok(Condition::CreateCoin(CreateCoin {
                            puzzle_hash: cc.puzzle_hash,
                            amount: cc.amount,
                            memos: hint,
                        }));
                    }

                    return Ok(Condition::CreateCoin(cc));
                }

                Ok(cond)
            })
            .collect::<Result<Vec<_>, WalletError>>()?,
    );

    let lead_coin_conditions = if total_amount_from_coins > total_amount {
        let hint = ctx.hint(minter_puzzle_hash)?;

        launch_singleton.create_coin(
            minter_puzzle_hash,
            total_amount_from_coins - total_amount,
            hint,
        )
    } else {
        launch_singleton
    };
    p2.spend(&mut ctx, lead_coin, lead_coin_conditions)?;

    Ok(SuccessResponse {
        coin_spends: ctx.take(),
        new_datastore: datastore,
    })
}

pub struct SyncStoreResponse {
    pub latest_store: Datastore,
    pub latest_height: u32,
    pub root_hash_history: Option<Vec<(Bytes32, u64)>>,
}

pub async fn sync_store(
    peer: &Peer,
    store: &Datastore,
    last_height: Option<u32>,
    last_header_hash: Bytes32,
    with_history: bool,
) -> Result<SyncStoreResponse, WalletError> {
    let mut latest_store = store.clone();
    let mut history = vec![];

    let response = peer
        .request_coin_state(
            vec![store.coin.coin_id()],
            last_height,
            last_header_hash,
            false,
        )
        .await
        .map_err(WalletError::Client)?
        .map_err(|_| WalletError::RejectCoinState)?;
    let mut last_coin_record = response
        .coin_states
        .into_iter()
        .next()
        .ok_or(WalletError::UnknownCoin)?;

    let mut ctx = SpendContext::new(); // just to run puzzles more easily

    while last_coin_record.spent_height.is_some() {
        let puzzle_and_solution_req = peer
            .request_puzzle_and_solution(
                last_coin_record.coin.coin_id(),
                last_coin_record.spent_height.unwrap(),
            )
            .await
            .map_err(WalletError::Client)?
            .map_err(|_| WalletError::RejectPuzzleSolution)?;

        let cs = CoinSpend {
            coin: last_coin_record.coin,
            puzzle_reveal: puzzle_and_solution_req.puzzle,
            solution: puzzle_and_solution_req.solution,
        };

        let new_store = Datastore::<DatastoreMetadata>::from_spend(
            &mut ctx,
            &cs,
            &latest_store.info.delegated_puzzles,
        )?
        .ok_or(WalletError::Parse("Store from spend is None".to_string()))?;

        if with_history {
            let resp: Result<RespondBlockHeader, RejectHeaderRequest> = peer
                .request_fallible(RequestBlockHeader {
                    height: last_coin_record.spent_height.unwrap(),
                })
                .await
                .map_err(WalletError::Client)?;
            let block_header = resp.map_err(|_| WalletError::RejectHeaderRequest)?;

            history.push((
                new_store.info.metadata.root_hash,
                block_header
                    .header_block
                    .foliage_transaction_block
                    .unwrap()
                    .timestamp,
            ));
        }

        let response = peer
            .request_coin_state(
                vec![new_store.coin.coin_id()],
                last_height,
                last_header_hash,
                false,
            )
            .await
            .map_err(WalletError::Client)?
            .map_err(|_| WalletError::RejectCoinState)?;

        last_coin_record = response
            .coin_states
            .into_iter()
            .next()
            .ok_or(WalletError::UnknownCoin)?;
        latest_store = new_store;
    }

    Ok(SyncStoreResponse {
        latest_store,
        latest_height: last_coin_record
            .created_height
            .ok_or(WalletError::UnknownCoin)?,
        root_hash_history: if with_history { Some(history) } else { None },
    })
}

pub async fn sync_store_using_launcher_id(
    peer: &Peer,
    launcher_id: Bytes32,
    last_height: Option<u32>,
    last_header_hash: Bytes32,
    with_history: bool,
) -> Result<SyncStoreResponse, WalletError> {
    let response = peer
        .request_coin_state(vec![launcher_id], last_height, last_header_hash, false)
        .await
        .map_err(WalletError::Client)?
        .map_err(|_| WalletError::RejectCoinState)?;
    let last_coin_record = response
        .coin_states
        .into_iter()
        .next()
        .ok_or(WalletError::UnknownCoin)?;

    let mut ctx = SpendContext::new(); // just to run puzzles more easily

    let puzzle_and_solution_req = peer
        .request_puzzle_and_solution(
            last_coin_record.coin.coin_id(),
            last_coin_record
                .spent_height
                .ok_or(WalletError::UnknownCoin)?,
        )
        .await
        .map_err(WalletError::Client)?
        .map_err(|_| WalletError::RejectPuzzleSolution)?;

    let cs = CoinSpend {
        coin: last_coin_record.coin,
        puzzle_reveal: puzzle_and_solution_req.puzzle,
        solution: puzzle_and_solution_req.solution,
    };

    let first_store = Datastore::<DatastoreMetadata>::from_spend(&mut ctx, &cs, &[])?
        .ok_or(WalletError::Parse("Store from spend is None".to_string()))?;

    let res = sync_store(
        peer,
        &first_store,
        last_height,
        last_header_hash,
        with_history,
    )
    .await?;

    // prepend root hash from launch
    let root_hash_history = if let Some(mut res_root_hash_history) = res.root_hash_history {
        let spent_timestamp = if let Some(spent_height) = last_coin_record.spent_height {
            let resp: Result<RespondBlockHeader, RejectHeaderRequest> = peer
                .request_fallible(RequestBlockHeader {
                    height: spent_height,
                })
                .await
                .map_err(WalletError::Client)?;
            let resp = resp.map_err(|_| WalletError::RejectHeaderRequest)?;

            resp.header_block
                .foliage_transaction_block
                .unwrap()
                .timestamp
        } else {
            0
        };

        res_root_hash_history.insert(0, (first_store.info.metadata.root_hash, spent_timestamp));
        Some(res_root_hash_history)
    } else {
        None
    };

    Ok(SyncStoreResponse {
        latest_store: res.latest_store,
        latest_height: res.latest_height,
        root_hash_history,
    })
}

pub async fn get_store_creation_height(
    peer: &Peer,
    launcher_id: Bytes32,
    last_height: Option<u32>,
    last_header_hash: Bytes32,
) -> Result<u32, WalletError> {
    let response = peer
        .request_coin_state(vec![launcher_id], last_height, last_header_hash, false)
        .await
        .map_err(WalletError::Client)?
        .map_err(|_| WalletError::RejectCoinState)?;
    let last_coin_record = response
        .coin_states
        .into_iter()
        .next()
        .ok_or(WalletError::UnknownCoin)?;

    last_coin_record
        .created_height
        .ok_or(WalletError::UnknownCoin)
}

#[derive(Clone, Debug)]
pub enum DataStoreInnerSpend {
    Owner(PublicKey),
    Admin(PublicKey),
    Writer(PublicKey),
    // does not include oracle since it can't change metadata/owners :(
}

fn update_store_with_conditions(
    ctx: &mut SpendContext,
    conditions: Conditions,
    datastore: Datastore,
    inner_spend_info: DataStoreInnerSpend,
    allow_admin: bool,
    allow_writer: bool,
) -> Result<SuccessResponse, WalletError> {
    let inner_datastore_spend = match inner_spend_info {
        DataStoreInnerSpend::Owner(pk) => {
            StandardLayer::new(pk).spend_with_conditions(ctx, conditions)?
        }
        DataStoreInnerSpend::Admin(pk) => {
            if !allow_admin {
                return Err(WalletError::Permission);
            }

            StandardLayer::new(pk).spend_with_conditions(ctx, conditions)?
        }
        DataStoreInnerSpend::Writer(pk) => {
            if !allow_writer {
                return Err(WalletError::Permission);
            }

            WriterLayer::new(StandardLayer::new(pk)).spend(ctx, conditions)?
        }
    };

    let parent_delegated_puzzles = datastore.info.delegated_puzzles.clone();
    let new_spend = datastore.spend(ctx, inner_datastore_spend)?;

    let new_datastore =
        Datastore::<DatastoreMetadata>::from_spend(ctx, &new_spend, &parent_delegated_puzzles)?
            .ok_or(WalletError::Parse("Store from spend is None".to_string()))?;

    Ok(SuccessResponse {
        coin_spends: vec![new_spend],
        new_datastore,
    })
}

pub fn update_store_ownership(
    datastore: Datastore,
    new_owner_puzzle_hash: Bytes32,
    new_delegated_puzzles: Vec<DelegatedPuzzle>,
    inner_spend_info: DataStoreInnerSpend,
) -> Result<SuccessResponse, WalletError> {
    let ctx = &mut SpendContext::new();

    let update_condition: Condition = match inner_spend_info {
        DataStoreInnerSpend::Owner(_) => {
            Datastore::<DatastoreMetadata>::owner_create_coin_condition(
                ctx,
                datastore.info.launcher_id,
                new_owner_puzzle_hash,
                new_delegated_puzzles,
                true,
            )?
        }
        DataStoreInnerSpend::Admin(_) => {
            let merkle_tree = get_merkle_tree(ctx, new_delegated_puzzles.clone())?;

            let new_merkle_root_condition = UpdateDatastoreMerkleRoot {
                new_merkle_root: merkle_tree.root(),
                memos: Datastore::<DatastoreMetadata>::get_recreation_memos(
                    datastore.info.launcher_id,
                    new_owner_puzzle_hash.into(),
                    new_delegated_puzzles,
                ),
            }
            .to_clvm(&mut **ctx)
            .map_err(DriverError::ToClvm)?;

            Condition::Other(new_merkle_root_condition)
        }
        _ => return Err(WalletError::Permission),
    };

    let update_conditions = Conditions::new().with(update_condition);

    update_store_with_conditions(
        ctx,
        update_conditions,
        datastore,
        inner_spend_info,
        true,
        false,
    )
}

pub fn update_store_metadata(
    datastore: Datastore,
    new_root_hash: Bytes32,
    new_label: Option<String>,
    new_description: Option<String>,
    new_bytes: Option<u64>,
    new_size_proof: Option<String>,
    inner_spend_info: DataStoreInnerSpend,
) -> Result<SuccessResponse, WalletError> {
    let ctx = &mut SpendContext::new();

    let new_metadata = DatastoreMetadata {
        root_hash: new_root_hash,
        label: new_label,
        description: new_description,
        bytes: new_bytes,
        size_proof: new_size_proof,
    };
    let mut new_metadata_condition = Conditions::new().with(
        Datastore::<DatastoreMetadata>::new_metadata_condition(ctx, new_metadata)?,
    );

    if let DataStoreInnerSpend::Owner(_) = inner_spend_info {
        new_metadata_condition = new_metadata_condition.with(
            Datastore::<DatastoreMetadata>::owner_create_coin_condition(
                ctx,
                datastore.info.launcher_id,
                datastore.info.owner_puzzle_hash,
                datastore.info.delegated_puzzles.clone(),
                false,
            )?,
        );
    }

    update_store_with_conditions(
        ctx,
        new_metadata_condition,
        datastore,
        inner_spend_info,
        true,
        true,
    )
}

pub fn melt_store(
    datastore: Datastore,
    owner_pk: PublicKey,
) -> Result<Vec<CoinSpend>, WalletError> {
    let ctx = &mut SpendContext::new();

    let melt_conditions = Conditions::new()
        .with(Condition::reserve_fee(1))
        .with(Condition::Other(
            MeltSingleton {}
                .to_clvm(&mut **ctx)
                .map_err(DriverError::ToClvm)?,
        ));

    let inner_datastore_spend =
        StandardLayer::new(owner_pk).spend_with_conditions(ctx, melt_conditions)?;

    let new_spend = datastore.spend(ctx, inner_datastore_spend)?;

    Ok(vec![new_spend])
}

pub fn oracle_spend(
    spender_synthetic_key: PublicKey,
    selected_coins: Vec<Coin>,
    datastore: Datastore,
    fee: u64,
) -> Result<SuccessResponse, WalletError> {
    let Some(DelegatedPuzzle::Oracle(oracle_ph, oracle_fee)) = datastore
        .info
        .delegated_puzzles
        .iter()
        .find(|dp| matches!(dp, DelegatedPuzzle::Oracle(_, _)))
    else {
        return Err(WalletError::Permission);
    };

    let spender_puzzle_hash: Bytes32 = StandardArgs::curry_tree_hash(spender_synthetic_key).into();

    let total_amount = oracle_fee + fee;

    let ctx = &mut SpendContext::new();

    let p2 = StandardLayer::new(spender_synthetic_key);

    let lead_coin = selected_coins[0];
    let lead_coin_name = lead_coin.coin_id();

    let total_amount_from_coins = selected_coins.iter().map(|c| c.amount).sum::<u64>();
    for coin in selected_coins.into_iter().skip(1) {
        p2.spend(
            ctx,
            coin,
            Conditions::new().assert_concurrent_spend(lead_coin_name),
        )?;
    }

    let assert_oracle_conds = Conditions::new().assert_puzzle_announcement(announcement_id(
        datastore.coin.puzzle_hash,
        Bytes::new("$".into()),
    ));

    let mut lead_coin_conditions = assert_oracle_conds;
    if total_amount_from_coins > total_amount {
        let hint = ctx.hint(spender_puzzle_hash)?;

        lead_coin_conditions = lead_coin_conditions.create_coin(
            spender_puzzle_hash,
            total_amount_from_coins - total_amount,
            hint,
        );
    }
    if fee > 0 {
        lead_coin_conditions = lead_coin_conditions.reserve_fee(fee);
    }
    p2.spend(ctx, lead_coin, lead_coin_conditions)?;

    let inner_datastore_spend = OracleLayer::new(*oracle_ph, *oracle_fee)
        .ok_or(DriverError::OddOracleFee)?
        .construct_spend(ctx, ())?;

    let parent_delegated_puzzles = datastore.info.delegated_puzzles.clone();
    let new_spend = datastore.spend(ctx, inner_datastore_spend)?;

    let new_datastore = Datastore::from_spend(ctx, &new_spend, &parent_delegated_puzzles)?
        .ok_or(WalletError::Parse("Store from spend is None".to_string()))?;
    ctx.insert(new_spend.clone());

    Ok(SuccessResponse {
        coin_spends: ctx.take(),
        new_datastore,
    })
}

pub fn add_fee(
    spender_synthetic_key: PublicKey,
    selected_coins: Vec<Coin>,
    coin_ids: Vec<Bytes32>,
    fee: u64,
) -> Result<Vec<CoinSpend>, WalletError> {
    let spender_puzzle_hash: Bytes32 = StandardArgs::curry_tree_hash(spender_synthetic_key).into();
    let total_amount_from_coins = selected_coins.iter().map(|c| c.amount).sum::<u64>();

    let mut ctx = SpendContext::new();

    let p2 = StandardLayer::new(spender_synthetic_key);

    let lead_coin = selected_coins[0];
    let lead_coin_name = lead_coin.coin_id();

    for coin in selected_coins.into_iter().skip(1) {
        p2.spend(
            &mut ctx,
            coin,
            Conditions::new().assert_concurrent_spend(lead_coin_name),
        )?;
    }

    let mut lead_coin_conditions = Conditions::new().reserve_fee(fee);
    if total_amount_from_coins > fee {
        let hint = ctx.hint(spender_puzzle_hash)?;

        lead_coin_conditions = lead_coin_conditions.create_coin(
            spender_puzzle_hash,
            total_amount_from_coins - fee,
            hint,
        );
    }
    for coin_id in coin_ids {
        lead_coin_conditions = lead_coin_conditions.assert_concurrent_spend(coin_id);
    }

    p2.spend(&mut ctx, lead_coin, lead_coin_conditions)?;

    Ok(ctx.take())
}

pub fn public_key_to_synthetic_key(pk: PublicKey) -> PublicKey {
    pk.derive_synthetic()
}

pub fn secret_key_to_synthetic_key(sk: SecretKey) -> SecretKey {
    sk.derive_synthetic()
}

#[derive(Debug, Clone, Copy)]
pub enum TargetNetwork {
    Mainnet,
    Testnet11,
}

impl TargetNetwork {
    fn get_constants(&self) -> &ConsensusConstants {
        match self {
            TargetNetwork::Mainnet => &MAINNET_CONSTANTS,
            TargetNetwork::Testnet11 => &TESTNET11_CONSTANTS,
        }
    }
}

pub fn sign_coin_spends(
    coin_spends: Vec<CoinSpend>,
    private_keys: Vec<SecretKey>,
    network: TargetNetwork,
) -> Result<Signature, SignerError> {
    let mut allocator = Allocator::new();

    let required_signatures = RequiredSignature::from_coin_spends(
        &mut allocator,
        &coin_spends,
        &AggSigConstants::new(network.get_constants().agg_sig_me_additional_data),
    )?;

    let key_pairs = private_keys
        .iter()
        .map(|sk| {
            (
                sk.public_key(),
                sk.clone(),
                sk.public_key().derive_synthetic(),
                sk.derive_synthetic(),
            )
        })
        .flat_map(|(pk1, sk1, pk2, sk2)| vec![(pk1, sk1), (pk2, sk2)])
        .collect::<HashMap<PublicKey, SecretKey>>();

    let mut sig = Signature::default();

    for required in required_signatures {
        let RequiredSignature::Bls(required) = required else {
            continue;
        };

        let sk = key_pairs.get(&required.public_key);

        if let Some(sk) = sk {
            sig += &sign(sk, required.message());
        }
    }

    Ok(sig)
}

pub async fn broadcast_spend_bundle(
    peer: &Peer,
    spend_bundle: SpendBundle,
) -> Result<TransactionAck, WalletError> {
    peer.send_transaction(spend_bundle)
        .await
        .map_err(WalletError::Client)
}

pub async fn get_header_hash(peer: &Peer, height: u32) -> Result<Bytes32, WalletError> {
    let resp: Result<RespondBlockHeader, RejectHeaderRequest> = peer
        .request_fallible(RequestBlockHeader { height })
        .await
        .map_err(WalletError::Client)?;

    resp.map_err(|_| WalletError::RejectHeaderRequest)
        .map(|resp| resp.header_block.header_hash())
}

pub async fn get_fee_estimate(peer: &Peer, target_time_seconds: u64) -> Result<u64, WalletError> {
    let target_time_seconds = target_time_seconds
        + SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards")
            .as_secs();

    let resp: RespondFeeEstimates = peer
        .request_infallible(RequestFeeEstimates {
            time_targets: vec![target_time_seconds],
        })
        .await
        .map_err(WalletError::Client)?;
    let fee_estimate_group = resp.estimates;

    if let Some(error_message) = fee_estimate_group.error {
        return Err(WalletError::FeeEstimateRejection(error_message));
    }

    if let Some(first_estimate) = fee_estimate_group.estimates.first() {
        if let Some(error_message) = &first_estimate.error {
            return Err(WalletError::FeeEstimateRejection(error_message.clone()));
        }

        return Ok(first_estimate.estimated_fee_rate.mojos_per_clvm_cost);
    }

    Err(WalletError::FeeEstimateRejection(
        "No fee estimates available".to_string(),
    ))
}

pub async fn is_coin_spent(
    peer: &Peer,
    coin_id: Bytes32,
    last_height: Option<u32>,
    last_header_hash: Bytes32,
) -> Result<bool, WalletError> {
    let response = peer
        .request_coin_state(vec![coin_id], last_height, last_header_hash, false)
        .await
        .map_err(WalletError::Client)?
        .map_err(|_| WalletError::RejectCoinState)?;

    if let Some(coin_state) = response.coin_states.first() {
        return Ok(coin_state.spent_height.is_some());
    }

    Ok(false)
}

// https://github.com/Chia-Network/chips/blob/main/CHIPs/chip-0002.md#signmessage
pub fn make_message(msg: Bytes) -> Result<Bytes32, WalletError> {
    let mut alloc = Allocator::new();
    let thing_ptr = clvm_tuple!("Chia Signed Message", msg)
        .to_clvm(&mut alloc)
        .map_err(DriverError::ToClvm)?;

    Ok(tree_hash(&alloc, thing_ptr).into())
}

pub fn sign_message(message: Bytes, sk: SecretKey) -> Result<Signature, WalletError> {
    Ok(sign(&sk, make_message(message)?))
}

pub fn verify_signature(
    message: Bytes,
    pk: PublicKey,
    sig: Signature,
) -> Result<bool, WalletError> {
    Ok(verify(&sig, &pk, make_message(message)?))
}

pub fn get_cost(coin_spends: Vec<CoinSpend>) -> Result<u64, WalletError> {
    let mut alloc = Allocator::new();

    let generator = solution_generator(
        coin_spends
            .into_iter()
            .map(|cs| (cs.coin, cs.puzzle_reveal, cs.solution)),
    )?;

    let conds = run_block_generator::<&[u8], _>(
        &mut alloc,
        &generator,
        [],
        u64::MAX,
        MEMPOOL_MODE | DONT_VALIDATE_SIGNATURE,
        &Signature::default(),
        None,
        TargetNetwork::Mainnet.get_constants(),
    )?;

    let conds = OwnedSpendBundleConditions::from(&alloc, conds);

    Ok(conds.cost)
}

pub struct PossibleLaunchersResponse {
    pub launcher_ids: Vec<Bytes32>,
    pub last_height: u32,
    pub last_header_hash: Bytes32,
}

pub async fn look_up_possible_launchers(
    peer: &Peer,
    previous_height: Option<u32>,
    previous_header_hash: Bytes32,
) -> Result<PossibleLaunchersResponse, WalletError> {
    let resp = get_unspent_coin_states(
        peer,
        DATASTORE_LAUNCHER_HINT,
        previous_height,
        previous_header_hash,
        true,
    )
    .await?;

    Ok(PossibleLaunchersResponse {
        last_header_hash: resp.last_header_hash,
        last_height: resp.last_height,
        launcher_ids: resp
            .coin_states
            .into_iter()
            .filter_map(|coin_state| {
                if coin_state.coin.puzzle_hash == SINGLETON_LAUNCHER_HASH.into() {
                    Some(coin_state.coin.coin_id())
                } else {
                    None
                }
            })
            .collect(),
    })
}

pub async fn subscribe_to_coin_states(
    peer: &Peer,
    coin_id: Bytes32,
    previous_height: Option<u32>,
    previous_header_hash: Bytes32,
) -> Result<Option<u32>, WalletError> {
    let response = peer
        .request_coin_state(vec![coin_id], previous_height, previous_header_hash, true)
        .await
        .map_err(WalletError::Client)?
        .map_err(|_| WalletError::RejectCoinState)?;

    if let Some(coin_state) = response.coin_states.first() {
        return Ok(coin_state.spent_height);
    }

    Err(WalletError::UnknownCoin)
}

pub async fn unsubscribe_from_coin_states(
    peer: &Peer,
    coin_id: Bytes32,
) -> Result<(), WalletError> {
    peer.remove_coin_subscriptions(Some(vec![coin_id]))
        .await
        .map_err(WalletError::Client)?;

    Ok(())
}

/// Mints a new NFT using a DID string.
///
/// # Arguments
/// * `peer` - The peer to query blockchain data
/// * `synthetic_key` - The synthetic key of the wallet
/// * `selected_coins` - Coins to spend for the transaction
/// * `did_string` - The DID string (e.g., "did:chia:1s8j4pquxfu5mhlldzu357qfqkwa9r35mdx5a0p0ehn76dr4ut4tqs0n6kv")
/// * `recipient_puzzle_hash` - The puzzle hash to send the NFT to
/// * `metadata` - The NFT metadata
/// * `royalty_puzzle_hash` - Optional royalty puzzle hash (defaults to recipient if None)
/// * `royalty_basis_points` - Royalty percentage in basis points (e.g., 300 = 3%)
/// * `fee` - Transaction fee
/// * `network` - The target network (mainnet/testnet)
///
/// # Returns
/// A vector of coin spends that mint the NFT
#[allow(clippy::too_many_arguments)]
pub async fn mint_nft(
    peer: &Peer,
    synthetic_key: PublicKey,
    selected_coins: Vec<Coin>,
    did_string: &str,
    recipient_puzzle_hash: Bytes32,
    metadata: NftMetadata,
    _royalty_puzzle_hash: Option<Bytes32>,
    royalty_basis_points: u16,
    fee: u64,
    network: TargetNetwork,
) -> Result<Vec<CoinSpend>, WalletError> {
    // Resolve the DID string to get the current coin and proof
    let (did_proof, did_coin) =
        resolve_did_string_and_generate_proof(peer, did_string, network).await?;
    let mut ctx = SpendContext::new();

    // Convert DID proof
    let did_proof = match did_proof {
        chia_puzzle_types::Proof::Eve(eve) => Proof::Eve(EveProof {
            parent_parent_coin_info: eve.parent_parent_coin_info,
            parent_amount: eve.parent_amount,
        }),
        chia_puzzle_types::Proof::Lineage(lineage) => Proof::Lineage(LineageProof {
            parent_parent_coin_info: lineage.parent_parent_coin_info,
            parent_inner_puzzle_hash: lineage.parent_inner_puzzle_hash,
            parent_amount: lineage.parent_amount,
        }),
    };

    // Create the DID singleton info (simplified DID structure)
    // Use the first 32 bytes of the public key (truncate from 48 to 32 bytes)
    let public_key_bytes = synthetic_key.derive_synthetic().to_bytes();
    let mut public_key_hash = [0u8; 32];
    public_key_hash.copy_from_slice(&public_key_bytes[..32]);
    let mut meta_data_allocator = Allocator::new();
    let node_metadata = metadata.to_clvm(&mut meta_data_allocator)?;
    let metadata_hashed_ptr = HashedPtr::from_ptr(&meta_data_allocator, node_metadata);
    let did_info: DidInfo = DidInfo::new(
        did_coin.coin_id(),
        None,
        1,
        metadata_hashed_ptr,
        public_key_hash.into(),
    );

    let did = Did::new(did_coin, did_proof, did_info);

    // Create StandardLayer for spending coins
    let p2 = StandardLayer::new(synthetic_key);

    // Create the NFT mint configuration with metadata
    let nft_mint = NftMint::new(
        metadata_hashed_ptr,
        recipient_puzzle_hash,
        royalty_basis_points,
        None, // No DID owner for now - we'll set this up differently
    );

    // Use IntermediateLauncher to mint the NFT
    let (mint_conditions, _nft) = IntermediateLauncher::new(did_coin.coin_id(), 0, 1)
        .create(&mut ctx)?
        .mint_nft(&mut ctx, &nft_mint)?;

    // Update the DID with the mint conditions
    let _updated_did = did.update(&mut ctx, &p2, mint_conditions)?;

    // Handle fee and change
    let total_input = selected_coins.iter().map(|coin| coin.amount).sum::<u64>();
    let total_needed = fee + 1; // 1 mojo for the NFT

    if total_input < total_needed {
        return Err(WalletError::InsufficientCoinAmount); // Not enough coins
    }

    let _change = total_input - total_needed;
    let change_puzzle_hash = StandardArgs::curry_tree_hash(synthetic_key).into();

    // Spend the selected coins
    spend_coins_together(
        &mut ctx,
        synthetic_key,
        &selected_coins,
        Conditions::new().reserve_fee(fee),
        total_needed as i64,
        change_puzzle_hash,
    )?;

    Ok(ctx.take())
}

/// Generates a DID proof for a DID coin by analyzing its parent.
/// This is a simplified version that automatically determines the proof type.
///
/// # Arguments
/// * `peer` - The peer to query blockchain data
/// * `did_coin` - The DID coin to generate proof for
/// * `network` - The target network (mainnet/testnet)
///
/// # Returns
/// A tuple containing the DID proof and the DID coin
pub async fn generate_did_proof(
    peer: &Peer,
    did_coin: Coin,
    network: TargetNetwork,
) -> Result<(chia_puzzle_types::Proof, Coin), WalletError> {
    let proof = generate_did_proof_from_chain(peer, did_coin, network).await?;
    Ok((proof, did_coin))
}

/// Generates a DID proof manually when you have the parent information.
///
/// # Arguments
/// * `did_coin` - The current DID coin
/// * `parent_coin` - The parent coin of the DID (None for eve proof)
/// * `parent_inner_puzzle_hash` - The parent's inner puzzle hash (for lineage proof)
///
/// # Returns
/// A DID proof that can be used to spend the DID coin
pub fn generate_did_proof_manual(
    did_coin: Coin,
    parent_coin: Option<Coin>,
    parent_inner_puzzle_hash: Option<Bytes32>,
) -> Result<chia_puzzle_types::Proof, WalletError> {
    match parent_coin {
        // Eve proof - first spend from launcher
        None => {
            // For eve proof, we need the launcher coin info
            // The parent_parent_coin_info is the coin that created the launcher
            // The parent_amount is the launcher coin amount (typically 1 mojo)
            Ok(chia_puzzle_types::Proof::Eve(chia_puzzle_types::EveProof {
                parent_parent_coin_info: did_coin.parent_coin_info,
                parent_amount: 1, // Launcher coins are typically 1 mojo
            }))
        }
        // Lineage proof - subsequent spends
        Some(parent) => {
            let parent_inner_puzzle_hash = parent_inner_puzzle_hash.ok_or(WalletError::Parse(
                "Parent inner puzzle hash is required".to_string(),
            ))?; // Need inner puzzle hash for lineage proof

            Ok(chia_puzzle_types::Proof::Lineage(
                chia_puzzle_types::LineageProof {
                    parent_parent_coin_info: parent.parent_coin_info,
                    parent_inner_puzzle_hash,
                    parent_amount: parent.amount,
                },
            ))
        }
    }
}

/// Generates a DID proof from a coin spend by analyzing the parent spend.
///
/// # Arguments
/// * `peer` - The peer to query blockchain data
/// * `did_coin` - The DID coin to generate proof for
/// * `network` - The target network (mainnet/testnet)
///
/// # Returns
/// A DID proof that can be used to spend the DID coin
pub async fn generate_did_proof_from_chain(
    peer: &Peer,
    did_coin: Coin,
    network: TargetNetwork,
) -> Result<chia_puzzle_types::Proof, WalletError> {
    // Get the parent coin state
    let parent_coin_states = peer
        .request_coin_state(
            vec![did_coin.parent_coin_info],
            None,
            match network {
                TargetNetwork::Mainnet => MAINNET_CONSTANTS.genesis_challenge,
                TargetNetwork::Testnet11 => TESTNET11_CONSTANTS.genesis_challenge,
            },
            false,
        )
        .await?
        .map_err(|_| WalletError::RejectCoinState)?
        .coin_states;

    let parent_coin_state = parent_coin_states.first().ok_or(WalletError::UnknownCoin)?;

    // Check if parent is a launcher (puzzle hash matches singleton launcher)
    if parent_coin_state.coin.puzzle_hash == SINGLETON_LAUNCHER_HASH.into() {
        // This is an eve proof - first spend from launcher
        return Ok(chia_puzzle_types::Proof::Eve(chia_puzzle_types::EveProof {
            parent_parent_coin_info: parent_coin_state.coin.parent_coin_info,
            parent_amount: parent_coin_state.coin.amount,
        }));
    }

    // This is a lineage proof - need to get the parent's puzzle and solution
    let parent_spend_height = parent_coin_state
        .spent_height
        .ok_or(WalletError::UnknownCoin)?;

    let _parent_spend = peer
        .request_puzzle_and_solution(parent_coin_state.coin.coin_id(), parent_spend_height)
        .await?
        .map_err(|_| WalletError::RejectPuzzleSolution)?;

    let _allocator = Allocator::new();

    // For now, create a basic lineage proof
    // This is a simplified approach - in production you'd want to properly parse the parent DID
    Ok(chia_puzzle_types::Proof::Lineage(
        chia_puzzle_types::LineageProof {
            parent_parent_coin_info: parent_coin_state.coin.parent_coin_info,
            parent_inner_puzzle_hash: Bytes32::default(), // Would need to parse from parent spend
            parent_amount: parent_coin_state.coin.amount,
        },
    ))
}

/// Creates a simple DID from a private key and selected coins.
///
/// # Arguments
/// * `synthetic_key` - The synthetic key that will control the DID
/// * `selected_coins` - Coins to spend for creating the DID
/// * `fee` - Transaction fee
///
/// # Returns
/// A tuple containing the coin spends and the created DID coin
pub fn create_simple_did(
    synthetic_key: PublicKey,
    selected_coins: Vec<Coin>,
    fee: u64,
) -> Result<(Vec<CoinSpend>, Coin), WalletError> {
    let mut ctx = SpendContext::new();

    let p2 = StandardLayer::new(synthetic_key);
    let puzzle_hash = StandardArgs::curry_tree_hash(synthetic_key).into();

    // Calculate total input and needed amount
    let total_input = selected_coins.iter().map(|coin| coin.amount).sum::<u64>();
    let total_needed = fee + 1; // 1 mojo for the DID

    if total_input < total_needed {
        return Err(WalletError::InsufficientCoinAmount); // Not enough coins
    }

    let change = total_input - total_needed;

    // Create the DID using the first coin as the parent for the launcher
    let first_coin = selected_coins[0];
    let launcher = Launcher::new(first_coin.coin_id(), 1);

    // Create the DID
    let (create_did_conditions, did) = launcher.create_simple_did(&mut ctx, &p2)?;

    // Spend all selected coins together
    let first_coin_id = first_coin.coin_id();

    for (i, &coin) in selected_coins.iter().enumerate() {
        if i == 0 {
            // First coin creates the DID and handles change/fee
            let mut conditions = create_did_conditions.clone();

            if change > 0 {
                let hint = ctx.hint(puzzle_hash)?;
                conditions = conditions.create_coin(puzzle_hash, change, hint);
            }

            if fee > 0 {
                conditions = conditions.reserve_fee(fee);
            }

            p2.spend(&mut ctx, coin, conditions)?;
        } else {
            // Other coins just assert concurrent spend
            p2.spend(
                &mut ctx,
                coin,
                Conditions::new().assert_concurrent_spend(first_coin_id),
            )?;
        }
    }

    Ok((ctx.take(), did.coin))
}

/// Resolves a DID string to find the current DID coin and generates its proof.
///
/// # Arguments
/// * `peer` - The peer to query blockchain data
/// * `did_string` - The DID string (e.g., "did:chia:1s8j4pquxfu5mhlldzu357qfqkwa9r35mdx5a0p0ehn76dr4ut4tqs0n6kv")
/// * `network` - The target network (mainnet/testnet)
///
/// # Returns
/// A tuple containing the DID proof and the current DID coin
pub async fn resolve_did_string_and_generate_proof(
    peer: &Peer,
    did_string: &str,
    network: TargetNetwork,
) -> Result<(chia_puzzle_types::Proof, Coin), WalletError> {
    // Parse DID string to extract launcher ID
    let parts: Vec<&str> = did_string.split(':').collect();

    if parts.len() != 3 || parts[0] != "did" || parts[1] != "chia" {
        return Err(WalletError::Parse("Invalid DID string".to_string()));
    }

    let bech32_part = parts[2];

    // Decode the bech32 address to get the launcher ID
    use chia_wallet_sdk::utils::Address;
    let address = Address::decode(bech32_part)
        .map_err(|_| WalletError::Parse("Cannot decode address".to_string()))?;

    let did_id = address.puzzle_hash;

    // First, get the launcher coin state to find the first DID coin
    let launcher_states = peer
        .request_coin_state(
            vec![did_id],
            None,
            match network {
                TargetNetwork::Mainnet => MAINNET_CONSTANTS.genesis_challenge,
                TargetNetwork::Testnet11 => TESTNET11_CONSTANTS.genesis_challenge,
            },
            false,
        )
        .await?
        .map_err(|_| WalletError::RejectCoinState)?
        .coin_states;

    let launcher_state = launcher_states.first().ok_or(WalletError::UnknownCoin)?;

    // Verify this is actually a launcher
    if launcher_state.coin.puzzle_hash != SINGLETON_LAUNCHER_HASH.into() {
        return Err(WalletError::PuzzleHashMismatch(
            "Coin puzzle hash does not match datastore singleton launcher hash".to_string(),
        ));
    }

    // Get the spend of the launcher to find the first DID coin
    let launcher_spend_height = launcher_state
        .spent_height
        .ok_or(WalletError::UnknownCoin)?;

    let launcher_spend = peer
        .request_puzzle_and_solution(launcher_state.coin.coin_id(), launcher_spend_height)
        .await?
        .map_err(|_| WalletError::RejectPuzzleSolution)?;

    let mut allocator = Allocator::new();

    // Run the launcher spend to find the created DID coin
    let launcher_puzzle = launcher_spend.puzzle.to_clvm(&mut allocator)?;
    let launcher_solution = launcher_spend.solution.to_clvm(&mut allocator)?;

    let output = clvmr::run_program(
        &mut allocator,
        &clvmr::ChiaDialect::new(0),
        launcher_puzzle,
        launcher_solution,
        u64::MAX,
    )
    .map_err(|_| WalletError::Clvm)?;

    let conditions =
        Vec::<Condition>::from_clvm(&allocator, output.1).map_err(|_| WalletError::Clvm)?;

    // Find the CREATE_COIN condition to get the first DID coin
    let mut first_did_coin: Option<Coin> = None;
    for condition in conditions {
        if let Some(create_coin) = condition.into_create_coin() {
            // DID coins have odd amounts (singleton property)
            if create_coin.amount % 2 == 1 {
                first_did_coin = Some(Coin::new(
                    launcher_state.coin.coin_id(),
                    create_coin.puzzle_hash,
                    create_coin.amount,
                ));
                break;
            }
        }
    }

    let first_did_coin = first_did_coin.ok_or(WalletError::UnknownCoin)?;

    // Now we need to trace the DID through all its spends to find the current coin
    let mut current_did_coin = first_did_coin;

    loop {
        // Check if this coin is spent
        let coin_states = peer
            .request_coin_state(
                vec![current_did_coin.coin_id()],
                None,
                match network {
                    TargetNetwork::Mainnet => MAINNET_CONSTANTS.genesis_challenge,
                    TargetNetwork::Testnet11 => TESTNET11_CONSTANTS.genesis_challenge,
                },
                false,
            )
            .await?
            .map_err(|_| WalletError::RejectCoinState)?
            .coin_states;

        let coin_state = coin_states.first().ok_or(WalletError::UnknownCoin)?;

        // If not spent, this is our current DID coin
        if coin_state.spent_height.is_none() {
            break;
        }

        // If spent, find the child DID coin
        let spend_height = coin_state.spent_height.unwrap();
        let spend = peer
            .request_puzzle_and_solution(current_did_coin.coin_id(), spend_height)
            .await?
            .map_err(|_| WalletError::RejectPuzzleSolution)?;

        // Parse the spend to find the child DID coin
        let spend_puzzle = spend.puzzle.to_clvm(&mut allocator)?;
        let spend_solution = spend.solution.to_clvm(&mut allocator)?;

        let spend_output = clvmr::run_program(
            &mut allocator,
            &clvmr::ChiaDialect::new(0),
            spend_puzzle,
            spend_solution,
            u64::MAX,
        )
        .map_err(|_| WalletError::Clvm)?;

        let spend_conditions = Vec::<Condition>::from_clvm(&allocator, spend_output.1)
            .map_err(|_| WalletError::Clvm)?;

        // Find the CREATE_COIN condition for the child DID
        let mut child_did_coin: Option<Coin> = None;
        for condition in spend_conditions {
            if let Some(create_coin) = condition.into_create_coin() {
                // DID coins have odd amounts (singleton property)
                if create_coin.amount % 2 == 1 {
                    child_did_coin = Some(Coin::new(
                        current_did_coin.coin_id(),
                        create_coin.puzzle_hash,
                        create_coin.amount,
                    ));
                    break;
                }
            }
        }

        current_did_coin = child_did_coin.ok_or(WalletError::UnknownCoin)?;
    }

    // Now generate the proof for the current DID coin
    let proof = generate_did_proof_from_chain(peer, current_did_coin, network).await?;

    Ok((proof, current_did_coin))
}

#[cfg(test)]
mod melt_kat {
    //! Custody KAT pinning `Datastore::from_spend`'s melt signal across the
    //! chia-wallet-sdk 0.34 -> 0.36 move (dig_ecosystem#2133, #3161).
    //!
    //! The just-merged digstore-chain #1981 melt classifier depends on the load-
    //! bearing fact that a childless datastore singleton spend (an owner melt)
    //! surfaces as `Err(DriverError::MissingChild)`, while a spend that recreates
    //! the datastore surfaces as `Ok(Some(_))`. This test drives a real
    //! peer-simulator mint -> melt and asserts both signals hold under 0.36.
    //!
    //! Its expected values are UNCHANGED by the 0.36 adoption: only the type's
    //! spelling moved (`DataStore` -> `Datastore`). Had either signal changed,
    //! this test would have gone red rather than needing an edit — which is the
    //! evidence that the melt classifier downstream is still safe.
    use super::*;
    use chia_wallet_sdk::test::{BlsPair, Simulator};

    #[test]
    fn from_spend_reports_owner_melt_as_missing_child() -> anyhow::Result<()> {
        let mut sim = Simulator::new();
        let owner = BlsPair::default();

        // In the simulator the standard puzzle is curried directly on the pair's
        // public key, so that key doubles as the "synthetic" key our wallet API
        // expects and the pair's secret key signs the spends.
        let owner_puzzle_hash: Bytes32 = StandardArgs::curry_tree_hash(owner.pk).into();
        let funding_coin = sim.new_coin(owner_puzzle_hash, 1);

        // Mint a datastore (no delegation layers, zero fee) and land it on chain.
        let minted = mint_store(
            owner.pk,
            vec![funding_coin],
            Bytes32::new([1; 32]),
            None,
            None,
            None,
            None,
            owner_puzzle_hash,
            vec![],
            0,
        )?;
        let datastore = minted.new_datastore.clone();
        sim.spend_coins(minted.coin_spends.clone(), std::slice::from_ref(&owner.sk))?;

        // Positive control: the launcher spend that CREATES the datastore (it
        // recreates the singleton with an odd-amount child) must be recognised as
        // a datastore, i.e. `Ok(Some(_))`. This proves `from_spend` genuinely
        // inspects the recreated child rather than returning the melt signal for
        // every datastore singleton spend.
        let mut ctx = SpendContext::new();
        let launcher_spend = minted
            .coin_spends
            .iter()
            .find(|cs| cs.coin.puzzle_hash == SINGLETON_LAUNCHER_HASH.into())
            .expect("mint must contain the singleton launcher spend");
        let launched = Datastore::<DatastoreMetadata>::from_spend(&mut ctx, launcher_spend, &[])?;
        assert!(
            launched.is_some(),
            "from_spend must recognise the datastore-creating launcher spend as Ok(Some)"
        );

        // Melt the datastore and land the melt on chain (proving it is a valid,
        // fully-executable datastore singleton spend, not a malformed one).
        let melt_spends = melt_store(datastore, owner.pk)?;
        assert_eq!(melt_spends.len(), 1, "melt produces exactly one spend");
        sim.spend_coins(melt_spends.clone(), std::slice::from_ref(&owner.sk))?;

        // The pinned property: a valid datastore singleton spend that recreates no
        // odd-amount child (the owner melt) is reported as `Err(MissingChild)`.
        let mut ctx = SpendContext::new();
        let result = Datastore::<DatastoreMetadata>::from_spend(&mut ctx, &melt_spends[0], &[]);
        assert!(
            matches!(result, Err(DriverError::MissingChild)),
            "0.36 must still surface an owner melt as Err(DriverError::MissingChild), got {result:?}"
        );

        Ok(())
    }
}