-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathAddresses.swift
More file actions
1733 lines (1466 loc) · 68.5 KB
/
Copy pathAddresses.swift
File metadata and controls
1733 lines (1466 loc) · 68.5 KB
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
import Foundation
import DashSDKFFI
/// Service for fetching Platform address information
public class Addresses: @unchecked Sendable {
private weak var sdk: SDK?
init(sdk: SDK) {
self.sdk = sdk
}
// MARK: - Single Address Query
/// Fetch information about a single Platform address
///
/// - Parameter addressBytes: Address bytes (21 bytes: type byte + 20-byte hash)
/// - Returns: PlatformAddressInfo containing nonce and balance, or nil if address not found
/// - Throws: SDKError if the query fails
public func getInfo(addressBytes: Data) throws -> PlatformAddressInfo? {
guard let sdk = sdk, let handle = sdk.handle else {
throw SDKError.invalidState("SDK not initialized")
}
guard addressBytes.count == 21 else {
throw SDKError.invalidParameter("Address bytes must be exactly 21 bytes (1 type + 20 hash), got \(addressBytes.count)")
}
let result = addressBytes.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) -> DashSDKResult in
let ptr = buffer.baseAddress?.assumingMemoryBound(to: UInt8.self)
return dash_sdk_address_fetch_info(handle, ptr, UInt(addressBytes.count))
}
// Check for errors
if let error = result.error {
let sdkError = SDKError.fromDashSDKError(error.pointee)
dash_sdk_error_free(error)
throw sdkError
}
guard let dataPtr = result.data else {
return nil
}
// Parse DashSDKAddressInfo
let infoPtr = dataPtr.assumingMemoryBound(to: DashSDKAddressInfo.self)
let ffiInfo = infoPtr.pointee
let addressInfo = PlatformAddressInfo(from: ffiInfo)
// Free the FFI struct
dash_sdk_address_info_free(infoPtr)
// Return nil if address not found (indicated by max values)
if !addressInfo.isFound {
return nil
}
return addressInfo
}
/// Fetch information about a single Platform address using hex string
///
/// - Parameter addressHex: Hex-encoded address (42 characters for 21 bytes)
/// - Returns: PlatformAddressInfo containing nonce and balance, or nil if address not found
/// - Throws: SDKError if the query fails or hex is invalid
public func getInfo(addressHex: String) throws -> PlatformAddressInfo? {
guard let addressBytes = Data(hexString: addressHex) else {
throw SDKError.invalidParameter("Invalid hex string for address")
}
return try getInfo(addressBytes: addressBytes)
}
/// Fetch information about a single Platform address using bech32m string
///
/// - Parameter bech32mAddress: Bech32m-encoded address (e.g., "tdashevo1qqyfsqyzcn5hzu7echru54njypdq0v4d7gv8pkdf")
/// - Returns: PlatformAddressInfo containing nonce and balance, or nil if address not found
/// - Throws: SDKError if the query fails or bech32m is invalid
public func getInfo(bech32mAddress: String) throws -> PlatformAddressInfo? {
guard let decoded = Bech32m.decode(bech32mAddress) else {
throw SDKError.invalidParameter("Invalid bech32m address")
}
guard decoded.data.count == 21 else {
throw SDKError.invalidParameter("Invalid Platform address: expected 21 bytes, got \(decoded.data.count)")
}
return try getInfo(addressBytes: decoded.data)
}
/// Fetch information about a single Platform address (auto-detects format)
///
/// - Parameter address: Address string - can be hex (42 chars) or bech32m (tdashevo1.../dashevo1...)
/// - Returns: PlatformAddressInfo containing nonce and balance, or nil if address not found
/// - Throws: SDKError if the query fails or address format is invalid
public func getInfo(address: String) throws -> PlatformAddressInfo? {
let trimmed = address.trimmingCharacters(in: .whitespacesAndNewlines)
// Check if it's a bech32m address (starts with dashevo1 or tdashevo1)
if trimmed.lowercased().hasPrefix("dashevo1") || trimmed.lowercased().hasPrefix("tdashevo1") {
return try getInfo(bech32mAddress: trimmed)
}
// Otherwise try as hex
return try getInfo(addressHex: trimmed)
}
// MARK: - Multiple Addresses Query
/// Fetch information about multiple Platform addresses
///
/// - Parameter addressesBytesList: Array of address bytes (each 21 bytes)
/// - Returns: PlatformAddressInfosResult containing info for all queried addresses
/// - Throws: SDKError if the query fails
public func getInfos(addressesBytesList: [Data]) throws -> PlatformAddressInfosResult {
guard let sdk = sdk, let handle = sdk.handle else {
throw SDKError.invalidState("SDK not initialized")
}
guard !addressesBytesList.isEmpty else {
return PlatformAddressInfosResult(infos: [:])
}
// Validate all addresses
for (index, bytes) in addressesBytesList.enumerated() {
guard bytes.count == 21 else {
throw SDKError.invalidParameter("Address at index \(index) must be exactly 21 bytes, got \(bytes.count)")
}
}
// Prepare arrays for FFI call
var addressPointers: [UnsafePointer<UInt8>?] = []
var addressLengths: [UInt] = []
var addressData: [Data] = [] // Keep data alive during the call
for bytes in addressesBytesList {
addressData.append(bytes)
}
// Create pointers
for data in addressData {
let pointer = data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) -> UnsafePointer<UInt8>? in
return buffer.baseAddress?.assumingMemoryBound(to: UInt8.self)
}
addressPointers.append(pointer)
addressLengths.append(UInt(data.count))
}
// Call FFI
let result = addressPointers.withUnsafeBufferPointer { pointersBuffer -> DashSDKResult in
addressLengths.withUnsafeBufferPointer { lengthsBuffer -> DashSDKResult in
return dash_sdk_addresses_fetch_infos(
handle,
pointersBuffer.baseAddress,
lengthsBuffer.baseAddress,
UInt(addressesBytesList.count)
)
}
}
// Check for errors
if let error = result.error {
let sdkError = SDKError.fromDashSDKError(error.pointee)
dash_sdk_error_free(error)
throw sdkError
}
guard let dataPtr = result.data else {
return PlatformAddressInfosResult(infos: [:])
}
// Parse DashSDKAddressInfoMap
let mapPtr = dataPtr.assumingMemoryBound(to: DashSDKAddressInfoMap.self)
let map = mapPtr.pointee
var infos: [Data: PlatformAddressInfo] = [:]
if map.count > 0 && map.entries != nil {
for i in 0..<map.count {
let entry = map.entries![Int(i)]
let addressBytes: Data
if entry.address != nil && entry.address_len > 0 {
addressBytes = Data(bytes: entry.address!, count: Int(entry.address_len))
} else {
continue
}
let info = PlatformAddressInfo(
addressBytes: addressBytes,
nonce: entry.nonce,
balance: entry.balance
)
infos[addressBytes] = info
}
}
// Free the FFI map
dash_sdk_address_info_map_free(mapPtr)
return PlatformAddressInfosResult(infos: infos)
}
/// Fetch information about multiple Platform addresses using hex strings
///
/// - Parameter addressHexList: Array of hex-encoded addresses
/// - Returns: PlatformAddressInfosResult containing info for all queried addresses
/// - Throws: SDKError if the query fails or any hex is invalid
public func getInfos(addressHexList: [String]) throws -> PlatformAddressInfosResult {
let addressesBytesList = try addressHexList.enumerated().map { (index, hex) -> Data in
guard let bytes = Data(hexString: hex) else {
throw SDKError.invalidParameter("Invalid hex string at index \(index)")
}
return bytes
}
return try getInfos(addressesBytesList: addressesBytesList)
}
/// Fetch information about multiple Platform addresses using bech32m strings
///
/// - Parameter bech32mAddresses: Array of bech32m-encoded addresses
/// - Returns: PlatformAddressInfosResult containing info for all queried addresses
/// - Throws: SDKError if the query fails or any bech32m is invalid
public func getInfos(bech32mAddresses: [String]) throws -> PlatformAddressInfosResult {
let addressesBytesList = try bech32mAddresses.enumerated().map { (index, bech32m) -> Data in
guard let decoded = Bech32m.decode(bech32m) else {
throw SDKError.invalidParameter("Invalid bech32m address at index \(index)")
}
guard decoded.data.count == 21 else {
throw SDKError.invalidParameter("Invalid Platform address at index \(index): expected 21 bytes")
}
return decoded.data
}
return try getInfos(addressesBytesList: addressesBytesList)
}
/// Fetch information about multiple Platform addresses (auto-detects format)
///
/// - Parameter addresses: Array of address strings - can be hex or bech32m (mixed formats allowed)
/// - Returns: PlatformAddressInfosResult containing info for all queried addresses
/// - Throws: SDKError if the query fails or any address format is invalid
public func getInfos(addresses: [String]) throws -> PlatformAddressInfosResult {
let addressesBytesList = try addresses.enumerated().map { (index, address) -> Data in
let trimmed = address.trimmingCharacters(in: .whitespacesAndNewlines)
// Check if it's a bech32m address
if trimmed.lowercased().hasPrefix("dashevo1") || trimmed.lowercased().hasPrefix("tdashevo1") {
guard let decoded = Bech32m.decode(trimmed) else {
throw SDKError.invalidParameter("Invalid bech32m address at index \(index)")
}
guard decoded.data.count == 21 else {
throw SDKError.invalidParameter("Invalid Platform address at index \(index): expected 21 bytes")
}
return decoded.data
}
// Otherwise try as hex
guard let bytes = Data(hexString: trimmed) else {
throw SDKError.invalidParameter("Invalid address format at index \(index)")
}
return bytes
}
return try getInfos(addressesBytesList: addressesBytesList)
}
// MARK: - Trunk State Query
/// Fetch the trunk state of the address tree for privacy-preserving address synchronization.
///
/// The trunk state contains:
/// - Elements: Addresses with balances found at the top levels of the tree
/// - Leaf boundaries: Subtrees that require further branch queries to explore
///
/// This is a low-level API used for privacy-preserving address synchronization.
/// Most applications should use the higher-level sync methods instead.
///
/// - Returns: PlatformTrunkState containing elements and leaf boundaries
/// - Throws: SDKError if the query fails
public func getTrunkState() throws -> PlatformTrunkState {
guard let sdk = sdk, let handle = sdk.handle else {
throw SDKError.invalidState("SDK not initialized")
}
let result = dash_sdk_address_fetch_trunk_state(handle)
// Check for errors
if let error = result.error {
let sdkError = SDKError.fromDashSDKError(error.pointee)
dash_sdk_error_free(error)
throw sdkError
}
guard let dataPtr = result.data else {
throw SDKError.invalidState("No trunk state data returned")
}
// Parse DashSDKTrunkState
let statePtr = dataPtr.assumingMemoryBound(to: DashSDKTrunkState.self)
let ffiState = statePtr.pointee
// Convert elements
var elements: [TrunkStateElement] = []
if ffiState.elements_count > 0 && ffiState.elements != nil {
for i in 0..<ffiState.elements_count {
let ffiElement = ffiState.elements![Int(i)]
let keyData: Data
if ffiElement.key != nil && ffiElement.key_len > 0 {
keyData = Data(bytes: ffiElement.key!, count: Int(ffiElement.key_len))
} else {
continue
}
elements.append(TrunkStateElement(
key: keyData,
nonce: ffiElement.nonce,
balance: ffiElement.balance
))
}
}
// Convert leaf boundaries
var leafBoundaries: [LeafBoundary] = []
if ffiState.leaf_boundaries_count > 0 && ffiState.leaf_boundaries != nil {
for i in 0..<ffiState.leaf_boundaries_count {
let ffiBoundary = ffiState.leaf_boundaries![Int(i)]
let keyData: Data
if ffiBoundary.key != nil && ffiBoundary.key_len > 0 {
keyData = Data(bytes: ffiBoundary.key!, count: Int(ffiBoundary.key_len))
} else {
continue
}
// Convert fixed-size array to Data
var hashArray = ffiBoundary.hash
let hashData = Data(bytes: &hashArray, count: 32)
leafBoundaries.append(LeafBoundary(
key: keyData,
hash: hashData,
estimatedCount: ffiBoundary.estimated_count
))
}
}
let checkpointHeight = ffiState.checkpoint_height
// Free the FFI struct
dash_sdk_trunk_state_free(statePtr)
return PlatformTrunkState(
elements: elements,
leafBoundaries: leafBoundaries,
checkpointHeight: checkpointHeight
)
}
// MARK: - Branch State Query
/// Fetch the branch state of a subtree in the address tree.
///
/// This is used after a trunk state query to explore subtrees indicated by leaf boundaries.
/// The result contains elements (addresses with balances) and deeper leaf boundaries.
///
/// - Parameters:
/// - key: Leaf boundary key bytes from trunk state
/// - depth: Query depth (how deep to explore)
/// - expectedHash: Expected hash of the subtree root (32 bytes, for proof verification)
/// - checkpointHeight: Block height from trunk state response for consistency
/// - Returns: PlatformBranchState containing elements and leaf boundaries
/// - Throws: SDKError if the query fails
public func getBranchState(
key: Data,
depth: UInt32,
expectedHash: Data,
checkpointHeight: UInt64
) throws -> PlatformBranchState {
guard let sdk = sdk, let handle = sdk.handle else {
throw SDKError.invalidState("SDK not initialized")
}
guard expectedHash.count == 32 else {
throw SDKError.invalidParameter("Expected hash must be exactly 32 bytes, got \(expectedHash.count)")
}
let result = key.withUnsafeBytes { (keyBuffer: UnsafeRawBufferPointer) -> DashSDKResult in
expectedHash.withUnsafeBytes { (hashBuffer: UnsafeRawBufferPointer) -> DashSDKResult in
let keyPtr = keyBuffer.baseAddress?.assumingMemoryBound(to: UInt8.self)
let hashPtr = hashBuffer.baseAddress?.assumingMemoryBound(to: UInt8.self)
return dash_sdk_address_fetch_branch_state(
handle,
keyPtr,
UInt(key.count),
depth,
hashPtr,
checkpointHeight
)
}
}
// Check for errors
if let error = result.error {
let sdkError = SDKError.fromDashSDKError(error.pointee)
dash_sdk_error_free(error)
throw sdkError
}
guard let dataPtr = result.data else {
throw SDKError.invalidState("No branch state data returned")
}
// Parse DashSDKBranchState
let statePtr = dataPtr.assumingMemoryBound(to: DashSDKBranchState.self)
let ffiState = statePtr.pointee
// Convert elements (same structure as trunk state)
var elements: [TrunkStateElement] = []
if ffiState.elements_count > 0 && ffiState.elements != nil {
for i in 0..<ffiState.elements_count {
let ffiElement = ffiState.elements![Int(i)]
let keyData: Data
if ffiElement.key != nil && ffiElement.key_len > 0 {
keyData = Data(bytes: ffiElement.key!, count: Int(ffiElement.key_len))
} else {
continue
}
elements.append(TrunkStateElement(
key: keyData,
nonce: ffiElement.nonce,
balance: ffiElement.balance
))
}
}
// Convert leaf boundaries
var leafBoundaries: [LeafBoundary] = []
if ffiState.leaf_boundaries_count > 0 && ffiState.leaf_boundaries != nil {
for i in 0..<ffiState.leaf_boundaries_count {
let ffiBoundary = ffiState.leaf_boundaries![Int(i)]
let boundaryKeyData: Data
if ffiBoundary.key != nil && ffiBoundary.key_len > 0 {
boundaryKeyData = Data(bytes: ffiBoundary.key!, count: Int(ffiBoundary.key_len))
} else {
continue
}
// Convert fixed-size array to Data
var hashArray = ffiBoundary.hash
let hashData = Data(bytes: &hashArray, count: 32)
leafBoundaries.append(LeafBoundary(
key: boundaryKeyData,
hash: hashData,
estimatedCount: ffiBoundary.estimated_count
))
}
}
// Free the FFI struct
dash_sdk_branch_state_free(statePtr)
return PlatformBranchState(
elements: elements,
leafBoundaries: leafBoundaries
)
}
// MARK: - Recent Balance Changes Query
/// Fetch recent address balance changes starting from a specific block height.
///
/// This returns all address balance changes that occurred since the specified start height.
/// Useful for syncing wallet balances after the initial sync.
///
/// - Parameter startHeight: Block height to start fetching changes from
/// - Returns: RecentBalanceChanges containing block-by-block changes
/// - Throws: SDKError if the query fails
public func getRecentBalanceChanges(startHeight: UInt64) throws -> RecentBalanceChanges {
guard let sdk = sdk, let handle = sdk.handle else {
throw SDKError.invalidState("SDK not initialized")
}
let result = dash_sdk_address_fetch_recent_balance_changes(handle, startHeight)
// Check for errors
if let error = result.error {
let sdkError = SDKError.fromDashSDKError(error.pointee)
dash_sdk_error_free(error)
throw sdkError
}
guard let dataPtr = result.data else {
// No changes found - return empty result
return RecentBalanceChanges(blocks: [])
}
// Parse DashSDKRecentBalanceChanges
let changesPtr = dataPtr.assumingMemoryBound(to: DashSDKRecentBalanceChanges.self)
let ffiChanges = changesPtr.pointee
// Convert blocks
var blocks: [BlockBalanceChanges] = []
if ffiChanges.blocks_count > 0 && ffiChanges.blocks != nil {
for i in 0..<ffiChanges.blocks_count {
let ffiBlock = ffiChanges.blocks![Int(i)]
// Convert address changes within this block
var addressChanges: [AddressBalanceChange] = []
if ffiBlock.changes_count > 0 && ffiBlock.changes != nil {
for j in 0..<ffiBlock.changes_count {
let ffiChange = ffiBlock.changes![Int(j)]
let addressData: Data
if ffiChange.address != nil && ffiChange.address_len > 0 {
addressData = Data(bytes: ffiChange.address!, count: Int(ffiChange.address_len))
} else {
continue
}
// Map operation type: 0 = SetCredits, 1 = AddToCredits
let operation: CreditOperationType
if ffiChange.operation_type.rawValue == 0 {
operation = .setCredits(credits: ffiChange.credits)
} else {
operation = .addToCredits(credits: ffiChange.credits)
}
addressChanges.append(AddressBalanceChange(
addressBytes: addressData,
operation: operation
))
}
}
blocks.append(BlockBalanceChanges(
blockHeight: ffiBlock.block_height,
changes: addressChanges
))
}
}
// Free the FFI struct
dash_sdk_recent_balance_changes_free(changesPtr)
return RecentBalanceChanges(blocks: blocks)
}
// MARK: - Compacted Balance Changes Query
/// Fetch recent compacted address balance changes starting from a specific block height.
///
/// This returns compacted (merged) address balance changes since the specified start height.
/// Compacted changes merge multiple blocks into ranges, which is more efficient for syncing.
/// The BlockAwareCreditOperation preserves per-block granularity for partial sync.
///
/// - Parameter startBlockHeight: Block height to start fetching changes from
/// - Returns: CompactedBalanceChanges containing range-by-range compacted changes
/// - Throws: SDKError if the query fails
public func getCompactedBalanceChanges(startBlockHeight: UInt64) throws -> CompactedBalanceChanges {
guard let sdk = sdk, let handle = sdk.handle else {
throw SDKError.invalidState("SDK not initialized")
}
let result = dash_sdk_address_fetch_compacted_balance_changes(handle, startBlockHeight)
// Check for errors
if let error = result.error {
let sdkError = SDKError.fromDashSDKError(error.pointee)
dash_sdk_error_free(error)
throw sdkError
}
guard let dataPtr = result.data else {
// No changes found - return empty result
return CompactedBalanceChanges(ranges: [])
}
// Parse DashSDKCompactedBalanceChanges
let changesPtr = dataPtr.assumingMemoryBound(to: DashSDKCompactedBalanceChanges.self)
let ffiChanges = changesPtr.pointee
// Convert ranges
var ranges: [CompactedBlockRange] = []
if ffiChanges.ranges_count > 0 && ffiChanges.ranges != nil {
for i in 0..<ffiChanges.ranges_count {
let ffiRange = ffiChanges.ranges![Int(i)]
// Convert address changes within this range
var addressChanges: [CompactedAddressChange] = []
if ffiRange.changes_count > 0 && ffiRange.changes != nil {
for j in 0..<ffiRange.changes_count {
let ffiChange = ffiRange.changes![Int(j)]
let addressData: Data
if ffiChange.address != nil && ffiChange.address_len > 0 {
addressData = Data(bytes: ffiChange.address!, count: Int(ffiChange.address_len))
} else {
continue
}
// Map operation type: 0 = BlockAwareSetCredits, 1 = BlockAwareAddToCreditsOperations
let operation: BlockAwareCreditOperation
if ffiChange.operation_type.rawValue == 0 { // BlockAwareSetCredits
operation = .setCredits(credits: ffiChange.set_credits_value)
} else { // BlockAwareAddToCreditsOperations
// Parse add entries
var entries: [(blockHeight: UInt64, credits: UInt64)] = []
if ffiChange.add_entries_count > 0 && ffiChange.add_entries != nil {
for k in 0..<ffiChange.add_entries_count {
let entry = ffiChange.add_entries![Int(k)]
entries.append((blockHeight: entry.block_height, credits: entry.credits))
}
}
operation = .addToCreditsOperations(entries: entries)
}
addressChanges.append(CompactedAddressChange(
addressBytes: addressData,
operation: operation
))
}
}
ranges.append(CompactedBlockRange(
startBlockHeight: ffiRange.start_block_height,
endBlockHeight: ffiRange.end_block_height,
changes: addressChanges
))
}
}
// Free the FFI struct
dash_sdk_compacted_balance_changes_free(changesPtr)
return CompactedBalanceChanges(ranges: ranges)
}
// MARK: - State Transitions
/// Input for address transfer operation
public struct AddressTransferInput {
/// Address bytes (21 bytes: type byte + 20-byte hash)
public let addressBytes: Data
/// Amount to spend from this address in credits
public let amount: UInt64
/// Nonce for this address (0 = auto-fetch, used for identity transitions)
public let nonce: UInt32
/// Private key for signing (32 bytes)
public let privateKey: Data
public init(addressBytes: Data, amount: UInt64, nonce: UInt32 = 0, privateKey: Data) {
self.addressBytes = addressBytes
self.amount = amount
self.nonce = nonce
self.privateKey = privateKey
}
}
/// Output for address transfer operation
public struct AddressTransferOutput {
/// Address bytes (21 bytes: type byte + 20-byte hash)
public let addressBytes: Data
/// Amount to receive at this address in credits
public let amount: UInt64
public init(addressBytes: Data, amount: UInt64) {
self.addressBytes = addressBytes
self.amount = amount
}
}
/// Transfer funds between Platform addresses
///
/// This is a state transition that moves credits from input addresses to output addresses.
/// Each input address must have a corresponding private key for signing.
///
/// - Parameters:
/// - inputs: Array of input addresses with amounts and private keys
/// - outputs: Array of output addresses with amounts
/// - feeFromInputIndex: Which input to deduct fees from (0-based, default 0)
/// - Returns: PlatformAddressInfosResult containing updated address balances after transfer
/// - Throws: SDKError if the transfer fails
public func transferFunds(
inputs: [AddressTransferInput],
outputs: [AddressTransferOutput],
feeFromInputIndex: UInt16 = 0
) throws -> PlatformAddressInfosResult {
guard let sdk = sdk, let handle = sdk.handle else {
throw SDKError.invalidState("SDK not initialized")
}
guard !inputs.isEmpty else {
throw SDKError.invalidParameter("Inputs array is empty")
}
guard !outputs.isEmpty else {
throw SDKError.invalidParameter("Outputs array is empty")
}
guard feeFromInputIndex < inputs.count else {
throw SDKError.invalidParameter("Fee input index \(feeFromInputIndex) is out of bounds (inputs count: \(inputs.count))")
}
// Validate inputs
for (index, input) in inputs.enumerated() {
guard input.addressBytes.count == 21 else {
throw SDKError.invalidParameter("Input address at index \(index) must be 21 bytes, got \(input.addressBytes.count)")
}
guard input.privateKey.count == 32 else {
throw SDKError.invalidParameter("Private key at index \(index) must be 32 bytes, got \(input.privateKey.count)")
}
}
// Validate outputs
for (index, output) in outputs.enumerated() {
guard output.addressBytes.count == 21 else {
throw SDKError.invalidParameter("Output address at index \(index) must be 21 bytes, got \(output.addressBytes.count)")
}
}
// Create FFI input structs
var ffiInputs: [DashSDKAddressTransferInput] = []
var inputData: [(address: Data, privateKey: Data)] = [] // Keep data alive
for input in inputs {
inputData.append((address: input.addressBytes, privateKey: input.privateKey))
}
for (index, data) in inputData.enumerated() {
let addressPtr = data.address.withUnsafeBytes { buffer -> UnsafePointer<UInt8>? in
return buffer.baseAddress?.assumingMemoryBound(to: UInt8.self)
}
let privateKeyPtr = data.privateKey.withUnsafeBytes { buffer -> UnsafePointer<UInt8>? in
return buffer.baseAddress?.assumingMemoryBound(to: UInt8.self)
}
ffiInputs.append(DashSDKAddressTransferInput(
address: addressPtr,
address_len: UInt(data.address.count),
amount: inputs[index].amount,
nonce: inputs[index].nonce,
private_key: privateKeyPtr
))
}
// Create FFI output structs
var ffiOutputs: [DashSDKAddressTransferOutput] = []
var outputData: [Data] = [] // Keep data alive
for output in outputs {
outputData.append(output.addressBytes)
}
for (index, data) in outputData.enumerated() {
let addressPtr = data.withUnsafeBytes { buffer -> UnsafePointer<UInt8>? in
return buffer.baseAddress?.assumingMemoryBound(to: UInt8.self)
}
ffiOutputs.append(DashSDKAddressTransferOutput(
address: addressPtr,
address_len: UInt(data.count),
amount: outputs[index].amount
))
}
// Call FFI
let result = ffiInputs.withUnsafeMutableBufferPointer { inputsBuffer -> DashSDKResult in
ffiOutputs.withUnsafeMutableBufferPointer { outputsBuffer -> DashSDKResult in
return dash_sdk_address_transfer_funds(
handle,
inputsBuffer.baseAddress,
UInt(inputs.count),
outputsBuffer.baseAddress,
UInt(outputs.count),
feeFromInputIndex
)
}
}
// Check for errors
if let error = result.error {
let sdkError = SDKError.fromDashSDKError(error.pointee)
dash_sdk_error_free(error)
throw sdkError
}
guard let dataPtr = result.data else {
return PlatformAddressInfosResult(infos: [:])
}
// Parse DashSDKAddressInfoMap
let mapPtr = dataPtr.assumingMemoryBound(to: DashSDKAddressInfoMap.self)
let map = mapPtr.pointee
var infos: [Data: PlatformAddressInfo] = [:]
if map.count > 0 && map.entries != nil {
for i in 0..<map.count {
let entry = map.entries![Int(i)]
let addressBytes: Data
if entry.address != nil && entry.address_len > 0 {
addressBytes = Data(bytes: entry.address!, count: Int(entry.address_len))
} else {
continue
}
let info = PlatformAddressInfo(
addressBytes: addressBytes,
nonce: entry.nonce,
balance: entry.balance
)
infos[addressBytes] = info
}
}
// Free the FFI map
dash_sdk_address_info_map_free(mapPtr)
return PlatformAddressInfosResult(infos: infos)
}
/// Pooling strategy for withdrawals
public enum PoolingStrategy {
/// Never pool withdrawals
case never
/// Pool if available
case ifAvailable
/// Standard pooling
case standard
var ffiValue: DashSDKPooling {
switch self {
// DashSDKPooling is a C enum; Swift doesn't always import named cases.
case .never: return DashSDKPooling(rawValue: 0)
case .ifAvailable: return DashSDKPooling(rawValue: 1)
case .standard: return DashSDKPooling(rawValue: 2)
}
}
}
/// Withdraw credits from Platform addresses to a Core (L1) Dash address
///
/// This is a state transition that moves credits from Platform addresses to a Dash Core (L1) address.
/// Each input address must have a corresponding private key for signing.
///
/// - Parameters:
/// - inputs: Array of input addresses with amounts and private keys
/// - coreAddress: Base58-encoded Dash Core address to withdraw to (e.g., "y...")
/// - coreFeePerByte: Core network fee per byte (0 means use default of 1)
/// - pooling: Pooling strategy for the withdrawal (default: .never)
/// - feeFromInputIndex: Which input to deduct fees from (0-based, default 0)
/// - changeAddress: Optional Platform address for change (nil if not used)
/// - Returns: PlatformAddressInfosResult containing updated address balances after withdrawal
/// - Throws: SDKError if the withdrawal fails
public func withdrawFunds(
inputs: [AddressTransferInput],
coreAddress: String,
coreFeePerByte: UInt32 = 0,
pooling: PoolingStrategy = .never,
feeFromInputIndex: UInt16 = 0,
changeAddress: Data? = nil
) throws -> PlatformAddressInfosResult {
guard let sdk = sdk, let handle = sdk.handle else {
throw SDKError.invalidState("SDK not initialized")
}
guard !inputs.isEmpty else {
throw SDKError.invalidParameter("Inputs array is empty")
}
guard !coreAddress.isEmpty else {
throw SDKError.invalidParameter("Core address is empty")
}
guard feeFromInputIndex < inputs.count else {
throw SDKError.invalidParameter("Fee input index \(feeFromInputIndex) is out of bounds (inputs count: \(inputs.count))")
}
// Validate inputs
for (index, input) in inputs.enumerated() {
guard input.addressBytes.count == 21 else {
throw SDKError.invalidParameter("Input address at index \(index) must be 21 bytes, got \(input.addressBytes.count)")
}
guard input.privateKey.count == 32 else {
throw SDKError.invalidParameter("Private key at index \(index) must be 32 bytes, got \(input.privateKey.count)")
}
}
// Validate change address if provided
if let change = changeAddress {
guard change.count == 21 else {
throw SDKError.invalidParameter("Change address must be 21 bytes, got \(change.count)")
}
}
// Create FFI input structs (same as transfer)
var ffiInputs: [DashSDKAddressTransferInput] = []
var inputData: [(address: Data, privateKey: Data)] = [] // Keep data alive
for input in inputs {
inputData.append((address: input.addressBytes, privateKey: input.privateKey))
}
for (index, data) in inputData.enumerated() {
let addressPtr = data.address.withUnsafeBytes { buffer -> UnsafePointer<UInt8>? in
return buffer.baseAddress?.assumingMemoryBound(to: UInt8.self)
}
let privateKeyPtr = data.privateKey.withUnsafeBytes { buffer -> UnsafePointer<UInt8>? in
return buffer.baseAddress?.assumingMemoryBound(to: UInt8.self)
}
ffiInputs.append(DashSDKAddressTransferInput(
address: addressPtr,
address_len: UInt(data.address.count),
amount: inputs[index].amount,
nonce: inputs[index].nonce,
private_key: privateKeyPtr
))
}
// Convert core address to C string
let coreAddressCString = coreAddress.utf8CString
// Prepare change address pointer
var changeAddressPtr: UnsafePointer<UInt8>? = nil
var changeAddressLen: UInt = 0
if let change = changeAddress {
changeAddressPtr = change.withUnsafeBytes { buffer -> UnsafePointer<UInt8>? in
return buffer.baseAddress?.assumingMemoryBound(to: UInt8.self)
}
changeAddressLen = UInt(change.count)
}
// Call FFI
let result = ffiInputs.withUnsafeMutableBufferPointer { inputsBuffer -> DashSDKResult in
coreAddressCString.withUnsafeBufferPointer { coreAddressBuffer -> DashSDKResult in
let coreAddressPtr = coreAddressBuffer.baseAddress
return dash_sdk_address_withdraw_funds(
handle,
inputsBuffer.baseAddress,
UInt(inputs.count),
coreAddressPtr,
coreFeePerByte,
pooling.ffiValue,
feeFromInputIndex,
changeAddressPtr,
changeAddressLen
)
}
}
// Check for errors
if let error = result.error {
let sdkError = SDKError.fromDashSDKError(error.pointee)
dash_sdk_error_free(error)
throw sdkError
}
guard let dataPtr = result.data else {
return PlatformAddressInfosResult(infos: [:])
}
// Parse DashSDKAddressInfoMap (same as transfer)
let mapPtr = dataPtr.assumingMemoryBound(to: DashSDKAddressInfoMap.self)
let map = mapPtr.pointee
var infos: [Data: PlatformAddressInfo] = [:]
if map.count > 0 && map.entries != nil {
for i in 0..<map.count {
let entry = map.entries![Int(i)]
let addressBytes: Data
if entry.address != nil && entry.address_len > 0 {
addressBytes = Data(bytes: entry.address!, count: Int(entry.address_len))
} else {
continue
}
let info = PlatformAddressInfo(
addressBytes: addressBytes,
nonce: entry.nonce,
balance: entry.balance
)
infos[addressBytes] = info
}
}
// Free the FFI map
dash_sdk_address_info_map_free(mapPtr)
return PlatformAddressInfosResult(infos: infos)
}
/// Asset lock proof type
public enum AssetLockProofType {