@@ -17,6 +17,10 @@ final class KyotoService: BDKSyncService {
17
17
var network : Network
18
18
var wallet : Wallet ?
19
19
20
+ private var client : CbfClient ?
21
+ private var node : CbfNode ?
22
+ private var connected = false
23
+
20
24
init (
21
25
keyClient: KeyClient = . live,
22
26
network: Network = . signet,
@@ -28,11 +32,19 @@ final class KyotoService: BDKSyncService {
28
32
}
29
33
30
34
func createWallet( params: String ? ) throws {
31
-
35
+ self . connection = try Connection . createConnection ( )
36
+ self . wallet = try buildWallet ( params: params)
32
37
}
33
38
34
39
func loadWallet( ) throws {
40
+ self . connection = try Connection . loadConnection ( )
41
+ let wallet = try loadWalleFromBackup ( )
42
+ self . wallet = wallet
35
43
44
+ let nodeComponents = try buildNode ( from: wallet)
45
+ self . client = nodeComponents. client
46
+ self . node = nodeComponents. node
47
+ startListen ( )
36
48
}
37
49
38
50
func deleteWallet( ) throws {
@@ -82,4 +94,66 @@ final class KyotoService: BDKSyncService {
82
94
func getAddress( ) throws -> String {
83
95
" "
84
96
}
97
+
98
+ // MARK: - Private
99
+
100
+ private func buildNode( from wallet: Wallet ) throws -> CbfComponents {
101
+ try CbfBuilder ( )
102
+ . dataDir ( dataDir: Connection . dataDir)
103
+ . logLevel ( logLevel: . debug)
104
+ . scanType ( scanType: . recovery( fromHeight: 200_000 ) )
105
+ . build ( wallet: wallet)
106
+ }
107
+
108
+ private func startListen( ) {
109
+ node? . run ( )
110
+ continuallyUpdate ( )
111
+ printLogs ( )
112
+ updateWarn ( )
113
+ }
114
+
115
+ private func continuallyUpdate( ) {
116
+ Task {
117
+ while true {
118
+ guard let update = await self . client? . update ( ) else { return }
119
+ try self . wallet? . applyUpdate ( update: update)
120
+ let _ = try self . wallet? . persist ( connection: self . connection ?? Connection . loadConnection ( ) )
121
+ print ( " ######### walletUpdated " )
122
+ // DispatchQueue.main.async {
123
+ // NotificationCenter.default.post(name: .walletUpdated, object: nil)
124
+ // }
125
+ }
126
+ }
127
+ }
128
+
129
+ private func printLogs( ) {
130
+ Task {
131
+ while true {
132
+ if let log = try ? await self . client? . nextLog ( ) {
133
+ print ( " \( log) " )
134
+ }
135
+ }
136
+ }
137
+ }
138
+
139
+ private func updateWarn( ) {
140
+ Task {
141
+ while true {
142
+ if let warn = try ? await self . client!. nextWarning ( ) {
143
+ switch warn {
144
+ case . needConnections:
145
+ print ( " ######### connectionsChanged " )
146
+ self . connected = false
147
+ // DispatchQueue.main.async {
148
+ // NotificationCenter.default.post(name: .connectionsChanged, object: nil)
149
+ // }
150
+ default :
151
+ #if DEBUG
152
+ print ( warn)
153
+ #endif
154
+ }
155
+ }
156
+ }
157
+ }
158
+ }
85
159
}
0 commit comments