-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathClient.swift
More file actions
1210 lines (1088 loc) · 33.6 KB
/
Client.swift
File metadata and controls
1210 lines (1088 loc) · 33.6 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 os
public typealias PreEventCallback = () async throws -> Void
public enum ClientError: Error, CustomStringConvertible, LocalizedError {
case creationError(String)
case missingInboxId
case invalidInboxId(String)
public var description: String {
switch self {
case .creationError(let err):
return "ClientError.creationError: \(err)"
case .missingInboxId:
return "ClientError.missingInboxId"
case .invalidInboxId(let inboxId):
return
"Invalid inboxId: \(inboxId). Inbox IDs cannot start with '0x'."
}
}
public var errorDescription: String? {
return description
}
}
/// Specify configuration options for creating a ``Client``.
public struct ClientOptions {
// Specify network options
public struct Api {
/// Specify which XMTP network to connect to. Defaults to ``.dev``
public var env: XMTPEnvironment = .dev
/// Specify whether the API client should use TLS security. In general this should only be false when using the `.local` environment.
public var isSecure: Bool = true
public var appVersion: String? = nil
public var gatewayUrl: String? = nil
public init(
env: XMTPEnvironment = .dev, isSecure: Bool = true,
appVersion: String? = nil,
gatewayUrl: String? = nil
) {
self.env = env
self.isSecure = isSecure
self.appVersion = appVersion
self.gatewayUrl = gatewayUrl
}
}
public var api = Api()
public var codecs: [any ContentCodec] = []
/// `preAuthenticateToInboxCallback` will be called immediately before an Auth Inbox signature is requested from the user
public var preAuthenticateToInboxCallback: PreEventCallback?
public var dbEncryptionKey: Data
public var dbDirectory: String?
public var historySyncUrl: String?
public var deviceSyncEnabled: Bool
public var debugEventsEnabled: Bool
public init(
api: Api = Api(),
codecs: [any ContentCodec] = [],
preAuthenticateToInboxCallback: PreEventCallback? = nil,
dbEncryptionKey: Data,
dbDirectory: String? = nil,
historySyncUrl: String? = nil,
useDefaultHistorySyncUrl: Bool = true,
deviceSyncEnabled: Bool = true,
debugEventsEnabled: Bool = false
) {
self.api = api
self.codecs = codecs
self.preAuthenticateToInboxCallback = preAuthenticateToInboxCallback
self.dbEncryptionKey = dbEncryptionKey
self.dbDirectory = dbDirectory
if useDefaultHistorySyncUrl && historySyncUrl == nil {
self.historySyncUrl = api.env.getHistorySyncUrl()
} else {
self.historySyncUrl = historySyncUrl
}
self.deviceSyncEnabled = deviceSyncEnabled
self.debugEventsEnabled = debugEventsEnabled
}
}
/// Cache for API clients to avoid creating duplicate connections.
/// Cache keys are constructed from v3Host, gatewayHost, isSecure, and appVersion
/// to ensure proper isolation between different API configurations.
actor ApiClientCache {
private var apiClientCache: [String: XmtpApiClient] = [:]
private var syncApiClientCache: [String: XmtpApiClient] = [:]
/// Creates a cache key from API configuration parameters
/// - Parameters:
/// - v3Host: The v3 host URL
/// - gatewayHost: The gateway host URL (optional)
/// - isSecure: Whether the connection uses TLS
/// - appVersion: The app version string (optional)
/// - Returns: A unique cache key string
static func makeCacheKey(
v3Host: String,
gatewayHost: String?,
isSecure: Bool,
appVersion: String?
) -> String {
let gateway = gatewayHost ?? "none"
let version = appVersion ?? "none"
return "\(v3Host)|\(gateway)|\(isSecure)|\(version)"
}
func getClient(forKey key: String) -> XmtpApiClient? {
return apiClientCache[key]
}
func setClient(_ client: XmtpApiClient, forKey key: String) {
apiClientCache[key] = client
}
func getSyncClient(forKey key: String) -> XmtpApiClient? {
return syncApiClientCache[key]
}
func setSyncClient(_ client: XmtpApiClient, forKey key: String) {
syncApiClientCache[key] = client
}
}
public typealias InboxId = String
public final class Client {
public let inboxID: InboxId
public let libXMTPVersion: String = getVersionInfo()
public let dbPath: String
public let installationID: String
public let publicIdentity: PublicIdentity
public let environment: XMTPEnvironment
private let ffiClient: FfiXmtpClient
private static let apiCache = ApiClientCache()
public lazy var conversations: Conversations = .init(
client: self, ffiConversations: ffiClient.conversations(),
ffiClient: ffiClient)
public lazy var preferences: PrivatePreferences = .init(
client: self, ffiClient: ffiClient)
public lazy var debugInformation: XMTPDebugInformation = .init(
client: self, ffiClient: ffiClient)
static var codecRegistry = CodecRegistry()
public static func register(codec: any ContentCodec) {
codecRegistry.register(codec: codec)
}
static func initializeClient(
publicIdentity: PublicIdentity,
options: ClientOptions,
signingKey: SigningKey?,
inboxId: InboxId,
apiClient: XmtpApiClient? = nil,
buildOffline: Bool = false
) async throws -> Client {
let (libxmtpClient, dbPath) = try await initFFiClient(
accountIdentifier: publicIdentity,
options: options,
inboxId: inboxId,
buildOffline: buildOffline
)
let client = try Client(
ffiClient: libxmtpClient,
dbPath: dbPath,
installationID: libxmtpClient.installationId().toHex,
inboxID: libxmtpClient.inboxId(),
environment: options.api.env,
publicIdentity: publicIdentity
)
try await options.preAuthenticateToInboxCallback?()
if let signatureRequest = client.ffiClient.signatureRequest() {
if let signingKey = signingKey {
do {
try await handleSignature(
for: signatureRequest, signingKey: signingKey)
try await client.ffiClient.registerIdentity(
signatureRequest: signatureRequest)
} catch {
throw ClientError.creationError(
"Failed to sign the message: \(error.localizedDescription)"
)
}
} else {
// add log messages here for logging 1) dbDirectory, 2) number of files in dbDirectory, 3) dbPath
let dbPathDirectory = URL(fileURLWithPath: dbPath)
.deletingLastPathComponent().path
XMTPLogger.database.error(
"custom dbDirectory: \(options.dbDirectory ?? "nil")")
XMTPLogger.database.error("dbPath: \(dbPath)")
XMTPLogger.database.error(
"dbPath Directory: \(dbPathDirectory)")
XMTPLogger.database.error(
"Number of files in dbDirectory: \(getNumberOfFilesInDirectory(directory: dbPathDirectory))"
)
throw ClientError.creationError(
"No signing key found, you must pass a SigningKey in order to create an MLS client"
)
}
}
// Register codecs
for codec in options.codecs {
register(codec: codec)
}
return client
}
public static func create(
account: SigningKey, options: ClientOptions
)
async throws -> Client
{
let identity = account.identity
let inboxId = try await getOrCreateInboxId(
api: options.api, publicIdentity: identity)
return try await initializeClient(
publicIdentity: identity,
options: options,
signingKey: account,
inboxId: inboxId
)
}
public static func build(
publicIdentity: PublicIdentity, options: ClientOptions,
inboxId: InboxId? = nil
)
async throws -> Client
{
let resolvedInboxId: String
if let existingInboxId = inboxId {
resolvedInboxId = existingInboxId
} else {
resolvedInboxId = try await getOrCreateInboxId(
api: options.api, publicIdentity: publicIdentity)
}
return try await initializeClient(
publicIdentity: publicIdentity,
options: options,
signingKey: nil,
inboxId: resolvedInboxId,
buildOffline: inboxId != nil
)
}
@available(
*,
deprecated,
message: """
This function is delicate and should be used with caution.
Creating an FfiClient without signing or registering will create a broken experience.
Use `create()` instead.
"""
)
public static func ffiCreateClient(
identity: PublicIdentity, clientOptions: ClientOptions
) async throws -> Client {
let recoveredInboxId = try await getOrCreateInboxId(
api: clientOptions.api, publicIdentity: identity)
let (ffiClient, dbPath) = try await initFFiClient(
accountIdentifier: identity,
options: clientOptions,
inboxId: recoveredInboxId
)
return try Client(
ffiClient: ffiClient,
dbPath: dbPath,
installationID: ffiClient.installationId().toHex,
inboxID: ffiClient.inboxId(),
environment: clientOptions.api.env,
publicIdentity: identity
)
}
private static func initFFiClient(
accountIdentifier: PublicIdentity,
options: ClientOptions,
inboxId: InboxId,
buildOffline: Bool = false
) async throws -> (FfiXmtpClient, String) {
let mlsDbDirectory = options.dbDirectory
var directoryURL: URL
if let mlsDbDirectory = mlsDbDirectory {
let fileManager = FileManager.default
directoryURL = URL(
fileURLWithPath: mlsDbDirectory, isDirectory: true)
// Check if the directory exists, if not, create it
if !fileManager.fileExists(atPath: directoryURL.path) {
do {
try fileManager.createDirectory(
at: directoryURL, withIntermediateDirectories: true,
attributes: nil)
} catch {
throw ClientError.creationError(
"Failed db directory \(mlsDbDirectory)")
}
}
} else {
directoryURL = URL.documentsDirectory
}
let alias = "xmtp-\(options.api.env.rawValue)-\(inboxId).db3"
var dbURL = directoryURL.appendingPathComponent(alias).path
var fileExists = FileManager.default.fileExists(atPath: dbURL)
if !fileExists {
let legacyAlias =
"xmtp-\(options.api.env.legacyRawValue)-\(inboxId).db3"
let legacyDbURL = directoryURL.appendingPathComponent(legacyAlias)
.path
let legacyFileExists = FileManager.default.fileExists(
atPath: legacyDbURL)
if legacyFileExists {
dbURL = legacyDbURL
}
}
let deviceSyncMode: FfiSyncWorkerMode =
!options.deviceSyncEnabled ? .disabled : .enabled
let ffiClient = try await createClient(
api: connectToApiBackend(api: options.api),
syncApi: connectToSyncApiBackend(api: options.api),
db: dbURL,
encryptionKey: options.dbEncryptionKey,
inboxId: inboxId,
accountIdentifier: accountIdentifier.ffiPrivate,
nonce: 0,
legacySignedPrivateKeyProto: nil,
deviceSyncServerUrl: options.historySyncUrl,
deviceSyncMode: deviceSyncMode,
allowOffline: buildOffline,
disableEvents: options.debugEventsEnabled
)
return (ffiClient, dbURL)
}
private static func handleSignature(
for signatureRequest: FfiSignatureRequest, signingKey: SigningKey
) async throws {
let signedData = try await signingKey.sign(
signatureRequest.signatureText())
switch signingKey.type {
case .SCW:
guard let chainId = signingKey.chainId else {
throw ClientError.creationError(
"Chain id must be present to sign Smart Contract Wallet")
}
try await signatureRequest.addScwSignature(
signatureBytes: signedData.rawData,
address: signingKey.identity.identifier,
chainId: UInt64(chainId),
blockNumber: signingKey.blockNumber.map { UInt64($0) }
)
case .EOA:
try await signatureRequest.addEcdsaSignature(
signatureBytes: signedData.rawData)
}
}
public static func connectToApiBackend(api: ClientOptions.Api) async throws
-> XmtpApiClient
{
let cacheKey = ApiClientCache.makeCacheKey(
v3Host: api.env.url,
gatewayHost: api.gatewayUrl,
isSecure: api.isSecure,
appVersion: api.appVersion
)
// Check for an existing connected client
if let cached = await apiCache.getClient(forKey: cacheKey),
try await isConnected(api: cached)
{
return cached
}
// Either not cached or not connected; create new client
let newClient = try await connectToBackend(
v3Host: api.env.url,
gatewayHost: api.gatewayUrl,
isSecure: api.isSecure,
appVersion: api.appVersion
)
await apiCache.setClient(newClient, forKey: cacheKey)
return newClient
}
public static func connectToSyncApiBackend(api: ClientOptions.Api)
async throws
-> XmtpApiClient
{
let cacheKey = ApiClientCache.makeCacheKey(
v3Host: api.env.url,
gatewayHost: api.gatewayUrl,
isSecure: api.isSecure,
appVersion: api.appVersion
)
// Check for an existing connected client
if let cached = await apiCache.getSyncClient(forKey: cacheKey),
try await isConnected(api: cached)
{
return cached
}
// Either not cached or not connected; create new client
let newClient = try await connectToBackend(
v3Host: api.env.url,
gatewayHost: api.gatewayUrl,
isSecure: api.isSecure,
appVersion: api.appVersion
)
await apiCache.setSyncClient(newClient, forKey: cacheKey)
return newClient
}
public static func getOrCreateInboxId(
api: ClientOptions.Api, publicIdentity: PublicIdentity
) async throws -> InboxId {
var inboxId: String
do {
inboxId =
try await getInboxIdForIdentifier(
api: connectToApiBackend(api: api),
accountIdentifier: publicIdentity.ffiPrivate)
?? generateInboxId(
accountIdentifier: publicIdentity.ffiPrivate, nonce: 0)
} catch {
inboxId = try generateInboxId(
accountIdentifier: publicIdentity.ffiPrivate, nonce: 0)
}
return inboxId
}
public static func revokeInstallations(
api: ClientOptions.Api,
signingKey: SigningKey,
inboxId: InboxId,
installationIds: [String]
) async throws {
let apiClient = try await connectToApiBackend(api: api)
let rootIdentity = signingKey.identity.ffiPrivate
let ids = installationIds.map { $0.hexToData }
let signatureRequest: FfiSignatureRequest
#if canImport(XMTPiOS)
signatureRequest = try await XMTPiOS.revokeInstallations(
api: apiClient, recoveryIdentifier: rootIdentity, inboxId: inboxId,
installationIds: ids)
#else
signatureRequest = try await XMTP.revokeInstallations(
api: apiClient, recoveryIdentifier: rootIdentity, inboxId: inboxId,
installationIds: ids)
#endif
do {
try await Client.handleSignature(
for: signatureRequest,
signingKey: signingKey)
try await applySignatureRequest(
api: apiClient, signatureRequest: signatureRequest)
} catch {
throw ClientError.creationError(
"Failed to sign the message: \(error.localizedDescription)")
}
}
@available(
*,
deprecated,
message: """
This function is delicate and should be used with caution.
Should only be used if trying to manage the signature flow independently;
otherwise use `revokeInstallations()` instead.
"""
)
public static func ffiApplySignatureRequest(
api: ClientOptions.Api,
signatureRequest: SignatureRequest
)
async throws
{
let apiClient = try await connectToApiBackend(api: api)
try await applySignatureRequest(
api: apiClient,
signatureRequest: signatureRequest.ffiSignatureRequest)
}
@available(
*,
deprecated,
message: """
This function is delicate and should be used with caution.
Should only be used if trying to manage the signature flow independently;
otherwise use `revokeInstallations()` instead.
"""
)
public static func ffiRevokeInstallations(
api: ClientOptions.Api,
publicIdentity: PublicIdentity,
inboxId: InboxId,
installationIds: [String]
) async throws
-> SignatureRequest
{
let apiClient = try await connectToApiBackend(api: api)
let rootIdentity = publicIdentity.ffiPrivate
let ids = installationIds.map { $0.hexToData }
let signatureRequest: FfiSignatureRequest
#if canImport(XMTPiOS)
signatureRequest = try await XMTPiOS.revokeInstallations(
api: apiClient, recoveryIdentifier: rootIdentity, inboxId: inboxId,
installationIds: ids)
#else
signatureRequest = try await XMTP.revokeInstallations(
api: apiClient, recoveryIdentifier: rootIdentity, inboxId: inboxId,
installationIds: ids)
#endif
return SignatureRequest(ffiSignatureRequest: signatureRequest)
}
private static func prepareClient(
api: ClientOptions.Api,
identity: PublicIdentity = PublicIdentity(
kind: .ethereum,
identifier: "0x0000000000000000000000000000000000000000")
) async throws -> FfiXmtpClient {
let inboxId = try await getOrCreateInboxId(
api: api, publicIdentity: identity)
return try await createClient(
api: connectToApiBackend(api: api),
syncApi: connectToApiBackend(api: api),
db: nil,
encryptionKey: nil,
inboxId: inboxId,
accountIdentifier: identity.ffiPrivate,
nonce: 0,
legacySignedPrivateKeyProto: nil,
deviceSyncServerUrl: nil,
deviceSyncMode: nil,
allowOffline: false,
disableEvents: false
)
}
public static func canMessage(
accountIdentities: [PublicIdentity], api: ClientOptions.Api
) async throws -> [String: Bool] {
let ffiClient = try await prepareClient(api: api)
let ffiIdentifiers = accountIdentities.map { $0.ffiPrivate }
let result = try await ffiClient.canMessage(
accountIdentifiers: ffiIdentifiers)
return Dictionary(
uniqueKeysWithValues: result.map { ($0.key.identifier, $0.value) })
}
public static func inboxStatesForInboxIds(
inboxIds: [InboxId],
api: ClientOptions.Api
) async throws -> [InboxState] {
let apiClient = try await connectToApiBackend(api: api)
let result = try await inboxStateFromInboxIds(
api: apiClient, inboxIds: inboxIds)
return result.map { InboxState(ffiInboxState: $0) }
}
public static func keyPackageStatusesForInstallationIds(
installationIds: [String],
api: ClientOptions.Api
) async throws -> [String: FfiKeyPackageStatus] {
let ffiClient = try await prepareClient(api: api)
let byteArrays = installationIds.map { $0.hexToData }
let result =
try await ffiClient.getKeyPackageStatusesForInstallationIds(
installationIds: byteArrays)
var statusMap: [String: FfiKeyPackageStatus] = [:]
for (keyBytes, status) in result {
let keyHex = keyBytes.toHex
statusMap[keyHex] = status
}
return statusMap
}
init(
ffiClient: FfiXmtpClient, dbPath: String,
installationID: String, inboxID: InboxId, environment: XMTPEnvironment,
publicIdentity: PublicIdentity
) throws {
self.ffiClient = ffiClient
self.dbPath = dbPath
self.installationID = installationID
self.inboxID = inboxID
self.environment = environment
self.publicIdentity = publicIdentity
}
@available(
*, deprecated,
message:
"This function is delicate and should be used with caution. Adding a wallet already associated with an inboxId will cause the wallet to loose access to that inbox. See: inboxIdFromIdentity(publicIdentity)"
)
public func addAccount(
newAccount: SigningKey, allowReassignInboxId: Bool = false
)
async throws
{
let inboxId: String? =
allowReassignInboxId
? nil : try await inboxIdFromIdentity(identity: newAccount.identity)
if allowReassignInboxId || (inboxId?.isEmpty ?? true) {
let signatureRequest = try await ffiAddIdentity(
identityToAdd: newAccount.identity,
allowReassignInboxId: allowReassignInboxId
)
do {
try await Client.handleSignature(
for: signatureRequest.ffiSignatureRequest,
signingKey: newAccount)
try await ffiApplySignatureRequest(
signatureRequest: signatureRequest)
} catch {
throw ClientError.creationError(
"Failed to sign the message: \(error.localizedDescription)")
}
} else {
throw ClientError.creationError(
"This wallet is already associated with inbox \(inboxId ?? "Unknown")"
)
}
}
public func removeAccount(
recoveryAccount: SigningKey, identityToRemove: PublicIdentity
) async throws {
let signatureRequest = try await ffiRevokeIdentity(
identityToRemove: identityToRemove)
do {
try await Client.handleSignature(
for: signatureRequest.ffiSignatureRequest,
signingKey: recoveryAccount)
try await ffiApplySignatureRequest(
signatureRequest: signatureRequest)
} catch {
throw ClientError.creationError(
"Failed to sign the message: \(error.localizedDescription)")
}
}
public func revokeAllOtherInstallations(signingKey: SigningKey) async throws
{
let signatureRequest = try await ffiRevokeAllOtherInstallations()
do {
try await Client.handleSignature(
for: signatureRequest.ffiSignatureRequest,
signingKey: signingKey)
try await ffiApplySignatureRequest(
signatureRequest: signatureRequest)
} catch {
throw ClientError.creationError(
"Failed to sign the message: \(error.localizedDescription)")
}
}
public func revokeInstallations(
signingKey: SigningKey, installationIds: [String]
) async throws {
let installations = installationIds.map { $0.hexToData }
let signatureRequest = try await ffiRevokeInstallations(
ids: installations)
do {
try await Client.handleSignature(
for: signatureRequest.ffiSignatureRequest,
signingKey: signingKey)
try await ffiApplySignatureRequest(
signatureRequest: signatureRequest)
} catch {
throw ClientError.creationError(
"Failed to sign the message: \(error.localizedDescription)")
}
}
public func canMessage(identity: PublicIdentity) async throws -> Bool {
let canMessage = try await canMessage(identities: [
identity
])
return canMessage[identity.identifier] ?? false
}
public func canMessage(identities: [PublicIdentity]) async throws
-> [String: Bool]
{
let ffiIdentifiers = identities.map { $0.ffiPrivate }
let result = try await ffiClient.canMessage(
accountIdentifiers: ffiIdentifiers)
return Dictionary(
uniqueKeysWithValues: result.map { ($0.key.identifier, $0.value) })
}
public func deleteLocalDatabase() throws {
try dropLocalDatabaseConnection()
let fm = FileManager.default
try fm.removeItem(atPath: dbPath)
}
@available(
*, deprecated,
message:
"This function is delicate and should be used with caution. App will error if database not properly reconnected. See: reconnectLocalDatabase()"
)
public func dropLocalDatabaseConnection() throws {
try ffiClient.releaseDbConnection()
}
public func reconnectLocalDatabase() async throws {
try await ffiClient.dbReconnect()
}
public func inboxIdFromIdentity(identity: PublicIdentity) async throws
-> InboxId?
{
return try await ffiClient.findInboxId(identifier: identity.ffiPrivate)
}
public func signWithInstallationKey(message: String) throws -> Data {
return try ffiClient.signWithInstallationKey(text: message)
}
public func verifySignature(message: String, signature: Data) throws -> Bool
{
do {
try ffiClient.verifySignedWithInstallationKey(
signatureText: message, signatureBytes: signature)
return true
} catch {
return false
}
}
public func verifySignatureWithInstallationId(
message: String, signature: Data, installationId: String
) throws -> Bool {
do {
try ffiClient.verifySignedWithPublicKey(
signatureText: message, signatureBytes: signature,
publicKey: installationId.hexToData)
return true
} catch {
return false
}
}
public func inboxState(refreshFromNetwork: Bool) async throws -> InboxState
{
return InboxState(
ffiInboxState: try await ffiClient.inboxState(
refreshFromNetwork: refreshFromNetwork))
}
public func inboxStatesForInboxIds(
refreshFromNetwork: Bool, inboxIds: [InboxId]
) async throws -> [InboxState] {
return try await ffiClient.addressesFromInboxId(
refreshFromNetwork: refreshFromNetwork, inboxIds: inboxIds
).map { InboxState(ffiInboxState: $0) }
}
public func createArchive(
path: String,
encryptionKey: Data,
opts: ArchiveOptions = ArchiveOptions()
) async throws {
try await ffiClient.createArchive(
path: path, opts: opts.toFfi(), key: encryptionKey)
}
public func importArchive(path: String, encryptionKey: Data) async throws {
try await ffiClient.importArchive(path: path, key: encryptionKey)
}
public func archiveMetadata(path: String, encryptionKey: Data) async throws
-> ArchiveMetadata
{
let ffiMetadata = try await ffiClient.archiveMetadata(
path: path, key: encryptionKey)
return ArchiveMetadata(ffiMetadata)
}
@available(
*,
deprecated,
message: """
This function is delicate and should be used with caution.
Should only be used if trying to manage the signature flow independently;
otherwise use `addAccount()`, `removeAccount()`, or `revoke()` instead.
"""
)
public func ffiApplySignatureRequest(signatureRequest: SignatureRequest)
async throws
{
try await ffiClient.applySignatureRequest(
signatureRequest: signatureRequest.ffiSignatureRequest)
}
@available(
*,
deprecated,
message: """
This function is delicate and should be used with caution.
Should only be used if trying to manage the signature flow independently;
otherwise use `revokeInstallations()` instead.
"""
)
public func ffiRevokeInstallations(ids: [Data]) async throws
-> SignatureRequest
{
let ffiSigReq = try await ffiClient.revokeInstallations(
installationIds: ids)
return SignatureRequest(ffiSignatureRequest: ffiSigReq)
}
@available(
*,
deprecated,
message: """
This function is delicate and should be used with caution.
Should only be used if trying to manage the signature flow independently;
otherwise use `revokeAllOtherInstallations()` instead.
"""
)
public func ffiRevokeAllOtherInstallations() async throws
-> SignatureRequest
{
let ffiSigReq = try await ffiClient.revokeAllOtherInstallations()
return SignatureRequest(ffiSignatureRequest: ffiSigReq)
}
@available(
*,
deprecated,
message: """
This function is delicate and should be used with caution.
Should only be used if trying to manage the signature flow independently;
otherwise use `removeIdentity()` instead.
"""
)
public func ffiRevokeIdentity(identityToRemove: PublicIdentity) async throws
-> SignatureRequest
{
let ffiSigReq = try await ffiClient.revokeIdentity(
identifier: identityToRemove.ffiPrivate)
return SignatureRequest(ffiSignatureRequest: ffiSigReq)
}
@available(
*,
deprecated,
message: """
This function is delicate and should be used with caution.
Should only be used if trying to manage the create and register flow independently;
otherwise use `addIdentity()` instead.
"""
)
public func ffiAddIdentity(
identityToAdd: PublicIdentity, allowReassignInboxId: Bool = false
) async throws
-> SignatureRequest
{
let inboxId: InboxId? =
await !allowReassignInboxId
? try inboxIdFromIdentity(
identity: PublicIdentity(
kind: identityToAdd.kind,
identifier: identityToAdd.identifier
)
) : nil
if allowReassignInboxId || (inboxId?.isEmpty ?? true) {
let ffiSigReq = try await ffiClient.addIdentity(
newIdentity: identityToAdd.ffiPrivate)
return SignatureRequest(ffiSignatureRequest: ffiSigReq)
} else {
throw ClientError.creationError(
"This wallet is already associated with inbox \(inboxId ?? "Unknown")"
)
}
}
@available(
*,
deprecated,
message: """
This function is delicate and should be used with caution.
Should only be used if trying to manage the signature flow independently;
otherwise use `create()` instead.
"""
)
public func ffiSignatureRequest() -> SignatureRequest? {
guard let ffiReq = ffiClient.signatureRequest() else {
return nil
}
return SignatureRequest(ffiSignatureRequest: ffiReq)
}
@available(
*,
deprecated,
message: """
This function is delicate and should be used with caution.
Should only be used if trying to manage the create and register flow independently;
otherwise use `create()` instead.
"""
)
public func ffiRegisterIdentity(signatureRequest: SignatureRequest)
async throws
{
try await ffiClient.registerIdentity(
signatureRequest: signatureRequest.ffiSignatureRequest)
}
}
extension Client {
/// Log level for XMTP logging
public enum LogLevel {
/// Error level logs only
case error
/// Warning level and above
case warn
/// Info level and above
case info
/// Debug level and above
case debug
fileprivate var ffiLogLevel: FfiLogLevel {
switch self {
case .error: return .error
case .warn: return .warn
case .info: return .info
case .debug: return .debug
}
}
}
/// Activates persistent logging for LibXMTP
/// - Parameters:
/// - logLevel: The level of logging to capture
/// - rotationSchedule: When log files should rotate
/// - maxFiles: Maximum number of log files to keep
/// - customLogDirectory: Optional custom directory path for logs
public static func activatePersistentLibXMTPLogWriter(
logLevel: LogLevel,
rotationSchedule: FfiLogRotation,
maxFiles: Int,
customLogDirectory: URL? = nil
) {
let fileManager = FileManager.default
let logDirectory =
customLogDirectory
?? URL.documentsDirectory.appendingPathComponent("xmtp_logs")
// Check if directory exists and is writable before proceeding
if !fileManager.fileExists(atPath: logDirectory.path) {
do {
try fileManager.createDirectory(
at: logDirectory,
withIntermediateDirectories: true,
attributes: nil
)
} catch {
os_log(
"Failed to create log directory: %{public}@",