diff --git a/Package.swift b/Package.swift index 5775f8242..047a7c771 100644 --- a/Package.swift +++ b/Package.swift @@ -4,7 +4,7 @@ import PackageDescription var swiftSettings: [SwiftSetting] = [ - .enableExperimentalFeature("StrictConcurrency") + .enableExperimentalFeature("StrictConcurrency"), ] let sargonBinaryTargetName = "SargonCoreRS" @@ -24,7 +24,7 @@ if useLocalFramework { binaryTarget = .binaryTarget( name: sargonBinaryTargetName, url: - "https://github.com/radixdlt/sargon/releases/download/\(releaseTag)/libsargon-rs.xcframework.zip", + "https://github.com/radixdlt/sargon/releases/download/\(releaseTag)/libsargon-rs.xcframework.zip", checksum: releaseChecksum ) } @@ -38,22 +38,22 @@ let package = Package( .library( name: "Sargon", targets: ["Sargon"] - ) + ), ], dependencies: [ - // We use XCTestDynamicOverlay to have different `description` of e.g. Decimal192 + // We use XCTestDynamicOverlay to have different `description` of e.g. Decimal192 // for tests vs not tests (we use a .test `Locale`) .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.1.2"), - + // `XCTAssertNoDifference` used in test .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.0"), - // Hopefully only temporary! We use `SwiftJSON` to be able to mark some Sargon models - // as `Swift.Codable`. See the SargonObjectCodable protocol for details. - // In the future hopefully no JSON coding happens in wallets, - // i.e. Sargon does ALL JSON coding, then we can remove this. + // Hopefully only temporary! We use `SwiftJSON` to be able to mark some Sargon models + // as `Swift.Codable`. See the SargonObjectCodable protocol for details. + // In the future hopefully no JSON coding happens in wallets, + // i.e. Sargon does ALL JSON coding, then we can remove this. .package(url: "https://github.com/SwiftyJSON/SwiftyJSON", from: "5.0.2"), - + // Multicast / Share of notifications in EventBus .package(url: "https://github.com/sideeffect-io/AsyncExtensions", exact: "0.5.3"), ], @@ -70,7 +70,7 @@ let package = Package( .target(name: "SargonUniFFI"), "SwiftyJSON", .product(name: "XCTestDynamicOverlay", package: "xctest-dynamic-overlay"), - "AsyncExtensions" + "AsyncExtensions", ], path: "apple/Sources/Sargon", swiftSettings: swiftSettings diff --git a/apple/Sources/Sargon/Drivers/EntropyProvider/EntropyProvider+RandomData.swift b/apple/Sources/Sargon/Drivers/EntropyProvider/EntropyProvider+RandomData.swift index 5b109846f..26e8c0242 100644 --- a/apple/Sources/Sargon/Drivers/EntropyProvider/EntropyProvider+RandomData.swift +++ b/apple/Sources/Sargon/Drivers/EntropyProvider/EntropyProvider+RandomData.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-03. -// - import Foundation import SargonUniFFI @@ -16,19 +9,21 @@ extension EntropyProviderDriver where Self == EntropyProvider { public static var shared: Self { Self.shared } } +// MARK: - EntropyProvider /// An `EntropyProviderDriver` actor which uses CSRNG `SystemRandomNumberGenerator` /// to generate 32 bytes. public final actor EntropyProvider { - internal init() {} - + init() {} + /// Singleton `EntropyProviderDriver` of type `EntropyProvider`, /// being an `actor` that uses CSRNG `SystemRandomNumberGenerator` public static let shared = EntropyProvider() } +// MARK: EntropyProviderDriver extension EntropyProvider: EntropyProviderDriver { /// Generates 32 bytes using CSRNG `SystemRandomNumberGenerator` - nonisolated public func generateSecureRandomBytes() -> Entropy32Bytes { + public nonisolated func generateSecureRandomBytes() -> Entropy32Bytes { Entropy32Bytes.generate() } } diff --git a/apple/Sources/Sargon/Drivers/EventBus/EventBus.swift b/apple/Sources/Sargon/Drivers/EventBus/EventBus.swift index cfb2c9e71..24b98d596 100644 --- a/apple/Sources/Sargon/Drivers/EventBus/EventBus.swift +++ b/apple/Sources/Sargon/Drivers/EventBus/EventBus.swift @@ -1,23 +1,16 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - +import AsyncExtensions import Foundation import SargonUniFFI -import AsyncExtensions // Makes it possible to type `.shared` on an initalizer/func taking // `some EventBusDriver` as parameter. extension EventBusDriver where Self == EventBus { - /// Singleton `EventBusDriver` of type `EventBus` being an `actor` which forwards `EventNotification`s /// originally emitted by `SargonOS` (Rust side). public static var shared: Self { Self.shared } } +// MARK: - EventBus /// An `EventBusDriver` actor which handles incoming /// `EventNotifications` and forwards them to any /// subscriber of `notifications()`, being a multicasted @@ -26,35 +19,35 @@ public final actor EventBus { /// A stream we multicast on. private let stream = AsyncThrowingPassthroughSubject() private let subject: Subject -#if DEBUG + #if DEBUG public init() { subject = .init() } -#else + #else private init() { subject = .init() } -#endif + #endif } extension EventBus { - public typealias Element = EventNotification public typealias Subject = AsyncPassthroughSubject - + /// Singleton `EventBusDriver` of type `EventBus` being an `actor` which forwards `EventNotification`s /// originally emitted by `SargonOS` (Rust side). public static let shared = EventBus() - + /// A multicasted async sequence of `EventNotification` values /// over time, originally emitted by `SargonOS` (Rust side). public func notifications() -> AsyncMulticastSequence> { subject - .multicast(stream) - .autoconnect() + .multicast(stream) + .autoconnect() } } +// MARK: EventBusDriver extension EventBus: EventBusDriver { /// This method is called by `SargonOS` (Rust side) and we should /// "forward" the events to subscribers (Swift swide), i.e. `@SharedReader`s of profile values, diff --git a/apple/Sources/Sargon/Drivers/EventBus/EventNotification+Swiftified.swift b/apple/Sources/Sargon/Drivers/EventBus/EventNotification+Swiftified.swift index 7a33e85a6..10aa6866e 100644 --- a/apple/Sources/Sargon/Drivers/EventBus/EventNotification+Swiftified.swift +++ b/apple/Sources/Sargon/Drivers/EventBus/EventNotification+Swiftified.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-15. -// - import Foundation import SargonUniFFI @@ -18,15 +11,17 @@ extension EventProfileModified { extension Event { public var profileModified: EventProfileModified? { switch self { - case let .profileModified(change): return change - default: return nil + case let .profileModified(change): change + default: nil } } + public var addressOfNewAccount: AccountAddress? { profileModified?.addedAccount } } +// MARK: - EventNotification + Comparable extension EventNotification: Comparable { /// `EventNotification` are made `Comparable` by /// sorting on `timestamp`. @@ -36,7 +31,6 @@ extension EventNotification: Comparable { } extension Event { - /// Discriminant of the `Event`. public var kind: EventKind { eventKind(event: self) diff --git a/apple/Sources/Sargon/Drivers/FileSystem/FileSystemDriver+Data+ContentsOf+URL.swift b/apple/Sources/Sargon/Drivers/FileSystem/FileSystemDriver+Data+ContentsOf+URL.swift index 698850dba..8d380bb38 100644 --- a/apple/Sources/Sargon/Drivers/FileSystem/FileSystemDriver+Data+ContentsOf+URL.swift +++ b/apple/Sources/Sargon/Drivers/FileSystem/FileSystemDriver+Data+ContentsOf+URL.swift @@ -1,24 +1,18 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - import Foundation import SargonUniFFI +// MARK: - FileManager + @unchecked Sendable extension FileManager: @unchecked Sendable {} // Makes it possible to type `.shared` on an initalizer/func taking // `some FileSystemDriver` as parameter. extension FileSystemDriver where Self == FileSystem { - /// Singleton `FileSystemDriver` of type `FileSystem`being an `actor` which /// uses a `FileManager` for File I/O CRUD operations. public static var shared: Self { Self.shared } } +// MARK: - FileSystem /// `FileSystemDriver` being an `actor` which /// uses a `FileManager` for File I/O CRUD operations. public final actor FileSystem { @@ -26,7 +20,7 @@ public final actor FileSystem { public init(fileManager: FileManager = .default) { self.fileManager = fileManager } - + /// Singleton `FileSystemDriver` of type `FileSystem`being an `actor` which /// uses a `FileManager` for File I/O CRUD operations. public static let shared = FileSystem(fileManager: .default) @@ -44,28 +38,28 @@ extension FileSystem { _ io: @Sendable (URL) throws -> T ) throws -> T { let url = URL(file: path) -#if os(macOS) - guard url.startAccessingSecurityScopedResource() else { - throw CommonError.NotPermissionToAccessFile(path: path) - } - defer { url.stopAccessingSecurityScopedResource() } - #endif + #if os(macOS) + guard url.startAccessingSecurityScopedResource() else { + throw CommonError.NotPermissionToAccessFile(path: path) + } + defer { url.stopAccessingSecurityScopedResource() } + #endif return try io(url) } } extension FileSystem { private static func appDirPathNotNecessarilyExisting(fileManager: FileManager) throws -> String { -#if os(iOS) + #if os(iOS) return try fileManager.urls( for: .cachesDirectory, in: .userDomainMask ).first!.path() -#elseif os(macOS) + #elseif os(macOS) URL.temporaryDirectory.path() -#else + #else fatalError("Unsupported OS") -#endif + #endif } } @@ -80,9 +74,9 @@ extension FileSystem { } #endif +// MARK: - FileSystem + FileSystemDriver extension FileSystem: FileSystemDriver { - - public func writableAppDirPath() async throws -> String { + public func writableAppDirPath() async throws -> String { try with(path: Self.appDirPathNotNecessarilyExisting(fileManager: fileManager)) { let directoryExists = fileManager.fileExists(atPath: $0.path()) if !directoryExists { @@ -90,29 +84,29 @@ extension FileSystem: FileSystemDriver { } return $0.path() } - } - + } + public func loadFromFile(path: String) async throws -> BagOfBytes? { - return try with(path: path) { - let fileExists = fileManager.fileExists(atPath: $0.path()) - do { - return try Data(contentsOf: $0) - } catch { - if fileExists { - throw error - } else { - return nil - } - } + try with(path: path) { + let fileExists = fileManager.fileExists(atPath: $0.path()) + do { + return try Data(contentsOf: $0) + } catch { + if fileExists { + throw error + } else { + return nil + } + } } } - - public func saveToFile(path: String, data: BagOfBytes, isAllowedToOverwrite: Bool) async throws { - try with(path: path) { + + public func saveToFile(path: String, data: BagOfBytes, isAllowedToOverwrite: Bool) async throws { + try with(path: path) { try data.write(to: $0, options: isAllowedToOverwrite ? [] : [.withoutOverwriting]) - } - } - + } + } + public func deleteFile(path: String) async throws { try with(path: path) { try fileManager.removeItem(at: $0) diff --git a/apple/Sources/Sargon/Drivers/HostInfo/HostInfoDriver+DeviceInfo.swift b/apple/Sources/Sargon/Drivers/HostInfo/HostInfoDriver+DeviceInfo.swift index 13e51cf09..e37eeea2b 100644 --- a/apple/Sources/Sargon/Drivers/HostInfo/HostInfoDriver+DeviceInfo.swift +++ b/apple/Sources/Sargon/Drivers/HostInfo/HostInfoDriver+DeviceInfo.swift @@ -1,45 +1,39 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-03. -// - import Foundation import SargonUniFFI +// MARK: - AppleHostInfoDriver /// An `HostInfoDriver` actor being able to read host info, i.e /// details about the iPhone the app is running on. public final actor AppleHostInfoDriver { - fileprivate var appVersion: String + private var appVersion: String public init(appVersion: String) { self.appVersion = appVersion } } extension AppleHostInfoDriver { - nonisolated public func hostAppVersion() async -> String { + public nonisolated func hostAppVersion() async -> String { await self.appVersion } } #if canImport(UIKit) import UIKit + extension AppleHostInfoDriver: HostInfoDriver { - public func hostOs() async -> HostOs { - return await HostOs.ios(version: UIDevice.current.systemVersion) + await HostOs.ios(version: UIDevice.current.systemVersion) } - nonisolated public func hostDeviceName() async -> String { + public nonisolated func hostDeviceName() async -> String { await UIDevice.current.name } - - nonisolated public func hostDeviceSystemVersion() async -> String { + + public nonisolated func hostDeviceSystemVersion() async -> String { await UIDevice.current.systemVersion } - - nonisolated public func hostDeviceModel() async -> String { + + public nonisolated func hostDeviceModel() async -> String { await UIDevice.current.model } } @@ -48,17 +42,16 @@ extension AppleHostInfoDriver: HostInfoDriver { extension AppleHostInfoDriver: HostInfoDriver { public func hostOs() async -> HostOs { let info = ProcessInfo.processInfo.operatingSystemVersion - let version = "\(info.majorVersion).\(info.minorVersion).\(info.patchVersion)" + let version = "\(info.majorVersion).\(info.minorVersion).\(info.patchVersion)" return HostOs.ios(version: version) } - - nonisolated public func hostDeviceModel() async -> String { - + + public nonisolated func hostDeviceModel() async -> String { let service = IOServiceGetMatchingService( kIOMainPortDefault, IOServiceMatching("IOPlatformExpertDevice") ) - + guard let modelData = IORegistryEntryCreateCFProperty( service, @@ -71,11 +64,11 @@ extension AppleHostInfoDriver: HostInfoDriver { else { return "Unknown Model" } - + return modelString.trimmingCharacters(in: .controlCharacters.union(.whitespaces)) } - - nonisolated public func hostDeviceName() async -> String { + + public nonisolated func hostDeviceName() async -> String { "Unknown Name" } } diff --git a/apple/Sources/Sargon/Drivers/Logging/LoggingDriver+SwiftLog.swift b/apple/Sources/Sargon/Drivers/Logging/LoggingDriver+SwiftLog.swift index d20080b58..f5ee3b423 100644 --- a/apple/Sources/Sargon/Drivers/Logging/LoggingDriver+SwiftLog.swift +++ b/apple/Sources/Sargon/Drivers/Logging/LoggingDriver+SwiftLog.swift @@ -1,13 +1,6 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-03. -// - import Foundation -import SargonUniFFI import os +import SargonUniFFI /// A public globally accessible `Logger` with `category` "Swift" which /// Swift Sargon uses, and which iOS wallet can use too, it uses the @@ -22,18 +15,18 @@ extension LoggingDriver where Self == Log { public static var shared: Self { Self.shared } } +// MARK: - Log /// A `LoggingDriver` actor capable of logging on behalf of /// Rust Sargon core, that is, when we write e.g. `debug!("hey Swift from Rust");` /// in Rust code, that message will in fact be logged by a `os.Logger` held by this `Log` /// actor. public final actor Log { - /// The `Logger` to which Rust delegates logged messages. - nonisolated fileprivate let rustLogger: Logger - - ///The `Logger` Swift Sargon uses to log messages, accessed - ///using global variable `log` (aliasa for `Log.shared.swiftLogger`). - nonisolated internal let swiftLogger: Logger + private nonisolated let rustLogger: Logger + + /// The `Logger` Swift Sargon uses to log messages, accessed + /// using global variable `log` (aliasa for `Log.shared.swiftLogger`). + nonisolated let swiftLogger: Logger private init( subsystem: String = "Sargon", @@ -49,15 +42,14 @@ public final actor Log { category: swiftCategory ) } - + /// LoggingDriver singleton, a shared actor. public static let shared = Log() - } -// MARK: `LoggingDriver` conformance. +// MARK: LoggingDriver extension Log: LoggingDriver { - nonisolated public func log( + public nonisolated func log( level: LogLevel, msg: String ) { @@ -93,23 +85,25 @@ public func logSystemDiagnosis() { print("logSystemDiagnosis - RUST") rustLoggerLogAtEveryLevel() print("logSystemDiagnosis - Swift") - levels.forEach { level in + for level in levels { log.log(level: .init(sargonLogLevel: level), "Swift test: '\(String(describing: level))'") } } +// MARK: - LogFilter + CaseIterable extension LogFilter: CaseIterable { public static let allCases: [Self] = rustLoggerGetAllFilters() } +// MARK: - LogLevel + CaseIterable extension LogLevel: CaseIterable { public static let allCases: [Self] = rustLoggerGetAllLevels() } +// MARK: - Logger + @unchecked Sendable extension Logger: @unchecked Sendable {} extension OSLogType { - /// Rust has 5 log levels, so does Swift. /// /// The mapping might look a bit strange since we do NOT map `error` -> `error`, @@ -118,14 +112,14 @@ extension OSLogType { /// serious to Swift. init(sargonLogLevel sargon: Sargon.LogLevel) { switch sargon { - case .error: + case .error: // yes this is correct we dont map `error` -> `error`. self = .fault case .warn: // Swift does not have warn, we use error, and we use Swifts fault for Rust error. self = .error case .info: self = .info - case .debug: + case .debug: // yes this is correct we dont map `debug` -> `debug`. self = .default case .trace: @@ -135,9 +129,7 @@ extension OSLogType { } } - extension OSLogType { - init(sargonFilterLevel sargon: Sargon.LogFilter) { if let level = LogLevel(rawValue: sargon.rawValue) { self.init(sargonLogLevel: level) @@ -146,4 +138,3 @@ extension OSLogType { } } } - diff --git a/apple/Sources/Sargon/Drivers/Networking/NetworkingDriver+URLSession.swift b/apple/Sources/Sargon/Drivers/Networking/NetworkingDriver+URLSession.swift index 0c2154351..265d519c5 100644 --- a/apple/Sources/Sargon/Drivers/Networking/NetworkingDriver+URLSession.swift +++ b/apple/Sources/Sargon/Drivers/Networking/NetworkingDriver+URLSession.swift @@ -1,19 +1,16 @@ import Foundation import SargonUniFFI - // Makes it possible to type `.shared` on an initalizer/func taking // `some NetworkingDriver` as parameter. extension NetworkingDriver where Self == URLSession { - /// Singleton `NetworkingDriver` of type `URLSession`, which /// uses `URLSession.shared`. public static var shared: Self { Self.shared } } -// MARK: `NetworkingDriver` conformance +// MARK: - URLSession + NetworkingDriver extension URLSession: NetworkingDriver { - public func executeNetworkRequest( request sargonRequest: NetworkRequest ) async throws -> NetworkResponse { diff --git a/apple/Sources/Sargon/Drivers/ProfileStateChange/ProfileStateChange.swift b/apple/Sources/Sargon/Drivers/ProfileStateChange/ProfileStateChange.swift index 8cadba8c1..5dbc3b612 100644 --- a/apple/Sources/Sargon/Drivers/ProfileStateChange/ProfileStateChange.swift +++ b/apple/Sources/Sargon/Drivers/ProfileStateChange/ProfileStateChange.swift @@ -2,16 +2,17 @@ import SargonUniFFI public typealias ProfileStateChangeEventPublisher = EventPublisher +// MARK: - ProfileStateChangeEventPublisher + ProfileStateChangeDriver extension ProfileStateChangeEventPublisher: ProfileStateChangeDriver { - public static let shared = ProfileStateChangeEventPublisher() + public static let shared = ProfileStateChangeEventPublisher() - public func handleProfileStateChange(changedProfileState: ProfileState) async { - subject.send(changedProfileState) - } + public func handleProfileStateChange(changedProfileState: ProfileState) async { + subject.send(changedProfileState) + } } extension ProfileStateChangeDriver where Self == ProfileStateChangeEventPublisher { - public static var shared: Self { - ProfileStateChangeEventPublisher.shared - } + public static var shared: Self { + ProfileStateChangeEventPublisher.shared + } } diff --git a/apple/Sources/Sargon/Drivers/TestDrivers/SecureStorage/SecureStorageDriver+InsecureTestOnlyEphemeral_SecureStorage.swift b/apple/Sources/Sargon/Drivers/TestDrivers/SecureStorage/SecureStorageDriver+InsecureTestOnlyEphemeral_SecureStorage.swift index c588f3429..8289be270 100644 --- a/apple/Sources/Sargon/Drivers/TestDrivers/SecureStorage/SecureStorageDriver+InsecureTestOnlyEphemeral_SecureStorage.swift +++ b/apple/Sources/Sargon/Drivers/TestDrivers/SecureStorage/SecureStorageDriver+InsecureTestOnlyEphemeral_SecureStorage.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-03. -// - import Foundation import SargonUniFFI @@ -24,14 +17,13 @@ extension Insecure︕!TestOnly︕!Ephemeral︕!SecureStorage: SecureStorag public func loadData(key: SecureStorageKey) async throws -> Data? { dictionary[key] } - + public func saveData(key: SecureStorageKey, data: Data) async throws { dictionary[key] = data } - + public func deleteDataForKey(key: SecureStorageKey) async throws { dictionary.removeValue(forKey: key) } - } #endif diff --git a/apple/Sources/Sargon/Drivers/TestDrivers/TestDrivers.swift b/apple/Sources/Sargon/Drivers/TestDrivers/TestDrivers.swift index f4ebb3c61..e8888b383 100644 --- a/apple/Sources/Sargon/Drivers/TestDrivers/TestDrivers.swift +++ b/apple/Sources/Sargon/Drivers/TestDrivers/TestDrivers.swift @@ -1,18 +1,9 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-13. -// - import Foundation import SargonUniFFI #if DEBUG - extension BIOS { - public static func insecure( bundle: Bundle = .main, userDefaultsSuite: String = "test" @@ -20,7 +11,7 @@ extension BIOS { BIOS( bundle: bundle, userDefaultsSuite: userDefaultsSuite, - secureStorageDriver: Insecure︕!TestOnly︕!Ephemeral︕!SecureStorage.init( + secureStorageDriver: Insecure︕!TestOnly︕!Ephemeral︕!SecureStorage( keychainService: "test" ) ) diff --git a/apple/Sources/Sargon/Drivers/UnsafeStorage/UnsafeStorageDriver+UserDefaults.swift b/apple/Sources/Sargon/Drivers/UnsafeStorage/UnsafeStorageDriver+UserDefaults.swift index 546276c32..00f29187a 100644 --- a/apple/Sources/Sargon/Drivers/UnsafeStorage/UnsafeStorageDriver+UserDefaults.swift +++ b/apple/Sources/Sargon/Drivers/UnsafeStorage/UnsafeStorageDriver+UserDefaults.swift @@ -1,24 +1,18 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - import Foundation import SargonUniFFI +// MARK: - UserDefaults + @unchecked Sendable extension UserDefaults: @unchecked Sendable {} // Makes it possible to type `.shared` on an initalizer/func taking // `some UnsafeStorageDriver` as parameter. extension UnsafeStorageDriver where Self == UnsafeStorage { - /// Singleton `UnsafeStorageDriver` of type `UnsafeStorage, /// which uses `UserDefaults.standard` as storage public static var shared: Self { Self.shared } } +// MARK: - UnsafeStorage /// An `UnsafeStorageDriver` implementation which /// wraps `UserDefaults`. public final class UnsafeStorage: Sendable { @@ -27,6 +21,7 @@ public final class UnsafeStorage: Sendable { public init(userDefaults: UserDefaults = .standard) { self.userDefaults = userDefaults } + /// Singleton `UnsafeStorageDriver` of type `UnsafeStorage, /// which uses `UserDefaults.standard` as storage public static let shared = UnsafeStorage() @@ -40,18 +35,17 @@ extension UnsafeStorageKey { } } -// MARK: `UnsafeStorageDriver` confirmance +// MARK: - UnsafeStorage + UnsafeStorageDriver extension UnsafeStorage: UnsafeStorageDriver { public func loadData(key: Key) -> Data? { userDefaults.data(forKey: key.identifier) } - + public func saveData(key: Key, data: Data) { userDefaults.setValue(data, forKey: key.identifier) } - + public func deleteDataForKey(key: Key) { userDefaults.removeObject(forKey: key.identifier) } - } diff --git a/apple/Sources/Sargon/Exports.swift b/apple/Sources/Sargon/Exports.swift index 0bc55c8a4..a4c3ada4d 100644 --- a/apple/Sources/Sargon/Exports.swift +++ b/apple/Sources/Sargon/Exports.swift @@ -6,5 +6,5 @@ // DISADVANTAGE: // Here in Sargon we can refer to symbols inside of `SargonUniFFI` without having to do `import SargonUniFFI` in some file `Foo.swift` // unfortunately since Xcode 15 the `@_exported import SargonUniFFI` only helps with COMPILATION but NOT code HIGHLIGHTING, meaning that -// we get no code highlighting of those `SargonUniFFI` symbols inside of `Foo.swift`. +// we get no code highlighting of those `SargonUniFFI` symbols inside of `Foo.swift`. @_exported import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/AccessControllerAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/AccessControllerAddress+Wrap+Functions.swift index f7095c4e4..c630babed 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/AccessControllerAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/AccessControllerAddress+Wrap+Functions.swift @@ -4,10 +4,10 @@ extension AccessControllerAddress { public init(validatingAddress bech32String: String) throws { self = try newAccessControllerAddress(bech32: bech32String) } - - public func formatted(_ format: AddressFormat = .default) -> String { - accessControllerAddressFormatted(address: self, format: format) - } + + public func formatted(_ format: AddressFormat = .default) -> String { + accessControllerAddressFormatted(address: self, format: format) + } /// The bech32 encoded string for this address. public var address: String { @@ -17,16 +17,14 @@ extension AccessControllerAddress { public var networkID: NetworkId { accessControllerAddressNetworkId(address: self) } - } #if DEBUG extension AccessControllerAddress { - public static func random(networkID: NetworkID) -> Self { newAccessControllerAddressRandom(networkId: networkID) } - + public func mapTo(networkID: NetworkID) -> Self { accessControllerAddressMapToNetwork(address: self, networkId: networkID) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/AccountAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/AccountAddress+Wrap+Functions.swift index f3e727e8f..3fe988e81 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/AccountAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/AccountAddress+Wrap+Functions.swift @@ -53,18 +53,16 @@ extension AccountAddress { public var shortFormat: String { formatted(AddressFormat.default) } - } #if DEBUG - extension AccountAddress { - - public static func random(networkID: NetworkID) -> Self { - newAccountAddressRandom(networkId: networkID) - } +extension AccountAddress { + public static func random(networkID: NetworkID) -> Self { + newAccountAddressRandom(networkId: networkID) + } - public func mapTo(networkID: NetworkID) -> Self { - accountAddressMapToNetwork(address: self, networkId: networkID) - } + public func mapTo(networkID: NetworkID) -> Self { + accountAddressMapToNetwork(address: self, networkId: networkID) } -#endif // DEBUG +} +#endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/Address+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/Address+Wrap+Functions.swift index b7c514a01..3805c7328 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/Address+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/Address+Wrap+Functions.swift @@ -8,11 +8,11 @@ extension Address { public init(validatingAddress bech32String: String) throws { self = try newAddressFromBech32(string: bech32String) } - + public var networkID: NetworkID { addressNetworkId(address: self) } - + public var address: String { addressToString(address: self) } @@ -24,4 +24,4 @@ extension Address { addressMapToNetwork(address: self, networkId: networkID) } } -#endif \ No newline at end of file +#endif diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/AddressOfAccountOrPersona+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/AddressOfAccountOrPersona+Wrap+Functions.swift index b063d9caa..78389c58d 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/AddressOfAccountOrPersona+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/AddressOfAccountOrPersona+Wrap+Functions.swift @@ -13,12 +13,10 @@ extension AddressOfAccountOrPersona { public var networkID: NetworkId { addressOfAccountOrPersonaNetworkId(address: self) } - + public func formatted(_ format: AddressFormat) -> String { addressOfAccountOrPersonaFormatted(address: self, format: format) } - - } #if DEBUG @@ -26,7 +24,7 @@ extension AddressOfAccountOrPersona { public static func random(networkID: NetworkID) -> Self { .account(newAccountAddressRandom(networkId: networkID)) } - + public func mapTo(networkID: NetworkID) -> Self { addressOfAccountOrPersonaMapToNetwork(address: self, networkId: networkID) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/ComponentAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/ComponentAddress+Wrap+Functions.swift index 15b8f9474..80a9dc75d 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/ComponentAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/ComponentAddress+Wrap+Functions.swift @@ -4,10 +4,10 @@ extension ComponentAddress { public init(validatingAddress bech32String: String) throws { self = try newComponentAddress(bech32: bech32String) } - - public func formatted(_ format: AddressFormat = .default) -> String { - componentAddressFormatted(address: self, format: format) - } + + public func formatted(_ format: AddressFormat = .default) -> String { + componentAddressFormatted(address: self, format: format) + } /// The bech32 encoded string for this address. public var address: String { @@ -22,7 +22,7 @@ extension ComponentAddress { public var isGlobal: Bool { componentAddressIsGlobal(address: self) } - + /// If the `EntityType == .InternalGenericComponent` public var isInternal: Bool { componentAddressIsInternal(address: self) @@ -31,11 +31,10 @@ extension ComponentAddress { #if DEBUG extension ComponentAddress { - public static func random(networkID: NetworkID) -> Self { newComponentAddressRandom(networkId: networkID) } - + public func mapTo(networkID: NetworkID) -> Self { componentAddressMapToNetwork(address: self, networkId: networkID) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/IdentityAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/IdentityAddress+Wrap+Functions.swift index 0d77e8e13..22b08e75d 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/IdentityAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/IdentityAddress+Wrap+Functions.swift @@ -11,10 +11,10 @@ extension IdentityAddress { networkId: networkID ) } - - public func formatted(_ format: AddressFormat = .default) -> String { - identityAddressFormatted(address: self, format: format) - } + + public func formatted(_ format: AddressFormat = .default) -> String { + identityAddressFormatted(address: self, format: format) + } /// The bech32 encoded string for this address. public var address: String { @@ -24,17 +24,14 @@ extension IdentityAddress { public var networkID: NetworkId { identityAddressNetworkId(address: self) } - - } #if DEBUG extension IdentityAddress { - public static func random(networkID: NetworkID) -> Self { newIdentityAddressRandom(networkId: networkID) } - + public func mapTo(networkID: NetworkID) -> Self { identityAddressMapToNetwork(address: self, networkId: networkID) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/LegacyOlympiaAccountAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/LegacyOlympiaAccountAddress+Wrap+Functions.swift index 412bf0630..1fb461bdd 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/LegacyOlympiaAccountAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/LegacyOlympiaAccountAddress+Wrap+Functions.swift @@ -2,51 +2,51 @@ import SargonUniFFI extension LegacyOlympiaAccountAddress { public init(validatingAddress bech32String: String) throws { - self = try newLegacyOlympiaAccountAddressFromString( - string: bech32String - ) + self = try newLegacyOlympiaAccountAddressFromString( + string: bech32String + ) } - + public init(publicKey: Secp256k1PublicKey) { - self = newLegacyOlympiaAccountAddressFromPublicKey( - publicKey: publicKey - ) - } - - public func formatted(_ format: AddressFormat = .default) -> String { - legacyOlympiaAccountAddressFormatted(address: self, format: format) - } - + self = newLegacyOlympiaAccountAddressFromPublicKey( + publicKey: publicKey + ) + } + + public func formatted(_ format: AddressFormat = .default) -> String { + legacyOlympiaAccountAddressFormatted(address: self, format: format) + } + /// The bech32 encoded string for this address. public var address: String { - legacyOlympiaAccountAddressToString( - address: self - ) + legacyOlympiaAccountAddressToString( + address: self + ) } - + public var networkID: NetworkId { // We do not allow creation of Non-Mainnet Olympia Addresses. .mainnet } - + public func toBabylonAddress() -> AccountAddress { - legacyOlympiaAccountAddressToBabylonAccountAddress( - address: self - ) + legacyOlympiaAccountAddressToBabylonAccountAddress( + address: self + ) } - + public func isLegacyOfBabylonAddress(_ babylon: AccountAddress) -> Bool { - legacyOlympiaAccountAddressIsLegacyOfBabylon( - legacyOlympiaAddress: self, - babylonAccountAddress: babylon - ) + legacyOlympiaAccountAddressIsLegacyOfBabylon( + legacyOlympiaAddress: self, + babylonAccountAddress: babylon + ) } } extension AccountAddress { - public func wasMigratedFromLegacyOlympia( - address legacy: LegacyOlympiaAccountAddress - ) -> Bool { + public func wasMigratedFromLegacyOlympia( + address legacy: LegacyOlympiaAccountAddress + ) -> Bool { legacy.isLegacyOfBabylonAddress(self) } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/LockerAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/LockerAddress+Wrap+Functions.swift index 0bd5e4569..1dae0e274 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/LockerAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/LockerAddress+Wrap+Functions.swift @@ -4,10 +4,10 @@ extension LockerAddress { public init(validatingAddress bech32String: String) throws { self = try newLockerAddress(bech32: bech32String) } - - public func formatted(_ format: AddressFormat = .default) -> String { - lockerAddressFormatted(address: self, format: format) - } + + public func formatted(_ format: AddressFormat = .default) -> String { + lockerAddressFormatted(address: self, format: format) + } /// The bech32 encoded string for this address. public var address: String { @@ -17,16 +17,14 @@ extension LockerAddress { public var networkID: NetworkId { lockerAddressNetworkId(address: self) } - } #if DEBUG extension LockerAddress { - public static func random(networkID: NetworkID) -> Self { newLockerAddressRandom(networkId: networkID) } - + public func mapTo(networkID: NetworkID) -> Self { lockerAddressMapToNetwork(address: self, networkId: networkID) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/ManifestEncounteredAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/ManifestEncounteredAddress+Wrap+Functions.swift index 0eb51f42c..24fa66484 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/ManifestEncounteredAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/ManifestEncounteredAddress+Wrap+Functions.swift @@ -13,12 +13,10 @@ extension ManifestEncounteredComponentAddress { public var networkID: NetworkId { manifestEncounteredComponentAddressNetworkId(address: self) } - + public func formatted(_ format: AddressFormat) -> String { manifestEncounteredComponentAddressFormatted(address: self, format: format) } - - } #if DEBUG @@ -26,7 +24,7 @@ extension ManifestEncounteredComponentAddress { public static func random(networkID: NetworkID) -> Self { .component(newComponentAddressRandom(networkId: networkID)) } - + public func mapTo(networkID: NetworkID) -> Self { manifestEncounteredComponentAddressMapToNetwork(address: self, networkId: networkID) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/NonFungibleResourceAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/NonFungibleResourceAddress+Wrap+Functions.swift index 37e03f25c..205c1957a 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/NonFungibleResourceAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/NonFungibleResourceAddress+Wrap+Functions.swift @@ -13,29 +13,24 @@ extension NonFungibleResourceAddress { public var networkID: NetworkId { nonFungibleResourceAddressNetworkId(address: self) } - - public var asResourceAddress: ResourceAddress { - nonFungibleResourceAddressAsResourceAddress(address: self) - } - - public func formatted(_ format: AddressFormat = .default) -> String { - asResourceAddress.formatted(format) - } - - + public var asResourceAddress: ResourceAddress { + nonFungibleResourceAddressAsResourceAddress(address: self) + } + + public func formatted(_ format: AddressFormat = .default) -> String { + asResourceAddress.formatted(format) + } } #if DEBUG extension NonFungibleResourceAddress { - public static func random(networkID: NetworkID) -> Self { newNonFungibleResourceAddressRandom(networkId: networkID) } - + public func mapTo(networkID: NetworkID) -> Self { nonFungibleResourceAddressMapToNetwork(address: self, networkId: networkID) } - } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/PackageAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/PackageAddress+Wrap+Functions.swift index 60c13b2dc..c7f19b1b8 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/PackageAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/PackageAddress+Wrap+Functions.swift @@ -4,10 +4,10 @@ extension PackageAddress { public init(validatingAddress bech32String: String) throws { self = try newPackageAddress(bech32: bech32String) } - - public func formatted(_ format: AddressFormat = .default) -> String { - packageAddressFormatted(address: self, format: format) - } + + public func formatted(_ format: AddressFormat = .default) -> String { + packageAddressFormatted(address: self, format: format) + } /// The bech32 encoded string for this address. public var address: String { @@ -17,16 +17,14 @@ extension PackageAddress { public var networkID: NetworkId { packageAddressNetworkId(address: self) } - } #if DEBUG extension PackageAddress { - public static func random(networkID: NetworkID) -> Self { newPackageAddressRandom(networkId: networkID) } - + public func mapTo(networkID: NetworkID) -> Self { packageAddressMapToNetwork(address: self, networkId: networkID) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/PoolAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/PoolAddress+Wrap+Functions.swift index d7af91a78..fe8778c25 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/PoolAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/PoolAddress+Wrap+Functions.swift @@ -5,10 +5,10 @@ extension PoolAddress { self = try newPoolAddress(bech32: bech32String) } - public func formatted(_ format: AddressFormat = .default) -> String { - poolAddressFormatted(address: self, format: format) - } - + public func formatted(_ format: AddressFormat = .default) -> String { + poolAddressFormatted(address: self, format: format) + } + /// The bech32 encoded string for this address. public var address: String { poolAddressBech32Address(address: self) @@ -22,16 +22,14 @@ extension PoolAddress { public var poolKind: PoolKind { poolAddressKind(address: self) } - } #if DEBUG extension PoolAddress { - public static func random(networkID: NetworkID) -> Self { newPoolAddressRandom(networkId: networkID) } - + public func mapTo(networkID: NetworkID) -> Self { poolAddressMapToNetwork(address: self, networkId: networkID) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/ResourceAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/ResourceAddress+Wrap+Functions.swift index af699791f..c532022d8 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/ResourceAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/ResourceAddress+Wrap+Functions.swift @@ -13,10 +13,10 @@ extension ResourceAddress { public var networkID: NetworkId { resourceAddressNetworkId(address: self) } - - public func formatted(_ format: AddressFormat = .default) -> String { - resourceAddressFormatted(address: self, format: format) - } + + public func formatted(_ format: AddressFormat = .default) -> String { + resourceAddressFormatted(address: self, format: format) + } /// If this is an address of a **fungible** resource or not. public var isFungible: Bool { @@ -27,21 +27,19 @@ extension ResourceAddress { public var isNonFungible: Bool { resourceAddressIsNonFungible(address: self) } - + /// Returns the XRD resource on network identified by `networkID`. public static func xrd(on networkID: NetworkID) -> Self { xrdAddressOfNetwork(networkId: networkID) } - } #if DEBUG extension ResourceAddress { - public static func random(networkID: NetworkID) -> Self { newResourceAddressRandom(networkId: networkID) } - + public func mapTo(networkID: NetworkID) -> Self { resourceAddressMapToNetwork(address: self, networkId: networkID) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/ValidatorAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/ValidatorAddress+Wrap+Functions.swift index 3f4197c17..25b422de7 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/ValidatorAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/ValidatorAddress+Wrap+Functions.swift @@ -4,10 +4,10 @@ extension ValidatorAddress { public init(validatingAddress bech32String: String) throws { self = try newValidatorAddress(bech32: bech32String) } - - public func formatted(_ format: AddressFormat = .default) -> String { - validatorAddressFormatted(address: self, format: format) - } + + public func formatted(_ format: AddressFormat = .default) -> String { + validatorAddressFormatted(address: self, format: format) + } /// The bech32 encoded string for this address. public var address: String { @@ -17,16 +17,14 @@ extension ValidatorAddress { public var networkID: NetworkId { validatorAddressNetworkId(address: self) } - } #if DEBUG extension ValidatorAddress { - public static func random(networkID: NetworkID) -> Self { newValidatorAddressRandom(networkId: networkID) } - + public func mapTo(networkID: NetworkID) -> Self { validatorAddressMapToNetwork(address: self, networkId: networkID) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Address/VaultAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Address/VaultAddress+Wrap+Functions.swift index 0cc550dfc..b0329e0fb 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Address/VaultAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Address/VaultAddress+Wrap+Functions.swift @@ -4,10 +4,10 @@ extension VaultAddress { public init(validatingAddress bech32String: String) throws { self = try newVaultAddress(bech32: bech32String) } - - public func formatted(_ format: AddressFormat = .default) -> String { - vaultAddressFormatted(address: self, format: format) - } + + public func formatted(_ format: AddressFormat = .default) -> String { + vaultAddressFormatted(address: self, format: format) + } /// The bech32 encoded string for this address. public var address: String { @@ -27,16 +27,14 @@ extension VaultAddress { public var isNonFungible: Bool { vaultAddressIsNonFungible(address: self) } - } #if DEBUG extension VaultAddress { - public static func random(networkID: NetworkID) -> Self { newVaultAddressRandom(networkId: networkID) } - + public func mapTo(networkID: NetworkID) -> Self { vaultAddressMapToNetwork(address: self, networkId: networkID) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/AccountPath+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/AccountPath+Wrap+Functions.swift index eb1778d16..8837c7d09 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/AccountPath+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/AccountPath+Wrap+Functions.swift @@ -1,15 +1,8 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-18. -// - import Foundation import SargonUniFFI extension AccountPath { - public init(networkID: NetworkID, keyKind: Cap26KeyKind, index: Hardened) { + public init(networkID: NetworkID, keyKind: Cap26KeyKind, index: Hardened) { self = newAccountPath(networkId: networkID, keyKind: keyKind, index: index) } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/HdPathComponent+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/HdPathComponent+Wrap+Functions.swift index bc98578f1..ccd09b210 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/HdPathComponent+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/HdPathComponent+Wrap+Functions.swift @@ -1,37 +1,31 @@ -// -// HdPathComponent+Wrap+Functions.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI extension HdPathComponent { - public func toBIP32String() -> String { - hdPathComponentToBip32String(component: self) - } - public func toBIP32StringDebug() -> String { - hdPathComponentToBip32StringDebug(component: self) - } + public func toBIP32String() -> String { + hdPathComponentToBip32String(component: self) + } + + public func toBIP32StringDebug() -> String { + hdPathComponentToBip32StringDebug(component: self) + } + + public init(globalKeySpace: UInt32) { + self = newHdPathComponentFromGlobalKeySpace(value: globalKeySpace) + } + + public init(localKeySpace: UInt32, keySpace: KeySpace) throws { + self = try newHdPathComponentFromLocalKeySpace(value: localKeySpace, keySpace: keySpace) + } + + public var keySpace: KeySpace { + hdPathComponentGetKeySpace(component: self) + } + + public func indexInGlobalKeySpace() -> UInt32 { + hdPathComponentIndexInGlobalKeySpace(component: self) + } - public init(globalKeySpace: UInt32) { - self = newHdPathComponentFromGlobalKeySpace(value: globalKeySpace) - } - - public init(localKeySpace: UInt32, keySpace: KeySpace) throws { - self = try newHdPathComponentFromLocalKeySpace(value: localKeySpace, keySpace: keySpace) - } - - public var keySpace: KeySpace { - hdPathComponentGetKeySpace(component: self) - } - - public func indexInGlobalKeySpace() -> UInt32 { - hdPathComponentIndexInGlobalKeySpace(component: self) - } - - public func indexInLocalKeySpace() -> UInt32 { - hdPathComponentIndexInLocalKeySpace(component: self) - } + public func indexInLocalKeySpace() -> UInt32 { + hdPathComponentIndexInLocalKeySpace(component: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/Securified+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/Securified+Wrap+Functions.swift index 70c130245..fb55fb820 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/Securified+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/Securified+Wrap+Functions.swift @@ -1,33 +1,25 @@ -// -// Securified+Wrap+Functions.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI - extension SecurifiedU30 { - public static let globalOffset: UInt32 = bip32ConstantGlobalOffsetSecurified() - - public init(u30: U30) { - self = newSecurified(u30: u30) - } - - public init(localKeySpace: UInt32) throws { - self = try newSecurifiedFromLocalKeySpace(value: localKeySpace) - } - - public init(globalKeySpace: UInt32) throws { - self = try newSecurifiedFromGlobalKeySpace(value: globalKeySpace) - } - - public func indexInLocalKeySpace() -> UInt32 { - securifiedIndexInLocalKeySpace(securified: self) - } - - public func indexInGlobalKeySpace() -> UInt32 { - securifiedIndexInGlobalKeySpace(securified: self) - } + public static let globalOffset: UInt32 = bip32ConstantGlobalOffsetSecurified() + + public init(u30: U30) { + self = newSecurified(u30: u30) + } + + public init(localKeySpace: UInt32) throws { + self = try newSecurifiedFromLocalKeySpace(value: localKeySpace) + } + + public init(globalKeySpace: UInt32) throws { + self = try newSecurifiedFromGlobalKeySpace(value: globalKeySpace) + } + + public func indexInLocalKeySpace() -> UInt32 { + securifiedIndexInLocalKeySpace(securified: self) + } + + public func indexInGlobalKeySpace() -> UInt32 { + securifiedIndexInGlobalKeySpace(securified: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/U30+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/U30+Wrap+Functions.swift index c6c7e2c1a..54770226e 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/U30+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/U30+Wrap+Functions.swift @@ -1,20 +1,11 @@ -// -// U30+Wrap+Functions.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI - extension U30 { - public init(value: UInt32) throws { - self = try newU30(value: value) - } - public var value: UInt32 { - u30GetValue(u30: self) - } -} - + public init(value: UInt32) throws { + self = try newU30(value: value) + } + public var value: UInt32 { + u30GetValue(u30: self) + } +} diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/U31+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/U31+Wrap+Functions.swift index 6d3e7f79f..b1941d1fb 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/U31+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/U31+Wrap+Functions.swift @@ -1,18 +1,11 @@ -// -// U31+Wrap+Functions.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI extension U31 { - public init(value: UInt32) throws { - self = try newU31(value: value) - } - public var value: UInt32 { - u31GetValue(u31: self) - } -} + public init(value: UInt32) throws { + self = try newU31(value: value) + } + public var value: UInt32 { + u31GetValue(u31: self) + } +} diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/Unhardened+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/Unhardened+Wrap+Functions.swift index 26963132d..4742c35dc 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/Unhardened+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/Unhardened+Wrap+Functions.swift @@ -1,34 +1,25 @@ -// -// Unhardened+Wrap+Functions.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI - extension Unhardened { - - public static let globalOffset: UInt32 = 0 - - public init(u31: U31) { - self = newUnhardened(u31: u31) - } + public static let globalOffset: UInt32 = 0 + + public init(u31: U31) { + self = newUnhardened(u31: u31) + } + + public init(localKeySpace: UInt32) throws { + self = try newUnhardenedFromLocalKeySpace(value: localKeySpace) + } - public init(localKeySpace: UInt32) throws { - self = try newUnhardenedFromLocalKeySpace(value: localKeySpace) - } - - public init(globalKeySpace: UInt32) throws { - self = try newUnhardenedFromGlobalKeySpace(value: globalKeySpace) - } + public init(globalKeySpace: UInt32) throws { + self = try newUnhardenedFromGlobalKeySpace(value: globalKeySpace) + } - public func indexInLocalKeySpace() -> UInt32 { - unhardenedIndexInLocalKeySpace(unhardened: self) - } + public func indexInLocalKeySpace() -> UInt32 { + unhardenedIndexInLocalKeySpace(unhardened: self) + } - public func indexInGlobalKeySpace() -> UInt32 { - unhardenedIndexInGlobalKeySpace(unhardened: self) - } + public func indexInGlobalKeySpace() -> UInt32 { + unhardenedIndexInGlobalKeySpace(unhardened: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/UnsecurifiedHardened+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/UnsecurifiedHardened+Wrap+Functions.swift index 8ad5cf9b1..d49caa5fe 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/UnsecurifiedHardened+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP32/UnsecurifiedHardened+Wrap+Functions.swift @@ -1,33 +1,25 @@ -// -// UnsecurifiedHardened+Wrap+Functions.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI extension UnsecurifiedHardened { - - public static let globalOffset: UInt32 = bip32ConstantGlobalOffsetHardened() - - public init(u30: U30) { - self = newUnsecurifiedHardened(u30: u30) - } + public static let globalOffset: UInt32 = bip32ConstantGlobalOffsetHardened() + + public init(u30: U30) { + self = newUnsecurifiedHardened(u30: u30) + } + + public init(localKeySpace: UInt32) throws { + self = try newUnsecurifiedHardenedFromLocalKeySpace(value: localKeySpace) + } - public init(localKeySpace: UInt32) throws { - self = try newUnsecurifiedHardenedFromLocalKeySpace(value: localKeySpace) - } - - public init(globalKeySpace: UInt32) throws { - self = try newUnsecurifiedHardenedFromGlobalKeySpace(value: globalKeySpace) - } + public init(globalKeySpace: UInt32) throws { + self = try newUnsecurifiedHardenedFromGlobalKeySpace(value: globalKeySpace) + } - public func indexInLocalKeySpace() -> UInt32 { - unsecurifiedHardenedIndexInLocalKeySpace(unsecurifiedHardened: self) - } + public func indexInLocalKeySpace() -> UInt32 { + unsecurifiedHardenedIndexInLocalKeySpace(unsecurifiedHardened: self) + } - public func indexInGlobalKeySpace() -> UInt32 { - unsecurifiedHardenedIndexInGlobalKeySpace(unsecurifiedHardened: self) - } + public func indexInGlobalKeySpace() -> UInt32 { + unsecurifiedHardenedIndexInGlobalKeySpace(unsecurifiedHardened: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP39/BIP39Language+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP39/BIP39Language+Wrap+Functions.swift index 86d2ac2b9..8aa6bade9 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP39/BIP39Language+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP39/BIP39Language+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP39/BIP39WordCount+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP39/BIP39WordCount+Wrap+Functions.swift index 738d4f8fe..3055a204f 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP39/BIP39WordCount+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP39/BIP39WordCount+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP44LikePath+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP44LikePath+Wrap+Functions.swift index fc4a096e7..32831422e 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP44LikePath+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/BIP44LikePath+Wrap+Functions.swift @@ -3,19 +3,19 @@ import SargonUniFFI public typealias HDPathValue = UInt32 extension BIP44LikePath { - public init(string: String) throws { - self = try newBip44LikePathFromString(string: string) - } - - public func toString() -> String { - bip44LikePathToString(path: self) - } - + public init(string: String) throws { + self = try newBip44LikePathFromString(string: string) + } + + public func toString() -> String { + bip44LikePathToString(path: self) + } + public init(index: HdPathComponent) { self = newBip44LikePathFromIndex(index: index) } - + public var addressIndex: HdPathComponent { - bip44LikePathGetAddressIndex(path: self) + bip44LikePathGetAddressIndex(path: self) } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/DerivationPath+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/DerivationPath+Wrap+Functions.swift index 25d80d04e..3128f49a2 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/DerivationPath+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/DerivationPath+Wrap+Functions.swift @@ -1,24 +1,16 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI extension DerivationPath { - public var path: HDPath { - derivationPathToHdPath(path: self) - } - - public func toString() -> String { - derivationPathToString(path: self) - } - - public init(string: String) throws { - self = try newDerivationPathFromString(string: string) - } + public var path: HDPath { + derivationPathToHdPath(path: self) + } + + public func toString() -> String { + derivationPathToString(path: self) + } + public init(string: String) throws { + self = try newDerivationPathFromString(string: string) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/IdentityPath+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/IdentityPath+Wrap+Functions.swift index 2ce28a285..ae07df848 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/IdentityPath+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/IdentityPath+Wrap+Functions.swift @@ -1,15 +1,8 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-18. -// - import Foundation import SargonUniFFI extension IdentityPath { - public init(networkID: NetworkID, keyKind: Cap26KeyKind, index: Hardened) { + public init(networkID: NetworkID, keyKind: Cap26KeyKind, index: Hardened) { self = newIdentityPath(networkId: networkID, keyKind: keyKind, index: index) } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/Mnemonic+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/Mnemonic+Wrap+Functions.swift index 78d5d143b..30c1ae919 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/Mnemonic+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/Mnemonic+Wrap+Functions.swift @@ -1,13 +1,13 @@ -import SargonUniFFI import Foundation +import SargonUniFFI extension Mnemonic { public var phrase: String { mnemonicPhrase(from: self) } - + public init(wordCount: BIP39WordCount, language: BIP39Language) { - let entropy: BIP39Entropy = switch wordCount { + let entropy = switch wordCount { case .twentyFour: BIP39Entropy.entropyOf32Bytes(.generate()) case .twentyOne: @@ -19,10 +19,10 @@ extension Mnemonic { case .twelve: BIP39Entropy.entropyOf16Bytes(.generate()) } - + self = newMnemonicGenerateWithEntropy(entropy: entropy, language: language) } - + public init(phrase: String, language: BIP39Language? = nil) throws { if let language { self = try newMnemonicFromPhraseLanguage(phrase: phrase, language: language) @@ -30,9 +30,8 @@ extension Mnemonic { self = try newMnemonicFromPhrase(phrase: phrase) } } - + public init(words: some Collection) throws { self = try newMnemonicFromWords(words: Array(words)) } - } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/MnemonicWithPassphrase+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/MnemonicWithPassphrase+Wrap+Functions.swift index 6cf8a1362..279119cfa 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/MnemonicWithPassphrase+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Derivation/MnemonicWithPassphrase+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI @@ -14,31 +7,31 @@ extension MnemonicWithPassphrase { jsonBytes: Data(jsonData) ) } - + public func jsonData() -> Data { mnemonicWithPassphraseToJsonBytes( mnemonicWithPassphrase: self ) } - - public func validate( - publicKeys: some Collection - ) -> Bool { + + public func validate( + publicKeys: some Collection + ) -> Bool { mnemonicWithPassphraseValidatePublicKeys( mnemonicWithPassphrase: self, hdKeys: Array(publicKeys) ) - } - + } + public func derivePublicKeys( paths: some Collection ) -> [HierarchicalDeterministicPublicKey] { mnemonicWithPassphraseDerivePublicKeys( mnemonicWithPassphrase: self, - derivationPaths: paths.map(\.asGeneral) + derivationPaths: paths.map(\.asGeneral) ) } - + public func sign( hash: Hash, path: some DerivationPathProtocol diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Hash/Hash+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Hash/Hash+Wrap+Functions.swift index 576da92e7..35c71d055 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Hash/Hash+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Hash/Hash+Wrap+Functions.swift @@ -11,12 +11,12 @@ extension Hash { public var bytes: Exactly32Bytes { hashGetBytes(hash: self) } - - public init(string: String) throws { - self = try newHashFromString(string: string) - } - - public init(bytes32: Exactly32Bytes) { - self = newHashFromBytes(bytes: bytes32) - } + + public init(string: String) throws { + self = try newHashFromString(string: string) + } + + public init(bytes32: Exactly32Bytes) { + self = newHashFromBytes(bytes: bytes32) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Hash/SignedTransactionIntentHash+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Hash/SignedTransactionIntentHash+Wrap+Functions.swift index e5df72b39..fbc9f5d70 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Hash/SignedTransactionIntentHash+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Hash/SignedTransactionIntentHash+Wrap+Functions.swift @@ -1,11 +1,11 @@ import SargonUniFFI extension SignedTransactionIntentHash { - public init(_ string: String) throws { - self = try newSignedTransactionIntentHashFromString(string: string) - } - - public func formatted(_ format: AddressFormat = .default) -> String { - signedTransactionIntentHashFormatted(address: self, format: format) - } + public init(_ string: String) throws { + self = try newSignedTransactionIntentHashFromString(string: string) + } + + public func formatted(_ format: AddressFormat = .default) -> String { + signedTransactionIntentHashFormatted(address: self, format: format) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Hash/TransactionIntentHash+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Hash/TransactionIntentHash+Wrap+Functions.swift index 9afeb6b47..088e45172 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Hash/TransactionIntentHash+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Hash/TransactionIntentHash+Wrap+Functions.swift @@ -1,10 +1,10 @@ import SargonUniFFI extension TransactionIntentHash { - public init(_ string: String) throws { - self = try newTransactionIntentHashFromString(string: string) - } - + public init(_ string: String) throws { + self = try newTransactionIntentHashFromString(string: string) + } + public func formatted(_ format: AddressFormat = .default) -> String { transactionIntentHashFormatted(address: self, format: format) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/IntentDiscriminator+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/IntentDiscriminator+Wrap+Functions.swift index 074c31d5d..37b65e817 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/IntentDiscriminator+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/IntentDiscriminator+Wrap+Functions.swift @@ -4,7 +4,7 @@ extension IntentDiscriminator { public static func secureRandom() -> Self { newIntentDiscriminatorRandom() } - + public var value: UInt64 { intentDiscriminatorGetValue(intentDiscriminator: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/Ed25519PublicKey+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/Ed25519PublicKey+Wrap+Functions.swift index 387a18fab..72e095038 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/Ed25519PublicKey+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/Ed25519PublicKey+Wrap+Functions.swift @@ -3,34 +3,34 @@ import SargonUniFFI // MARK: Initializers extension Ed25519PublicKey { - public init(hex: String) throws { - // Rust: `new_ed25519_public_key_from_hex` - self = try newEd25519PublicKeyFromHex(hex: hex) - } - - public init(bytes: some DataProtocol) throws { - // Rust: `new_ed25519_public_key_from_bytes` - self = try newEd25519PublicKeyFromBytes(bytes: Data(bytes)) - } - - public init(jsonStringLiteral: String) throws { - self = try newEd25519PublicKeyFromJsonString(jsonString: jsonStringLiteral) - } - - public func jsonStringLiteral() -> String { + public init(hex: String) throws { + // Rust: `new_ed25519_public_key_from_hex` + self = try newEd25519PublicKeyFromHex(hex: hex) + } + + public init(bytes: some DataProtocol) throws { + // Rust: `new_ed25519_public_key_from_bytes` + self = try newEd25519PublicKeyFromBytes(bytes: Data(bytes)) + } + + public init(jsonStringLiteral: String) throws { + self = try newEd25519PublicKeyFromJsonString(jsonString: jsonStringLiteral) + } + + public func jsonStringLiteral() -> String { ed25519PublicKeyToJsonString(ed25519PublicKey: self) - } + } } // MARK: Func -> Method / Computed Prop extension Ed25519PublicKey { - public var hex: String { - // Rust: `ed25519_public_key_to_hex` - ed25519PublicKeyToHex(publicKey: self) - } - - public var data: Data { - // Rust: `ed25519_public_key_to_bytes` - ed25519PublicKeyToBytes(publicKey: self) - } + public var hex: String { + // Rust: `ed25519_public_key_to_hex` + ed25519PublicKeyToHex(publicKey: self) + } + + public var data: Data { + // Rust: `ed25519_public_key_to_bytes` + ed25519PublicKeyToBytes(publicKey: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/HierarchicalDeterministicPublicKey+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/HierarchicalDeterministicPublicKey+Wrap+Functions.swift index bdb4048d7..0caca1cb2 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/HierarchicalDeterministicPublicKey+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/HierarchicalDeterministicPublicKey+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-20. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/PrivateHD+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/PrivateHD+Wrap+Functions.swift index ff861c2c7..bb60cc484 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/PrivateHD+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/PrivateHD+Wrap+Functions.swift @@ -1,15 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI extension PrivateHierarchicalDeterministicFactorSource { - public static func olympia( mnemonicWithPassphrase: MnemonicWithPassphrase, hostInfo: HostInfo @@ -19,7 +11,7 @@ extension PrivateHierarchicalDeterministicFactorSource { hostInfo: hostInfo ) } - + public static func babylon( isMainBDFS: Bool, mnemonicWithPassphrase: MnemonicWithPassphrase, diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/PublicKey+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/PublicKey+Wrap+Functions.swift index d4ada10eb..94038337e 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/PublicKey+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/PublicKey+Wrap+Functions.swift @@ -5,19 +5,19 @@ extension PublicKey { public init(hex: String) throws { self = try newPublicKeyFromHex(hex: hex) } - + public init(bytes: some DataProtocol) throws { self = try newPublicKeyFromBytes(bagOfBytes: Data(bytes)) } - + public var data: Data { publicKeyToBytes(publicKey: self) } - + public var hex: String { publicKeyToHex(publicKey: self) } - + public func isValidSignature( _ intoSignature: IntoSignatureProtocol, for hashedMessage: Hash @@ -29,4 +29,3 @@ extension PublicKey { ) } } - diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/Secp256k1PublicKey+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/Secp256k1PublicKey+Wrap+Functions.swift index a77e377ca..77d1d16af 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/Secp256k1PublicKey+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Keys/Secp256k1PublicKey+Wrap+Functions.swift @@ -7,7 +7,7 @@ extension Secp256k1PublicKey { // Rust: `new_secp256k1_public_key_from_hex` self = try newSecp256k1PublicKeyFromHex(hex: hex) } - + public init(bytes: some DataProtocol) throws { // Rust: `new_secp256k1_public_key_from_bytes` self = try newSecp256k1PublicKeyFromBytes(bytes: Data(bytes)) @@ -16,36 +16,35 @@ extension Secp256k1PublicKey { // MARK: Func -> Method / Computed Prop extension Secp256k1PublicKey { - - /// Returns the public key on **compressed** form (33 bytes) as - /// a hexadecimal string (66 chars). - /// - /// You can use `uncompressedData.hex` for uncompressed hex string. + /// Returns the public key on **compressed** form (33 bytes) as + /// a hexadecimal string (66 chars). + /// + /// You can use `uncompressedData.hex` for uncompressed hex string. public var hex: String { // Rust: `secp256k1_public_key_to_hex` secp256k1PublicKeyToHex(publicKey: self) } - - /// Returns the key on **compressed** form (33 bytes) - /// - /// Use `uncompressedData` for uncompressed format (65 bytes) - public var data: Data { - compressedData - } - - /// Returns the key on **compressed** form (33 bytes) - /// - /// Use `uncompressedData` for uncompressed format (65 bytes) + + /// Returns the key on **compressed** form (33 bytes) + /// + /// Use `uncompressedData` for uncompressed format (65 bytes) + public var data: Data { + compressedData + } + + /// Returns the key on **compressed** form (33 bytes) + /// + /// Use `uncompressedData` for uncompressed format (65 bytes) public var compressedData: Data { // Rust: `secp256k1_public_key_to_bytes` secp256k1PublicKeyToBytes(publicKey: self) } - - /// Returns the key on **uncompressed** form (65 bytes) - /// - /// Use `compressedData` for compressed format (33 bytes) - public var uncompressedData: Data { - // Rust: `secp256k1_public_key_to_bytes_uncompressed` - secp256k1PublicKeyToBytesUncompressed(publicKey: self) - } + + /// Returns the key on **uncompressed** form (65 bytes) + /// + /// Use `compressedData` for compressed format (33 bytes) + public var uncompressedData: Data { + // Rust: `secp256k1_public_key_to_bytes_uncompressed` + secp256k1PublicKeyToBytesUncompressed(publicKey: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Nonce+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Nonce+Wrap+Functions.swift index 74c9911fa..d4a5c8241 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Nonce+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Nonce+Wrap+Functions.swift @@ -1,11 +1,11 @@ import SargonUniFFI extension Nonce { - public static func secureRandom() -> Self { - newNonceRandom() - } - - public var value: UInt32 { - nonceGetValue(nonce: self) - } + public static func secureRandom() -> Self { + newNonceRandom() + } + + public var value: UInt32 { + nonceGetValue(nonce: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/SLIP10Curve+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/SLIP10Curve+Wrap+Functions.swift index 7cfdf8ad8..1d279756f 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/SLIP10Curve+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/SLIP10Curve+Wrap+Functions.swift @@ -4,17 +4,16 @@ extension SLIP10Curve { public init(_ string: String) throws { self = try newSlip10CurveFromString(curve: string) } - + public func toString() -> String { slip10CurveToString(curve: self) } - // SLIP10Curve -> SargonStringCodable public init(jsonStringLiteral: String) throws { self = try newSLIP10CurveFromJsonString(jsonString: jsonStringLiteral) } - + public func jsonStringLiteral() -> String { sLIP10CurveToJsonString(sLIP10Curve: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/Ed25519Signature+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/Ed25519Signature+Wrap+Functions.swift index 2ef8cf9ce..54eae7d58 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/Ed25519Signature+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/Ed25519Signature+Wrap+Functions.swift @@ -5,21 +5,20 @@ extension Ed25519Signature { public init(bytes: some DataProtocol) throws { self = try newEd25519SignatureFromBytes(bytes: Data(bytes)) } - + public init(exactly exactly64Bytes: Exactly64Bytes) { self = newEd25519SignatureFromExactly64Bytes(bytes: exactly64Bytes) } public init(jsonStringLiteral: String) throws { - self = try newEd25519SignatureFromJsonString(jsonString: jsonStringLiteral) - } - - public func jsonStringLiteral() -> String { + self = try newEd25519SignatureFromJsonString(jsonString: jsonStringLiteral) + } + + public func jsonStringLiteral() -> String { ed25519SignatureToJsonString(ed25519Signature: self) - } - + } + public func toString() -> String { ed25519SignatureToString(signature: self) } - } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/Secp256k1Signature+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/Secp256k1Signature+Wrap+Functions.swift index 5f537b777..3a6d4eba1 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/Secp256k1Signature+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/Secp256k1Signature+Wrap+Functions.swift @@ -5,13 +5,12 @@ extension Secp256k1Signature { public init(bytes: some DataProtocol) throws { self = try newSecp256k1SignatureFromBytes(bytes: Data(bytes)) } - + public init(exactly exactly65Bytes: Exactly65Bytes) { self = newSecp256k1SignatureFromExactly65Bytes(bytes: exactly65Bytes) } - + public func toString() -> String { secp256k1SignatureToString(signature: self) } - } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/Signature+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/Signature+Wrap+Functions.swift index 0e25dc051..3c545a60d 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/Signature+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/Signature+Wrap+Functions.swift @@ -5,11 +5,11 @@ extension Signature { public init(bytes: some DataProtocol) throws { self = try newSignatureFromBytes(bytes: Data(bytes)) } - + public func toString() -> String { signatureToString(signature: self) } - + public func toBytes() -> Data { signatureToBytes(signature: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/SignatureWithPublicKey+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/SignatureWithPublicKey+Wrap+Functions.swift index 73aa2770b..5cfdbd3ae 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/SignatureWithPublicKey+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Crypto/Signatures/SignatureWithPublicKey+Wrap+Functions.swift @@ -4,12 +4,12 @@ extension SignatureWithPublicKey { public var signature: Signature { signatureWithPublicKeyGetSignature(signatureWithPublicKey: self) } - + public var publicKey: PublicKey { signatureWithPublicKeyGetPublicKey(signatureWithPublicKey: self) } - + public func isValid(_ hash: Hash) -> Bool { - signatureWithPublicKeyIsValid(signatureWithPublicKey: self, forHash: hash) + signatureWithPublicKeyIsValid(signatureWithPublicKey: self, forHash: hash) } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy16Bytes+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy16Bytes+Wrap+Functions.swift index 3dcdd1db8..6bab8a2eb 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy16Bytes+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy16Bytes+Wrap+Functions.swift @@ -1,19 +1,11 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-25. -// - import Foundation import SargonUniFFI extension Entropy16Bytes { - public init(bytes: some DataProtocol) throws { self = try newEntropy16BytesFromBytes(bytes: Data(bytes)) } - + public var data: Data { entropy16BytesToBytes(bytes: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy20Bytes+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy20Bytes+Wrap+Functions.swift index 302c2b5ca..e84b38a14 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy20Bytes+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy20Bytes+Wrap+Functions.swift @@ -1,21 +1,12 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-25. -// - import Foundation import SargonUniFFI extension Entropy20Bytes { - public init(bytes: some DataProtocol) throws { self = try newEntropy20BytesFromBytes(bytes: Data(bytes)) } - + public var data: Data { entropy20BytesToBytes(bytes: self) } } - diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy24Bytes+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy24Bytes+Wrap+Functions.swift index 39415f5af..4a66ee5fa 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy24Bytes+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy24Bytes+Wrap+Functions.swift @@ -5,7 +5,7 @@ extension Entropy24Bytes { public init(bytes: some DataProtocol) throws { self = try newEntropy24BytesFromBytes(bytes: Data(bytes)) } - + public var data: Data { entropy24BytesToBytes(bytes: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy28Bytes+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy28Bytes+Wrap+Functions.swift index eb36dbca9..615d93112 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy28Bytes+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy28Bytes+Wrap+Functions.swift @@ -5,7 +5,7 @@ extension Entropy28Bytes { public init(bytes: some DataProtocol) throws { self = try newEntropy28BytesFromBytes(bytes: Data(bytes)) } - + public var data: Data { entropy28BytesToBytes(bytes: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy32Bytes+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy32Bytes+Wrap+Functions.swift index 59a7e48dc..797bf3719 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy32Bytes+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Entropy32Bytes+Wrap+Functions.swift @@ -5,9 +5,8 @@ extension Entropy32Bytes { public init(bytes: some DataProtocol) throws { self = try newEntropy32BytesFromBytes(bytes: Data(bytes)) } - + public var data: Data { entropy32BytesToBytes(bytes: self) } } - diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly29Bytes+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly29Bytes+Wrap+Functions.swift index 95fb0a842..eba355c32 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly29Bytes+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly29Bytes+Wrap+Functions.swift @@ -2,17 +2,15 @@ import Foundation import SargonUniFFI extension Exactly29Bytes { - public init(bytes: some DataProtocol) throws { self = try newExactly29Bytes(bytes: BagOfBytes(bytes)) } - + public var data: Data { exactly29BytesToBytes(bytes: self) } - + public var hex: String { exactly29BytesToHex(bytes: self) } } - diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly32Bytes+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly32Bytes+Wrap+Functions.swift index ed90c3112..626feab90 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly32Bytes+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly32Bytes+Wrap+Functions.swift @@ -2,7 +2,6 @@ import Foundation import SargonUniFFI extension Exactly32Bytes { - public func jsonStringLiteral() -> String { exactly32BytesToJsonString(exactly32Bytes: self) } @@ -14,17 +13,16 @@ extension Exactly32Bytes { jsonString: jsonStringLiteral ) } - + public init(bytes: some DataProtocol) throws { self = try newExactly32Bytes(bytes: BagOfBytes(bytes)) } - + public var data: Data { exactly32BytesToBytes(bytes: self) } - + public var hex: String { exactly32BytesToHex(bytes: self) } } - diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly33Bytes+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly33Bytes+Wrap+Functions.swift index 3f0786746..7e9b13188 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly33Bytes+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly33Bytes+Wrap+Functions.swift @@ -2,17 +2,15 @@ import Foundation import SargonUniFFI extension Exactly33Bytes { - public init(bytes: some DataProtocol) throws { self = try newExactly33Bytes(bytes: BagOfBytes(bytes)) } - + public var data: Data { exactly33BytesToBytes(bytes: self) } - + public var hex: String { exactly33BytesToHex(bytes: self) } } - diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly64Bytes+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly64Bytes+Wrap+Functions.swift index 3f220a184..b1a854a07 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly64Bytes+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly64Bytes+Wrap+Functions.swift @@ -2,17 +2,15 @@ import Foundation import SargonUniFFI extension Exactly64Bytes { - public init(bytes: some DataProtocol) throws { self = try newExactly64Bytes(bytes: BagOfBytes(bytes)) } - + public var data: Data { exactly64BytesToBytes(bytes: self) } - + public var hex: String { exactly64BytesToHex(bytes: self) } } - diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly65Bytes+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly65Bytes+Wrap+Functions.swift index 8c5f54faf..8de749b36 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly65Bytes+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/Bytes/Exactly65Bytes+Wrap+Functions.swift @@ -2,17 +2,15 @@ import Foundation import SargonUniFFI extension Exactly65Bytes { - public init(bytes: some DataProtocol) throws { self = try newExactly65Bytes(bytes: BagOfBytes(bytes)) } - + public var data: Data { exactly65BytesToBytes(bytes: self) } - + public var hex: String { exactly65BytesToHex(bytes: self) } } - diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/Decimal192+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/Decimal192+Wrap+Functions.swift index 09f1bfb14..2ccb22ea9 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/Decimal192+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/Decimal192+Wrap+Functions.swift @@ -6,32 +6,30 @@ import XCTestDynamicOverlay #endif // DEBUG extension Decimal192 { - public init(_ string: String) throws { self = try newDecimalFromString(string: string) } - + public init(_ float32: Float32) { self = newDecimalFromF32(value: float32) } - - public init(_ double: Double) throws { - self = try newDecimalFromF64(value: double) - } - + + public init(_ double: Double) throws { + self = try newDecimalFromF64(value: double) + } + public init(_ value: Int64) { self = newDecimalFromI64(value: value) } - + public init(_ value: UInt64) { self = newDecimalFromU64(value: value) } - + /// Creates the Decimal `10^exponent` public init(exponent: UInt8) { self = newDecimalExponent(exponent: exponent) } - } #if DEBUG @@ -40,39 +38,40 @@ extension Locale { } #endif // DEBUG +// MARK: - Decimal192 + CustomStringConvertible extension Decimal192: CustomStringConvertible { public var description: String { -#if DEBUG + #if DEBUG if !_XCTIsTesting { formattedPlain() } else { formattedPlain(locale: .test, useGroupingSeparator: false) } -#else + #else formattedPlain() -#endif // DEBUG + #endif // DEBUG } } +// MARK: - Decimal192 + CustomDebugStringConvertible extension Decimal192: CustomDebugStringConvertible { public var debugDescription: String { -#if DEBUG + #if DEBUG if !_XCTIsTesting { formattedPlain() } else { formattedPlain(locale: .test, useGroupingSeparator: false) } -#else + #else formattedPlain() -#endif // DEBUG + #endif // DEBUG } } - extension Decimal192 { public static let maxDivisibility: UInt8 = 18 - - public static let temporaryStandardFee: Self = transactionFeePreset() + + public static let temporaryStandardFee: Self = transactionFeePreset() } extension Decimal192 { @@ -81,7 +80,7 @@ extension Decimal192 { formattedString: String, locale: Locale = .autoupdatingCurrent ) throws { - let localConfig: LocaleConfig = LocaleConfig(locale: locale) + let localConfig = LocaleConfig(locale: locale) self = try newDecimalFromFormattedString( formattedString: formattedString, locale: localConfig @@ -91,7 +90,6 @@ extension Decimal192 { // MARK: Formatting extension Decimal192 { - /// A human readable, locale respecting string, rounded to `totalPlaces` places, counting all digits public func formatted( locale: Locale = .autoupdatingCurrent, @@ -121,7 +119,6 @@ extension Decimal192 { // MARK: Truncation and rounding extension Decimal192 { - private func rounded(decimalPlaces: UInt8, roundingMode: RoundingMode) -> Self { try! decimalRound( decimal: self, @@ -147,7 +144,6 @@ extension Decimal192 { public func ceil(decimalPlaces: UInt8) -> Self { rounded(decimalPlaces: decimalPlaces, roundingMode: .awayFromZero) } - } extension Decimal192 { @@ -158,18 +154,17 @@ extension Decimal192 { public var isNegative: Bool { decimalIsNegative(decimal: self) } - + public var isPositive: Bool { decimalIsPositive(decimal: self) } - + public var isZero: Bool { decimalIsZero(decimal: self) } } extension Decimal192 { - public func lessThan(other: Self) -> Bool { decimalLessThan(lhs: self, rhs: other) } @@ -188,31 +183,30 @@ extension Decimal192 { } extension Decimal192 { - public static var zero: Self { newDecimalFromU64(value: 0) } - + public func add(rhs: Self) -> Self { decimalAdd(lhs: self, rhs: rhs) } - + public func sub(rhs: Self) -> Self { decimalSub(lhs: self, rhs: rhs) } - + public func mul(rhs: Self) -> Self { decimalMul(lhs: self, rhs: rhs) } - + public func div(rhs: Self) -> Self { decimalDiv(lhs: self, rhs: rhs) } - + public func abs() -> Self { decimalAbs(decimal: self) } - + public func negate() -> Self { decimalNeg(decimal: self) } @@ -223,7 +217,7 @@ extension Decimal192 { public static var max: Self { decimalMax() } - + /// Negative value public static var min: Self { decimalMin() diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/DisplayName+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/DisplayName+Wrap+Functions.swift index e20e27cf4..d70af39b4 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/DisplayName+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/DisplayName+Wrap+Functions.swift @@ -6,11 +6,11 @@ extension DisplayName { self = try newDisplayName(name: name) } - public init(jsonStringLiteral: String) throws { - self = try newDisplayNameFromJsonString(jsonString: jsonStringLiteral) - } - - public func jsonStringLiteral() -> String { + public init(jsonStringLiteral: String) throws { + self = try newDisplayNameFromJsonString(jsonString: jsonStringLiteral) + } + + public func jsonStringLiteral() -> String { displayNameToJsonString(displayName: self) - } + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/NetworkDefinition+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/NetworkDefinition+Wrap+Functions.swift index 20941c267..982d4e0b7 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/NetworkDefinition+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/NetworkDefinition+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI @@ -13,4 +6,3 @@ extension NetworkDefinition { try newNetworkDefinitionLookupByName(logicalName: logicalName) } } - diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/NetworkID+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/NetworkID+Wrap+Functions.swift index f826f5bff..967bc6f9c 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/NetworkID+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/NetworkID+Wrap+Functions.swift @@ -4,13 +4,12 @@ extension NetworkID: CaseIterable { public init(discriminant: UInt8) throws { self = try newNetworkIdFromDiscriminant(discriminant: discriminant) } - + public static var allCases: [Self] { networkIdsAll() } - + public func toString() -> String { networkIdToString(id: self) - } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/NonFungibleGlobalID+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/NonFungibleGlobalID+Wrap+Functions.swift index a5335f75a..982a6424b 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/NonFungibleGlobalID+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/NonFungibleGlobalID+Wrap+Functions.swift @@ -1,15 +1,15 @@ import SargonUniFFI extension NonFungibleGlobalID { - public init(_ string: String) throws { - self = try newNonFungibleGlobalIdFromString(string: string) - } - - public func toRawString() -> String { - nonFungibleGlobalIdToString(globalId: self) - } - - public func formatted(_ format: AddressFormat = .default) -> String { - nonFungibleGlobalIdFormatted(globalId: self, format: format) - } + public init(_ string: String) throws { + self = try newNonFungibleGlobalIdFromString(string: string) + } + + public func toRawString() -> String { + nonFungibleGlobalIdToString(globalId: self) + } + + public func formatted(_ format: AddressFormat = .default) -> String { + nonFungibleGlobalIdFormatted(globalId: self, format: format) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/NonFungibleLocalID+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/NonFungibleLocalID+Wrap+Functions.swift index eb19c743f..78b3815a1 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/NonFungibleLocalID+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/NonFungibleLocalID+Wrap+Functions.swift @@ -5,43 +5,43 @@ extension NonFungibleLocalID { public func toRawString() -> String { nonFungibleLocalIdAsStr(id: self) } - + public init(integer value: UInt64) { self = newNonFungibleLocalIdInt(value: value) } - - public func formatted(_ format: AddressFormat = .default) -> String { - nonFungibleLocalIdFormatted(id: self, format: format) - } - - public func toUserFacingString() -> String { - nonFungibleLocalIdToUserFacingString(id: self) - } - - /// Tries to decode an String representation of any NonFungibleLocalID, either: - /// * integer - /// * bytes - /// * ruid - /// * string - /// - /// Not to be confused with `NonFungibleLocalID.stringID` which tries to decode + + public func formatted(_ format: AddressFormat = .default) -> String { + nonFungibleLocalIdFormatted(id: self, format: format) + } + + public func toUserFacingString() -> String { + nonFungibleLocalIdToUserFacingString(id: self) + } + + /// Tries to decode an String representation of any NonFungibleLocalID, either: + /// * integer + /// * bytes + /// * ruid + /// * string + /// + /// Not to be confused with `NonFungibleLocalID.stringID` which tries to decode /// a `NonFungibleLocalID.string` variant - public init(_ string: String) throws { - self = try newNonFungibleLocalIdFromString(localId: string) - } - - /// Tries to decode a `NonFungibleLocalID.string` - /// - /// Not to be confused with `init(:String)` which tries to decode - /// a string into any case of `NonFungibleLocalID` + public init(_ string: String) throws { + self = try newNonFungibleLocalIdFromString(localId: string) + } + + /// Tries to decode a `NonFungibleLocalID.string` + /// + /// Not to be confused with `init(:String)` which tries to decode + /// a string into any case of `NonFungibleLocalID` public static func stringID(_ string: String) throws -> Self { try newNonFungibleLocalIdString(string: string) } - + public init(bytes: some DataProtocol) throws { self = try newNonFungibleLocalIdBytes(bytes: Data(bytes)) } - + public init(ruid ruidBytes: some DataProtocol) throws { self = try newNonFungibleLocalIdRuid(bytes: Data(ruidBytes)) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/NonFungibleLocalIDString+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/NonFungibleLocalIDString+Wrap+Functions.swift index ece59bd2d..b62283431 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/NonFungibleLocalIDString+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/NonFungibleLocalIDString+Wrap+Functions.swift @@ -1,7 +1,7 @@ import SargonUniFFI extension NonFungibleLocalIDString { - public init(validating string: String) throws { - self = try newNonFungibleLocalIdStringFromStr(string: string) - } + public init(validating string: String) throws { + self = try newNonFungibleLocalIdStringFromStr(string: string) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/RequestedQuantity+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/RequestedQuantity+Wrap+Functions.swift index 1189d48b8..5abf06d55 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/RequestedQuantity+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/RequestedQuantity+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI @@ -12,17 +5,16 @@ extension RequestedQuantity { public var isValid: Bool { requestedQuantityIsValid(requestedQuantity: self) } - + public func isFulfilled(by numberOfIds: Int) -> Bool { requestedQuantityIsFulfilledByIds(requestedQuantity: self, numberOfIds: UInt64(numberOfIds)) } - + public init(jsonData: some DataProtocol) throws { self = try newRequestedQuantityFromJsonBytes(jsonBytes: Data(jsonData)) } - + public func jsonData() -> Data { requestedQuantityToJsonBytes(requestedQuantity: self) } - } diff --git a/apple/Sources/Sargon/Extensions/Methods/Prelude/SargonError+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Prelude/SargonError+Wrap+Functions.swift index 06cd7064e..8957c67a8 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Prelude/SargonError+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Prelude/SargonError+Wrap+Functions.swift @@ -4,7 +4,7 @@ extension SargonError { public var errorMessage: String { errorMessageFromError(error: self) } - + public var errorCode: UInt32 { errorCodeFromError(error: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile+Supporting+Types/AccountForDisplay+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile+Supporting+Types/AccountForDisplay+Wrap+Functions.swift index ef0c061b0..86eb8bfee 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile+Supporting+Types/AccountForDisplay+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile+Supporting+Types/AccountForDisplay+Wrap+Functions.swift @@ -1,15 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-16. -// - import Foundation import SargonUniFFI extension AccountForDisplay { - public init(_ account: Account) { self = newAccountForDisplayFromAccount(account: account) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile+Supporting+Types/AccountOrPersona+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile+Supporting+Types/AccountOrPersona+Wrap+Functions.swift index 139eb6430..33392c751 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile+Supporting+Types/AccountOrPersona+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile+Supporting+Types/AccountOrPersona+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-27. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile+Supporting+Types/AuthorizedDappDetailed+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile+Supporting+Types/AuthorizedDappDetailed+Wrap+Functions.swift index 260223b9d..b7900d813 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile+Supporting+Types/AuthorizedDappDetailed+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile+Supporting+Types/AuthorizedDappDetailed+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Matias Bzurovski on 29/8/24. -// - import Foundation import SargonUniFFI @@ -12,7 +5,7 @@ extension AuthorizedDappDetailed { public mutating func showDeposits(_ show: Bool) { preferences.deposits = show ? .visible : .hidden } - + public var isDepositsVisible: Bool { preferences.deposits == .visible } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Account/AppearanceID+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Account/AppearanceID+Wrap+Functions.swift index aa560973c..16b51f3e8 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Account/AppearanceID+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Account/AppearanceID+Wrap+Functions.swift @@ -4,9 +4,8 @@ extension AppearanceID: CaseIterable { public static var allCases: [Self] { appearanceIdsAll() } - + public static func fromNumberOfAccounts(_ numberOfAccounts: Int) -> Self { newAppearanceIdFromNumberOfAccountsOnNetwork(count: UInt64(numberOfAccounts)) } - } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/AppPreferences+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/AppPreferences+Wrap+Functions.swift index 4e220f281..62af2e825 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/AppPreferences+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/AppPreferences+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/AuthorizedDapp+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/AuthorizedDapp+Wrap+Functions.swift index 7a0070411..4028ac36c 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/AuthorizedDapp+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/AuthorizedDapp+Wrap+Functions.swift @@ -1,27 +1,19 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-18. -// - import Foundation import SargonUniFFI extension AuthorizedDapp { - public init(jsonData: some DataProtocol) throws { self = try newAuthorizedDappFromJsonBytes(jsonBytes: Data(jsonData)) } - + public func jsonData() -> Data { authorizedDappToJsonBytes(authorizedDapp: self) } - + public mutating func showDeposits(_ show: Bool) { preferences.deposits = show ? .visible : .hidden } - + public var isDepositsVisible: Bool { preferences.deposits == .visible } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/DepositRule+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/DepositRule+Wrap+Functions.swift index 2b4988c86..a0dbd88f5 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/DepositRule+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/DepositRule+Wrap+Functions.swift @@ -1,20 +1,13 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI // DepositRule -> SargonStringCodable extension DepositRule { - public init(jsonStringLiteral: String) throws { - self = try newDepositRuleFromJsonString(jsonString: jsonStringLiteral) - } - - public func jsonStringLiteral() -> String { + public init(jsonStringLiteral: String) throws { + self = try newDepositRuleFromJsonString(jsonString: jsonStringLiteral) + } + + public func jsonStringLiteral() -> String { depositRuleToJsonString(depositRule: self) - } + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/DeviceInfo+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/DeviceInfo+Wrap+Functions.swift index 2e3e56b3b..7d6f6c437 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/DeviceInfo+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/DeviceInfo+Wrap+Functions.swift @@ -1,19 +1,11 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-18. -// - import Foundation import SargonUniFFI extension DeviceInfo { - public init(jsonData: some DataProtocol) throws { self = try newDeviceInfoFromJsonBytes(jsonBytes: Data(jsonData)) } - + public func jsonData() -> Data { deviceInfoToJsonBytes(deviceInfo: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/ArculusCardFactorSource+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/ArculusCardFactorSource+Wrap+Functions.swift index b81d6d971..02a223d62 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/ArculusCardFactorSource+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/ArculusCardFactorSource+Wrap+Functions.swift @@ -1,15 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-02. -// - import Foundation import SargonUniFFI extension ArculusCardFactorSource { - public init( mnemonicWithPassphrase mwp: MnemonicWithPassphrase, hint: ArculusCardHint @@ -19,7 +11,7 @@ extension ArculusCardFactorSource { hint: hint ) } - + public init( mnemonicWithPassphrase mwp: MnemonicWithPassphrase, name: String diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/ArculusCardModel+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/ArculusCardModel+Wrap+Functions.swift index 7bb3a32f6..22fa374bf 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/ArculusCardModel+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/ArculusCardModel+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-02. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/DeviceFactorSource+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/DeviceFactorSource+Wrap+Functions.swift index c44598851..926b9473f 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/DeviceFactorSource+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/DeviceFactorSource+Wrap+Functions.swift @@ -1,15 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI extension DeviceFactorSource { - public static func olympia( mnemonicWithPassphrase: MnemonicWithPassphrase, hostInfo: HostInfo @@ -19,7 +11,7 @@ extension DeviceFactorSource { hostInfo: hostInfo ) } - + public static func babylon( mnemonicWithPassphrase: MnemonicWithPassphrase, isMain: Bool, @@ -31,8 +23,7 @@ extension DeviceFactorSource { hostInfo: hostInfo ) } - - + public var isMainBDFS: Bool { deviceFactorSourceIsMainBdfs(deviceFactorSource: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSource+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSource+Wrap+Functions.swift index 132e6ed74..0490fa814 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSource+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSource+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI @@ -12,10 +5,11 @@ extension FactorSource { public func toString() -> String { factorSourceToString(factorSource: self) } - + public var supportsOlympia: Bool { factorSourceSupportsOlympia(factorSource: self) } + public var supportsBabylon: Bool { factorSourceSupportsBabylon(factorSource: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceCommon+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceCommon+Wrap+Functions.swift index a5c017e53..ecb1a2cfa 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceCommon+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceCommon+Wrap+Functions.swift @@ -1,25 +1,16 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI extension FactorSourceCommon { - /// Creates a new `FactorSourceCommon` with crypto parameters /// for "Babylon" public static func babylon(isMain: Bool = false) -> Self { newFactorSourceCommonBdfs(isMain: isMain) } - + /// Creates a new `FactorSourceCommon` with crypto parameters /// for "Olympia" public static func olympia() -> Self { newFactorSourceCommonOlympia() } } - diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceCryptoParameters+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceCryptoParameters+Wrap+Functions.swift index 044457a18..718699843 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceCryptoParameters+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceCryptoParameters+Wrap+Functions.swift @@ -1,24 +1,17 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI extension FactorSourceCryptoParameters { public static let babylon: Self = newFactorSourceCryptoParametersPresetBabylonOnly() - + public static let olympia: Self = newFactorSourceCryptoParametersPresetOlympiaOnly() - + public static let babylonOlympiaCompatible: Self = newFactorSourceCryptoParametersPresetBabylonOlympiaCompatible() - + public var supportsOlympia: Bool { factorSourceCryptoParametersSupportsOlympia(parameters: self) } - + public var supportsBabylon: Bool { factorSourceCryptoParametersSupportsBabylon(parameters: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceID+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceID+Wrap+Functions.swift index 2b0657690..18b61324b 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceID+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceID+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceIDFromAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceIDFromAddress+Wrap+Functions.swift index 960346022..3869ec69c 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceIDFromAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceIDFromAddress+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI @@ -12,11 +5,11 @@ extension FactorSourceIDFromAddress { public func toString() -> String { factorSourceIdFromAddressToString(factorSourceId: self) } - + public init(jsonData: some DataProtocol) throws { self = try newFactorSourceIDFromAddressFromJsonBytes(jsonBytes: Data(jsonData)) } - + public func jsonData() -> Data { factorSourceIDFromAddressToJsonBytes(factorSourceIDFromAddress: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceIDFromHash+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceIDFromHash+Wrap+Functions.swift index 671284431..9b794badd 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceIDFromHash+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceIDFromHash+Wrap+Functions.swift @@ -1,30 +1,22 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI extension FactorSourceIDFromHash { - public init(kind: FactorSourceKind, mnemonicWithPassphrase: MnemonicWithPassphrase) { self = newFactorSourceIdFromHashFromMnemonicWithPassphrase( factorSourceKind: kind, mnemonicWithPassphrase: mnemonicWithPassphrase ) } - + public init(jsonData: some DataProtocol) throws { self = try newFactorSourceIDFromHashFromJsonBytes(jsonBytes: Data(jsonData)) } - + public func jsonData() -> Data { factorSourceIDFromHashToJsonBytes(factorSourceIDFromHash: self) } - + public func toString() -> String { factorSourceIdFromHashToString(factorSourceId: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceKind+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceKind+Wrap+Functions.swift index 52b352552..6010cbc06 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceKind+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/FactorSourceKind+Wrap+Functions.swift @@ -1,21 +1,12 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI extension FactorSourceKind { - - public init(string: String) throws { - self = try newFactorSourceKindFromString(string: string) - } - - public func toString() -> String { - factorSourceKindToString(kind: self) - } -} + public init(string: String) throws { + self = try newFactorSourceKindFromString(string: string) + } + public func toString() -> String { + factorSourceKindToString(kind: self) + } +} diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/LedgerHardwareWalletFactorSource+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/LedgerHardwareWalletFactorSource+Wrap+Functions.swift index b4638cd77..5f6cc2a4e 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/LedgerHardwareWalletFactorSource+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/LedgerHardwareWalletFactorSource+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-02. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/LedgerHardwareWalletModel+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/LedgerHardwareWalletModel+Wrap+Functions.swift index 3a779b6d5..710374687 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/LedgerHardwareWalletModel+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/LedgerHardwareWalletModel+Wrap+Functions.swift @@ -1,19 +1,12 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI extension LedgerHardwareWalletModel { - public init(string: String) throws { - self = try newLedgerHwWalletModelFromString(string: string) - } - - public func toString() -> String { - ledgerHwWalletModelToString(model: self) - } + public init(string: String) throws { + self = try newLedgerHwWalletModelFromString(string: string) + } + + public func toString() -> String { + ledgerHwWalletModelToString(model: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/OffDeviceMnemonicFactorSource+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/OffDeviceMnemonicFactorSource+Wrap+Functions.swift index 9574dd875..577f36a84 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/OffDeviceMnemonicFactorSource+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/OffDeviceMnemonicFactorSource+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-02. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/PassphraseFactorSource+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/PassphraseFactorSource+Functions.swift index e708323c7..1628c31bd 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/PassphraseFactorSource+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/PassphraseFactorSource+Functions.swift @@ -1,15 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-02. -// - import Foundation import SargonUniFFI extension PassphraseFactorSource { - public init( mnemonicWithPassphrase mwp: MnemonicWithPassphrase ) { diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/SecurityQuestionsFactorSource+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/SecurityQuestionsFactorSource+Wrap+Functions.swift index e7da24b60..ec24872f1 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/SecurityQuestionsFactorSource+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/SecurityQuestionsFactorSource+Wrap+Functions.swift @@ -1,18 +1,17 @@ import Foundation import SargonUniFFI - extension SecurityQuestionsNotProductionReadyFactorSource { public init( mnemonic: Mnemonic, questionsAndAnswers: [SecurityNotProductionReadyQuestionAndAnswer] ) throws { - self = try newSecurityQuestionsFactorSourceByEncryptingMnemonic( - mnemonic: mnemonic, - with: questionsAndAnswers - ) + self = try newSecurityQuestionsFactorSourceByEncryptingMnemonic( + mnemonic: mnemonic, + with: questionsAndAnswers + ) } - + public func decrypt(questionsAndAnswers: [SecurityNotProductionReadyQuestionAndAnswer]) throws -> Mnemonic { try securityQuestionsFactorSourceDecrypt(factorSource: self, with: questionsAndAnswers) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/TrustedContactFactorSource+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/TrustedContactFactorSource+Wrap+Functions.swift index e3a201f24..51ab2008a 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/TrustedContactFactorSource+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Factor/TrustedContactFactorSource+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-02. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/FiatCurrency+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/FiatCurrency+Wrap+Functions.swift index fcdf3e119..a325012e8 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/FiatCurrency+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/FiatCurrency+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI @@ -13,7 +6,7 @@ extension FiatCurrency { public init(jsonStringLiteral: String) throws { self = try newFiatCurrencyFromJsonString(jsonString: jsonStringLiteral) } - + public func jsonStringLiteral() -> String { fiatCurrencyToJsonString(fiatCurrency: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Gateway+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Gateway+Wrap+Functions.swift index ba8ef6d3a..df96490b0 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Gateway+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Gateway+Wrap+Functions.swift @@ -5,26 +5,25 @@ extension Gateway { public func getID() -> URL { gatewayId(gateway: self) } - + public func toString() -> String { gatewayToString(gateway: self) } - + public var isWellknown: Bool { gatewayIsWellknown(gateway: self) } - + public static let wellknown: [Gateway] = gatewayWellknownGateways() - + public init(url: String, networkID: NetworkID) throws { self = try newGatewayWithUrlOnNetwork(url: url, networkId: networkID) } - + public static func forNetwork(id networkID: NetworkID) -> Self { newGatewayForNetworkId(networkId: networkID) } - + public static let mainnet = gatewayMainnet() public static let stokenet = gatewayStokenet() } - diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Header+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Header+Wrap+Functions.swift index add658168..3b4e52ec2 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Header+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Header+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI @@ -12,7 +5,7 @@ extension Header { public init(jsonData: some DataProtocol) throws { self = try newHeaderFromJsonBytes(jsonBytes: Data(jsonData)) } - + public func jsonData() -> Data { headerToJsonBytes(header: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/MFA/SecurityStructureMetadata+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/MFA/SecurityStructureMetadata+Wrap+Functions.swift index fff608417..978b895f0 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/MFA/SecurityStructureMetadata+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/MFA/SecurityStructureMetadata+Wrap+Functions.swift @@ -1,15 +1,8 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-06. -// - import Foundation import SargonUniFFI extension SecurityStructureMetadata { - public init(name: DisplayName) { - self = newSecurityStructureMetadataNamed(name: name) - } + public init(name: DisplayName) { + self = newSecurityStructureMetadataNamed(name: name) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/MFA/SecurityStructureOfFactorSources+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/MFA/SecurityStructureOfFactorSources+Wrap+Functions.swift index c99f02e89..f628ec8ef 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/MFA/SecurityStructureOfFactorSources+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/MFA/SecurityStructureOfFactorSources+Wrap+Functions.swift @@ -2,18 +2,18 @@ import Foundation import SargonUniFFI extension SecurityStructureOfFactorSources { - public init( - metadata: SecurityStructureMetadata, - numberOfDaysUntilAutoConfirmation: UInt16, - matrixOfFactors: MatrixOfFactorSources - ) { + public init( + metadata: SecurityStructureMetadata, + numberOfDaysUntilAutoConfirmation: UInt16, + matrixOfFactors: MatrixOfFactorSources + ) { assert(matrixOfFactors.primaryRole.thresholdFactors.count >= matrixOfFactors.primaryRole.threshold) assert(matrixOfFactors.recoveryRole.thresholdFactors.count >= matrixOfFactors.recoveryRole.threshold) assert(matrixOfFactors.confirmationRole.thresholdFactors.count >= matrixOfFactors.confirmationRole.threshold) - self = newSecurityStructureOfFactorSourcesAutoInDays( - metadata: metadata, - numberOfDaysUntilAutoConfirmation: numberOfDaysUntilAutoConfirmation, - matrixOfFactors: matrixOfFactors - ) - } + self = newSecurityStructureOfFactorSourcesAutoInDays( + metadata: metadata, + numberOfDaysUntilAutoConfirmation: numberOfDaysUntilAutoConfirmation, + matrixOfFactors: matrixOfFactors + ) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/OnLedgerSettings+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/OnLedgerSettings+Wrap+Functions.swift index 146d3cf2c..ff95157f4 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/OnLedgerSettings+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/OnLedgerSettings+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-20. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/Persona+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/Persona+Wrap+Functions.swift index 6f54eb99c..61da91bb3 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/Persona+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/Persona+Wrap+Functions.swift @@ -1,10 +1,2 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - import Foundation import SargonUniFFI - diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/PersonaData/PersonaDataEntryEmailAddress+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/PersonaData/PersonaDataEntryEmailAddress+Wrap+Functions.swift index 000dfbe12..c55178415 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/PersonaData/PersonaDataEntryEmailAddress+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/PersonaData/PersonaDataEntryEmailAddress+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - import Foundation import SargonUniFFI @@ -13,7 +6,7 @@ extension EmailAddress { public init(jsonStringLiteral: String) throws { self = try newPersonaDataEntryEmailAddressFromJsonString(jsonString: jsonStringLiteral) } - + public func jsonStringLiteral() -> String { personaDataEntryEmailAddressToJsonString(personaDataEntryEmailAddress: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/PersonaData/PersonaDataEntryName+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/PersonaData/PersonaDataEntryName+Wrap+Functions.swift index 09aaa946f..0c5d7443c 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/PersonaData/PersonaDataEntryName+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/PersonaData/PersonaDataEntryName+Wrap+Functions.swift @@ -1,9 +1,3 @@ -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - import Foundation import SargonUniFFI @@ -11,7 +5,7 @@ extension PersonaDataEntryName { public init(jsonData: some DataProtocol) throws { self = try newPersonaDataEntryNameFromJsonBytes(jsonBytes: Data(jsonData)) } - + public func jsonData() -> Data { personaDataEntryNameToJsonBytes(personaDataEntryName: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/PersonaData/PersonaDataEntryPhoneNumber+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/PersonaData/PersonaDataEntryPhoneNumber+Wrap+Functions.swift index 38c37bff0..f6ee9d54d 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/PersonaData/PersonaDataEntryPhoneNumber+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Persona/PersonaData/PersonaDataEntryPhoneNumber+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - import Foundation import SargonUniFFI @@ -13,7 +6,7 @@ extension PersonaDataEntryPhoneNumber { public init(jsonStringLiteral: String) throws { self = try newPersonaDataEntryPhoneNumberFromJsonString(jsonString: jsonStringLiteral) } - + public func jsonStringLiteral() -> String { personaDataEntryPhoneNumberToJsonString(personaDataEntryPhoneNumber: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/Profile+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/Profile+Wrap+Functions.swift index a3d836621..60bfbe888 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/Profile+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/Profile+Wrap+Functions.swift @@ -2,17 +2,16 @@ import Foundation import SargonUniFFI extension Profile { - /// Just a convenience for `analyzeContents(of: String(data: data, encoding: .utf8)!)` public static func analyzeContents(data: some DataProtocol) -> ProfileFileContents { let contents = String(data: Data(data), encoding: .utf8)! return analyzeContents(of: contents) } - + public static func analyzeContents(of contents: String) -> ProfileFileContents { profileAnalyzeContentsOfFile(contents: contents) } - + public func toJSONString(prettyPrinted: Bool = false) -> String { profileToJsonString(profile: self, prettyPrinted: prettyPrinted) } @@ -21,28 +20,28 @@ extension Profile { public func profileSnapshot() -> Data { Data(toJSONString(prettyPrinted: false).utf8) } - + @available(*, deprecated, message: "Use `toJSONString(prettyPrinted:) instead") public func jsonData() -> Data { profileSnapshot() } - + @available(*, deprecated, message: "Use `init(jsonString:) instead") public init(jsonData: some DataProtocol) throws { let jsonString = String(data: Data(jsonData), encoding: .utf8)! try self.init(jsonString: jsonString) } - + public init(jsonString: String) throws { self = try newProfileFromJsonString(jsonStr: jsonString) } - + @available(*, deprecated, message: "Use `init(encryptedProfileJSONString:decryptionPassword)` instead") public init(encrypted bytes: some DataProtocol, decryptionPassword: String) throws { let jsonString = String(data: Data(bytes), encoding: .utf8)! try self.init(encryptedProfileJSONString: jsonString, decryptionPassword: decryptionPassword) } - + public init( encryptedProfileJSONString jsonString: String, decryptionPassword: String @@ -52,12 +51,11 @@ extension Profile { decryptionPassword: decryptionPassword ) } - + public func toString() -> String { profileToString(profile: self) } - - + public func toDebugString() -> String { profileToDebugString(profile: self) } @@ -68,7 +66,7 @@ extension Profile { let jsonString = encryptedJsonString(password: password) return Data(jsonString.utf8) } - + /// Returns an Encrypted Profile as JSON String public func encryptedJsonString(password: String) -> String { profileEncryptWithPassword(profile: self, encryptionPassword: password) @@ -81,7 +79,7 @@ extension Profile { let jsonString = String(data: jsonData, encoding: .utf8)! return checkIfProfileJsonStringContainsLegacyP2PLinks(jsonString: jsonString) } - + public static func checkIfProfileJsonStringContainsLegacyP2PLinks(jsonString: String) -> Bool { checkIfProfileJsonContainsLegacyP2pLinks(jsonStr: jsonString) } @@ -93,7 +91,7 @@ extension Profile { let jsonString = String(data: jsonData, encoding: .utf8)! return checkIfEncryptedProfileJsonStringContainsLegacyP2PLinks(jsonString: jsonString, password: password) } - + public static func checkIfEncryptedProfileJsonStringContainsLegacyP2PLinks(jsonString: String, password: String) -> Bool { checkIfEncryptedProfileJsonContainsLegacyP2pLinks(jsonStr: jsonString, password: password) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/ProfileNetwork+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/ProfileNetwork+Wrap+Functions.swift index 408f4f506..efa50bc4d 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/ProfileNetwork+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/ProfileNetwork+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-28. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/ResourceAppPreference+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/ResourceAppPreference+Wrap+Functions.swift index b22ad721b..327053fc9 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/ResourceAppPreference+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/ResourceAppPreference+Wrap+Functions.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Matias Bzurovski on 13/8/24. -// - import Foundation import SargonUniFFI @@ -12,11 +5,11 @@ extension [ResourceAppPreference] { public var hiddenResources: [ResourceIdentifier] { resourcePreferencesGetHiddenResources(resourcePreferences: self) } - + public mutating func hideResource(resource: ResourceIdentifier) { self = resourcePreferencesHideResource(resourcePreferences: self, resource: resource) } - + public mutating func unhideResource(resource: ResourceIdentifier) { self = resourcePreferencesUnhideResource(resourcePreferences: self, resource: resource) } diff --git a/apple/Sources/Sargon/Extensions/Methods/Profile/SavedGateways+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/Profile/SavedGateways+Wrap+Functions.swift index cfaaa9217..f4066bb1b 100644 --- a/apple/Sources/Sargon/Extensions/Methods/Profile/SavedGateways+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/Profile/SavedGateways+Wrap+Functions.swift @@ -1,25 +1,17 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-18. -// - import Foundation import SargonUniFFI extension SavedGateways { - public init(current: Gateway) { self = newSavedGateways(current: current) } - + public var all: [Gateway] { savedGatewaysGetAllElements(gateways: self) } - + public static let `default`: Self = newSavedGatewaysDefault() - + /// Swaps current and other gateways: /// /// * Adds (old)`current` to `other` (throws error if it was already present) @@ -33,5 +25,4 @@ extension SavedGateways { gateways: self ) } - } diff --git a/apple/Sources/Sargon/Extensions/Methods/RET/Blob+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RET/Blob+Wrap+Functions.swift index eeff3e820..ac8bc7894 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RET/Blob+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RET/Blob+Wrap+Functions.swift @@ -2,15 +2,14 @@ import Foundation import SargonUniFFI extension Blob { - public init(data: some DataProtocol) { self = newBlobFromBytes(bytes: Data(data)) } - + public var data: Data { blobToBytes(blob: self) } - + public var hex: String { blobToString(blob: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/RET/Blobs+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RET/Blobs+Wrap+Functions.swift index f156ca547..f2feded34 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RET/Blobs+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RET/Blobs+Wrap+Functions.swift @@ -4,8 +4,8 @@ extension Blobs { public init(_ blobs: [Blob]) { self = newBlobsFromBlobList(blobs: Array(blobs)) } - - public var blobs: [Blob] { - blobsListOfBlobs(blobs: self) - } + + public var blobs: [Blob] { + blobsListOfBlobs(blobs: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RET/IntentSignature+Wrap+Function.swift b/apple/Sources/Sargon/Extensions/Methods/RET/IntentSignature+Wrap+Function.swift index b8b3ac4f4..74db3cee5 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RET/IntentSignature+Wrap+Function.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RET/IntentSignature+Wrap+Function.swift @@ -1,13 +1,13 @@ import SargonUniFFI extension IntentSignature { - public init(signatureWithPublicKey: SignatureWithPublicKey) { - self = newIntentSignatureFromSignatureWithPublicKey( - signatureWithPublicKey: signatureWithPublicKey - ) - } - - public var signatureWithPublicKey: SignatureWithPublicKey { - intentSignatureGetSignatureWithPublicKey(intentSignature: self) - } + public init(signatureWithPublicKey: SignatureWithPublicKey) { + self = newIntentSignatureFromSignatureWithPublicKey( + signatureWithPublicKey: signatureWithPublicKey + ) + } + + public var signatureWithPublicKey: SignatureWithPublicKey { + intentSignatureGetSignatureWithPublicKey(intentSignature: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RET/Message+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RET/Message+Wrap+Functions.swift index 88e62b8dc..510b3c372 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RET/Message+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RET/Message+Wrap+Functions.swift @@ -4,7 +4,7 @@ extension Message { public static func plaintext(string: String) -> Self { newMessagePlaintextString(string: string) } - + public var plaintext: String? { messageAsPlaintext(message: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/RET/NotarySignature+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RET/NotarySignature+Wrap+Functions.swift index 805ada274..c561eece5 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RET/NotarySignature+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RET/NotarySignature+Wrap+Functions.swift @@ -4,7 +4,7 @@ extension NotarySignature { public init(signature: Signature) { self = newNotarySignature(signature: signature) } - + public var signature: Signature { notarySignatureGetSignature(notarySignature: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/RET/ResourceSpecifier+Warp+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RET/ResourceSpecifier+Warp+Functions.swift index f4b3219c1..90246234f 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RET/ResourceSpecifier+Warp+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RET/ResourceSpecifier+Warp+Functions.swift @@ -1,7 +1,7 @@ import SargonUniFFI extension ResourceSpecifier { - public var resourceAddress: ResourceAddress { - resourceSpecifierGetAddress(specifier: self) - } + public var resourceAddress: ResourceAddress { + resourceSpecifierGetAddress(specifier: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RET/SignedIntent+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RET/SignedIntent+Wrap+Functions.swift index 5c9a79569..88d4491fb 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RET/SignedIntent+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RET/SignedIntent+Wrap+Functions.swift @@ -1,7 +1,7 @@ import SargonUniFFI extension SignedIntent { - public func hash() -> SignedTransactionIntentHash { - signedIntentHash(signedIntent: self) - } + public func hash() -> SignedTransactionIntentHash { + signedIntentHash(signedIntent: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RET/Subintent+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RET/Subintent+Wrap+Functions.swift index d024320e1..c2eab54ce 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RET/Subintent+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RET/Subintent+Wrap+Functions.swift @@ -2,11 +2,11 @@ import Foundation import SargonUniFFI extension Subintent { - public func hash() -> SubintentHash { - subintentHash(subintent: self) - } + public func hash() -> SubintentHash { + subintentHash(subintent: self) + } - public func compile() -> CompiledSubintent { - subintentCompile(subintent: self) - } + public func compile() -> CompiledSubintent { + subintentCompile(subintent: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RET/SubintentManifest+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RET/SubintentManifest+Wrap+Functions.swift index fcc9ed55e..a69d52d12 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RET/SubintentManifest+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RET/SubintentManifest+Wrap+Functions.swift @@ -1,25 +1,25 @@ import Foundation import SargonUniFFI +// MARK: - SubintentManifest + CustomStringConvertible extension SubintentManifest: CustomStringConvertible { - public var description: String { manifestString } + public var description: String { manifestString } } extension SubintentManifest { + public var manifestString: String { + subintentManifestString(manifest: self) + } - public var manifestString: String { - subintentManifestString(manifest: self) - } + public var blobs: Blobs { + subintentManifestBlobs(manifest: self) + } - public var blobs: Blobs { - subintentManifestBlobs(manifest: self) - } + public var involvedPoolAddresses: [PoolAddress] { + subintentManifestInvolvedPoolAddresses(manifest: self) + } - public var involvedPoolAddresses: [PoolAddress] { - subintentManifestInvolvedPoolAddresses(manifest: self) - } - - public var involvedResourceAddresses: [ResourceAddress] { - subintentManifestInvolvedResourceAddresses(manifest: self) - } + public var involvedResourceAddresses: [ResourceAddress] { + subintentManifestInvolvedResourceAddresses(manifest: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RET/TransactionIntent+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RET/TransactionIntent+Wrap+Functions.swift index bafc7a908..16c2f0c95 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RET/TransactionIntent+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RET/TransactionIntent+Wrap+Functions.swift @@ -5,7 +5,7 @@ extension TransactionIntent { public func hash() -> TransactionIntentHash { transactionIntentHash(intent: self) } - + public func compile() -> CompiledTransactionIntent { transactionIntentCompile(intent: self) } diff --git a/apple/Sources/Sargon/Extensions/Methods/RET/TransactionManifest+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RET/TransactionManifest+Wrap+Functions.swift index 9195b770b..b77bc7bff 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RET/TransactionManifest+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RET/TransactionManifest+Wrap+Functions.swift @@ -1,12 +1,12 @@ import Foundation import SargonUniFFI +// MARK: - TransactionManifest + CustomStringConvertible extension TransactionManifest: CustomStringConvertible { public var description: String { instructionsString } } extension TransactionManifest { - public init(instructionsString: String, networkID: NetworkID, blobs: Blobs = []) throws { self = try newTransactionManifestFromInstructionsStringAndBlobs( instructionsString: instructionsString, @@ -23,21 +23,21 @@ extension TransactionManifest { transactionManifestInstructionsString(manifest: self) } - public var blobs: Blobs { - transactionManifestBlobs(manifest: self) - } - - public var involvedPoolAddresses: [PoolAddress] { - transactionManifestInvolvedPoolAddresses(manifest: self) - } - - public var involvedResourceAddresses: [ResourceAddress] { - transactionManifestInvolvedResourceAddresses(manifest: self) - } - - public var summary: ManifestSummary { - get throws { - try transactionManifestSummary(manifest: self) - } - } + public var blobs: Blobs { + transactionManifestBlobs(manifest: self) + } + + public var involvedPoolAddresses: [PoolAddress] { + transactionManifestInvolvedPoolAddresses(manifest: self) + } + + public var involvedResourceAddresses: [ResourceAddress] { + transactionManifestInvolvedResourceAddresses(manifest: self) + } + + public var summary: ManifestSummary { + get throws { + try transactionManifestSummary(manifest: self) + } + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RET/TransactionManifestV2+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RET/TransactionManifestV2+Wrap+Functions.swift index 4c0efbf41..b30a12b35 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RET/TransactionManifestV2+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RET/TransactionManifestV2+Wrap+Functions.swift @@ -1,19 +1,19 @@ import Foundation import SargonUniFFI +// MARK: - TransactionManifestV2 + CustomStringConvertible extension TransactionManifestV2: CustomStringConvertible { public var description: String { manifestString } } extension TransactionManifestV2 { - public var manifestString: String { transactionManifestStringV2(manifest: self) } - public var blobs: Blobs { - transactionManifestBlobsV2(manifest: self) - } + public var blobs: Blobs { + transactionManifestBlobsV2(manifest: self) + } public var involvedPoolAddresses: [PoolAddress] { transactionManifestInvolvedPoolAddressesV2(manifest: self) diff --git a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/Mobile/RadixConnectMobile.swift b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/Mobile/RadixConnectMobile.swift index 8e0787542..39d115fb9 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/Mobile/RadixConnectMobile.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/Mobile/RadixConnectMobile.swift @@ -2,7 +2,7 @@ import Foundation import SargonUniFFI extension RadixConnectMobile { - public static func live(sessionStorage: any RadixConnectMobileSessionStorage) -> RadixConnectMobile { - RadixConnectMobile(networkingDriver: URLSession.shared, sessionStorage: sessionStorage) - } + public static func live(sessionStorage: any RadixConnectMobileSessionStorage) -> RadixConnectMobile { + RadixConnectMobile(networkingDriver: URLSession.shared, sessionStorage: sessionStorage) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/LinkConnectionQRData+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/LinkConnectionQRData+Wrap+Functions.swift index af76956c7..bcefe5009 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/LinkConnectionQRData+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/LinkConnectionQRData+Wrap+Functions.swift @@ -2,11 +2,11 @@ import Foundation import SargonUniFFI extension LinkConnectionQrData { - public init(jsonData: some DataProtocol) throws { - self = try newLinkConnectionQRDataFromJsonBytes(jsonBytes: Data(jsonData)) - } - - public func jsonData() -> Data { - linkConnectionQRDataToJsonBytes(linkConnectionQRData: self) - } + public init(jsonData: some DataProtocol) throws { + self = try newLinkConnectionQRDataFromJsonBytes(jsonBytes: Data(jsonData)) + } + + public func jsonData() -> Data { + linkConnectionQRDataToJsonBytes(linkConnectionQRData: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/P2PLink+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/P2PLink+Wrap+Functions.swift index 94e6d5b80..d1337e0f8 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/P2PLink+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/P2PLink+Wrap+Functions.swift @@ -2,19 +2,19 @@ import Foundation import SargonUniFFI extension P2pLink { - public init(jsonData: some DataProtocol) throws { - self = try newP2PLinkFromJsonBytes(jsonBytes: Data(jsonData)) - } - - public func jsonData() -> Data { - p2PLinkToJsonBytes(p2PLink: self) - } + public init(jsonData: some DataProtocol) throws { + self = try newP2PLinkFromJsonBytes(jsonBytes: Data(jsonData)) + } - public var id: ID { - p2pLinkId(link: self) - } + public func jsonData() -> Data { + p2PLinkToJsonBytes(p2PLink: self) + } - public var clientID: Hash { - connectionPassword.value.hash() - } -} \ No newline at end of file + public var id: ID { + p2pLinkId(link: self) + } + + public var clientID: Hash { + connectionPassword.value.hash() + } +} diff --git a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/RadixConnectPassword+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/RadixConnectPassword+Wrap+Functions.swift index b442d84d6..d06df3d7a 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/RadixConnectPassword+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/RadixConnectPassword+Wrap+Functions.swift @@ -2,15 +2,15 @@ import Foundation import SargonUniFFI extension RadixConnectPassword { - public init(jsonStringLiteral: String) throws { - self = try newRadixConnectPasswordFromJsonString(jsonString: jsonStringLiteral) - } - - public func jsonStringLiteral() -> String { + public init(jsonStringLiteral: String) throws { + self = try newRadixConnectPasswordFromJsonString(jsonString: jsonStringLiteral) + } + + public func jsonStringLiteral() -> String { radixConnectPasswordToJsonString(radixConnectPassword: self) - } + } - public var messageHash: Hash { - radixConnectPasswordMessageHash(password: self) - } + public var messageHash: Hash { + radixConnectPasswordMessageHash(password: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/RadixConnectPurpose+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/RadixConnectPurpose+Wrap+Functions.swift index e01cf5ea4..0e2950caf 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/RadixConnectPurpose+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/P2PLinks/RadixConnectPurpose+Wrap+Functions.swift @@ -2,16 +2,15 @@ import Foundation import SargonUniFFI extension RadixConnectPurpose { - - public init(string: String) { - self = newRadixConnectPurposeFromString(string: string) - } + public init(string: String) { + self = newRadixConnectPurposeFromString(string: string) + } - public init(jsonStringLiteral: String) throws { - self = try newRadixConnectPurposeFromJsonString(jsonString: jsonStringLiteral) - } - - public func jsonStringLiteral() -> String { + public init(jsonStringLiteral: String) throws { + self = try newRadixConnectPurposeFromJsonString(jsonString: jsonStringLiteral) + } + + public func jsonStringLiteral() -> String { radixConnectPurposeToJsonString(radixConnectPurpose: self) - } + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteraction/DappToWalletInteractionUnvalidated+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteraction/DappToWalletInteractionUnvalidated+Wrap+Functions.swift index f519c7059..a7cc11b05 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteraction/DappToWalletInteractionUnvalidated+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteraction/DappToWalletInteractionUnvalidated+Wrap+Functions.swift @@ -2,11 +2,11 @@ import Foundation import SargonUniFFI extension DappToWalletInteractionUnvalidated { - public func toJSONString() -> String { - dappToWalletInteractionUnvalidatedToJsonString(interactionUnvalidated: self) + public func toJSONString() -> String { + dappToWalletInteractionUnvalidatedToJsonString(interactionUnvalidated: self) } - public init(jsonString: String) throws { - self = try newDappToWalletInteractionUnvalidatedFromJsonString(jsonStr: jsonString) + public init(jsonString: String) throws { + self = try newDappToWalletInteractionUnvalidatedFromJsonString(jsonStr: jsonString) } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteraction/UnvalidatedTransactionManifest+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteraction/UnvalidatedTransactionManifest+Wrap+Functions.swift index f63645557..abc12deb1 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteraction/UnvalidatedTransactionManifest+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteraction/UnvalidatedTransactionManifest+Wrap+Functions.swift @@ -2,14 +2,14 @@ import Foundation import SargonUniFFI extension UnvalidatedTransactionManifest { - public init(manifest: TransactionManifest) { + public init(manifest: TransactionManifest) { self = newUnvalidatedTransactionManifestFromTransactionManifest(transactionManifest: manifest) } - public func transactionManifest(onNetwork networkID: NetworkID) throws -> TransactionManifest { - try newTransactionManifestFromUnvalidatedTransactionManifest( - unvalidatedTransactionManifest: self, - networkId: networkID - ) - } + public func transactionManifest(onNetwork networkID: NetworkID) throws -> TransactionManifest { + try newTransactionManifestFromUnvalidatedTransactionManifest( + unvalidatedTransactionManifest: self, + networkId: networkID + ) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteraction/WalletToDappInteractionResponse+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteraction/WalletToDappInteractionResponse+Wrap+Functions.swift index ea20e14e0..4fdf70eb0 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteraction/WalletToDappInteractionResponse+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteraction/WalletToDappInteractionResponse+Wrap+Functions.swift @@ -2,11 +2,11 @@ import Foundation import SargonUniFFI extension WalletToDappInteractionResponse { - public init(jsonData: some DataProtocol) throws { - self = try newWalletToDappInteractionResponseFromJsonBytes(jsonBytes: Data(jsonData)) - } - - public func jsonData() -> Data { - walletToDappInteractionResponseToJsonBytes(walletToDappInteractionResponse: self) - } + public init(jsonData: some DataProtocol) throws { + self = try newWalletToDappInteractionResponseFromJsonBytes(jsonBytes: Data(jsonData)) + } + + public func jsonData() -> Data { + walletToDappInteractionResponseToJsonBytes(walletToDappInteractionResponse: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteractionVersion+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteractionVersion+Wrap+Functions.swift index c94a6e6ed..aac7d2a76 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteractionVersion+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteractionVersion+Wrap+Functions.swift @@ -2,5 +2,5 @@ import Foundation import SargonUniFFI extension WalletInteractionVersion { - public static let current: Self = newWalletInteractionVersionCurrent() + public static let current: Self = newWalletInteractionVersionCurrent() } diff --git a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteractionWalletAccount+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteractionWalletAccount+Wrap+Functions.swift index 62caecb29..2d6801bfd 100644 --- a/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteractionWalletAccount+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/RadixConnect/WalletInteractionWalletAccount+Wrap+Functions.swift @@ -2,11 +2,11 @@ import Foundation import SargonUniFFI extension WalletInteractionWalletAccount { - public init(jsonData: some DataProtocol) throws { - self = try newWalletInteractionWalletAccountFromJsonBytes(jsonBytes: Data(jsonData)) - } - - public func jsonData() -> Data { - walletInteractionWalletAccountToJsonBytes(walletInteractionWalletAccount: self) - } + public init(jsonData: some DataProtocol) throws { + self = try newWalletInteractionWalletAccountFromJsonBytes(jsonBytes: Data(jsonData)) + } + + public func jsonData() -> Data { + walletInteractionWalletAccountToJsonBytes(walletInteractionWalletAccount: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Methods/System/Event/EventKind+Wrap+Functions.swift b/apple/Sources/Sargon/Extensions/Methods/System/Event/EventKind+Wrap+Functions.swift index 2bc465cb1..124d5559f 100644 --- a/apple/Sources/Sargon/Extensions/Methods/System/Event/EventKind+Wrap+Functions.swift +++ b/apple/Sources/Sargon/Extensions/Methods/System/Event/EventKind+Wrap+Functions.swift @@ -1,24 +1,17 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-24. -// - import Foundation import SargonUniFFI extension EventKind { public static let allCases: [Self] = eventKindAll() - + public var affectsCurrentAccounts: Bool { eventKindAffectsCurrentAccounts(eventKind: self) } - + public var affectsCurrentNetwork: Bool { eventKindAffectsCurrentNetwork(eventKind: self) } - + public var affectsSavedGateways: Bool { eventKindAffectsSavedGateways(eventKind: self) } diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Address/AccessControllerAddress+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Address/AccessControllerAddress+SampleValues.swift index 045fc8542..08bf5f9e4 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Address/AccessControllerAddress+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Address/AccessControllerAddress+SampleValues.swift @@ -4,9 +4,8 @@ import SargonUniFFI extension AccessControllerAddress { public static let sampleMainnet: Self = newAccessControllerAddressSampleMainnet() public static let sampleMainnetOther: Self = newAccessControllerAddressSampleMainnetOther() - + public static let sampleStokenet: Self = newAccessControllerAddressSampleStokenet() public static let sampleStokenetOther: Self = newAccessControllerAddressSampleStokenetOther() } #endif - diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Address/AccountAddress+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Address/AccountAddress+SampleValues.swift index 8a2f1c214..00d072662 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Address/AccountAddress+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Address/AccountAddress+SampleValues.swift @@ -2,14 +2,12 @@ import SargonUniFFI #if DEBUG extension AccountAddress { - public static let sample = Self.sampleMainnet public static let sampleOther = Self.sampleMainnetOther - + public static let sampleMainnet: Self = newAccountAddressSampleMainnet() public static let sampleMainnetOther: Self = newAccountAddressSampleMainnetOther() public static let sampleStokenet: Self = newAccountAddressSampleStokenet() public static let sampleStokenetOther: Self = newAccountAddressSampleStokenetOther() - } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Address/Address+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Address/Address+SampleValues.swift index 35cf9ab87..71a6665d4 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Address/Address+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Address/Address+SampleValues.swift @@ -2,12 +2,11 @@ import SargonUniFFI #if DEBUG extension Address { - public static let sampleMainnet: Self = newAddressSampleMainnet() public static let sampleMainnetOther: Self = newAddressSampleMainnetOther() public static let sampleStokenet: Self = newAddressSampleStokenet() public static let sampleStokenetOther: Self = newAddressSampleStokenetOther() - + public static var sampleValues: [Self] { addressSampleValuesAll() } diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Address/AddressOfAccountOrPersona+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Address/AddressOfAccountOrPersona+SampleValues.swift index 25354025c..cbfc18d52 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Address/AddressOfAccountOrPersona+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Address/AddressOfAccountOrPersona+SampleValues.swift @@ -4,9 +4,8 @@ import SargonUniFFI extension AddressOfAccountOrPersona { public static let sampleMainnet: Self = newAddressOfAccountOrPersonaSampleMainnet() public static let sampleMainnetOther: Self = newAddressOfAccountOrPersonaSampleMainnetOther() - + public static let sampleStokenet: Self = newAddressOfAccountOrPersonaSampleStokenet() public static let sampleStokenetOther: Self = newAddressOfAccountOrPersonaSampleStokenetOther() - } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Address/ComponentAddress+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Address/ComponentAddress+SampleValues.swift index a19418b71..ebfee8eec 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Address/ComponentAddress+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Address/ComponentAddress+SampleValues.swift @@ -4,7 +4,7 @@ import SargonUniFFI extension ComponentAddress { public static let sampleMainnet: Self = newComponentAddressSampleMainnetGlobal() public static let sampleMainnetOther: Self = newComponentAddressSampleMainnetInternal() - + public static let sampleStokenet: Self = newComponentAddressSampleStokenetGlobal() public static let sampleStokenetOther: Self = newComponentAddressSampleStokenetInternal() } diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Address/IdentityAddress+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Address/IdentityAddress+SampleValues.swift index 0542118ca..ee1c18fcb 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Address/IdentityAddress+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Address/IdentityAddress+SampleValues.swift @@ -2,10 +2,9 @@ import SargonUniFFI #if DEBUG extension IdentityAddress { - public static let sample = Self.sampleMainnet public static let sampleOther = Self.sampleMainnetOther - + public static let sampleMainnet: Self = newIdentityAddressSampleMainnet() public static let sampleMainnetOther: Self = newIdentityAddressSampleMainnetOther() @@ -13,4 +12,3 @@ extension IdentityAddress { public static let sampleStokenetOther: Self = newIdentityAddressSampleStokenetOther() } #endif - diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Address/LockerAddress+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Address/LockerAddress+SampleValues.swift index 9a6a7bd65..0180ee506 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Address/LockerAddress+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Address/LockerAddress+SampleValues.swift @@ -2,10 +2,9 @@ import SargonUniFFI #if DEBUG extension LockerAddress { - public static let sample = Self.sampleMainnet public static let sampleOther = Self.sampleMainnetOther - + public static let sampleMainnet: Self = newLockerAddressSampleMainnet() public static let sampleMainnetOther: Self = newLockerAddressSampleMainnetOther() @@ -13,4 +12,3 @@ extension LockerAddress { public static let sampleStokenetOther: Self = newLockerAddressSampleStokenetOther() } #endif - diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Address/NonFungibleResourceAddress+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Address/NonFungibleResourceAddress+SampleValues.swift index 4c7fda811..0daa86ecb 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Address/NonFungibleResourceAddress+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Address/NonFungibleResourceAddress+SampleValues.swift @@ -2,14 +2,12 @@ import SargonUniFFI #if DEBUG extension NonFungibleResourceAddress { - public static let sample = Self.sampleMainnet public static let sampleOther = Self.sampleMainnetOther - + public static let sampleMainnet: Self = newNonFungibleResourceAddressSampleMainnet() public static let sampleMainnetOther: Self = newNonFungibleResourceAddressSampleMainnetOther() public static let sampleStokenet: Self = newNonFungibleResourceAddressSampleStokenet() public static let sampleStokenetOther: Self = newNonFungibleResourceAddressSampleStokenetOther() - } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Address/PackageAddress+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Address/PackageAddress+SampleValues.swift index 665b561d2..53cdac521 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Address/PackageAddress+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Address/PackageAddress+SampleValues.swift @@ -4,7 +4,7 @@ import SargonUniFFI extension PackageAddress { public static let sampleMainnet: Self = newPackageAddressSampleMainnet() public static let sampleMainnetOther: Self = newPackageAddressSampleMainnetOther() - + public static let sampleStokenet: Self = newPackageAddressSampleStokenet() public static let sampleStokenetOther: Self = newPackageAddressSampleStokenetOther() } diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Address/PoolAddress+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Address/PoolAddress+SampleValues.swift index 56e745bb6..7a9bcd80d 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Address/PoolAddress+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Address/PoolAddress+SampleValues.swift @@ -4,14 +4,14 @@ import SargonUniFFI extension PoolAddress { public static let sampleMainnet = Self.sampleMainnetTwo public static let sampleMainnetOther = Self.sampleMainnetSingle - + public static let sampleStokenet = Self.sampleStokenetTwo public static let sampleStokenetOther = Self.sampleStokenetSingle - + public static let sampleMainnetSingle: Self = newPoolAddressSampleMainnetSingle() public static let sampleMainnetTwo: Self = newPoolAddressSampleMainnetTwo() public static let sampleMainnetMulti: Self = newPoolAddressSampleMainnetMulti() - + public static let sampleStokenetSingle: Self = newPoolAddressSampleStokenetSingle() public static let sampleStokenetTwo: Self = newPoolAddressSampleStokenetTwo() public static let sampleStokenetMulti: Self = newPoolAddressSampleStokenetMulti() @@ -22,12 +22,12 @@ extension PoolAddress { extension PoolAddress { public static var sampleValues: [Self] { [ - Self.sampleMainnetSingle, + sampleMainnetSingle, .sampleMainnetTwo, .sampleMainnetMulti, .sampleStokenetSingle, .sampleStokenetTwo, - .sampleStokenetMulti + .sampleStokenetMulti, ] } } diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Address/ResourceAddress+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Address/ResourceAddress+SampleValues.swift index 4109e0451..95491de70 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Address/ResourceAddress+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Address/ResourceAddress+SampleValues.swift @@ -2,32 +2,29 @@ import SargonUniFFI #if DEBUG extension ResourceAddress { - public static let sampleMainnet = Self.sampleMainnetXRD public static let sampleMainnetOther = Self.sampleMainnetCandy public static let sampleStokenet = Self.sampleStokenetXRD public static let sampleStokenetOther = Self.sampleStokenetGum - + public static let sampleMainnetXRD: Self = newResourceAddressSampleMainnetXrd() public static let sampleMainnetCandy: Self = newResourceAddressSampleMainnetCandy() - + /// Gumball Club membership NFT resource address public static let sampleMainnetNonFungibleGCMembership: Self = newResourceAddressSampleMainnetNftGcMembership() - + public static let sampleStokenetXRD: Self = newResourceAddressSampleStokenetXrd() public static let sampleStokenetGum: Self = newResourceAddressSampleStokenetGum() public static let sampleStokenetGC: Self = newResourceAddressSampleStokenetGcTokens() public static let sampleStokenetCandy: Self = newResourceAddressSampleStokenetCandy() - } #endif #if DEBUG extension ResourceAddress { - public static var sampleValues: [Self] { - return [ - Self.sampleMainnetXRD, + [ + sampleMainnetXRD, .sampleMainnetCandy, .sampleMainnetNonFungibleGCMembership, .sampleStokenetXRD, diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Address/ValidatorAddress+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Address/ValidatorAddress+SampleValues.swift index d94e6e0c5..18ccdb7cf 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Address/ValidatorAddress+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Address/ValidatorAddress+SampleValues.swift @@ -4,11 +4,10 @@ import SargonUniFFI extension ValidatorAddress { public static let sample = Self.sampleMainnet public static let sampleOther = Self.sampleMainnetOther - + public static let sampleMainnet: Self = newValidatorAddressSampleMainnet() public static let sampleMainnetOther: Self = newValidatorAddressSampleMainnetOther() public static let sampleStokenet: Self = newValidatorAddressSampleStokenet() public static let sampleStokenetOther: Self = newValidatorAddressSampleStokenetOther() } #endif - diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Address/VaultAddress+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Address/VaultAddress+SampleValues.swift index 05394b629..1f4aaa2ee 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Address/VaultAddress+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Address/VaultAddress+SampleValues.swift @@ -2,13 +2,12 @@ import SargonUniFFI #if DEBUG extension VaultAddress { - public static let sampleMainnet = Self.sampleMainnetFungible public static let sampleMainnetOther = Self.sampleMainnetNonFungible - + public static let sampleStokenet = Self.sampleStokenetFungible public static let sampleStokenetOther = Self.sampleStokenetNonFungible - + public static let sampleMainnetFungible: Self = newVaultAddressSampleMainnetFungible() public static let sampleMainnetNonFungible: Self = newVaultAddressSampleMainnetNonFungible() public static let sampleStokenetFungible: Self = newVaultAddressSampleStokenetFungible() diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/AccountPath+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/AccountPath+SampleValues.swift index 155c1331c..2dd0da606 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/AccountPath+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/AccountPath+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension AccountPath { - public static let sample: Self = newAccountPathSample() - public static let sampleOther: Self = newAccountPathSampleOther() + public static let sample: Self = newAccountPathSample() + public static let sampleOther: Self = newAccountPathSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/Hardened+Samples.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/Hardened+Samples.swift index fe11d6e76..cb78fc50e 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/Hardened+Samples.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/Hardened+Samples.swift @@ -1,16 +1,8 @@ -// -// Hardened+Samples.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI - #if DEBUG extension Hardened { - public static let sample: Self = newHardenedSample() - public static let sampleOther: Self = newHardenedSampleOther() + public static let sample: Self = newHardenedSample() + public static let sampleOther: Self = newHardenedSampleOther() } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/HdPathComponent+Samples.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/HdPathComponent+Samples.swift index 977db8f8c..93f3fe320 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/HdPathComponent+Samples.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/HdPathComponent+Samples.swift @@ -5,9 +5,10 @@ // Created by Alexander Cyon on 2024-10-25. // import SargonUniFFI + #if DEBUG extension HdPathComponent { - public static let sample: Self = newHdPathComponentSample() - public static let sampleOther: Self = newHdPathComponentSampleOther() + public static let sample: Self = newHdPathComponentSample() + public static let sampleOther: Self = newHdPathComponentSampleOther() } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/SecurifiedU30+Samples.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/SecurifiedU30+Samples.swift index dbedef790..6a5c17d61 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/SecurifiedU30+Samples.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/SecurifiedU30+Samples.swift @@ -1,15 +1,8 @@ -// -// SecurifiedU30+Samples.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI #if DEBUG extension SecurifiedU30 { - public static let sample: Self = newSecurifiedSample() - public static let sampleOther: Self = newSecurifiedSampleOther() + public static let sample: Self = newSecurifiedSample() + public static let sampleOther: Self = newSecurifiedSampleOther() } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/U30+Samples.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/U30+Samples.swift index 12cd5e3cf..6769f6288 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/U30+Samples.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/U30+Samples.swift @@ -1,15 +1,8 @@ -// -// U30+Samples.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI #if DEBUG extension U30 { - public static let sample: Self = newU30Sample() - public static let sampleOther: Self = newU30SampleOther() + public static let sample: Self = newU30Sample() + public static let sampleOther: Self = newU30SampleOther() } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/U31+Samples.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/U31+Samples.swift index de0c3a83a..397cbe9a3 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/U31+Samples.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/U31+Samples.swift @@ -1,15 +1,8 @@ -// -// U31+Samples.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI #if DEBUG extension U31 { - public static let sample: Self = newU31Sample() - public static let sampleOther: Self = newU31SampleOther() + public static let sample: Self = newU31Sample() + public static let sampleOther: Self = newU31SampleOther() } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/Unhardened+Samples.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/Unhardened+Samples.swift index c5a8ec4c8..e91071307 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/Unhardened+Samples.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/Unhardened+Samples.swift @@ -1,15 +1,8 @@ -// -// Unhardened+Samples.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI #if DEBUG extension Unhardened { - public static let sample: Self = newUnhardenedSample() - public static let sampleOther: Self = newUnhardenedSampleOther() + public static let sample: Self = newUnhardenedSample() + public static let sampleOther: Self = newUnhardenedSampleOther() } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/UnsecurifiedHardened+Samples.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/UnsecurifiedHardened+Samples.swift index bc56b1aa1..0c6c35c1c 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/UnsecurifiedHardened+Samples.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP32/UnsecurifiedHardened+Samples.swift @@ -1,15 +1,8 @@ -// -// UnsecurifiedHardened+Samples.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI #if DEBUG extension UnsecurifiedHardened { - public static let sample: Self = newUnsecurifiedHardenedSample() - public static let sampleOther: Self = newUnsecurifiedHardenedSampleOther() + public static let sample: Self = newUnsecurifiedHardenedSample() + public static let sampleOther: Self = newUnsecurifiedHardenedSampleOther() } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/BIP39Language+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/BIP39Language+SampleValues.swift index 435b2dc32..7b0ee9f95 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/BIP39Language+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/BIP39Language+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension BIP39Language { - public static let sample: Self = newBip39LanguageSample() - public static let sampleOther: Self = newBip39LanguageSampleOther() + public static let sample: Self = newBip39LanguageSample() + public static let sampleOther: Self = newBip39LanguageSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/BIP39Word+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/BIP39Word+SampleValues.swift index a33da5230..c8b21f05d 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/BIP39Word+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/BIP39Word+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-24. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/Mnemonic+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/Mnemonic+SampleValues.swift index f2ff5b549..b9518a3d6 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/Mnemonic+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/Mnemonic+SampleValues.swift @@ -4,7 +4,7 @@ import SargonUniFFI extension Mnemonic { public static let sample: Self = newMnemonicSample() public static let sampleOther: Self = newMnemonicSampleOther() - + public static let sampleDevice: Self = newMnemonicSampleDevice() public static let sampleDeviceOther: Self = newMnemonicSampleDeviceOther() public static let sampleDevice12Words: Self = newMnemonicSampleDevice12Words() @@ -20,8 +20,8 @@ extension Mnemonic { public static let samplePassphrase: Self = newMnemonicSamplePassphrase() public static let samplePassphraseOther: Self = newMnemonicSamplePassphraseOther() - public static let sample24ZooVote: Self = try! Self(phrase: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote") - + public static let sample24ZooVote: Self = try! Self(phrase: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote") + public static let sampleValues: [Self] = [ .sampleDevice, .sampleDeviceOther, @@ -36,7 +36,7 @@ extension Mnemonic { .sampleSecurityQuestions, .sampleSecurityQuestionsOther, .samplePassphrase, - .samplePassphraseOther + .samplePassphraseOther, ] } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/MnemonicWithPassphrase+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/MnemonicWithPassphrase+SampleValues.swift index 1d551b13d..eae9e6dbc 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/MnemonicWithPassphrase+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP39/MnemonicWithPassphrase+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP44LikePath+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP44LikePath+SampleValues.swift index 8f3d25942..ed5776b65 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP44LikePath+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/BIP44LikePath+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension BIP44LikePath { - public static let sample: Self = newBip44LikePathSample() - public static let sampleOther: Self = newBip44LikePathSampleOther() + public static let sample: Self = newBip44LikePathSample() + public static let sampleOther: Self = newBip44LikePathSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/DerivationPath+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/DerivationPath+SampleValues.swift index be088bc42..4fb600c81 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/DerivationPath+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/DerivationPath+SampleValues.swift @@ -1,17 +1,9 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI #if DEBUG extension DerivationPath { - public static let sample: Self = newDerivationPathSample() - public static let sampleOther: Self = newDerivationPathSampleOther() + public static let sample: Self = newDerivationPathSample() + public static let sampleOther: Self = newDerivationPathSampleOther() } #endif // DEBUG - diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/IdentityPath+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/IdentityPath+SampleValues.swift index 66565a142..644c1841a 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/IdentityPath+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Derivation/IdentityPath+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension IdentityPath { - public static let sample: Self = newIdentityPathSample() - public static let sampleOther: Self = newIdentityPathSampleOther() + public static let sample: Self = newIdentityPathSample() + public static let sampleOther: Self = newIdentityPathSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/Hash+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/Hash+SampleValues.swift index d51d0d997..712cc6ced 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/Hash+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/Hash+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension Hash { - public static let sample: Self = newHashSample() - public static let sampleOther: Self = newHashSampleOther() + public static let sample: Self = newHashSample() + public static let sampleOther: Self = newHashSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/SignedTransactionIntentHash+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/SignedTransactionIntentHash+SampleValues.swift index 95e671842..a393abe8a 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/SignedTransactionIntentHash+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/SignedTransactionIntentHash+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension SignedTransactionIntentHash { - public static let sample: Self = newSignedIntentHashSample() - public static let sampleOther: Self = newSignedIntentHashSampleOther() + public static let sample: Self = newSignedIntentHashSample() + public static let sampleOther: Self = newSignedIntentHashSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/SubintentHash+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/SubintentHash+SampleValues.swift index 217d6438d..d36cd80e3 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/SubintentHash+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/SubintentHash+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension SubintentHash { - public static let sample: Self = newSubintentHashSample() - public static let sampleOther: Self = newSubintentHashSampleOther() + public static let sample: Self = newSubintentHashSample() + public static let sampleOther: Self = newSubintentHashSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/TransactionIntentHash+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/TransactionIntentHash+SampleValues.swift index 78efbc35e..5f757ccfe 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/TransactionIntentHash+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Hash/TransactionIntentHash+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension TransactionIntentHash { - public static let sample: Self = newTransactionIntentHashSample() - public static let sampleOther: Self = newTransactionIntentHashSampleOther() + public static let sample: Self = newTransactionIntentHashSample() + public static let sampleOther: Self = newTransactionIntentHashSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Keys/Ed25519PublicKey+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Keys/Ed25519PublicKey+SampleValues.swift index dbd8d4bda..a6930c268 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Keys/Ed25519PublicKey+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Keys/Ed25519PublicKey+SampleValues.swift @@ -1,6 +1,7 @@ import SargonUniFFI #if DEBUG + // MARK: Sample Values extension Ed25519PublicKey { public static let sample: Self = newEd25519PublicKeySample() diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Keys/HierarchicalDeterministicPublicKey+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Keys/HierarchicalDeterministicPublicKey+SampleValues.swift index c68dc36dd..443aa7818 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Keys/HierarchicalDeterministicPublicKey+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Keys/HierarchicalDeterministicPublicKey+SampleValues.swift @@ -1,17 +1,9 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI #if DEBUG extension HierarchicalDeterministicPublicKey { - public static let sample: Self = newHierarchicalDeterministicPublicKeySample() - public static let sampleOther: Self = newHierarchicalDeterministicPublicKeySampleOther() + public static let sample: Self = newHierarchicalDeterministicPublicKeySample() + public static let sampleOther: Self = newHierarchicalDeterministicPublicKeySampleOther() } #endif // DEBUG - diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Keys/Secp256k1PublicKey+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Keys/Secp256k1PublicKey+SampleValues.swift index f8136a07a..1f23c70dc 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Keys/Secp256k1PublicKey+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Keys/Secp256k1PublicKey+SampleValues.swift @@ -1,6 +1,7 @@ import SargonUniFFI #if DEBUG + // MARK: Sample Values extension Secp256k1PublicKey { public static let sample: Self = newSecp256k1PublicKeySample() diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Nonce+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Nonce+SampleValues.swift index d725f80e3..b48db93f2 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Nonce+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Nonce+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension Nonce { - public static let sample: Self = newNonceSample() - public static let sampleOther: Self = newNonceSampleOther() + public static let sample: Self = newNonceSample() + public static let sampleOther: Self = newNonceSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Signatures/SignatureWithPublicKey+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Signatures/SignatureWithPublicKey+SampleValues.swift index 0339c5bac..8127deb68 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Signatures/SignatureWithPublicKey+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Crypto/Signatures/SignatureWithPublicKey+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension SignatureWithPublicKey { - public static let sample: Self = newSignatureWithPublicKeySample() - public static let sampleOther: Self = newSignatureWithPublicKeySampleOther() + public static let sample: Self = newSignatureWithPublicKeySample() + public static let sampleOther: Self = newSignatureWithPublicKeySampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/Bytes/BagOfBytes+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/Bytes/BagOfBytes+SampleValues.swift index 1cbe6928f..090d262dd 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/Bytes/BagOfBytes+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/Bytes/BagOfBytes+SampleValues.swift @@ -1,5 +1,5 @@ -import SargonUniFFI import Foundation +import SargonUniFFI #if DEBUG extension BagOfBytes { diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/Decimal192+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/Decimal192+SampleValues.swift index 947325c97..4f7007829 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/Decimal192+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/Decimal192+SampleValues.swift @@ -3,7 +3,7 @@ import SargonUniFFI #if DEBUG extension Decimal192 { - public static let sample: Self = 123456789 - public static let sampleOther: Self = Self.max + public static let sample: Self = 123_456_789 + public static let sampleOther: Self = .max } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/DependencyInformation+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/DependencyInformation+SampleValues.swift index 3847dc62b..018cab53b 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/DependencyInformation+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/DependencyInformation+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension DependencyInformation { - public static let sample: Self = newDependencyInformationSample() - public static let sampleOther: Self = newDependencyInformationSampleOther() + public static let sample: Self = newDependencyInformationSample() + public static let sampleOther: Self = newDependencyInformationSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NetworkID+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NetworkID+SampleValues.swift index ceadd2b68..0c828598a 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NetworkID+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NetworkID+SampleValues.swift @@ -3,7 +3,7 @@ import SargonUniFFI #if DEBUG extension NetworkID { public static let sample = Self.mainnet - + public static let sampleOther = Self.stokenet } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NonFungibleGlobalID+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NonFungibleGlobalID+SampleValues.swift index a010c0ea2..ec7d27d81 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NonFungibleGlobalID+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NonFungibleGlobalID+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension NonFungibleGlobalID { - public static let sample: Self = newNonFungibleGlobalIdSample() - public static let sampleOther: Self = newNonFungibleGlobalIdSampleOther() + public static let sample: Self = newNonFungibleGlobalIdSample() + public static let sampleOther: Self = newNonFungibleGlobalIdSampleOther() } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NonFungibleLocalID+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NonFungibleLocalID+SampleValues.swift index 6f5f930f9..790db8ab9 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NonFungibleLocalID+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NonFungibleLocalID+SampleValues.swift @@ -2,9 +2,9 @@ import SargonUniFFI #if DEBUG extension NonFungibleLocalID { - public static let sample: Self = newNonFungibleLocalIdSample() - public static let sampleOther: Self = newNonFungibleLocalIdSampleOther() - + public static let sample: Self = newNonFungibleLocalIdSample() + public static let sampleOther: Self = newNonFungibleLocalIdSampleOther() + /// Generates a new `NonFungibleLocalID::Bytes` with 64 bytes. public static func random() -> Self { newNonFungibleLocalIdRandom() diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NonFungibleLocalIDString+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NonFungibleLocalIDString+SampleValues.swift index a0c460ba2..f9759b871 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NonFungibleLocalIDString+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/NonFungibleLocalIDString+SampleValues.swift @@ -2,8 +2,7 @@ import SargonUniFFI #if DEBUG extension NonFungibleLocalIDString { - public static let sample: Self = "Member_237" - public static let sampleOther: Self = "foobar" + public static let sample: Self = "Member_237" + public static let sampleOther: Self = "foobar" } #endif // DEBUG - diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/RequestedQuantity+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/RequestedQuantity+SampleValues.swift index a8c779295..a47cbd557 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/RequestedQuantity+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/RequestedQuantity+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/ResourceOrNonFungible+SampeValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/ResourceOrNonFungible+SampeValues.swift index 162aefe9f..044bb998e 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/ResourceOrNonFungible+SampeValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/ResourceOrNonFungible+SampeValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/SargonBuildInformation+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/SargonBuildInformation+SampleValues.swift index 078092551..bd9480bbf 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Prelude/SargonBuildInformation+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Prelude/SargonBuildInformation+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension SargonBuildInformation { - public static let sample: Self = newSargonBuildInformationSample() - public static let sampleOther: Self = newSargonBuildInformationSampleOther() + public static let sample: Self = newSargonBuildInformationSample() + public static let sampleOther: Self = newSargonBuildInformationSampleOther() } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Account/Account+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Account/Account+SampleValues.swift index 2832989de..1c2ed01b4 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Account/Account+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Account/Account+SampleValues.swift @@ -10,12 +10,12 @@ extension Account { public static let sampleStokenetNadia: Self = newAccountSampleStokenetNadia() public static let sampleStokenetOlivia: Self = newAccountSampleStokenetOlivia() public static let sampleStokenetPaige: Self = newAccountSampleStokenetPaige() - + public static let sampleMainnet = Self.sampleMainnetAlice public static let sampleMainnetOther = Self.sampleMainnetBob public static let sampleMainnetThird = Self.sampleMainnetCarol public static let sampleMainnetFourth = Self.sampleMainnetDiana - + public static let sampleStokenet = Self.sampleStokenetNadia public static let sampleStokenetOther = Self.sampleStokenetOlivia public static let sampleStokenetThird = Self.sampleStokenetPaige diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Account/EntityFlag+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Account/EntityFlag+SampleValues.swift index 5918c479f..d7f33f176 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Account/EntityFlag+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Account/EntityFlag+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Account/ThirdPartyDeposits+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Account/ThirdPartyDeposits+SampleValues.swift index 8928f22d8..bc1d10932 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Account/ThirdPartyDeposits+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Account/ThirdPartyDeposits+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension ThirdPartyDeposits { - public static let sample: Self = newThirdPartyDepositsSample() - public static let sampleOther: Self = newThirdPartyDepositsSampleOther() + public static let sample: Self = newThirdPartyDepositsSample() + public static let sampleOther: Self = newThirdPartyDepositsSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/AppPreferences+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/AppPreferences+SampleValues.swift index 5c288886f..bc26a4333 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/AppPreferences+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/AppPreferences+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/AssetException+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/AssetException+SampleValues.swift index fb45ab159..46399c996 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/AssetException+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/AssetException+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/AssetPreferences+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/AssetPreferences+SampleValues.swift index a629ae2b6..ffd0b3c55 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/AssetPreferences+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/AssetPreferences+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Matias Bzurovski on 13/8/24. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/AuthorizedDapp/AuthorizedDapp+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/AuthorizedDapp/AuthorizedDapp+SampleValues.swift index a8aaac0c1..39f722551 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/AuthorizedDapp/AuthorizedDapp+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/AuthorizedDapp/AuthorizedDapp+SampleValues.swift @@ -2,13 +2,12 @@ import SargonUniFFI #if DEBUG extension AuthorizedDapp { - public static let sample = Self.sampleMainnet public static let sampleOther = Self.sampleMainnetOther - + public static let sampleMainnet: Self = newAuthorizedDappSampleMainnetDashboard() public static let sampleMainnetOther: Self = newAuthorizedDappSampleMainnetGumballclub() - + public static let sampleStokenet: Self = newAuthorizedDappSampleStokenetSandbox() public static let sampleStokenetOther: Self = newAuthorizedDappSampleStokenetDevconsole() } diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/AuthorizedDapp/AuthorizedPersonaSimple+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/AuthorizedDapp/AuthorizedPersonaSimple+SampleValues.swift index bafac9d33..d5317a249 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/AuthorizedDapp/AuthorizedPersonaSimple+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/AuthorizedDapp/AuthorizedPersonaSimple+SampleValues.swift @@ -2,13 +2,12 @@ import SargonUniFFI #if DEBUG extension AuthorizedPersonaSimple { - public static let sample = Self.sampleMainnet public static let sampleOther = Self.sampleMainnetOther - + public static let sampleMainnet: Self = newAuthorizedPersonaSimpleSampleMainnet() public static let sampleMainnetOther: Self = newAuthorizedPersonaSimpleSampleMainnetOther() - + public static let sampleStokenet: Self = newAuthorizedPersonaSimpleSampleStokenet() public static let sampleStokenetOther: Self = newAuthorizedPersonaSimpleSampleStokenetOther() } diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/Accounts+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/Accounts+SampleValues.swift index 2ac56bab1..51ea5171c 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/Accounts+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/Accounts+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AccountsForDisplay+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AccountsForDisplay+SampleValues.swift index 0be872a6c..4946fa733 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AccountsForDisplay+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AccountsForDisplay+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AccountsOrPersonas+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AccountsOrPersonas+SampleValues.swift index 06226a6aa..8d7db0910 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AccountsOrPersonas+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AccountsOrPersonas+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AssetsExceptionList+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AssetsExceptionList+SampleValues.swift index a8dd47746..992481cc1 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AssetsExceptionList+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AssetsExceptionList+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AuthorizedDapps+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AuthorizedDapps+SampleValues.swift index 1c38b0c26..c174446b3 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AuthorizedDapps+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/AuthorizedDapps+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/DepositorsAllowList+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/DepositorsAllowList+SampleValues.swift index 327be51f4..016495356 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/DepositorsAllowList+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/DepositorsAllowList+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/DetailedAuthorizedPersonas+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/DetailedAuthorizedPersonas+SampleValues.swift index acf954629..134e18524 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/DetailedAuthorizedPersonas+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/DetailedAuthorizedPersonas+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/EntityFlags+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/EntityFlags+SampleValues.swift index 33e1cdb0f..4ae0caba7 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/EntityFlags+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/EntityFlags+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/FactorSources+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/FactorSources+SampleValues.swift index b8e75de9a..54b8266c5 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/FactorSources+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/FactorSources+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/Gateways+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/Gateways+SampleValues.swift index 01adb9096..0a0128136 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/Gateways+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/Gateways+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/NetworkDefinition+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/NetworkDefinition+SampleValues.swift index 572c4b4cd..eac869199 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/NetworkDefinition+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/NetworkDefinition+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/Personas+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/Personas+SampleValues.swift index 0a96f5d69..549ac0167 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/Personas+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/Personas+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/ProfileNetworks+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/ProfileNetworks+SampleValues.swift index cf7bb0505..c28fb7aaf 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/ProfileNetworks+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/ProfileNetworks+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/ReferencesToAuthorizedPersonas+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/ReferencesToAuthorizedPersonas+SampleValues.swift index c0d3bd2cd..d31b7bd4d 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/ReferencesToAuthorizedPersonas+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/ReferencesToAuthorizedPersonas+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/SupportedCurves+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/SupportedCurves+SampleValues.swift index c6e30d507..c4aad0692 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/SupportedCurves+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Collection/SupportedCurves+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/DepositRule+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/DepositRule+SampleValues.swift index 1c668e696..b83d19861 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/DepositRule+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/DepositRule+SampleValues.swift @@ -1,16 +1,9 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI #if DEBUG extension DepositRule { - public static let sample: Self = newDepositRuleSample() - public static let sampleOther: Self = newDepositRuleSampleOther() + public static let sample: Self = newDepositRuleSample() + public static let sampleOther: Self = newDepositRuleSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/ArculusCardFactorSource+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/ArculusCardFactorSource+SampleValues.swift index 125746699..7937b7c72 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/ArculusCardFactorSource+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/ArculusCardFactorSource+SampleValues.swift @@ -1,17 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-28. -// - import Foundation import SargonUniFFI #if DEBUG extension ArculusCardFactorSource { public static let sample: Self = newArculusCardFactorSourceSample() - + public static let sampleOther: Self = newArculusCardFactorSourceSampleOther() } diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/FactorSourceID+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/FactorSourceID+SampleValues.swift index 332095cde..41094e6cf 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/FactorSourceID+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/FactorSourceID+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/FactorSourceKind+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/FactorSourceKind+SampleValues.swift index 5ebc69310..fd0b59d7c 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/FactorSourceKind+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/FactorSourceKind+SampleValues.swift @@ -1,16 +1,9 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI #if DEBUG extension FactorSourceKind { - public static let sample: Self = newFactorSourceKindSample() - public static let sampleOther: Self = newFactorSourceKindSampleOther() + public static let sample: Self = newFactorSourceKindSample() + public static let sampleOther: Self = newFactorSourceKindSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/OffDeviceMnemonicFactorSource+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/OffDeviceMnemonicFactorSource+SampleValues.swift index 23237da18..6d879c10b 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/OffDeviceMnemonicFactorSource+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/OffDeviceMnemonicFactorSource+SampleValues.swift @@ -1,17 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-28. -// - import Foundation import SargonUniFFI #if DEBUG extension OffDeviceMnemonicFactorSource { public static let sample: Self = newOffDeviceMnemonicFactorSourceSample() - + public static let sampleOther: Self = newOffDeviceMnemonicFactorSourceSampleOther() } diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/PassphraseFactorSource+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/PassphraseFactorSource+SampleValues.swift index ad13218b2..4b382c868 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/PassphraseFactorSource+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/PassphraseFactorSource+SampleValues.swift @@ -1,10 +1,3 @@ -// -// PassphraseFactorSource+SampleValues.swift -// -// -// Created by Michael Bakogiannis on 7/10/24. -// - import Foundation import SargonUniFFI @@ -16,4 +9,3 @@ extension PassphraseFactorSource { } #endif // DEBUG - diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/TrustedContactFactorSource+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/TrustedContactFactorSource+SampleValues.swift index b510cbd6c..f7d7f9f2f 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/TrustedContactFactorSource+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/TrustedContactFactorSource+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/TrustedContactFactorSourceContact+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/TrustedContactFactorSourceContact+SampleValues.swift index 52a5be388..bb586a9b0 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/TrustedContactFactorSourceContact+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSource/TrustedContactFactorSourceContact+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-28. -// - import Foundation import SargonUniFFI @@ -17,7 +10,7 @@ extension EmailAddress { #if DEBUG extension TrustedContactFactorSourceContact { - // FIXME replace with Sargon ones + // FIXME: replace with Sargon ones public static let sample: Self = newTrustedContactFactorSourceContactSample() public static let sampleOther: Self = newTrustedContactFactorSourceContactSampleOther() } diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSourceCryptoParameters+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSourceCryptoParameters+SampleValues.swift index 755a32b46..3cdae7272 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSourceCryptoParameters+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/FactorSourceCryptoParameters+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/HierarchicalDeterministicFactorInstance+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/HierarchicalDeterministicFactorInstance+SampleValues.swift index fdad2b011..7f70fe244 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/HierarchicalDeterministicFactorInstance+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Factor/HierarchicalDeterministicFactorInstance+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/FiatCurrency+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/FiatCurrency+SampleValues.swift index d5da7b245..fc687b9c0 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/FiatCurrency+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/FiatCurrency+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Header+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Header+SampleValues.swift index 6295f19d2..4a04c2de4 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Header+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Header+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/LedgerHardwareWalletModel+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/LedgerHardwareWalletModel+SampleValues.swift index efe40e4d3..b426e26eb 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/LedgerHardwareWalletModel+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/LedgerHardwareWalletModel+SampleValues.swift @@ -1,16 +1,9 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI #if DEBUG extension LedgerHardwareWalletModel { - public static let sample: Self = newLedgerHwWalletModelSample() - public static let sampleOther: Self = newLedgerHwWalletModelSampleOther() + public static let sample: Self = newLedgerHwWalletModelSample() + public static let sampleOther: Self = newLedgerHwWalletModelSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/MatrixOfFactorSources+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/MatrixOfFactorSources+SampleValues.swift index d47e03ad1..74ab8ba0b 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/MatrixOfFactorSources+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/MatrixOfFactorSources+SampleValues.swift @@ -1,16 +1,9 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI #if DEBUG extension MatrixOfFactorSources { - public static let sample: Self = newMatrixOfFactorSourcesSample() - public static let sampleOther: Self = newMatrixOfFactorSourcesSampleOther() + public static let sample: Self = newMatrixOfFactorSourcesSample() + public static let sampleOther: Self = newMatrixOfFactorSourcesSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/SecurityStructureMetadata+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/SecurityStructureMetadata+SampleValues.swift index 9641fc20e..94d7c5b85 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/SecurityStructureMetadata+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/SecurityStructureMetadata+SampleValues.swift @@ -1,16 +1,9 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI #if DEBUG extension SecurityStructureMetadata { - public static let sample: Self = newSecurityStructureMetadataSample() - public static let sampleOther: Self = newSecurityStructureMetadataSampleOther() + public static let sample: Self = newSecurityStructureMetadataSample() + public static let sampleOther: Self = newSecurityStructureMetadataSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/SecurityStructureOfFactorSourceIDs+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/SecurityStructureOfFactorSourceIDs+SampleValues.swift index 7f6d0c093..905b065de 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/SecurityStructureOfFactorSourceIDs+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/SecurityStructureOfFactorSourceIDs+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/SecurityStructureOfFactorSources+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/SecurityStructureOfFactorSources+SampleValues.swift index bab636d5a..c7ddf6594 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/SecurityStructureOfFactorSources+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/MFA/SecurityStructureOfFactorSources+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/OnLedgerSettings+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/OnLedgerSettings+SampleValues.swift index 13930a3ba..89e3f2b66 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/OnLedgerSettings+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/OnLedgerSettings+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-20. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/Persona+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/Persona+SampleValues.swift index 059b803fe..f5fff340e 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/Persona+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/Persona+SampleValues.swift @@ -1,30 +1,22 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI #if DEBUG extension Persona { - public static let sampleMainnetSatoshi: Self = newPersonaSampleMainnetSatoshi() public static let sampleMainnetBatman: Self = newPersonaSampleMainnetBatman() public static let sampleMainnetRipley: Self = newPersonaSampleMainnetRipley() public static let sampleMainnetTuring: Self = newPersonaSampleMainnetTuring() - + public static let sampleMainnet: Self = .sampleMainnetSatoshi public static let sampleMainnetOther: Self = .sampleMainnetBatman public static let sampleMainnetThird: Self = .sampleMainnetRipley public static let sampleMainnetForth: Self = .sampleMainnetTuring - + public static let sampleStokenetSkywalker: Self = newPersonaSampleStokenetLeiaSkywalker() public static let sampleStokenetGranger: Self = newPersonaSampleStokenetHermione() public static let sampleStokenetConnor: Self = newPersonaSampleStokenetConnor() - + public static let sampleStokenet: Self = .sampleStokenetSkywalker public static let sampleStokenetOther: Self = .sampleStokenetGranger public static let sampleStokenetThird: Self = .sampleStokenetConnor diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/PersonaData+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/PersonaData+SampleValues.swift index c4b3f1961..4b40b49da 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/PersonaData+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/PersonaData+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/PersonaDataEntryName+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/PersonaDataEntryName+SampleValues.swift index d17ec6ab7..8cc0a3918 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/PersonaDataEntryName+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/PersonaDataEntryName+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/PersonaDataEntryPhoneNumber+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/PersonaDataEntryPhoneNumber+SampleValues.swift index 2d49210a1..148501113 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/PersonaDataEntryPhoneNumber+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/PersonaDataEntryPhoneNumber+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/SharedPersonaData+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/SharedPersonaData+SampleValues.swift index 2e31a81ea..21795ce92 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/SharedPersonaData+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/Persona/PersonaData/SharedPersonaData+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Profile/ProfileNetwork+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Profile/ProfileNetwork+SampleValues.swift index c626b2a22..ed9951512 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Profile/ProfileNetwork+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Profile/ProfileNetwork+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/RET/Blob+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/RET/Blob+SampleValues.swift index e70ca8cd0..e918c209d 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/RET/Blob+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/RET/Blob+SampleValues.swift @@ -4,7 +4,7 @@ import SargonUniFFI #if DEBUG extension Blob { public static let sample = Self(data: BagOfBytes.sampleAced) - + public static let sampleOther = try! Self( data: Data( hex: String(repeating: "deadbeefabbafadecafe", count: 100) diff --git a/apple/Sources/Sargon/Extensions/SampleValues/RET/IntentSignature+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/RET/IntentSignature+SampleValues.swift index 284ff329f..0b9353318 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/RET/IntentSignature+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/RET/IntentSignature+SampleValues.swift @@ -3,7 +3,7 @@ import SargonUniFFI #if DEBUG extension IntentSignature { - public static let sample: Self = newIntentSignatureSample() - public static let sampleOther: Self = newIntentSignatureSampleOther() + public static let sample: Self = newIntentSignatureSample() + public static let sampleOther: Self = newIntentSignatureSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/RET/ResourceSpecifier+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/RET/ResourceSpecifier+SampleValues.swift index d3a523701..d79621afe 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/RET/ResourceSpecifier+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/RET/ResourceSpecifier+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension ResourceSpecifier { - public static let sample: Self = newResourceSpecifierSample() - public static let sampleOther: Self = newResourceSpecifierSampleOther() + public static let sample: Self = newResourceSpecifierSample() + public static let sampleOther: Self = newResourceSpecifierSampleOther() } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/RET/SignedIntent+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/RET/SignedIntent+SampleValues.swift index 608ac7d84..1371ee3c4 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/RET/SignedIntent+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/RET/SignedIntent+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension SignedIntent { - public static let sample: Self = newSignedIntentSample() - public static let sampleOther: Self = newSignedIntentSampleOther() + public static let sample: Self = newSignedIntentSample() + public static let sampleOther: Self = newSignedIntentSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/RET/Subintent+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/RET/Subintent+SampleValues.swift index 151e62f34..2539a69f2 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/RET/Subintent+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/RET/Subintent+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension Subintent { - public static let sample: Self = newSubintentSample() - public static let sampleOther: Self = newSubintentSampleOther() + public static let sample: Self = newSubintentSample() + public static let sampleOther: Self = newSubintentSampleOther() } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/RET/SubintentManifest+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/RET/SubintentManifest+SampleValues.swift index d2b52f4b6..04ba93301 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/RET/SubintentManifest+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/RET/SubintentManifest+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension SubintentManifest { - public static let sample: Self = newSubintentManifestSample() - public static let sampleOther: Self = newSubintentManifestSampleOther() + public static let sample: Self = newSubintentManifestSample() + public static let sampleOther: Self = newSubintentManifestSampleOther() } #endif diff --git a/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/Collection/P2PLinks+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/Collection/P2PLinks+SampleValues.swift index ab8134be5..8bb283a39 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/Collection/P2PLinks+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/Collection/P2PLinks+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/P2PLinks/P2PLink+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/P2PLinks/P2PLink+SampleValues.swift index 308c34fff..02703080f 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/P2PLinks/P2PLink+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/P2PLinks/P2PLink+SampleValues.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/P2PLinks/RadixConnectPassword+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/P2PLinks/RadixConnectPassword+SampleValues.swift index 86567d359..14adee099 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/P2PLinks/RadixConnectPassword+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/P2PLinks/RadixConnectPassword+SampleValues.swift @@ -6,4 +6,4 @@ extension RadixConnectPassword { public static let sample: Self = newRadixConnectPasswordSample() public static let sampleOther: Self = newRadixConnectPasswordSampleOther() } -#endif // DEBUG \ No newline at end of file +#endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/P2PLinks/RadixConnectPurpose+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/P2PLinks/RadixConnectPurpose+SampleValues.swift index c69865a88..712816e80 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/P2PLinks/RadixConnectPurpose+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/P2PLinks/RadixConnectPurpose+SampleValues.swift @@ -6,4 +6,4 @@ extension RadixConnectPurpose { public static let sample: Self = newRadixConnectPurposeSample() public static let sampleOther: Self = newRadixConnectPurposeSampleOther() } -#endif // DEBUG \ No newline at end of file +#endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/WalletInteraction/WalletToDappInteractionResponse+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/WalletInteraction/WalletToDappInteractionResponse+SampleValues.swift index c2b0ca869..514d9a230 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/WalletInteraction/WalletToDappInteractionResponse+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/WalletInteraction/WalletToDappInteractionResponse+SampleValues.swift @@ -6,4 +6,4 @@ extension WalletToDappInteractionResponse { public static let sample: Self = newWalletToDappInteractionResponseSample() public static let sampleOther: Self = newWalletToDappInteractionResponseSampleOther() } -#endif // DEBUG \ No newline at end of file +#endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/WalletInteractionWalletAccount+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/WalletInteractionWalletAccount+SampleValues.swift index adbbaa476..07eb89e3c 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/WalletInteractionWalletAccount+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/RadixConnect/WalletInteractionWalletAccount+SampleValues.swift @@ -6,4 +6,4 @@ extension WalletInteractionWalletAccount { public static let sample: Self = newWalletInteractionWalletAccountSample() public static let sampleOther: Self = newWalletInteractionWalletAccountSampleOther() } -#endif // DEBUG \ No newline at end of file +#endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/SampleValues/System/Drivers/HostOS+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/System/Drivers/HostOS+SampleValues.swift index fc26cd7e0..b339fbd23 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/System/Drivers/HostOS+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/System/Drivers/HostOS+SampleValues.swift @@ -7,4 +7,3 @@ extension HostOs { public static let sampleOther: Self = newHostOsSampleOther() } #endif // DEBUG - diff --git a/apple/Sources/Sargon/Extensions/SampleValues/Transaction/TransactionHeader+SampleValues.swift b/apple/Sources/Sargon/Extensions/SampleValues/Transaction/TransactionHeader+SampleValues.swift index a979f0370..42fd6ce94 100644 --- a/apple/Sources/Sargon/Extensions/SampleValues/Transaction/TransactionHeader+SampleValues.swift +++ b/apple/Sources/Sargon/Extensions/SampleValues/Transaction/TransactionHeader+SampleValues.swift @@ -2,7 +2,7 @@ import SargonUniFFI #if DEBUG extension TransactionHeader { - public static let sample = newTransactionHeaderSample() - public static let sampleOther = newTransactionHeaderSampleOther() + public static let sample = newTransactionHeaderSample() + public static let sampleOther = newTransactionHeaderSampleOther() } #endif diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Address/Address+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Address/Address+Swiftified.swift index 4129462af..f8e1e92d2 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Address/Address+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Address/Address+Swiftified.swift @@ -1,18 +1,18 @@ import SargonUniFFI +// MARK: - Address + AddressProtocol extension Address: AddressProtocol { - public var asGeneral: Address { self } - + public func asSpecific(type: A.Type = A.self) throws -> A { try A(validatingAddress: self.address) } - + #if DEBUG public static func random(networkID: NetworkID) -> Self { - Self.account(.random(networkID: networkID)) + account(.random(networkID: networkID)) } #endif // DEBUG } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Address/NonFungibleResourceAddress+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Address/NonFungibleResourceAddress+Swiftified.swift index c1c26ac79..b9c535072 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Address/NonFungibleResourceAddress+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Address/NonFungibleResourceAddress+Swiftified.swift @@ -1,5 +1,6 @@ import SargonUniFFI +// MARK: - NonFungibleResourceAddress + AddressProtocol extension NonFungibleResourceAddress: AddressProtocol {} extension NonFungibleResourceAddress { @@ -7,4 +8,3 @@ extension NonFungibleResourceAddress { .resource(asResourceAddress) } } - diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Address/ResourceAddress+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Address/ResourceAddress+Swiftified.swift index 314a3b7d2..6254742bb 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Address/ResourceAddress+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Address/ResourceAddress+Swiftified.swift @@ -1,25 +1,25 @@ import Foundation import SargonUniFFI +// MARK: - ResourceAddress + AddressProtocol extension ResourceAddress: AddressProtocol {} extension ResourceAddress { + public var isXRD: Bool { + self == self.xrdOnSameNetwork + } - public var isXRD: Bool { - self == self.xrdOnSameNetwork - } - - public var asNonFungibleResourceAddress: NonFungibleResourceAddress? { + public var asNonFungibleResourceAddress: NonFungibleResourceAddress? { try? NonFungibleResourceAddress(validatingAddress: address) } - + public func isXRD(on networkID: NetworkID) -> Bool { self == Self.xrd(on: networkID) } - + /// The ResourceAddress of XRD of mainnet public static let mainnetXRD = Self.xrd(on: .mainnet) - + public var asGeneral: Address { .resource(self) } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/AccountPath+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/AccountPath+Swiftified.swift index 438bd066f..60c78064d 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/AccountPath+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/AccountPath+Swiftified.swift @@ -1,23 +1,20 @@ import Foundation import SargonUniFFI -extension AccountPath: SargonModel, DerivationPathProtocol { - -} +// MARK: - AccountPath + SargonModel, DerivationPathProtocol +extension AccountPath: SargonModel, DerivationPathProtocol {} extension AccountPath { - public init(string: String) throws { - switch try DerivationPath(string: string) { - case let .account(value): - self = value - case .identity, .bip44Like: + public init(string: String) throws { + switch try DerivationPath(string: string) { + case let .account(value): + self = value + case .identity, .bip44Like: throw SargonError.WrongEntityKind(expected: .account, found: .identity) - } + } + } - } - - public var asGeneral: DerivationPath { - .account(value: self) - } + public var asGeneral: DerivationPath { + .account(value: self) + } } - diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/Hardened+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/Hardened+Swiftified.swift index c3603d8a9..6235451ac 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/Hardened+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/Hardened+Swiftified.swift @@ -1,10 +1,3 @@ -// -// Hardened+Swiftified.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI extension Hardened: SargonModel {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/HdPathComponent+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/HdPathComponent+Swiftified.swift index 35ea52912..d9d362d49 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/HdPathComponent+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/HdPathComponent+Swiftified.swift @@ -1,29 +1,24 @@ -// -// HdPathComponent+Swiftified.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - import SargonUniFFI +// MARK: - HdPathComponent + BaseHDPathComponentProtocol extension HdPathComponent: BaseHDPathComponentProtocol {} - +// MARK: - HdPathComponent + CustomDebugStringConvertible extension HdPathComponent: CustomDebugStringConvertible { - public var debugDescription: String { - toBIP32String() - } + public var debugDescription: String { + toBIP32String() + } } +// MARK: - HdPathComponent + CustomStringConvertible extension HdPathComponent: CustomStringConvertible { - public var description: String { - toBIP32StringDebug() - } + public var description: String { + toBIP32StringDebug() + } } extension HdPathComponent { - public func asHardened() throws -> Hardened { - try hdPathComponentToHardened(component: self) - } + public func asHardened() throws -> Hardened { + try hdPathComponentToHardened(component: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/Securified+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/Securified+Swiftified.swift index 0ea377d34..45c1ffaa3 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/Securified+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/Securified+Swiftified.swift @@ -1,9 +1 @@ -// -// Securified+Swiftified.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - - extension SecurifiedU30: HDPathComponentProtocol {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/Unhardened+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/Unhardened+Swiftified.swift index 3fb344217..2b9146670 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/Unhardened+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/Unhardened+Swiftified.swift @@ -1,9 +1 @@ -// -// Unhardened+Swiftified.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - - extension Unhardened: HDPathComponentProtocol {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/UnsecurifiedHardened+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/UnsecurifiedHardened+Swiftified.swift index a88511afb..d49872a65 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/UnsecurifiedHardened+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP32/UnsecurifiedHardened+Swiftified.swift @@ -1,8 +1 @@ -// -// UnsecurifiedHardened+Swiftified.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - extension UnsecurifiedHardened: HDPathComponentProtocol {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP39/BIP39Language+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP39/BIP39Language+Swiftified.swift index 8220271db..f4b5a5716 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP39/BIP39Language+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP39/BIP39Language+Swiftified.swift @@ -1,12 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI public typealias BIP39Language = Bip39Language + +// MARK: - BIP39Language + SargonModel extension BIP39Language: SargonModel {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP39/BIP39WordCount+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP39/BIP39WordCount+Swiftified.swift index 196c78605..1cc6527e1 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP39/BIP39WordCount+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP39/BIP39WordCount+Swiftified.swift @@ -1,15 +1,9 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI public typealias BIP39WordCount = Bip39WordCount +// MARK: - BIP39WordCount + SargonModel extension BIP39WordCount: SargonModel { public static let sample: Self = .twentyFour public static let sampleOther: Self = .twelve @@ -21,7 +15,7 @@ extension BIP39WordCount { } } -// MARK: Identifiable +// MARK: - BIP39WordCount + Identifiable extension BIP39WordCount: Identifiable { public typealias ID = RawValue public var id: ID { @@ -29,7 +23,7 @@ extension BIP39WordCount: Identifiable { } } -// MARK: Comparable +// MARK: - BIP39WordCount + Comparable extension BIP39WordCount: Comparable { public static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue @@ -39,14 +33,14 @@ extension BIP39WordCount: Comparable { extension BIP39WordCount { public mutating func increaseBy3() { guard self < .twentyFour else { - return assertionFailure("At max word count (24)") + return assertionFailure("At max word count (24)") } self = .init(rawValue: rawValue + 3)! } public mutating func decreaseBy3() { - guard self > .twelve else { - return assertionFailure("At min word count (12)") + guard self > .twelve else { + return assertionFailure("At min word count (12)") } self = .init(rawValue: rawValue - 3)! } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP39Word+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP39Word+Swiftified.swift index 3004f4074..dd0490d4a 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP39Word+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP39Word+Swiftified.swift @@ -1,11 +1,14 @@ import SargonUniFFI public typealias BIP39Word = Bip39Word + +// MARK: - BIP39Word + SargonModel extension BIP39Word: SargonModel {} + +// MARK: - BIP39Word + Identifiable extension BIP39Word: Identifiable { - public typealias ID = U11 - + public var id: ID { index } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP44LikePath+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP44LikePath+Swiftified.swift index 771700eee..8f4e854c9 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP44LikePath+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/BIP44LikePath+Swiftified.swift @@ -3,17 +3,20 @@ import SargonUniFFI public typealias BIP44LikePath = Bip44LikePath +// MARK: - BIP44LikePath + SargonModel, DerivationPathProtocol extension BIP44LikePath: SargonModel, DerivationPathProtocol { - public var asGeneral: DerivationPath { - .bip44Like(value: self) - } - public var asDerivationPath: DerivationPath { - .bip44Like(value: self) - } + public var asGeneral: DerivationPath { + .bip44Like(value: self) + } + + public var asDerivationPath: DerivationPath { + .bip44Like(value: self) + } } +// MARK: - BIP44LikePath + CustomStringConvertible extension BIP44LikePath: CustomStringConvertible { - public var description: String { - toString() - } + public var description: String { + toString() + } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/DerivationPath+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/DerivationPath+Swiftified.swift index c782ac5e9..6c0be182c 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/DerivationPath+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/DerivationPath+Swiftified.swift @@ -1,61 +1,58 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI +// MARK: - DerivationPath + SargonModel extension DerivationPath: SargonModel {} + +// MARK: - DerivationPath + CustomStringConvertible extension DerivationPath: CustomStringConvertible { - public var description: String { - toString() - } + public var description: String { + toString() + } } +// MARK: - DerivationPath + DerivationPathProtocol extension DerivationPath: DerivationPathProtocol { - public var asGeneral: DerivationPath { - self - } - - public var asDerivationPath: DerivationPath { self } + public var asGeneral: DerivationPath { + self + } + + public var asDerivationPath: DerivationPath { self } } public typealias HDPath = HdPath extension DerivationPath { /// Returns the last path component - public var lastPathComponent: HdPathComponent { - self.path.components.last! // safe to unwrap, we disallow empty paths. + public var lastPathComponent: HdPathComponent { + self.path.components.last! // safe to unwrap, we disallow empty paths. + } + + public var curve: SLIP10Curve { + switch self { + case .bip44Like: .secp256k1 + case .account, .identity: .curve25519 + } + } + + public static func forEntity( + kind: EntityKind, + networkID: NetworkID, + index: Hardened + ) -> Self { + switch kind { + case .account: + AccountPath( + networkID: networkID, + keyKind: .transactionSigning, + index: index + ).asGeneral + case .persona: + IdentityPath( + networkID: networkID, + keyKind: .transactionSigning, + index: index + ).asGeneral + } } - - public var curve: SLIP10Curve { - switch self { - case .bip44Like: .secp256k1 - case .account, .identity: .curve25519 - } - } - - public static func forEntity( - kind: EntityKind, - networkID: NetworkID, - index: Hardened - ) -> Self { - switch kind { - case .account: - AccountPath( - networkID: networkID, - keyKind: .transactionSigning, - index: index - ).asGeneral - case .persona: - IdentityPath( - networkID: networkID, - keyKind: .transactionSigning, - index: index - ).asGeneral - } - } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/IdentityPath+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/IdentityPath+Swiftified.swift index 3eab7554f..77d5a71a2 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/IdentityPath+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/IdentityPath+Swiftified.swift @@ -1,19 +1,20 @@ import Foundation import SargonUniFFI +// MARK: - IdentityPath + SargonModel, DerivationPathProtocol extension IdentityPath: SargonModel, DerivationPathProtocol {} extension IdentityPath { - public init(string: String) throws { - switch try DerivationPath(string: string) { - case let .identity(value): - self = value - case .account, .bip44Like: + public init(string: String) throws { + switch try DerivationPath(string: string) { + case let .identity(value): + self = value + case .account, .bip44Like: throw SargonError.WrongEntityKind(expected: .identity, found: .account) - } - } - - public var asGeneral: DerivationPath { - .identity(value: self) - } + } + } + + public var asGeneral: DerivationPath { + .identity(value: self) + } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/Mnemonic+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/Mnemonic+Swiftified.swift index e5fa22bc2..9ac4c79bc 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/Mnemonic+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/Mnemonic+Swiftified.swift @@ -1,8 +1,10 @@ import Foundation import SargonUniFFI +// MARK: - Mnemonic + SargonModel extension Mnemonic: SargonModel {} +// MARK: - Mnemonic + CustomStringConvertible extension Mnemonic: CustomStringConvertible { public var description: String { phrase diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/MnemonicWithPassphrase+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/MnemonicWithPassphrase+Swiftified.swift index d7e1ec002..191a36f1d 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/MnemonicWithPassphrase+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Derivation/MnemonicWithPassphrase+Swiftified.swift @@ -1,14 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI +// MARK: - MnemonicWithPassphrase + SargonModel extension MnemonicWithPassphrase: SargonModel {} + +// MARK: - MnemonicWithPassphrase + SargonObjectCodable extension MnemonicWithPassphrase: SargonObjectCodable {} extension MnemonicWithPassphrase { diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Hash/Hash+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Hash/Hash+Swiftified.swift index 0f2267a01..7ae27ef83 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Hash/Hash+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Hash/Hash+Swiftified.swift @@ -1,25 +1,26 @@ import Foundation import SargonUniFFI +// MARK: - Hash + SargonModel extension Hash: SargonModel {} extension Hash { - - public var hex: String { - data.hex - } - - public func hash() -> Self { - data.hash() - } + public var hex: String { + data.hex + } - public var data: Data { - bytes.data - } + public func hash() -> Self { + data.hash() + } + + public var data: Data { + bytes.data + } } +// MARK: - Hash + CustomStringConvertible extension Hash: CustomStringConvertible { - public var description: String { - hex - } + public var description: String { + hex + } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Hash/PublicKeyHash+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Hash/PublicKeyHash+Swiftified.swift index 07fa1692d..1205b57cd 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Hash/PublicKeyHash+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Hash/PublicKeyHash+Swiftified.swift @@ -1,6 +1,7 @@ import Foundation import SargonUniFFI +// MARK: - PublicKeyHash + SargonModel extension PublicKeyHash: SargonModel {} extension PublicKeyHash { @@ -9,6 +10,7 @@ extension PublicKeyHash { } } +// MARK: - PublicKeyHash + ToDataProtocol extension PublicKeyHash: ToDataProtocol { public var data: Data { switch self { diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/Ed25519PublicKey+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/Ed25519PublicKey+Swiftified.swift index 925772312..89412ec83 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/Ed25519PublicKey+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/Ed25519PublicKey+Swiftified.swift @@ -1,10 +1,12 @@ import Foundation import SargonUniFFI +// MARK: - Ed25519PublicKey + SargonStringCodable extension Ed25519PublicKey: SargonStringCodable {} - + +// MARK: - Ed25519PublicKey + PublicKeyProtocol extension Ed25519PublicKey: PublicKeyProtocol { - public var asGeneral: PublicKey { + public var asGeneral: PublicKey { PublicKey.ed25519(self) } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/HierarchicalDeterministicPublicKey+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/HierarchicalDeterministicPublicKey+Swiftified.swift index da7e482c1..d19761294 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/HierarchicalDeterministicPublicKey+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/HierarchicalDeterministicPublicKey+Swiftified.swift @@ -1,12 +1,4 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI extension HierarchicalDeterministicPublicKey: SargonModel {} - diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/PublicKey+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/PublicKey+Swiftified.swift index 90147b8c3..6ddc47d5b 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/PublicKey+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/PublicKey+Swiftified.swift @@ -2,15 +2,14 @@ import Foundation import SargonUniFFI extension PublicKey: PublicKeyProtocol { - public var asGeneral: PublicKey { + public var asGeneral: PublicKey { self } - + public var curve: SLIP10Curve { switch self { - case .ed25519: return .curve25519 - case .secp256k1: return .secp256k1 + case .ed25519: .curve25519 + case .secp256k1: .secp256k1 } } - } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/Secp256k1PublicKey+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/Secp256k1PublicKey+Swiftified.swift index 034e86196..93a54288d 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/Secp256k1PublicKey+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Keys/Secp256k1PublicKey+Swiftified.swift @@ -2,7 +2,7 @@ import Foundation import SargonUniFFI extension Secp256k1PublicKey: PublicKeyProtocol { - public var asGeneral: PublicKey { + public var asGeneral: PublicKey { PublicKey.secp256k1(self) } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/SLIP10Curve+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/SLIP10Curve+Swiftified.swift index db3b60040..44748ee04 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/SLIP10Curve+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/SLIP10Curve+Swiftified.swift @@ -2,7 +2,10 @@ import SargonUniFFI public typealias SLIP10Curve = Slip10Curve -extension SLIP10Curve: SargonModel { } +// MARK: - SLIP10Curve + SargonModel +extension SLIP10Curve: SargonModel {} + +// MARK: - SLIP10Curve + Identifiable extension SLIP10Curve: Identifiable { public typealias ID = String public var id: ID { @@ -10,6 +13,7 @@ extension SLIP10Curve: Identifiable { } } +// MARK: - SLIP10Curve + CustomStringConvertible extension SLIP10Curve: CustomStringConvertible { public var description: String { toString() @@ -22,4 +26,5 @@ extension SLIP10Curve { } } +// MARK: - SLIP10Curve + SargonStringCodable extension SLIP10Curve: SargonStringCodable {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/Ed25519Signature+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/Ed25519Signature+Swiftified.swift index ae4356610..981e59998 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/Ed25519Signature+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/Ed25519Signature+Swiftified.swift @@ -1,17 +1,19 @@ import Foundation import SargonUniFFI +// MARK: - Ed25519Signature + SargonStringCodable extension Ed25519Signature: SargonStringCodable {} +// MARK: - Ed25519Signature + SignatureProtocol extension Ed25519Signature: SignatureProtocol { public var data: Data { bytes.data } - + public var hex: String { toString() } - + public var signature: Signature { .ed25519(value: self) } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/Secp256k1Signature+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/Secp256k1Signature+Swiftified.swift index 332903cb6..c3ba370b6 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/Secp256k1Signature+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/Secp256k1Signature+Swiftified.swift @@ -5,11 +5,11 @@ extension Secp256k1Signature: SignatureProtocol { public var data: Data { bytes.data } - + public var hex: String { toString() } - + public var signature: Signature { .secp256k1(value: self) } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/Signature+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/Signature+Swiftified.swift index 6e7b546c9..9194e24e8 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/Signature+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/Signature+Swiftified.swift @@ -5,13 +5,12 @@ extension Signature: SignatureProtocol { public var data: Data { toBytes() } - + public var hex: String { toString() } - + public var signature: Signature { self } } - diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/SignatureWithPublicKey+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/SignatureWithPublicKey+Swiftified.swift index a00d09204..2a87c88dd 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/SignatureWithPublicKey+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Crypto/Signatures/SignatureWithPublicKey+Swiftified.swift @@ -1,8 +1,10 @@ import Foundation import SargonUniFFI +// MARK: - SignatureWithPublicKey + SargonModel extension SignatureWithPublicKey: SargonModel {} +// MARK: - SignatureWithPublicKey + CustomStringConvertible extension SignatureWithPublicKey: CustomStringConvertible { public var description: String { """ @@ -12,4 +14,5 @@ extension SignatureWithPublicKey: CustomStringConvertible { } } +// MARK: - SignatureWithPublicKey + IntoSignatureProtocol extension SignatureWithPublicKey: IntoSignatureProtocol {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/BIP39Entropy+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/BIP39Entropy+Swiftified.swift index 5f043cf8e..c611ca286 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/BIP39Entropy+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/BIP39Entropy+Swiftified.swift @@ -1,4 +1,4 @@ -import SargonUniFFI import Foundation +import SargonUniFFI public typealias BIP39Entropy = Bip39Entropy diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly32Bytes+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly32Bytes+Swiftified.swift index 7f27492f1..2ea748436 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly32Bytes+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly32Bytes+Swiftified.swift @@ -1,8 +1,10 @@ import Foundation import SargonUniFFI -extension Exactly32Bytes: ExactlyNBytesProtocol { +// MARK: - Exactly32Bytes + ExactlyNBytesProtocol +extension Exactly32Bytes: ExactlyNBytesProtocol { public static let length = 32 } +// MARK: - Exactly32Bytes + SargonStringCodable extension Exactly32Bytes: SargonStringCodable {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly33Bytes+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly33Bytes+Swiftified.swift index 419be780e..f7d47fa36 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly33Bytes+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly33Bytes+Swiftified.swift @@ -1,6 +1,6 @@ import Foundation import SargonUniFFI -extension Exactly33Bytes: ExactlyNBytesProtocol { +extension Exactly33Bytes: ExactlyNBytesProtocol { public static let length = 33 } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly64Bytes+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly64Bytes+Swiftified.swift index 904d2024b..27b645703 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly64Bytes+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly64Bytes+Swiftified.swift @@ -1,6 +1,6 @@ import Foundation import SargonUniFFI -extension Exactly64Bytes: ExactlyNBytesProtocol { +extension Exactly64Bytes: ExactlyNBytesProtocol { public static let length = 64 } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly65Bytes+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly65Bytes+Swiftified.swift index 44bd76bac..7eca589cd 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly65Bytes+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Bytes/Exactly65Bytes+Swiftified.swift @@ -1,6 +1,6 @@ import Foundation import SargonUniFFI -extension Exactly65Bytes: ExactlyNBytesProtocol { +extension Exactly65Bytes: ExactlyNBytesProtocol { public static let length = 65 } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Decimal192+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Decimal192+Swiftified.swift index 592ea6c3f..a9d20b9eb 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Decimal192+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/Decimal192+Swiftified.swift @@ -1,44 +1,54 @@ import Foundation import SargonUniFFI +// MARK: - Decimal192 + SargonModel extension Decimal192: SargonModel {} +// MARK: - Decimal192 + ExpressibleByIntegerLiteral extension Decimal192: ExpressibleByIntegerLiteral { public init(integerLiteral i64: Int64) { self = Self(i64) } } +// MARK: - Decimal192 + Comparable extension Decimal192: Comparable { public static func > (lhs: Self, rhs: Self) -> Bool { lhs.greaterThan(other: rhs) } + public static func < (lhs: Self, rhs: Self) -> Bool { lhs.lessThan(other: rhs) } + public static func >= (lhs: Self, rhs: Self) -> Bool { lhs.greaterThanOrEqual(other: rhs) } + public static func <= (lhs: Self, rhs: Self) -> Bool { lhs.lessThanOrEqual(other: rhs) } } +// MARK: - Decimal192 + AdditiveArithmetic extension Decimal192: AdditiveArithmetic { public static func + (lhs: Self, rhs: Self) -> Self { lhs.add(rhs: rhs) } + public static func - (lhs: Self, rhs: Self) -> Self { lhs.sub(rhs: rhs) } } +// MARK: - Decimal192 + SignedNumeric extension Decimal192: SignedNumeric { - public prefix static func - (operand: Self) -> Self { + public static prefix func - (operand: Self) -> Self { operand.negate() } } +// MARK: - Decimal192 + Numeric extension Decimal192: Numeric { public typealias Magnitude = Self @@ -54,7 +64,7 @@ extension Decimal192: Numeric { lhs = lhs * rhs } - public init?(exactly source: T) where T: BinaryInteger { + public init?(exactly source: some BinaryInteger) { if let u64 = UInt64(exactly: source) { self = Self(u64) } else if let i64 = Int64(exactly: source) { @@ -76,17 +86,15 @@ extension Decimal192 { // this can never fail Double(self.toRawString())! } - } - extension Decimal192 { - public func toRawString() -> String { decimalToString(decimal: self) } } +// MARK: - Decimal192 + Codable extension Decimal192: Codable { @inlinable public func encode(to encoder: Encoder) throws { @@ -103,14 +111,14 @@ extension Decimal192: Codable { } extension Decimal192 { - public static let one: Self = 1 - public static let two: Self = 2 - public static let three: Self = 3 - public static let four: Self = 4 - public static let five: Self = 5 - public static let six: Self = 6 + public static let one: Self = 1 + public static let two: Self = 2 + public static let three: Self = 3 + public static let four: Self = 4 + public static let five: Self = 5 + public static let six: Self = 6 public static let seven: Self = 7 public static let eight: Self = 8 - public static let nine: Self = 9 - public static let ten: Self = 10 + public static let nine: Self = 9 + public static let ten: Self = 10 } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/DependencyInformation+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/DependencyInformation+Swiftified.swift index d82b1e48c..732bc2848 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/DependencyInformation+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/DependencyInformation+Swiftified.swift @@ -1,6 +1,9 @@ import SargonUniFFI +// MARK: - DependencyInformation + SargonModel extension DependencyInformation: SargonModel {} + +// MARK: - DependencyInformation + CustomStringConvertible extension DependencyInformation: CustomStringConvertible { public var description: String { toString() diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/DisplayName+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/DisplayName+Swiftified.swift index 44c4463d7..6b438d129 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/DisplayName+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/DisplayName+Swiftified.swift @@ -1,9 +1,13 @@ import Foundation import SargonUniFFI +// MARK: - DisplayName + SargonModel extension DisplayName: SargonModel {} + +// MARK: - DisplayName + SargonStringCodable extension DisplayName: SargonStringCodable {} +// MARK: - DisplayName + CustomStringConvertible extension DisplayName: CustomStringConvertible { public var description: String { value diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NetworkID+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NetworkID+Swiftified.swift index ba1437d7d..0f6291801 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NetworkID+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NetworkID+Swiftified.swift @@ -3,14 +3,17 @@ import SargonUniFFI public typealias NetworkID = NetworkId +// MARK: - NetworkID + SargonModel extension NetworkID: SargonModel {} +// MARK: - NetworkID + CustomStringConvertible extension NetworkID: CustomStringConvertible { public var description: String { toString() } } +// MARK: - NetworkID + Codable extension NetworkID: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NonFungibleGlobalID+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NonFungibleGlobalID+Swiftified.swift index c8bb2ee4a..fb38bc221 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NonFungibleGlobalID+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NonFungibleGlobalID+Swiftified.swift @@ -2,20 +2,21 @@ import SargonUniFFI public typealias NonFungibleGlobalID = NonFungibleGlobalId +// MARK: - NonFungibleGlobalID + IdentifiableByStringProtocol extension NonFungibleGlobalID: IdentifiableByStringProtocol { - public var localID: NonFungibleLocalID { - nonFungibleLocalId - } + public var localID: NonFungibleLocalID { + nonFungibleLocalId + } } extension NonFungibleGlobalID { - public init( - nonFungibleResourceAddress: NonFungibleResourceAddress, - localID: NonFungibleLocalID - ) { - self.init( - resourceAddress: nonFungibleResourceAddress.asResourceAddress, - nonFungibleLocalId: localID - ) - } + public init( + nonFungibleResourceAddress: NonFungibleResourceAddress, + localID: NonFungibleLocalID + ) { + self.init( + resourceAddress: nonFungibleResourceAddress.asResourceAddress, + nonFungibleLocalId: localID + ) + } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NonFungibleLocalID+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NonFungibleLocalID+Swiftified.swift index 9c5a2db1e..882ad6428 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NonFungibleLocalID+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NonFungibleLocalID+Swiftified.swift @@ -3,8 +3,10 @@ import SargonUniFFI public typealias NonFungibleLocalID = NonFungibleLocalId +// MARK: - NonFungibleLocalID + IdentifiableByStringProtocol extension NonFungibleLocalID: IdentifiableByStringProtocol {} +// MARK: - NonFungibleLocalID + ExpressibleByIntegerLiteral extension NonFungibleLocalID: ExpressibleByIntegerLiteral { public init(integerLiteral value: UInt64) { self.init(integer: value) diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NonFungibleLocalIDString+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NonFungibleLocalIDString+Swiftified.swift index a29756ce5..73e1e6489 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NonFungibleLocalIDString+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/NonFungibleLocalIDString+Swiftified.swift @@ -2,12 +2,14 @@ import Foundation import SargonUniFFI public typealias NonFungibleLocalIDString = NonFungibleLocalIdString + +// MARK: - NonFungibleLocalIDString + SargonModel extension NonFungibleLocalIDString: SargonModel {} #if DEBUG extension NonFungibleLocalIDString: ExpressibleByStringLiteral { - public init(stringLiteral value: String) { - try! self.init(validating: value) - } + public init(stringLiteral value: String) { + try! self.init(validating: value) + } } #endif diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/RequestedQuantity+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/RequestedQuantity+Swiftified.swift index 930ef743e..f5d0cda4a 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/RequestedQuantity+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/RequestedQuantity+Swiftified.swift @@ -1,18 +1,13 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI +// MARK: - RequestedQuantity + SargonModel extension RequestedQuantity: SargonModel {} + +// MARK: - RequestedQuantity + SargonObjectCodable extension RequestedQuantity: SargonObjectCodable {} extension RequestedQuantity { - public static func exactly(_ quantity: Int) -> Self { .init(quantifier: .exactly, quantity: UInt16(quantity)) } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/SargonBuildInformation+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/SargonBuildInformation+Swiftified.swift index 39e8934a2..64020d09e 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/SargonBuildInformation+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/SargonBuildInformation+Swiftified.swift @@ -1,10 +1,11 @@ import Foundation import SargonUniFFI +// MARK: - SargonBuildInformation + SargonModel extension SargonBuildInformation: SargonModel {} extension SargonBuildInformation { - public static func get() -> Self { - buildInformation() - } + public static func get() -> Self { + buildInformation() + } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/SargonError+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/SargonError+Swiftified.swift index cca645422..8ad3267ff 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Prelude/SargonError+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Prelude/SargonError+Swiftified.swift @@ -3,31 +3,35 @@ import SargonUniFFI public typealias SargonError = CommonError +// MARK: - SargonError + SargonModel extension SargonError: SargonModel {} +// MARK: - SargonError + CustomDebugStringConvertible extension SargonError: CustomDebugStringConvertible { public var debugDescription: String { "\(errorCode): \(errorMessage)" } } +// MARK: - SargonError + CustomStringConvertible extension SargonError: CustomStringConvertible { public var description: String { errorMessage } } +// MARK: - SargonError + LocalizedError extension SargonError: LocalizedError { public var errorDescription: String? { let errorCodeFormatted = "Error code: \(errorCode)" - var errorMessageFormatted: String? + var errorMessageFormatted: String? #if DEBUG - errorMessageFormatted = "Error message: \(errorMessage)" + errorMessageFormatted = "Error message: \(errorMessage)" #endif return [errorCodeFormatted, errorMessageFormatted] - .compactMap { $0 } - .joined(separator: "\n") + .compactMap { $0 } + .joined(separator: "\n") } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AccountForDisplay+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AccountForDisplay+Swiftified.swift index e26dd3693..8f96f4272 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AccountForDisplay+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AccountForDisplay+Swiftified.swift @@ -1,19 +1,13 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-28. -// - import Foundation import SargonUniFFI +// MARK: - AccountForDisplay + SargonModel extension AccountForDisplay: SargonModel {} +// MARK: - AccountForDisplay + Identifiable extension AccountForDisplay: Identifiable { public typealias ID = AccountAddress public var id: ID { address } - } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AccountOrPersona+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AccountOrPersona+Swiftified.swift index cc3efcbe4..bda4e0554 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AccountOrPersona+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AccountOrPersona+Swiftified.swift @@ -1,62 +1,56 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-27. -// - import Foundation import SargonUniFFI +// MARK: - AddressOfAccountOrPersona + BaseEntityAddressProtocol extension AddressOfAccountOrPersona: BaseEntityAddressProtocol {} extension AccountOrPersona { public static func account(_ account: Account) -> Self { .accountEntity(account) } - + public static func persona(_ persona: Persona) -> Self { .personaEntity(persona) } } +// MARK: - AccountOrPersona + EntityBaseProtocol extension AccountOrPersona: EntityBaseProtocol { public var address: EntityAddress { id } - + public var asGeneral: AccountOrPersona { self } - + public typealias ID = AddressOfAccountOrPersona public typealias EntityAddress = AddressOfAccountOrPersona - + public var securityState: EntitySecurityState { property(\.securityState) } - + /// The ID of the network this entity exists on. public var networkId: NetworkID { property(\.networkID) } - + /// A required non empty display name, used by presentation layer and sent to Dapps when requested. public var displayName: DisplayName { property(\.displayName) } - + /// Flags that are currently set on entity. public var flags: [EntityFlag] { property(\.flags) } - + public var entityKind: EntityKind { switch self { case let .accountEntity(value): value.entityKind case let .personaEntity(value): value.entityKind } } - - + public func asAccount() throws -> Account { try extract() } @@ -64,11 +58,11 @@ extension AccountOrPersona: EntityBaseProtocol { public func asPersona() throws -> Persona { try extract() } - + public func extract(_ type: F.Type = F.self) -> F? where F: EntityProtocol { F.extract(from: self) } - + public func extract(as _: F.Type = F.self) throws -> F where F: EntityProtocol { guard let extracted = extract(F.self) else { throw IncorrectEntityType( @@ -78,7 +72,7 @@ extension AccountOrPersona: EntityBaseProtocol { } return extracted } - + public struct IncorrectEntityType: Swift.Error { public let expectedKind: EntityKind public let actualKind: EntityKind @@ -89,7 +83,6 @@ extension AccountOrPersona: EntityBaseProtocol { \.virtualHierarchicalDeterministicFactorInstances ) } - } extension AccountOrPersona { @@ -99,5 +92,4 @@ extension AccountOrPersona { case let .personaEntity(entity): entity[keyPath: keyPath] } } - } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AuthorizedDappDetailed+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AuthorizedDappDetailed+Swiftified.swift index 218e08c1e..a31c1ff85 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AuthorizedDappDetailed+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AuthorizedDappDetailed+Swiftified.swift @@ -1,15 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-28. -// - import Foundation import SargonUniFFI +// MARK: - AuthorizedDappDetailed + SargonModel extension AuthorizedDappDetailed: SargonModel {} +// MARK: - AuthorizedDappDetailed + Identifiable extension AuthorizedDappDetailed: Identifiable { public typealias ID = DappDefinitionAddress public var id: ID { diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AuthorizedPersonaDetailed+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AuthorizedPersonaDetailed+Swiftified.swift index 836558bf1..e5d0c4a98 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AuthorizedPersonaDetailed+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/AuthorizedPersonaDetailed+Swiftified.swift @@ -1,14 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-28. -// - import Foundation import SargonUniFFI +// MARK: - AuthorizedPersonaDetailed + SargonModel extension AuthorizedPersonaDetailed: SargonModel {} + +// MARK: - AuthorizedPersonaDetailed + Identifiable extension AuthorizedPersonaDetailed: Identifiable { public typealias ID = IdentityAddress public var id: ID { diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/ProfileFileContents+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/ProfileFileContents+Swiftified.swift index e0ff4c8cd..e9e1c847c 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/ProfileFileContents+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile+Supporting+Types/ProfileFileContents+Swiftified.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-01. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/Account+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/Account+Swiftified.swift index 156cba2ae..c9cd9b90c 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/Account+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/Account+Swiftified.swift @@ -1,8 +1,9 @@ import SargonUniFFI +// MARK: - Account + EntityBaseProtocol extension Account: EntityBaseProtocol { public typealias EntityAddress = AccountAddress - + public var asGeneral: AccountOrPersona { .account(self) } @@ -14,18 +15,19 @@ extension Account { } } +// MARK: - Account + EntityProtocol extension Account: EntityProtocol { public static let kind: EntityKind = .account - + public static func extract(from someEntity: some EntityBaseProtocol) -> Self? { guard case let .accountEntity(account) = someEntity.asGeneral else { return nil } return account } - + public struct ExtraProperties: SargonModel { public var appearanceID: AppearanceID public let onLedgerSettings: OnLedgerSettings - + public init( appearanceID: AppearanceID, onLedgerSettings: OnLedgerSettings = .default @@ -34,7 +36,7 @@ extension Account: EntityProtocol { self.onLedgerSettings = onLedgerSettings } } - + public init( networkID: NetworkID, address: AccountAddress, @@ -52,14 +54,13 @@ extension Account: EntityProtocol { onLedgerSettings: extraProperties.onLedgerSettings ) } - + public static func deriveVirtualAddress( networkID: NetworkID, factorInstance: HierarchicalDeterministicFactorInstance ) -> AccountAddress { AccountAddress(publicKey: factorInstance.publicKey.publicKey, networkID: networkID) } - } #if DEBUG diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/AppearanceID+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/AppearanceID+Swiftified.swift index 21d923678..acc2441b5 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/AppearanceID+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/AppearanceID+Swiftified.swift @@ -2,19 +2,25 @@ import SargonUniFFI public typealias AppearanceID = AppearanceId +// MARK: - AppearanceID + SargonModel extension AppearanceID: SargonModel {} + +// MARK: - AppearanceID + Identifiable extension AppearanceID: Identifiable { public typealias ID = UInt8 public var id: ID { value } } + +// MARK: - AppearanceID + CustomStringConvertible extension AppearanceID: CustomStringConvertible { public var description: String { value.description } } +// MARK: - AppearanceID + Codable extension AppearanceID: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/EntityFlag+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/EntityFlag+Swiftified.swift index 8b3df77da..9e2d67cb3 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/EntityFlag+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/EntityFlag+Swiftified.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-14. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/FiatCurrency+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/FiatCurrency+Swiftified.swift index fa421e7b1..95085e07e 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/FiatCurrency+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/FiatCurrency+Swiftified.swift @@ -1,14 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI +// MARK: - FiatCurrency + SargonModel extension FiatCurrency: SargonModel {} + +// MARK: - FiatCurrency + SargonStringCodable extension FiatCurrency: SargonStringCodable {} extension FiatCurrency { @@ -17,6 +13,7 @@ extension FiatCurrency { } } +// MARK: - FiatCurrency + CustomStringConvertible extension FiatCurrency: CustomStringConvertible { public var description: String { jsonStringLiteral() diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/OnLedgerSettings+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/OnLedgerSettings+Swiftified.swift index 4975c9d28..ceeaf445b 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/OnLedgerSettings+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/OnLedgerSettings+Swiftified.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-20. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/ThirdPartyDeposits/DepositRule+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/ThirdPartyDeposits/DepositRule+Swiftified.swift index a95542798..378f4612c 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/ThirdPartyDeposits/DepositRule+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/ThirdPartyDeposits/DepositRule+Swiftified.swift @@ -1,12 +1,8 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI +// MARK: - DepositRule + SargonModel extension DepositRule: SargonModel {} + +// MARK: - DepositRule + SargonStringCodable extension DepositRule: SargonStringCodable {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/ThirdPartyDeposits/ThirdPartyDeposits+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/ThirdPartyDeposits/ThirdPartyDeposits+Swiftified.swift index c3334e332..c8fcba61a 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/ThirdPartyDeposits/ThirdPartyDeposits+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Account/ThirdPartyDeposits/ThirdPartyDeposits+Swiftified.swift @@ -1,14 +1,14 @@ import SargonUniFFI +// MARK: - ThirdPartyDeposits + SargonModel extension ThirdPartyDeposits: SargonModel {} extension ThirdPartyDeposits { - /// With `assetsExceptionList` and `depositorsAllowList` set to `nil`, marking they are unknown. public static func accountRecoveryScanned(depositRule: DepositRule = .acceptAll) -> Self { - Self.init(depositRule: depositRule, assetsExceptionList: nil, depositorsAllowList: nil) + Self(depositRule: depositRule, assetsExceptionList: nil, depositorsAllowList: nil) } - + public var isAssetsExceptionsUnknown: Bool { assetsExceptionList == nil } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/AppPreferences+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/AppPreferences+Swiftified.swift index 262d591be..47cb1c20d 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/AppPreferences+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/AppPreferences+Swiftified.swift @@ -1,13 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI +// MARK: - AppPreferences + SargonModel extension AppPreferences: SargonModel {} extension AppPreferences { diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/AssetException+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/AssetException+Swiftified.swift index 55033ee9d..5eec4d4af 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/AssetException+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/AssetException+Swiftified.swift @@ -1,15 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI +// MARK: - AssetException + SargonModel extension AssetException: SargonModel {} +// MARK: - AssetException + Identifiable extension AssetException: Identifiable { public typealias ID = ResourceAddress public var id: ID { diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/AuthorizedDapp/AuthorizedDapp+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/AuthorizedDapp/AuthorizedDapp+Swiftified.swift index 4b4e119b2..814d58dba 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/AuthorizedDapp/AuthorizedDapp+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/AuthorizedDapp/AuthorizedDapp+Swiftified.swift @@ -1,16 +1,12 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI public typealias DappDefinitionAddress = AccountAddress +// MARK: - AuthorizedDapp + SargonModel extension AuthorizedDapp: SargonModel {} + +// MARK: - AuthorizedDapp + SargonObjectCodable extension AuthorizedDapp: SargonObjectCodable {} #if DEBUG @@ -21,17 +17,18 @@ extension AuthorizedDapp { } #endif // DEBUG +// MARK: - AuthorizedDapp + Identifiable extension AuthorizedDapp: Identifiable { public typealias ID = DappDefinitionAddress - + public var dAppDefinitionAddress: DappDefinitionAddress { dappDefinitionAddress } - + public var id: ID { dAppDefinitionAddress } - + public var networkID: NetworkID { networkId } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/AuthorizedDapp/AuthorizedPersonaSimple+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/AuthorizedDapp/AuthorizedPersonaSimple+Swiftified.swift index 2707fbc31..81b337757 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/AuthorizedDapp/AuthorizedPersonaSimple+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/AuthorizedDapp/AuthorizedPersonaSimple+Swiftified.swift @@ -1,14 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-14. -// - import Foundation import SargonUniFFI +// MARK: - AuthorizedPersonaSimple + SargonModel extension AuthorizedPersonaSimple: SargonModel {} + +// MARK: - AuthorizedPersonaSimple + Identifiable extension AuthorizedPersonaSimple: Identifiable { public typealias ID = IdentityAddress public var id: ID { diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/DeviceInfo+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/DeviceInfo+Swiftified.swift index c43715931..afe26998c 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/DeviceInfo+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/DeviceInfo+Swiftified.swift @@ -1,4 +1,7 @@ import Foundation +// MARK: - DeviceInfo + SargonModel extension DeviceInfo: SargonModel {} + +// MARK: - DeviceInfo + SargonObjectCodable extension DeviceInfo: SargonObjectCodable {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/EntitySecurityState+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/EntitySecurityState+Swiftified.swift index 5f58bca93..101762178 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/EntitySecurityState+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/EntitySecurityState+Swiftified.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-27. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/ArculusCardFactorSource+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/ArculusCardFactorSource+Swiftified.swift index 4670f1723..c81a7a6cf 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/ArculusCardFactorSource+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/ArculusCardFactorSource+Swiftified.swift @@ -1,44 +1,42 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-14. -// - import Foundation import SargonUniFFI +// MARK: - ArculusCardModel + CustomStringConvertible extension ArculusCardModel: CustomStringConvertible { public var description: String { toString() } } +// MARK: - ArculusCardFactorSource + SargonModel extension ArculusCardFactorSource: SargonModel {} + +// MARK: - ArculusCardFactorSource + Identifiable extension ArculusCardFactorSource: Identifiable { public typealias ID = FactorSourceIDFromHash } +// MARK: - ArculusCardFactorSource + FactorSourceProtocol extension ArculusCardFactorSource: FactorSourceProtocol { public static let kind: FactorSourceKind = .arculusCard - + public static func extract(from someFactorSource: some BaseFactorSourceProtocol) -> Self? { guard case let .arculusCard(factorSource) = someFactorSource.asGeneral else { return nil } return factorSource } - + public var asGeneral: FactorSource { .arculusCard(value: self) } - + public var factorSourceID: FactorSourceID { id.asGeneral } - + public var factorSourceKind: FactorSourceKind { .arculusCard } - + public var supportsOlympia: Bool { asGeneral.supportsOlympia } public var supportsBabylon: Bool { asGeneral.supportsBabylon } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/DeviceFactorSource+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/DeviceFactorSource+Swiftified.swift index c0da9057d..4dd1ea17b 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/DeviceFactorSource+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/DeviceFactorSource+Swiftified.swift @@ -1,39 +1,35 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-14. -// - import Foundation import SargonUniFFI +// MARK: - DeviceFactorSource + SargonModel extension DeviceFactorSource: SargonModel {} +// MARK: - DeviceFactorSource + Identifiable extension DeviceFactorSource: Identifiable { public typealias ID = FactorSourceIDFromHash } +// MARK: - DeviceFactorSource + FactorSourceProtocol extension DeviceFactorSource: FactorSourceProtocol { public static let kind: FactorSourceKind = .device - + public static func extract(from someFactorSource: some BaseFactorSourceProtocol) -> Self? { guard case let .device(factorSource) = someFactorSource.asGeneral else { return nil } return factorSource } - + public var asGeneral: FactorSource { .device(value: self) } - + public var factorSourceID: FactorSourceID { id.asGeneral } - + public var factorSourceKind: FactorSourceKind { .device } - + public var supportsOlympia: Bool { asGeneral.supportsOlympia } public var supportsBabylon: Bool { asGeneral.supportsBabylon } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSource+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSource+Swiftified.swift index 883570cad..8834bf605 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSource+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSource+Swiftified.swift @@ -1,13 +1,16 @@ import SargonUniFFI +// MARK: - FactorSource + SargonModel extension FactorSource: SargonModel {} +// MARK: - FactorSource + CustomStringConvertible extension FactorSource: CustomStringConvertible { public var description: String { toString() } } +// MARK: - FactorSource + Identifiable extension FactorSource: Identifiable { public typealias ID = FactorSourceID public var id: ID { @@ -23,11 +26,12 @@ extension FactorSource: Identifiable { } } +// MARK: - FactorSource + BaseFactorSourceProtocol extension FactorSource: BaseFactorSourceProtocol { public var factorSourceID: FactorSourceID { id } - + public var factorSourceKind: FactorSourceKind { switch self { case let .device(value): value.factorSourceKind @@ -39,7 +43,7 @@ extension FactorSource: BaseFactorSourceProtocol { case let .passphrase(value): value.factorSourceKind } } - + public var common: FactorSourceCommon { get { switch self { @@ -78,13 +82,13 @@ extension FactorSource: BaseFactorSourceProtocol { } } } - + public var asGeneral: FactorSource { self } - + public func extract(_ type: F.Type = F.self) -> F? where F: FactorSourceProtocol { F.extract(from: self) } - + public func extract(as _: F.Type = F.self) throws -> F where F: FactorSourceProtocol { guard let extracted = extract(F.self) else { throw IncorrectFactorSourceType( @@ -94,31 +98,37 @@ extension FactorSource: BaseFactorSourceProtocol { } return extracted } - + public struct IncorrectFactorSourceType: Swift.Error { public let expectedKind: FactorSourceKind public let actualKind: FactorSourceKind } - + public var asDevice: DeviceFactorSource? { extract() } + public var asLedger: LedgerHardwareWalletFactorSource? { extract() } + public var asArculus: ArculusCardFactorSource? { extract() } + public var asOffDeviceMnemonic: OffDeviceMnemonicFactorSource? { extract() } + public var asSecurityQuestions: SecurityQuestionsNotProductionReadyFactorSource? { extract() } + public var asTrustedContact: TrustedContactFactorSource? { extract() } + public var asPassphrase: PassphraseFactorSource? { - extract() - } + extract() + } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceCommon+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceCommon+Swiftified.swift index da6fa2690..a2f7613f9 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceCommon+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceCommon+Swiftified.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-02. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceID+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceID+Swiftified.swift index 13e2e8cc1..481b3f09d 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceID+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceID+Swiftified.swift @@ -1,22 +1,19 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-14. -// - import Foundation import SargonUniFFI public typealias FactorSourceID = FactorSourceId + +// MARK: - FactorSourceID + SargonModel extension FactorSourceID: SargonModel {} +// MARK: - FactorSourceID + CustomStringConvertible extension FactorSourceID: CustomStringConvertible { public var description: String { toString() } } +// MARK: - FactorSourceID + FactorSourceIDProtocol extension FactorSourceID: FactorSourceIDProtocol { public var asGeneral: FactorSourceID { self @@ -24,19 +21,17 @@ extension FactorSourceID: FactorSourceIDProtocol { } extension FactorSourceID { - public func extract(_ type: F.Type = F.self) -> F? where F: FactorSourceIDSpecificProtocol { F.extract(from: self) } - + public func extract(as _: F.Type = F.self) throws -> F where F: FactorSourceIDSpecificProtocol { guard let extracted = extract(F.self) else { throw IncorrectFactorSourceIDType() } return extracted } - - } +// MARK: - IncorrectFactorSourceIDType public struct IncorrectFactorSourceIDType: Swift.Error {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceIDFromAddress+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceIDFromAddress+Swiftified.swift index 05c46805e..70232feb7 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceIDFromAddress+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceIDFromAddress+Swiftified.swift @@ -1,22 +1,20 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-14. -// - import Foundation import SargonUniFFI public typealias FactorSourceIDFromAddress = FactorSourceIdFromAddress +// MARK: - FactorSourceIDFromAddress + SargonModel extension FactorSourceIDFromAddress: SargonModel {} + +// MARK: - FactorSourceIDFromAddress + SargonObjectCodable extension FactorSourceIDFromAddress: SargonObjectCodable {} +// MARK: - FactorSourceIDFromAddress + FactorSourceIDSpecificProtocol extension FactorSourceIDFromAddress: FactorSourceIDSpecificProtocol { public var asGeneral: FactorSourceID { .address(value: self) } + public static func extract(from someFactorSourceID: some FactorSourceIDProtocol) -> Self? { guard case let .address(id) = someFactorSourceID.asGeneral else { return nil } return id diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceIDFromHash+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceIDFromHash+Swiftified.swift index 8c3b66fa7..0070f7ff3 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceIDFromHash+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceIDFromHash+Swiftified.swift @@ -1,26 +1,22 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-14. -// - import Foundation import SargonUniFFI public typealias FactorSourceIDFromHash = FactorSourceIdFromHash +// MARK: - FactorSourceIDFromHash + SargonModel extension FactorSourceIDFromHash: SargonModel {} + +// MARK: - FactorSourceIDFromHash + SargonObjectCodable extension FactorSourceIDFromHash: SargonObjectCodable {} +// MARK: - FactorSourceIDFromHash + FactorSourceIDSpecificProtocol extension FactorSourceIDFromHash: FactorSourceIDSpecificProtocol { public var asGeneral: FactorSourceID { .hash(value: self) } + public static func extract(from someFactorSourceID: some FactorSourceIDProtocol) -> Self? { guard case let .hash(id) = someFactorSourceID.asGeneral else { return nil } return id } } - - diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceIDProtocol.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceIDProtocol.swift index db9b99105..f10f6d8d6 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceIDProtocol.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceIDProtocol.swift @@ -1,12 +1,6 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-24. -// - import Foundation +// MARK: - FactorSourceIDProtocol public protocol FactorSourceIDProtocol: SargonModel & CustomStringConvertible { var asGeneral: FactorSourceID { get } func toString() -> String @@ -18,6 +12,7 @@ extension FactorSourceIDProtocol { } } +// MARK: - FactorSourceIDSpecificProtocol public protocol FactorSourceIDSpecificProtocol: FactorSourceIDProtocol & Codable { static func extract(from someFactorSourceID: some FactorSourceIDProtocol) -> Self? } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceKind+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceKind+Swiftified.swift index 835f2f2d5..bf94f8dbb 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceKind+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceKind+Swiftified.swift @@ -1,27 +1,22 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI +// MARK: - FactorSourceKind + SargonModel extension FactorSourceKind: SargonModel {} + +// MARK: - FactorSourceKind + CustomStringConvertible extension FactorSourceKind: CustomStringConvertible { - public var description: String { - toString() - } + public var description: String { + toString() + } } extension FactorSourceKind { - - public var rawValue: String { - toString() - } + public var rawValue: String { + toString() + } - public init?(rawValue: String) { - try? self.init(string: rawValue) - } + public init?(rawValue: String) { + try? self.init(string: rawValue) + } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceProtocol.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceProtocol.swift index a233392e9..f9b61ce07 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceProtocol.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/FactorSourceProtocol.swift @@ -1,13 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-14. -// - import Foundation import SargonUniFFI +// MARK: - BaseFactorSourceProtocol public protocol BaseFactorSourceProtocol: SargonModel { var factorSourceID: FactorSourceID { get } var factorSourceKind: FactorSourceKind { get } @@ -18,15 +12,14 @@ public protocol BaseFactorSourceProtocol: SargonModel { } extension BaseFactorSourceProtocol { - public var kind: FactorSourceKind { factorSourceKind } - + public var cryptoParameters: FactorSourceCryptoParameters { common.cryptoParameters } - + public var addedOn: Date { common.addedOn } @@ -34,21 +27,22 @@ extension BaseFactorSourceProtocol { public var lastUsedOn: Date { common.lastUsedOn } - + public mutating func flag(_ flag: FactorSourceFlag) { common.flags.append(flag) } - + public var isFlaggedForDeletion: Bool { common.flags.contains(.deletedByUser) } - } +// MARK: - FactorSourceProtocol public protocol FactorSourceProtocol: BaseFactorSourceProtocol { static var kind: FactorSourceKind { get } static func extract(from: some BaseFactorSourceProtocol) -> Self? } + extension FactorSourceProtocol { public var factorSourceKind: FactorSourceKind { Self.kind } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/LedgerHardwareWalletFactorSource+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/LedgerHardwareWalletFactorSource+Swiftified.swift index 520a53559..02e5e21ba 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/LedgerHardwareWalletFactorSource+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/LedgerHardwareWalletFactorSource+Swiftified.swift @@ -1,39 +1,35 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-14. -// - import Foundation import SargonUniFFI +// MARK: - LedgerHardwareWalletFactorSource + SargonModel extension LedgerHardwareWalletFactorSource: SargonModel {} +// MARK: - LedgerHardwareWalletFactorSource + Identifiable extension LedgerHardwareWalletFactorSource: Identifiable { public typealias ID = FactorSourceIDFromHash } +// MARK: - LedgerHardwareWalletFactorSource + FactorSourceProtocol extension LedgerHardwareWalletFactorSource: FactorSourceProtocol { public static let kind: FactorSourceKind = .ledgerHqHardwareWallet - + public static func extract(from someFactorSource: some BaseFactorSourceProtocol) -> Self? { guard case let .ledger(factorSource) = someFactorSource.asGeneral else { return nil } return factorSource } - + public var asGeneral: FactorSource { .ledger(value: self) } - + public var factorSourceID: FactorSourceID { id.asGeneral } - + public var factorSourceKind: FactorSourceKind { .ledgerHqHardwareWallet } - + public var supportsOlympia: Bool { asGeneral.supportsOlympia } public var supportsBabylon: Bool { asGeneral.supportsBabylon } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/OffDeviceMnemonicFactorSource+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/OffDeviceMnemonicFactorSource+Swiftified.swift index 06247513d..f8b4765f5 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/OffDeviceMnemonicFactorSource+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/OffDeviceMnemonicFactorSource+Swiftified.swift @@ -1,38 +1,35 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-14. -// - import Foundation import SargonUniFFI +// MARK: - OffDeviceMnemonicFactorSource + SargonModel extension OffDeviceMnemonicFactorSource: SargonModel {} + +// MARK: - OffDeviceMnemonicFactorSource + Identifiable extension OffDeviceMnemonicFactorSource: Identifiable { public typealias ID = FactorSourceIDFromHash } +// MARK: - OffDeviceMnemonicFactorSource + FactorSourceProtocol extension OffDeviceMnemonicFactorSource: FactorSourceProtocol { public static let kind: FactorSourceKind = .offDeviceMnemonic - + public static func extract(from someFactorSource: some BaseFactorSourceProtocol) -> Self? { guard case let .offDeviceMnemonic(factorSource) = someFactorSource.asGeneral else { return nil } return factorSource } - + public var asGeneral: FactorSource { .offDeviceMnemonic(value: self) } - + public var factorSourceID: FactorSourceID { id.asGeneral } - + public var factorSourceKind: FactorSourceKind { .offDeviceMnemonic } - + public var supportsOlympia: Bool { asGeneral.supportsOlympia } public var supportsBabylon: Bool { asGeneral.supportsBabylon } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/PassphraseFactorSource+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/PassphraseFactorSource+Swiftified.swift index 34da7e75a..b88170a76 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/PassphraseFactorSource+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/PassphraseFactorSource+Swiftified.swift @@ -1,18 +1,15 @@ -// -// PassphraseFactorSource+Swiftified.swift -// -// -// Created by Michael Bakogiannis on 7/10/24. -// - import Foundation import SargonUniFFI +// MARK: - PassphraseFactorSource + SargonModel extension PassphraseFactorSource: SargonModel {} + +// MARK: - PassphraseFactorSource + Identifiable extension PassphraseFactorSource: Identifiable { public typealias ID = FactorSourceIDFromHash } +// MARK: - PassphraseFactorSource + FactorSourceProtocol extension PassphraseFactorSource: FactorSourceProtocol { public static let kind: FactorSourceKind = .passphrase diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/PrivateHierarchicalDeterministicFactorSource+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/PrivateHierarchicalDeterministicFactorSource+Swiftified.swift index 821b76e16..b2f885073 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/PrivateHierarchicalDeterministicFactorSource+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/PrivateHierarchicalDeterministicFactorSource+Swiftified.swift @@ -1,42 +1,35 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI +// MARK: - PrivateHierarchicalDeterministicFactorSource + SargonModel extension PrivateHierarchicalDeterministicFactorSource: SargonModel {} + +// MARK: - PrivateHierarchicalDeterministicFactorSource + BaseFactorSourceProtocol extension PrivateHierarchicalDeterministicFactorSource: BaseFactorSourceProtocol { - public var common: FactorSourceCommon { get { factorSource.common } set { factorSource.common = newValue } } - + public var factorSourceID: FactorSourceID { factorSource.factorSourceID } - + public var factorSourceKind: FactorSourceKind { factorSource.factorSourceKind } - + public var asGeneral: FactorSource { factorSource.asGeneral } - + public var supportsOlympia: Bool { factorSource.supportsOlympia } - + public var supportsBabylon: Bool { factorSource.supportsBabylon } - - } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/SecurityQuestionsFactorSource+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/SecurityQuestionsFactorSource+Swiftified.swift index b55832b9c..bf4958211 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/SecurityQuestionsFactorSource+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/SecurityQuestionsFactorSource+Swiftified.swift @@ -1,34 +1,31 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-14. -// - import Foundation import SargonUniFFI +// MARK: - SecurityQuestionsNotProductionReadyFactorSource + SargonModel extension SecurityQuestionsNotProductionReadyFactorSource: SargonModel {} + +// MARK: - SecurityQuestionsNotProductionReadyFactorSource + Identifiable extension SecurityQuestionsNotProductionReadyFactorSource: Identifiable { public typealias ID = FactorSourceIDFromHash } +// MARK: - SecurityQuestionsNotProductionReadyFactorSource + FactorSourceProtocol extension SecurityQuestionsNotProductionReadyFactorSource: FactorSourceProtocol { public static let kind: FactorSourceKind = .securityQuestions - + public static func extract(from someFactorSource: some BaseFactorSourceProtocol) -> Self? { guard case let .securityQuestions(factorSource) = someFactorSource.asGeneral else { return nil } return factorSource } - + public var asGeneral: FactorSource { .securityQuestions(value: self) } - + public var factorSourceID: FactorSourceID { id.asGeneral } - + public var supportsOlympia: Bool { asGeneral.supportsOlympia } public var supportsBabylon: Bool { asGeneral.supportsBabylon } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/TrustedContactFactorSource+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/TrustedContactFactorSource+Swiftified.swift index e85917e84..00caaa29e 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/TrustedContactFactorSource+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSource/TrustedContactFactorSource+Swiftified.swift @@ -1,38 +1,35 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-14. -// - import Foundation import SargonUniFFI +// MARK: - TrustedContactFactorSource + SargonModel extension TrustedContactFactorSource: SargonModel {} + +// MARK: - TrustedContactFactorSource + Identifiable extension TrustedContactFactorSource: Identifiable { public typealias ID = FactorSourceIDFromAddress } +// MARK: - TrustedContactFactorSource + FactorSourceProtocol extension TrustedContactFactorSource: FactorSourceProtocol { public static let kind: FactorSourceKind = .trustedContact - + public static func extract(from someFactorSource: some BaseFactorSourceProtocol) -> Self? { guard case let .trustedContact(factorSource) = someFactorSource.asGeneral else { return nil } return factorSource } - + public var asGeneral: FactorSource { .trustedContact(value: self) } - + public var factorSourceID: FactorSourceID { id.asGeneral } - + public var factorSourceKind: FactorSourceKind { .trustedContact } - + public var supportsOlympia: Bool { asGeneral.supportsOlympia } public var supportsBabylon: Bool { asGeneral.supportsBabylon } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSourceCryptoParameters+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSourceCryptoParameters+Swiftified.swift index 9a3cd0f62..82f97c728 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSourceCryptoParameters+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/FactorSourceCryptoParameters+Swiftified.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/HierarchicalDeterministicFactorInstance+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/HierarchicalDeterministicFactorInstance+Swiftified.swift index 240a5db69..7c925a3a3 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/HierarchicalDeterministicFactorInstance+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/HierarchicalDeterministicFactorInstance+Swiftified.swift @@ -1,13 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI +// MARK: - HierarchicalDeterministicFactorInstance + SargonModel extension HierarchicalDeterministicFactorInstance: SargonModel {} extension HierarchicalDeterministicFactorInstance { @@ -28,4 +22,3 @@ extension HierarchicalDeterministicFactorInstance { ) } } - diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/LedgerHardwareWalletModel+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/LedgerHardwareWalletModel+Swiftified.swift index f97c21e0d..804fa17be 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/LedgerHardwareWalletModel+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Factor/LedgerHardwareWalletModel+Swiftified.swift @@ -1,20 +1,17 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation +// MARK: - LedgerHardwareWalletModel + SargonModel extension LedgerHardwareWalletModel: SargonModel {} + +// MARK: - LedgerHardwareWalletModel + CustomStringConvertible extension LedgerHardwareWalletModel: CustomStringConvertible { - public var description: String { - toString() - } + public var description: String { + toString() + } } + extension LedgerHardwareWalletModel { - public var rawValue: String { - toString() - } + public var rawValue: String { + toString() + } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Gateway/Gateway+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Gateway/Gateway+Swiftified.swift index 7c40433a0..de0fef167 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Gateway/Gateway+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Gateway/Gateway+Swiftified.swift @@ -1,12 +1,17 @@ -import SargonUniFFI import Foundation +import SargonUniFFI +// MARK: - Gateway + SargonModel extension Gateway: SargonModel {} + +// MARK: - Gateway + CustomStringConvertible extension Gateway: CustomStringConvertible { public var description: String { toString() } } + +// MARK: - Gateway + Identifiable extension Gateway: Identifiable { public typealias ID = URL public var id: ID { @@ -14,37 +19,34 @@ extension Gateway: Identifiable { } } - extension Gateway { - public var networkID: NetworkID { - network.id - } + public var networkID: NetworkID { + network.id + } } extension Gateway { - - public static var nebunet: Self { - Self.forNetwork(id: .nebunet) - } - - public static var kisharnet: Self { - Self.forNetwork(id: .kisharnet) - } + public static var nebunet: Self { + forNetwork(id: .nebunet) + } - public static var ansharnet: Self { - Self.forNetwork(id: .ansharnet) - } + public static var kisharnet: Self { + forNetwork(id: .kisharnet) + } - public static var hammunet: Self { - Self.forNetwork(id: .hammunet) - } + public static var ansharnet: Self { + forNetwork(id: .ansharnet) + } - public static var enkinet: Self { - Self.forNetwork(id: .enkinet) - } + public static var hammunet: Self { + forNetwork(id: .hammunet) + } - public static var mardunet: Self { - Self.forNetwork(id: .mardunet) - } + public static var enkinet: Self { + forNetwork(id: .enkinet) + } + public static var mardunet: Self { + forNetwork(id: .mardunet) + } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Gateway/SavedGateways+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Gateway/SavedGateways+Swiftified.swift index 7adff914c..4d37958b2 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Gateway/SavedGateways+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Gateway/SavedGateways+Swiftified.swift @@ -1,12 +1,6 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-14. -// - import SargonUniFFI +// MARK: - SavedGateways + SargonModel extension SavedGateways: SargonModel {} extension SavedGateways { public static let preset: Self = .default diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Header+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Header+Swiftified.swift index 98a303fa8..65872b81d 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Header+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Header+Swiftified.swift @@ -1,12 +1,8 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation import SargonUniFFI +// MARK: - Header + SargonModel extension Header: SargonModel {} + +// MARK: - Header + SargonObjectCodable extension Header: SargonObjectCodable {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/MatrixOfFactorSources+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/MatrixOfFactorSources+Swiftified.swift index 53e577dbb..91e64b8e0 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/MatrixOfFactorSources+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/MatrixOfFactorSources+Swiftified.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-06. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/SecurityStructureMetadata+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/SecurityStructureMetadata+Swiftified.swift index b1b308675..9ba61fd9f 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/SecurityStructureMetadata+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/SecurityStructureMetadata+Swiftified.swift @@ -1,7 +1,10 @@ import Foundation import SargonUniFFI +// MARK: - SecurityStructureMetadata + SargonModel extension SecurityStructureMetadata: SargonModel {} + +// MARK: - SecurityStructureMetadata + Identifiable extension SecurityStructureMetadata: Identifiable { - public typealias ID = UUID + public typealias ID = UUID } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/SecurityStructureOfFactorSourceIDs+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/SecurityStructureOfFactorSourceIDs+Swiftified.swift index 08653c012..3d7985e41 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/SecurityStructureOfFactorSourceIDs+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/SecurityStructureOfFactorSourceIDs+Swiftified.swift @@ -1,7 +1,10 @@ import Foundation import SargonUniFFI +// MARK: - SecurityStructureOfFactorSourceIDs + SargonModel extension SecurityStructureOfFactorSourceIDs: SargonModel {} + +// MARK: - SecurityStructureOfFactorSourceIDs + Identifiable extension SecurityStructureOfFactorSourceIDs: Identifiable { public typealias ID = UUID public var id: ID { diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/SecurityStructureOfFactorSources+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/SecurityStructureOfFactorSources+Swiftified.swift index d8cbd158b..fb5d053e3 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/SecurityStructureOfFactorSources+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/MFA/SecurityStructureOfFactorSources+Swiftified.swift @@ -1,7 +1,10 @@ import Foundation import SargonUniFFI +// MARK: - SecurityStructureOfFactorSources + SargonModel extension SecurityStructureOfFactorSources: SargonModel {} + +// MARK: - SecurityStructureOfFactorSources + Identifiable extension SecurityStructureOfFactorSources: Identifiable { public typealias ID = UUID public var id: ID { diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/NetworkDefinition+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/NetworkDefinition+Swiftified.swift index 0c0c2dae4..da87d320e 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/NetworkDefinition+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/NetworkDefinition+Swiftified.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/Persona+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/Persona+Swiftified.swift index b745e20b3..40063b336 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/Persona+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/Persona+Swiftified.swift @@ -1,27 +1,23 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI +// MARK: - Persona + EntityBaseProtocol extension Persona: EntityBaseProtocol { public typealias EntityAddress = IdentityAddress - + public var asGeneral: AccountOrPersona { .persona(self) } } + +// MARK: - Persona + EntityProtocol extension Persona: EntityProtocol { public static let kind: EntityKind = .persona public static func extract(from someEntity: some EntityBaseProtocol) -> Self? { guard case let .personaEntity(persona) = someEntity.asGeneral else { return nil } return persona } - + /// Ephemeral, only used as arg passed to init. public struct ExtraProperties: SargonModel { public var personaData: PersonaData @@ -29,7 +25,7 @@ extension Persona: EntityProtocol { self.personaData = personaData } } - + public init( networkID: NetworkID, address: IdentityAddress, @@ -46,7 +42,7 @@ extension Persona: EntityProtocol { personaData: extraProperties.personaData ) } - + public static func deriveVirtualAddress( networkID: NetworkID, factorInstance: HierarchicalDeterministicFactorInstance diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/BasePersonaDataEntryProtocol.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/BasePersonaDataEntryProtocol.swift index f7d2df6a6..468aaeea0 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/BasePersonaDataEntryProtocol.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/BasePersonaDataEntryProtocol.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaData+Entry.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaData+Entry.swift index ad693c57d..18c600466 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaData+Entry.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaData+Entry.swift @@ -1,16 +1,9 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - import Foundation import SargonUniFFI // MARK: - PersonaData.Entry extension PersonaData { - public enum Entry: + public enum Entry: SargonModel, Codable, BasePersonaDataEntryProtocol, @@ -30,11 +23,10 @@ extension PersonaData.Entry { #endif // DEBUG extension PersonaData.Entry { - public func embed() -> PersonaData.Entry { self } - + public var description: String { switch self { case let .name(name): @@ -47,6 +39,7 @@ extension PersonaData.Entry { } } +// MARK: - PersonaData.Entry.Kind extension PersonaData.Entry { public enum Kind: String, Sendable, Hashable, Codable { case fullName diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaData+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaData+Swiftified.swift index 2986df946..6b5985f23 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaData+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaData+Swiftified.swift @@ -1,13 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI +// MARK: - PersonaData + SargonModel extension PersonaData: SargonModel {} public typealias AnyIdentifiedPersonaEntry = PersonaData.IdentifiedEntry @@ -31,16 +25,15 @@ extension AnyIdentifiedPersonaEntry: SargonModel { // MARK: - PersonaData.IdentifiedEntry extension PersonaData { - public struct IdentifiedEntry: BaseSargonModel, Codable, Identifiable, CustomStringConvertible - where - Value: - SargonModel & - Codable & BasePersonaDataEntryProtocol + where + Value: + SargonModel & + Codable & BasePersonaDataEntryProtocol { public typealias ID = PersonaDataEntryID public let id: ID @@ -63,9 +56,7 @@ extension PersonaData { } } - extension PersonaData { - public init() { self.init( name: nil, @@ -81,7 +72,7 @@ extension PersonaData { public static var `default`: Self { self.init() } - + public var entries: [AnyIdentifiedPersonaEntry] { var sequence: [AnyIdentifiedPersonaEntry?] = [] sequence.append(name?.embed()) @@ -89,5 +80,4 @@ extension PersonaData { sequence.append(contentsOf: phoneNumbers.collection.map { $0.embed() }) return sequence.compactMap { $0 } } - } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryEmailAddress+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryEmailAddress+Swiftified.swift index 12fed23dd..83fe54aa1 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryEmailAddress+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryEmailAddress+Swiftified.swift @@ -1,16 +1,15 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - import Foundation import SargonUniFFI public typealias PersonaDataEntryEmailAddress = EmailAddress + +// MARK: - EmailAddress + SargonModel extension EmailAddress: SargonModel {} + +// MARK: - EmailAddress + SargonStringCodable extension EmailAddress: SargonStringCodable {} + +// MARK: - EmailAddress + CustomStringConvertible extension EmailAddress: CustomStringConvertible { public var description: String { email @@ -22,12 +21,12 @@ extension EmailAddress: PersonaDataEntryProtocol { public static var kind: PersonaData.Entry.Kind { .emailAddress } - + public static func extract(from entry: PersonaData.Entry) -> Self? { guard case let .emailAddress(value) = entry else { return nil } return value } - + public func embed() -> PersonaData.Entry { .emailAddress(self) } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryName+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryName+Swiftified.swift index 379f4646e..8abc3dee4 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryName+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryName+Swiftified.swift @@ -1,18 +1,25 @@ import Foundation import SargonUniFFI +// MARK: - PersonaDataEntryName + SargonModel extension PersonaDataEntryName: SargonModel {} + +// MARK: - PersonaDataEntryName + SargonObjectCodable extension PersonaDataEntryName: SargonObjectCodable {} + +// MARK: - PersonaDataEntryName + CustomStringConvertible extension PersonaDataEntryName: CustomStringConvertible { public var description: String { formatted } } +// MARK: - PersonaDataEntryName.Variant extension PersonaDataEntryName { public typealias Variant = Sargon.PersonaDataNameVariant } +// MARK: - PersonaDataEntryName.Variant + CaseIterable extension PersonaDataEntryName.Variant: CaseIterable { public static var allCases: [Self] { [.eastern, .western] @@ -26,36 +33,33 @@ extension PersonaDataEntryName { case .western: [givenNames, familyName] case .eastern: [familyName, givenNames] } - }().filter({ !$0.isEmpty }) - + }().filter { !$0.isEmpty } + var formatted: [String] = [] formatted.append(names.joined(separator: " ")) if !nickname.isEmpty { formatted.append("\"\(nickname)\"") } - + return formatted - .filter({ !$0.isEmpty }) + .filter { !$0.isEmpty } .joined(separator: "\n") } } - // MARK: - PersonaDataEntryName + PersonaDataEntryProtocol extension PersonaDataEntryName: PersonaDataEntryProtocol { public static var kind: PersonaData.Entry.Kind { .fullName } - + public func embed() -> PersonaData.Entry { .name(self) } - + public static func extract(from entry: PersonaData.Entry) -> Self? { guard case let .name(value) = entry else { return nil } return value } } - - diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryPhoneNumber+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryPhoneNumber+Swiftified.swift index ce4e01f70..a6bae06a0 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryPhoneNumber+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryPhoneNumber+Swiftified.swift @@ -1,8 +1,13 @@ import Foundation import SargonUniFFI +// MARK: - PersonaDataEntryPhoneNumber + SargonModel extension PersonaDataEntryPhoneNumber: SargonModel {} + +// MARK: - PersonaDataEntryPhoneNumber + SargonStringCodable extension PersonaDataEntryPhoneNumber: SargonStringCodable {} + +// MARK: - PersonaDataEntryPhoneNumber + CustomStringConvertible extension PersonaDataEntryPhoneNumber: CustomStringConvertible { public var description: String { number @@ -14,12 +19,12 @@ extension PersonaDataEntryPhoneNumber: PersonaDataEntryProtocol { public static var kind: PersonaData.Entry.Kind { .phoneNumber } - + public static func extract(from entry: PersonaData.Entry) -> Self? { guard case let .phoneNumber(value) = entry else { return nil } return value } - + public func embed() -> PersonaData.Entry { .phoneNumber(self) } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryProtocol.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryProtocol.swift index 8d7f7821f..98e2fcb9a 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryProtocol.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/PersonaDataEntryProtocol.swift @@ -1,17 +1,8 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - import Foundation import SargonUniFFI - - // MARK: - PersonaDataEntryProtocol -public protocol PersonaDataEntryProtocol: +public protocol PersonaDataEntryProtocol: BasePersonaDataEntryProtocol & SargonModel & Codable & diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/SharedPersonaData+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/SharedPersonaData+Swiftified.swift index deb82ff8c..07ee860ea 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/SharedPersonaData+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Persona/PersonaData/SharedPersonaData+Swiftified.swift @@ -1,13 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation import SargonUniFFI +// MARK: - SharedPersonaData + SargonModel extension SharedPersonaData: SargonModel {} extension SharedPersonaData { @@ -16,15 +10,14 @@ extension SharedPersonaData { emailAddresses: nil, phoneNumbers: nil ) - + public var entryIDs: Set { var ids: [PersonaDataEntryID] = [ - name + name, ].compactMap { $0 } ids.append(contentsOf: emailAddresses?.ids ?? []) ids.append(contentsOf: phoneNumbers?.ids ?? []) - + return Set(ids) } - } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Profile+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Profile+Swiftified.swift index 6776b333d..d11ac3fba 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/Profile+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/Profile+Swiftified.swift @@ -1,13 +1,16 @@ import SargonUniFFI +// MARK: - Profile + SargonModel extension Profile: SargonModel {} +// MARK: - Profile + Encodable @available(*, unavailable, message: "Profile should not use Swift `Encodable` (Codable), since it is too slow.") extension Profile: Encodable { @available(*, unavailable, message: "Profile should not use Swift `Encodable` (Codable), since it is too slow.") public func encode(to encoder: any Encoder) throws { fatalError("Unreachable") } } +// MARK: - Profile + Decodable @available(*, unavailable, message: "Profile should not use Swift `Encodable` (Codable), since it is too slow.") extension Profile: Decodable { @available(*, unavailable, message: "Profile should not use Swift `Encodable` (Codable), since it is too slow.") @@ -15,7 +18,6 @@ extension Profile: Decodable { } extension Profile { - public init( header: Header, deviceFactorSource: DeviceFactorSource @@ -30,6 +32,8 @@ extension Profile { } public typealias ProfileID = ProfileId + +// MARK: - Profile + Identifiable extension Profile: Identifiable { public typealias ID = ProfileID public var id: ID { @@ -37,16 +41,16 @@ extension Profile: Identifiable { } } +// MARK: - Profile + CustomStringConvertible extension Profile: CustomStringConvertible { public var description: String { toString() } } - +// MARK: - Profile + CustomDebugStringConvertible extension Profile: CustomDebugStringConvertible { public var debugDescription: String { toDebugString() } } - diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/ProfileNetwork+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/ProfileNetwork+Swiftified.swift index 5e4f795f4..d137606f4 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/ProfileNetwork+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/ProfileNetwork+Swiftified.swift @@ -1,14 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI +// MARK: - ProfileNetwork + SargonModel extension ProfileNetwork: SargonModel {} + +// MARK: - ProfileNetwork + Identifiable extension ProfileNetwork: Identifiable { public typealias ID = NetworkID } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Profile/UnsecuredEntityControl+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Profile/UnsecuredEntityControl+Swiftified.swift index 066b57e93..a9fa3b22d 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Profile/UnsecuredEntityControl+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Profile/UnsecuredEntityControl+Swiftified.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-27. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RET/Blob+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RET/Blob+Swiftified.swift index b7cb562bf..bf20996fe 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RET/Blob+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RET/Blob+Swiftified.swift @@ -1,7 +1,9 @@ import SargonUniFFI +// MARK: - Blob + SargonModel extension Blob: SargonModel {} +// MARK: - Blob + CustomStringConvertible extension Blob: CustomStringConvertible { public var description: String { hex diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RET/Blobs+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RET/Blobs+Swiftified.swift index 50d3c6f04..b4b2e21e0 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RET/Blobs+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RET/Blobs+Swiftified.swift @@ -1,7 +1,9 @@ import SargonUniFFI +// MARK: - Blobs + SargonModel extension Blobs: SargonModel {} +// MARK: - Blobs + ExpressibleByArrayLiteral extension Blobs: ExpressibleByArrayLiteral { public typealias ArrayLiteralElement = Blob public init(arrayLiteral blobs: ArrayLiteralElement...) { diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RET/CompiledNotarizedIntent+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RET/CompiledNotarizedIntent+Swiftified.swift index f09ba8ee7..08b40005a 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RET/CompiledNotarizedIntent+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RET/CompiledNotarizedIntent+Swiftified.swift @@ -1,8 +1,10 @@ import Foundation import SargonUniFFI +// MARK: - CompiledNotarizedIntent + SargonModel extension CompiledNotarizedIntent: SargonModel {} +// MARK: - CompiledNotarizedIntent + CustomStringConvertible extension CompiledNotarizedIntent: CustomStringConvertible { public var description: String { data.hex diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RET/IntentSignature+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RET/IntentSignature+Swiftified.swift index 1ebf5c98d..923951aea 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RET/IntentSignature+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RET/IntentSignature+Swiftified.swift @@ -1,6 +1,9 @@ import SargonUniFFI +// MARK: - IntentSignature + SargonModel extension IntentSignature: SargonModel {} + +// MARK: - IntentSignature + CustomStringConvertible extension IntentSignature: CustomStringConvertible { public var description: String { signatureWithPublicKey.description diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RET/ResourceOrNonFungible+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RET/ResourceOrNonFungible+Swiftified.swift index 0bb27a03f..8ad845142 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RET/ResourceOrNonFungible+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RET/ResourceOrNonFungible+Swiftified.swift @@ -1,16 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import Foundation import SargonUniFFI - +// MARK: - ResourceOrNonFungible + SargonModel extension ResourceOrNonFungible: SargonModel {} +// MARK: - ResourceOrNonFungible + Identifiable extension ResourceOrNonFungible: Identifiable { public typealias ID = Self public var id: ID { @@ -20,7 +14,6 @@ extension ResourceOrNonFungible: Identifiable { extension ResourceOrNonFungible { public var resourceAddress: ResourceAddress { - switch self { case let .nonFungible(value): value.resourceAddress case let .resource(value): value diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RET/SignedIntent+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RET/SignedIntent+Swiftified.swift index f8d6b2ace..a3a0a226f 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RET/SignedIntent+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RET/SignedIntent+Swiftified.swift @@ -1,4 +1,3 @@ import SargonUniFFI extension SignedIntent: SargonModel {} - diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RET/TransactionManifest+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RET/TransactionManifest+Swiftified.swift index 11bff00d0..6b382c83e 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RET/TransactionManifest+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RET/TransactionManifest+Swiftified.swift @@ -1,154 +1,151 @@ import SargonUniFFI +// MARK: - TransactionManifest + SargonModel extension TransactionManifest: SargonModel {} // MARK: Build Manifest extension TransactionManifest { - - // Not DEBUG only, since used in PROD for Stokenet. - public static func faucet( - includeLockFeeInstruction: Bool, - addressOfReceivingAccount: AccountAddress - ) -> Self { - manifestForFaucet( - includeLockFeeInstruction: includeLockFeeInstruction, - addressOfReceivingAccount: addressOfReceivingAccount - ) - } - - public static func setOwnerKeys( - addressOfAccountOrPersona: AddressOfAccountOrPersona, - ownerKeyHashes: [PublicKeyHash] - ) -> Self { - manifestSetOwnerKeysHashes( - addressOfAccountOrPersona: addressOfAccountOrPersona, - ownerKeyHashes: ownerKeyHashes - ) - } - - public static func stakesClaim( - accountAddress: AccountAddress, - stakeClaims: [StakeClaim] - ) -> Self { - manifestStakesClaim( - accountAddress: accountAddress, - stakeClaims: stakeClaims - ) - } - - public static func assetsTransfers( - transfers: PerAssetTransfers - ) -> Self { - manifestPerAssetTransfers(transfers: transfers) - } + // Not DEBUG only, since used in PROD for Stokenet. + public static func faucet( + includeLockFeeInstruction: Bool, + addressOfReceivingAccount: AccountAddress + ) -> Self { + manifestForFaucet( + includeLockFeeInstruction: includeLockFeeInstruction, + addressOfReceivingAccount: addressOfReceivingAccount + ) + } + + public static func setOwnerKeys( + addressOfAccountOrPersona: AddressOfAccountOrPersona, + ownerKeyHashes: [PublicKeyHash] + ) -> Self { + manifestSetOwnerKeysHashes( + addressOfAccountOrPersona: addressOfAccountOrPersona, + ownerKeyHashes: ownerKeyHashes + ) + } + + public static func stakesClaim( + accountAddress: AccountAddress, + stakeClaims: [StakeClaim] + ) -> Self { + manifestStakesClaim( + accountAddress: accountAddress, + stakeClaims: stakeClaims + ) + } + + public static func assetsTransfers( + transfers: PerAssetTransfers + ) -> Self { + manifestPerAssetTransfers(transfers: transfers) + } + + public static func markingAccountAsDappDefinitionType( + accountAddress: AccountAddress + ) -> Self { + manifestMarkingAccountAsDappDefinitionType(accountAddress: accountAddress) + } - public static func markingAccountAsDappDefinitionType( - accountAddress: AccountAddress - ) -> Self { - manifestMarkingAccountAsDappDefinitionType(accountAddress: accountAddress) - } - - public static func thirdPartyDepositUpdate( - accountAddress: AccountAddress, - from currentInProfile: ThirdPartyDeposits, - to newFromUI: ThirdPartyDeposits - ) -> Self { - manifestThirdPartyDepositUpdate( - accountAddress: accountAddress, - from: currentInProfile, - to: newFromUI - ) - } + public static func thirdPartyDepositUpdate( + accountAddress: AccountAddress, + from currentInProfile: ThirdPartyDeposits, + to newFromUI: ThirdPartyDeposits + ) -> Self { + manifestThirdPartyDepositUpdate( + accountAddress: accountAddress, + from: currentInProfile, + to: newFromUI + ) + } - public static func accountLockerClaim( - lockerAddress: LockerAddress, - claimant: AccountAddress, - claimableResources: [AccountLockerClaimableResource] - ) -> Self { - manifestAccountLockerClaim( - lockerAddress: lockerAddress, - claimant: claimant, - claimableResources: claimableResources - ) - } + public static func accountLockerClaim( + lockerAddress: LockerAddress, + claimant: AccountAddress, + claimableResources: [AccountLockerClaimableResource] + ) -> Self { + manifestAccountLockerClaim( + lockerAddress: lockerAddress, + claimant: claimant, + claimableResources: claimableResources + ) + } } // MARK: Modify Manifest extension TransactionManifest { - public func modify( - lockFee fee: Decimal192 = .temporaryStandardFee, - addressOfFeePayer: AccountAddress - ) -> Self { - modifyManifestLockFee( - manifest: self, - addressOfFeePayer: addressOfFeePayer, - fee: fee - ) - } + public func modify( + lockFee fee: Decimal192 = .temporaryStandardFee, + addressOfFeePayer: AccountAddress + ) -> Self { + modifyManifestLockFee( + manifest: self, + addressOfFeePayer: addressOfFeePayer, + fee: fee + ) + } - public func modify( - addGuarantees guarantees: [TransactionGuarantee] - ) throws -> Self { - try modifyManifestAddGuarantees( - manifest: self, - guarantees: guarantees - ) - } + public func modify( + addGuarantees guarantees: [TransactionGuarantee] + ) throws -> Self { + try modifyManifestAddGuarantees( + manifest: self, + guarantees: guarantees + ) + } } #if DEBUG extension TransactionManifest { + public static func createFungibleToken( + addressOfOwner: AccountAddress + ) -> Self { + manifestCreateFungibleToken(addressOfOwner: addressOfOwner) + } + + public static func createFungibleTokenWithMetadata( + addressOfOwner: AccountAddress, + initialSupply: Decimal192, + metadata: TokenDefinitionMetadata + ) -> Self { + manifestCreateFungibleTokenWithMetadata( + addressOfOwner: addressOfOwner, + initialSupply: initialSupply, + metadata: metadata + ) + } - public static func createFungibleToken( - addressOfOwner: AccountAddress - ) -> Self { - manifestCreateFungibleToken(addressOfOwner: addressOfOwner) - } - - public static func createFungibleTokenWithMetadata( - addressOfOwner: AccountAddress, - initialSupply: Decimal192, - metadata: TokenDefinitionMetadata - ) -> Self { - manifestCreateFungibleTokenWithMetadata( - addressOfOwner: addressOfOwner, - initialSupply: initialSupply, - metadata: metadata - ) - } - - - public static func createMultipleFungibleTokens( - addressOfOwner: AccountAddress, + public static func createMultipleFungibleTokens( + addressOfOwner: AccountAddress, count: UInt8? = 10 - ) -> Self { + ) -> Self { manifestCreateMultipleFungibleTokens( addressOfOwner: addressOfOwner, count: count ) - } + } - public static func createMultipleNonFungibleTokens( - addressOfOwner: AccountAddress, + public static func createMultipleNonFungibleTokens( + addressOfOwner: AccountAddress, collectionCount: UInt8? = nil, nftsPerCollection: UInt8? = nil - ) -> Self { + ) -> Self { manifestCreateMultipleNonFungibleTokens( addressOfOwner: addressOfOwner, collectionCount: collectionCount, nftsPerCollection: nftsPerCollection ) - } + } - public static func createNonFungibleToken( - addressOfOwner: AccountAddress, + public static func createNonFungibleToken( + addressOfOwner: AccountAddress, nftsPerCollection: UInt8? = nil - ) -> Self { + ) -> Self { manifestCreateNonFungibleToken( addressOfOwner: addressOfOwner, nftsPerCollection: nftsPerCollection ) - } - + } } #endif // DEBUG diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RET/TransactionManifestV2+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RET/TransactionManifestV2+Swiftified.swift index 2f19921a3..af2ea8ba5 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RET/TransactionManifestV2+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RET/TransactionManifestV2+Swiftified.swift @@ -1,3 +1,3 @@ import SargonUniFFI -extension TransactionManifestV2: SargonModel {} \ No newline at end of file +extension TransactionManifestV2: SargonModel {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/LinkConnectionQRData+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/LinkConnectionQRData+Swiftified.swift index fd9b4488b..19709f58f 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/LinkConnectionQRData+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/LinkConnectionQRData+Swiftified.swift @@ -3,5 +3,8 @@ import SargonUniFFI public typealias LinkConnectionQRData = LinkConnectionQrData +// MARK: - LinkConnectionQrData + SargonModel extension LinkConnectionQrData: SargonModel {} + +// MARK: - LinkConnectionQrData + SargonObjectCodable extension LinkConnectionQrData: SargonObjectCodable {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/P2PLink+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/P2PLink+Swiftified.swift index cb9583557..004761de5 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/P2PLink+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/P2PLink+Swiftified.swift @@ -1,18 +1,15 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import Foundation import SargonUniFFI public typealias P2PLink = P2pLink +// MARK: - P2PLink + SargonModel extension P2PLink: SargonModel {} + +// MARK: - P2PLink + SargonObjectCodable extension P2PLink: SargonObjectCodable {} +// MARK: - P2PLink + Identifiable extension P2PLink: Identifiable { public typealias ID = PublicKeyHash } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/RadixConnectPassword+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/RadixConnectPassword+Swiftified.swift index 444ce02c8..a1e72c1d3 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/RadixConnectPassword+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/RadixConnectPassword+Swiftified.swift @@ -1,5 +1,8 @@ import Foundation import SargonUniFFI +// MARK: - RadixConnectPassword + SargonModel extension RadixConnectPassword: SargonModel {} -extension RadixConnectPassword: SargonStringCodable {} \ No newline at end of file + +// MARK: - RadixConnectPassword + SargonStringCodable +extension RadixConnectPassword: SargonStringCodable {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/RadixConnectPurpose+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/RadixConnectPurpose+Swiftified.swift index 8240130e0..215d3dc45 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/RadixConnectPurpose+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/P2PLinks/RadixConnectPurpose+Swiftified.swift @@ -1,13 +1,14 @@ import Foundation import SargonUniFFI +// MARK: - RadixConnectPurpose + SargonModel extension RadixConnectPurpose: SargonModel {} + +// MARK: - RadixConnectPurpose + SargonStringCodable extension RadixConnectPurpose: SargonStringCodable {} extension RadixConnectPurpose { - - public init(rawValue: String) { - self.init(string: rawValue) - } + public init(rawValue: String) { + self.init(string: rawValue) + } } - diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/WalletInteraction/UnvalidatedTransactionManifest+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/WalletInteraction/UnvalidatedTransactionManifest+Swiftified.swift index b57a7aebe..79cef6cd9 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/WalletInteraction/UnvalidatedTransactionManifest+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/WalletInteraction/UnvalidatedTransactionManifest+Swiftified.swift @@ -1,4 +1,4 @@ import Foundation import SargonUniFFI -extension UnvalidatedTransactionManifest: SargonModel {} \ No newline at end of file +extension UnvalidatedTransactionManifest: SargonModel {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/WalletInteraction/WalletToDappInteractionResponse+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/WalletInteraction/WalletToDappInteractionResponse+Swiftified.swift index 1271a8eb2..b94c4dd45 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/WalletInteraction/WalletToDappInteractionResponse+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/WalletInteraction/WalletToDappInteractionResponse+Swiftified.swift @@ -1,5 +1,8 @@ import Foundation import SargonUniFFI +// MARK: - WalletToDappInteractionResponse + SargonModel extension WalletToDappInteractionResponse: SargonModel {} + +// MARK: - WalletToDappInteractionResponse + SargonObjectCodable extension WalletToDappInteractionResponse: SargonObjectCodable {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/WalletInteractionWalletAccount+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/WalletInteractionWalletAccount+Swiftified.swift index f34c9dbe5..84c3e228e 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/WalletInteractionWalletAccount+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/RadixConnect/WalletInteractionWalletAccount+Swiftified.swift @@ -1,5 +1,8 @@ import Foundation import SargonUniFFI +// MARK: - WalletInteractionWalletAccount + SargonModel extension WalletInteractionWalletAccount: SargonModel {} + +// MARK: - WalletInteractionWalletAccount + SargonObjectCodable extension WalletInteractionWalletAccount: SargonObjectCodable {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/System/BIOS/BIOS+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/System/BIOS/BIOS+Swiftified.swift index e4fdd865f..82ba53526 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/System/BIOS/BIOS+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/System/BIOS/BIOS+Swiftified.swift @@ -1,18 +1,12 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-03. -// - import Foundation import SargonUniFFI public typealias BIOS = Bios + +// MARK: - BIOS + @unchecked Sendable extension BIOS: @unchecked Sendable {} extension BIOS { - public convenience init( bundle: Bundle, userDefaultsSuite: String, @@ -25,7 +19,7 @@ extension BIOS { ) // https://en.wikipedia.org/wiki/Power-on_self-test log.info("📬 BIOS POST (Power-On Self Test)") - + self.init(drivers: drivers) } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Drivers+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Drivers+Swiftified.swift index b85da7b0d..5bfe9c472 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Drivers+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Drivers+Swiftified.swift @@ -1,17 +1,9 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-03. -// - import Foundation import SargonUniFFI - +// MARK: - Drivers + @unchecked Sendable extension Drivers: @unchecked Sendable {} - extension Drivers { public convenience init( bundle: Bundle, @@ -24,7 +16,7 @@ extension Drivers { secureStorageDriver: secureStorageDriver ) } - + public convenience init( appVersion: String, userDefaultsSuite: String, @@ -41,7 +33,6 @@ extension Drivers { } extension Drivers { - public convenience init( secureStorage: SecureStorageDriver, hostInfo: HostInfoDriver, @@ -56,7 +47,7 @@ extension Drivers { eventBus: .shared, fileSystem: .shared, unsafeStorage: unsafeStorage, - profileStateChangeDriver: .shared + profileStateChangeDriver: .shared ) } } diff --git a/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/HostOS+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/HostOS+Swiftified.swift index bd7d40fae..e933e8e0b 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/HostOS+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/HostOS+Swiftified.swift @@ -1,12 +1,6 @@ -// -// File.swift -// -// -// Created by Michael Bakogiannis on 24/7/24. -// - import Foundation +// MARK: - HostOs + SargonModel extension HostOs: SargonModel {} extension HostOs { diff --git a/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkMethod+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkMethod+Swiftified.swift index 9de356d34..01244287c 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkMethod+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkMethod+Swiftified.swift @@ -1,7 +1,10 @@ import Foundation import SargonUniFFI +// MARK: - NetworkMethod + SargonModel extension NetworkMethod: SargonModel {} + +// MARK: - NetworkMethod + CustomStringConvertible extension NetworkMethod: CustomStringConvertible { public var description: String { toString() diff --git a/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkRequest+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkRequest+Swiftified.swift index d072c4d9f..28ab11b2e 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkRequest+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkRequest+Swiftified.swift @@ -1,16 +1,9 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-13. -// - import Foundation import SargonUniFFI extension URL { public init(validating string: String) throws { - guard let url = Self.init(string: string) else { + guard let url = Self(string: string) else { throw SargonError.InvalidUrl(badValue: string) } self = url diff --git a/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkRequest+URLRequest+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkRequest+URLRequest+Swiftified.swift index 8d7cfd4db..10b9628a7 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkRequest+URLRequest+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkRequest+URLRequest+Swiftified.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-03. -// - import Foundation import SargonUniFFI @@ -17,5 +10,3 @@ extension URLRequest { self = request } } - - diff --git a/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkResponse+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkResponse+Swiftified.swift index 755426a66..eca1d0579 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkResponse+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/System/Drivers/Networking/NetworkResponse+Swiftified.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-03. -// - import Foundation import SargonUniFFI diff --git a/apple/Sources/Sargon/Extensions/Swiftified/System/Event/EventKind+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/System/Event/EventKind+Swiftified.swift index 4fd3f5354..2d45700a0 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/System/Event/EventKind+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/System/Event/EventKind+Swiftified.swift @@ -1,16 +1,11 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-24. -// - import Foundation import SargonUniFFI +// MARK: - EventKind + SargonModel extension EventKind: SargonModel { public static let sample: Self = .accountAdded public static let sampleOther: Self = .accountUpdated } -extension EventKind: CaseIterable {} +// MARK: - EventKind + CaseIterable +extension EventKind: CaseIterable {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/System/SargonOS+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/System/SargonOS+Swiftified.swift index 2c70a82af..703d15e7d 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/System/SargonOS+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/System/SargonOS+Swiftified.swift @@ -1,14 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-03. -// - import Foundation import SargonUniFFI - public typealias SargonOS = SargonOs +// MARK: - SargonOS + @unchecked Sendable extension SargonOS: @unchecked Sendable {} diff --git a/apple/Sources/Sargon/Extensions/Swiftified/Transaction/AccountOrAddressOf+Swiftified.swift b/apple/Sources/Sargon/Extensions/Swiftified/Transaction/AccountOrAddressOf+Swiftified.swift index f4e86ec0e..66ce64b49 100644 --- a/apple/Sources/Sargon/Extensions/Swiftified/Transaction/AccountOrAddressOf+Swiftified.swift +++ b/apple/Sources/Sargon/Extensions/Swiftified/Transaction/AccountOrAddressOf+Swiftified.swift @@ -1,13 +1,16 @@ import SargonUniFFI +// MARK: - AccountOrAddressOf + SargonModel extension AccountOrAddressOf: SargonModel {} +// MARK: - AccountOrAddressOf + CustomStringConvertible extension AccountOrAddressOf: CustomStringConvertible { public var description: String { accountAddress.address } } +// MARK: - AccountOrAddressOf + Identifiable extension AccountOrAddressOf: Identifiable { public typealias ID = AccountAddress public var id: ID { diff --git a/apple/Sources/Sargon/MigrateToRust/PersonaData+Entry/PersonaDataIdentified+Extensions.swift b/apple/Sources/Sargon/MigrateToRust/PersonaData+Entry/PersonaDataIdentified+Extensions.swift index 9b83df4eb..fa2870bf8 100644 --- a/apple/Sources/Sargon/MigrateToRust/PersonaData+Entry/PersonaDataIdentified+Extensions.swift +++ b/apple/Sources/Sargon/MigrateToRust/PersonaData+Entry/PersonaDataIdentified+Extensions.swift @@ -1,5 +1,5 @@ -import SargonUniFFI import Foundation +import SargonUniFFI extension PersonaDataIdentifiedPhoneNumber { public func embed() -> AnyIdentifiedPersonaEntry { @@ -43,7 +43,6 @@ struct PersonaFieldCollectionValueWithIDNotFound: Swift.Error { public typealias PersonaDataEntryID = UUID extension PersonaData.Entry { - public func extract( _ type: F.Type = F.self ) -> F? where F: PersonaDataEntryProtocol { diff --git a/apple/Sources/Sargon/Protocols/AddressProtocol.swift b/apple/Sources/Sargon/Protocols/AddressProtocol.swift index 16f12786c..a719e92f4 100644 --- a/apple/Sources/Sargon/Protocols/AddressProtocol.swift +++ b/apple/Sources/Sargon/Protocols/AddressProtocol.swift @@ -8,6 +8,7 @@ public protocol BaseBaseAddressProtocol: SargonModel, ExpressibleByStringLiteral public protocol BaseBaseAddressProtocol: SargonModel {} #endif // DEBUG +// MARK: - BaseAddressProtocol public protocol BaseAddressProtocol: BaseBaseAddressProtocol, Codable, CustomStringConvertible { init(validatingAddress bech32String: String) throws var networkID: NetworkID { get } @@ -20,7 +21,6 @@ extension AddressProtocol { } } - extension BaseAddressProtocol { public var description: String { address @@ -48,23 +48,24 @@ extension BaseAddressProtocol { } #endif // DEBUG +// MARK: - AddressProtocol public protocol AddressProtocol: BaseAddressProtocol & Identifiable where Self.ID == String { - func formatted(_ format: AddressFormat) -> String - var asGeneral: Address { get } -#if DEBUG + func formatted(_ format: AddressFormat) -> String + var asGeneral: Address { get } + #if DEBUG static func random(networkID: NetworkID) -> Self func mapTo(networkID: NetworkID) -> Self static var sampleMainnet: Self { get } static var sampleMainnetOther: Self { get } static var sampleStokenet: Self { get } static var sampleStokenetOther: Self { get } -#endif // DEBUG + #endif // DEBUG } #if DEBUG extension AddressProtocol { - public static var sample: Self { Self.sampleMainnet } - public static var sampleOther: Self { Self.sampleMainnetOther } + public static var sample: Self { sampleMainnet } + public static var sampleOther: Self { sampleMainnetOther } } #endif // DEBUG @@ -72,22 +73,20 @@ extension AddressProtocol { extension AddressProtocol { public static var sampleValues: [Self] { [ - Self.sampleMainnet, - Self.sampleMainnetOther, - Self.sampleStokenet, - Self.sampleStokenetOther + sampleMainnet, + sampleMainnetOther, + sampleStokenet, + sampleStokenetOther, ] } } #endif // DEBUG - extension AddressProtocol { - - public var id: ID { - address - } - + public var id: ID { + address + } + /// Returns the`ResourceAddress` of `XRD` on the same network /// as this address. public var xrdOnSameNetwork: ResourceAddress { diff --git a/apple/Sources/Sargon/Protocols/BinaryProtocol.swift b/apple/Sources/Sargon/Protocols/BinaryProtocol.swift index 8387f93f8..74cbd73df 100644 --- a/apple/Sources/Sargon/Protocols/BinaryProtocol.swift +++ b/apple/Sources/Sargon/Protocols/BinaryProtocol.swift @@ -7,35 +7,38 @@ public protocol BaseBinaryProtocol: SargonModel, ExpressibleByStringLiteral, Exp public protocol BaseBinaryProtocol: SargonModel {} #endif +// MARK: - ToDataProtocol public protocol ToDataProtocol { var data: Data { get } } + +// MARK: - Hash + ToDataProtocol extension Hash: ToDataProtocol {} +// MARK: - BinaryProtocol public protocol BinaryProtocol: BaseBinaryProtocol, ToDataProtocol, CustomStringConvertible { associatedtype Digest: Equatable & ToDataProtocol init(hex: String) throws init(bytes: some DataProtocol) throws - + var hex: String { get } - + func hash() -> Digest } extension BinaryProtocol { - public var count: Int { data.count } - + public var hex: String { data.hex } - + public init(hex: String) throws { try self.init(bytes: Data(hex: hex)) } - + public var description: String { hex } @@ -52,7 +55,7 @@ extension BinaryProtocol { public init(stringLiteral value: String) { try! self.init(hex: value) } - + public init(arrayLiteral value: UInt8...) { try! self.init(bytes: value) } diff --git a/apple/Sources/Sargon/Protocols/CAP26PathProtocol.swift b/apple/Sources/Sargon/Protocols/CAP26PathProtocol.swift index 43a0914bd..edf0f0883 100644 --- a/apple/Sources/Sargon/Protocols/CAP26PathProtocol.swift +++ b/apple/Sources/Sargon/Protocols/CAP26PathProtocol.swift @@ -1,18 +1,16 @@ import SargonUniFFI +// MARK: - DerivationPathProtocol public protocol DerivationPathProtocol: HDPathProtocol { - var asGeneral: DerivationPath { get } + var asGeneral: DerivationPath { get } } - - extension DerivationPathProtocol { - public func toString() -> String { - asGeneral.toString() - } - public var description: String { - toString() - } -} - + public func toString() -> String { + asGeneral.toString() + } + public var description: String { + toString() + } +} diff --git a/apple/Sources/Sargon/Protocols/EntityAddressProtocol.swift b/apple/Sources/Sargon/Protocols/EntityAddressProtocol.swift index 822b204cd..1f9ccbcd2 100644 --- a/apple/Sources/Sargon/Protocols/EntityAddressProtocol.swift +++ b/apple/Sources/Sargon/Protocols/EntityAddressProtocol.swift @@ -1,9 +1,11 @@ import Foundation import SargonUniFFI +// MARK: - BaseEntityAddressProtocol /// Just a marker protocol public protocol BaseEntityAddressProtocol: AddressProtocol {} +// MARK: - EntityAddressProtocol public protocol EntityAddressProtocol: BaseEntityAddressProtocol { init(publicKey: PublicKey, networkID: NetworkID) } diff --git a/apple/Sources/Sargon/Protocols/EntityProtocol.swift b/apple/Sources/Sargon/Protocols/EntityProtocol.swift index 40b8a9333..507df188f 100644 --- a/apple/Sources/Sargon/Protocols/EntityProtocol.swift +++ b/apple/Sources/Sargon/Protocols/EntityProtocol.swift @@ -8,6 +8,7 @@ public protocol BaseBaseEntityProtocol: SargonModel { public protocol BaseBaseEntityProtocol: SargonModel {} #endif // DEBUG +// MARK: - EntityBaseProtocol public protocol EntityBaseProtocol: BaseBaseEntityProtocol, CustomStringConvertible, Identifiable where ID == EntityAddress { associatedtype EntityAddress: BaseEntityAddressProtocol var networkId: NetworkID { get } @@ -17,21 +18,21 @@ public protocol EntityBaseProtocol: BaseBaseEntityProtocol, CustomStringConverti var securityState: EntitySecurityState { get } var entityKind: EntityKind { get } var asGeneral: AccountOrPersona { get } - -#if DEBUG + + #if DEBUG static var sampleMainnet: Self { get } static var sampleMainnetOther: Self { get } static var sampleMainnetThird: Self { get } static var sampleStokenet: Self { get } static var sampleStokenetOther: Self { get } static var sampleStokenetThird: Self { get } -#endif // DEBUG + #endif // DEBUG } extension EntityBaseProtocol { public var id: ID { address } public var networkID: NetworkID { networkId } - + public var isDeleted: Bool { flags.contains(.tombstonedByUser) } @@ -39,7 +40,7 @@ extension EntityBaseProtocol { public var isHidden: Bool { flags.contains(.hiddenByUser) } - + public var virtualHierarchicalDeterministicFactorInstances: Set { var factorInstances = Set() switch securityState { @@ -49,22 +50,22 @@ extension EntityBaseProtocol { factorInstances.insert(authSigning) } return factorInstances - // TODO: Handle when MFA is integrated + // TODO: Handle when MFA is integrated // case .securified(value: let value): // return [] } } - + public var hasAuthenticationSigningKey: Bool { switch securityState { case let .unsecured(unsecuredEntityControl): unsecuredEntityControl.authenticationSigning != nil - // TODO: Handle when MFA is integrated + // TODO: Handle when MFA is integrated // case .securified(value: let value): // false // TODO handle that in the future } } - + public var deviceFactorSourceID: FactorSourceIDFromHash? { switch self.securityState { case let .unsecured(control): @@ -72,9 +73,9 @@ extension EntityBaseProtocol { guard factorSourceID.kind == .device else { return nil } - + return factorSourceID - // TODO: Handle when MFA is integrated + // TODO: Handle when MFA is integrated // case .securified(value: _): // return nil // TODO handle that in the future } @@ -89,8 +90,8 @@ extension EntityBaseProtocol { #if DEBUG extension EntityBaseProtocol { - public static var sample: Self { Self.sampleMainnet } - public static var sampleOther: Self { Self.sampleMainnetOther } + public static var sample: Self { sampleMainnet } + public static var sampleOther: Self { sampleMainnetOther } } #endif // DEBUG @@ -98,35 +99,35 @@ extension EntityBaseProtocol { extension EntityBaseProtocol { public static var sampleValuesMainnet: [Self] { [ - Self.sampleMainnet, - Self.sampleMainnetOther, - Self.sampleMainnetThird, + sampleMainnet, + sampleMainnetOther, + sampleMainnetThird, ] } + public static var sampleValuesStokenet: [Self] { [ - Self.sampleStokenet, - Self.sampleStokenetOther, - Self.sampleStokenetThird, + sampleStokenet, + sampleStokenetOther, + sampleStokenetThird, ] } - + public static var sampleValues: [Self] { - Self.sampleValuesMainnet + Self.sampleValuesStokenet + sampleValuesMainnet + sampleValuesStokenet } } #endif // DEBUG - +// MARK: - EntityProtocol public protocol EntityProtocol: EntityBaseProtocol { - associatedtype ExtraProperties: SargonModel - + static func deriveVirtualAddress( networkID: NetworkID, factorInstance: HierarchicalDeterministicFactorInstance ) -> EntityAddress - + init( networkID: NetworkID, address: EntityAddress, @@ -134,7 +135,7 @@ public protocol EntityProtocol: EntityBaseProtocol { displayName: DisplayName, extraProperties: ExtraProperties ) - + static var kind: EntityKind { get } static func extract(from someEntityProtocol: some EntityBaseProtocol) -> Self? } diff --git a/apple/Sources/Sargon/Protocols/ExactlyNBytesProtocol.swift b/apple/Sources/Sargon/Protocols/ExactlyNBytesProtocol.swift index c62df14e2..6677baf56 100644 --- a/apple/Sources/Sargon/Protocols/ExactlyNBytesProtocol.swift +++ b/apple/Sources/Sargon/Protocols/ExactlyNBytesProtocol.swift @@ -1,12 +1,13 @@ -import SargonUniFFI import Foundation +import SargonUniFFI +// MARK: - ExactlyNBytesProtocol public protocol ExactlyNBytesProtocol: BinaryProtocol { static var length: Int { get } } extension ExactlyNBytesProtocol { public static func generate() -> Self { - try! Self.init(bytes: Data.random(byteCount: Self.length)) + try! Self(bytes: Data.random(byteCount: length)) } } diff --git a/apple/Sources/Sargon/Protocols/HDPathComponentProtocol.swift b/apple/Sources/Sargon/Protocols/HDPathComponentProtocol.swift index 04ee3b809..f6dcca593 100644 --- a/apple/Sources/Sargon/Protocols/HDPathComponentProtocol.swift +++ b/apple/Sources/Sargon/Protocols/HDPathComponentProtocol.swift @@ -1,18 +1,12 @@ -// -// HDPathComponentModels.swift.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-24. -// - +// MARK: - BaseHDPathComponentProtocol public protocol BaseHDPathComponentProtocol: SargonModel { - init(globalKeySpace: UInt32) throws - func indexInLocalKeySpace() -> UInt32 - func indexInGlobalKeySpace() -> UInt32 + init(globalKeySpace: UInt32) throws + func indexInLocalKeySpace() -> UInt32 + func indexInGlobalKeySpace() -> UInt32 } +// MARK: - HDPathComponentProtocol public protocol HDPathComponentProtocol: BaseHDPathComponentProtocol { static var globalOffset: UInt32 { get } - init(localKeySpace: UInt32) throws + init(localKeySpace: UInt32) throws } - diff --git a/apple/Sources/Sargon/Protocols/HDPathProtocol.swift b/apple/Sources/Sargon/Protocols/HDPathProtocol.swift index 49e01c1c1..af3ee75f8 100644 --- a/apple/Sources/Sargon/Protocols/HDPathProtocol.swift +++ b/apple/Sources/Sargon/Protocols/HDPathProtocol.swift @@ -5,16 +5,16 @@ public protocol BaseHDPathProtocol: BaseSargonModel, CustomStringConvertible, Ex public protocol BaseHDPathProtocol: BaseSargonModel, CustomStringConvertible {} #endif // DEBUG +// MARK: - HDPathProtocol public protocol HDPathProtocol: BaseHDPathProtocol { - init(string: String) throws - func toString() -> String + init(string: String) throws + func toString() -> String } #if DEBUG extension HDPathProtocol { - public init(stringLiteral value: String) { - try! self.init(string: value) - } + public init(stringLiteral value: String) { + try! self.init(string: value) + } } #endif - diff --git a/apple/Sources/Sargon/Protocols/IdentifiableByStringProtocol.swift b/apple/Sources/Sargon/Protocols/IdentifiableByStringProtocol.swift index 5ebd25e28..7aa5469fd 100644 --- a/apple/Sources/Sargon/Protocols/IdentifiableByStringProtocol.swift +++ b/apple/Sources/Sargon/Protocols/IdentifiableByStringProtocol.swift @@ -7,15 +7,14 @@ public protocol BaseIdentifiableByStringProtocol: SargonModel & ExpressibleByStr public protocol BaseIdentifiableByStringProtocol: SargonModel {} #endif // DEBUG - +// MARK: - IdentifiableByStringProtocol public protocol IdentifiableByStringProtocol: BaseIdentifiableByStringProtocol & Codable & CustomStringConvertible & Identifiable where Self.ID == String { init(_ string: String) throws - + /// A non user facing, raw, string representation of the value. - func toRawString() -> String - + func toRawString() -> String + func formatted(_ format: AddressFormat) -> String - } extension IdentifiableByStringProtocol { @@ -43,7 +42,6 @@ extension IdentifiableByStringProtocol where Self: Codable { } } - #if DEBUG extension IdentifiableByStringProtocol { public init(stringLiteral value: String) { @@ -51,4 +49,3 @@ extension IdentifiableByStringProtocol { } } #endif // DEBUG - diff --git a/apple/Sources/Sargon/Protocols/PublicKeyProtocol.swift b/apple/Sources/Sargon/Protocols/PublicKeyProtocol.swift index 268963419..9d1962812 100644 --- a/apple/Sources/Sargon/Protocols/PublicKeyProtocol.swift +++ b/apple/Sources/Sargon/Protocols/PublicKeyProtocol.swift @@ -1,8 +1,9 @@ import Foundation import SargonUniFFI +// MARK: - PublicKeyProtocol public protocol PublicKeyProtocol: BinaryProtocol where Digest == PublicKeyHash { - var asGeneral: PublicKey { get } + var asGeneral: PublicKey { get } } extension PublicKeyProtocol { diff --git a/apple/Sources/Sargon/Protocols/SargonModel.swift b/apple/Sources/Sargon/Protocols/SargonModel.swift index 12f501956..a7958860a 100644 --- a/apple/Sources/Sargon/Protocols/SargonModel.swift +++ b/apple/Sources/Sargon/Protocols/SargonModel.swift @@ -1,17 +1,17 @@ +// MARK: - BaseSargonModel public protocol BaseSargonModel: Sendable, Hashable {} #if DEBUG public protocol SargonModel: BaseSargonModel { - static var sample: Self { get } - static var sampleOther: Self { get } + static var sample: Self { get } + static var sampleOther: Self { get } } #else public protocol SargonModel: BaseSargonModel {} #endif // if DEBUG - #if DEBUG extension SargonModel { - public static var sampleValues: [Self] { [Self.sample, Self.sampleOther] } + public static var sampleValues: [Self] { [sample, sampleOther] } } #endif // DEBUG diff --git a/apple/Sources/Sargon/Protocols/SignatureProtocol.swift b/apple/Sources/Sargon/Protocols/SignatureProtocol.swift index 07901e2f3..296320e25 100644 --- a/apple/Sources/Sargon/Protocols/SignatureProtocol.swift +++ b/apple/Sources/Sargon/Protocols/SignatureProtocol.swift @@ -1,5 +1,7 @@ +// MARK: - IntoSignatureProtocol public protocol IntoSignatureProtocol { var signature: Signature { get } } +// MARK: - SignatureProtocol public protocol SignatureProtocol: BinaryProtocol & IntoSignatureProtocol {} diff --git a/apple/Sources/Sargon/Protocols/TransactionHashProtocol.swift b/apple/Sources/Sargon/Protocols/TransactionHashProtocol.swift index 19715eb32..9428bec32 100644 --- a/apple/Sources/Sargon/Protocols/TransactionHashProtocol.swift +++ b/apple/Sources/Sargon/Protocols/TransactionHashProtocol.swift @@ -1,14 +1,15 @@ - +// MARK: - TransactionHashProtocol public protocol TransactionHashProtocol: IdentifiableByStringProtocol { var networkId: NetworkID { get } - var bech32EncodedTxId: String { get } + var bech32EncodedTxId: String { get } } + extension TransactionHashProtocol { - public var networkID: NetworkID { - networkId - } - - public func toRawString() -> String { - bech32EncodedTxId - } + public var networkID: NetworkID { + networkId + } + + public func toRawString() -> String { + bech32EncodedTxId + } } diff --git a/apple/Sources/Sargon/SargonOS/BIOS+Static+Shared.swift b/apple/Sources/Sargon/SargonOS/BIOS+Static+Shared.swift index d22df5af2..f31c48301 100644 --- a/apple/Sources/Sargon/SargonOS/BIOS+Static+Shared.swift +++ b/apple/Sources/Sargon/SargonOS/BIOS+Static+Shared.swift @@ -1,57 +1,48 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - import Foundation import SargonUniFFI extension BIOS { - public nonisolated(unsafe) static var shared: BIOS { - guard let shared = Self._shared else { + guard let shared = _shared else { fatalError("BIOS not created, create it with `BIOS.creatingShared:drivers`") } return shared } - + /// Can be access later with `OS.shared` @discardableResult public static func creatingShared( drivers: Drivers ) -> BIOS { - Self._creatingShared(drivers: drivers, isEmulatingFreshInstall: false) + _creatingShared(drivers: drivers, isEmulatingFreshInstall: false) } - } extension BIOS { private nonisolated(unsafe) static var _shared: BIOS! - + /// Can be access later with `OS.shared` @discardableResult public static func _creatingShared( drivers: Drivers, isEmulatingFreshInstall: Bool ) -> BIOS { - Self.settingShared( + settingShared( shared: BIOS(drivers: drivers), isEmulatingFreshInstall: isEmulatingFreshInstall ) } - + /// Can be access later with `OS.shared` @discardableResult - internal static func settingShared( + static func settingShared( shared: BIOS, isEmulatingFreshInstall: Bool = false ) -> BIOS { if !isEmulatingFreshInstall { assert(_shared == nil, "Should not be created twice") } - Self._shared = shared + _shared = shared setRustLogLevel(.debug) return shared } diff --git a/apple/Sources/Sargon/SargonOS/SargonOS+SargonOSProtocol.swift b/apple/Sources/Sargon/SargonOS/SargonOS+SargonOSProtocol.swift index ac6b02981..7b73efaec 100644 --- a/apple/Sources/Sargon/SargonOS/SargonOS+SargonOSProtocol.swift +++ b/apple/Sources/Sargon/SargonOS/SargonOS+SargonOSProtocol.swift @@ -1,24 +1,16 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - import Foundation +// MARK: - SargonOS + SargonOSProtocol extension SargonOS: SargonOSProtocol { public var os: SargonOS { self } } // MARK: SargonOSProtocol Conformance extension SargonOS { - @discardableResult public func createAccount( named accountName: DisplayName ) async throws -> Account { try await createAndSaveNewAccount(networkId: currentNetworkID, name: accountName) } - } diff --git a/apple/Sources/Sargon/SargonOS/SargonOS+Static+Shared.swift b/apple/Sources/Sargon/SargonOS/SargonOS+Static+Shared.swift index 6ecfd9edf..c6d782f76 100644 --- a/apple/Sources/Sargon/SargonOS/SargonOS+Static+Shared.swift +++ b/apple/Sources/Sargon/SargonOS/SargonOS+Static+Shared.swift @@ -1,13 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - import Foundation import SargonUniFFI +// MARK: - SargonOSAlreadyBooted struct SargonOSAlreadyBooted: LocalizedError { var errorDescription: String? { "Radix Wallet core already initialized, should not have been initialized twice. This is a Radix developer error." @@ -15,14 +9,13 @@ struct SargonOSAlreadyBooted: LocalizedError { } extension SargonOS { - public nonisolated(unsafe) static var shared: SargonOS { - guard let shared = Self._shared else { + guard let shared = _shared else { fatalError("`SargonOS.shared` not created, create it with `SargonOS.creatingShared:bootingWith` and pass it a `BIOS`.") } return shared } - + /// Can be access later with `OS.shared` @discardableResult public static func creatingShared( @@ -33,14 +26,12 @@ extension SargonOS { isEmulatingFreshInstall: false ) } - } extension SargonOS { - /// Can be access later with `OS.shared` @discardableResult - internal static func _creatingShared( + static func _creatingShared( bootingWith bios: BIOS, isEmulatingFreshInstall: Bool ) async throws -> SargonOS { @@ -51,8 +42,6 @@ extension SargonOS { Self._shared = shared return shared } - - internal nonisolated(unsafe) static var _shared: SargonOS! - -} + nonisolated(unsafe) static var _shared: SargonOS! +} diff --git a/apple/Sources/Sargon/SargonOS/SargonOSProtocol.swift b/apple/Sources/Sargon/SargonOS/SargonOSProtocol.swift index 34a503829..ed0b31907 100644 --- a/apple/Sources/Sargon/SargonOS/SargonOSProtocol.swift +++ b/apple/Sources/Sargon/SargonOS/SargonOSProtocol.swift @@ -1,17 +1,11 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - import Foundation import SargonUniFFI +// MARK: - SargonOSProtocol /// A protocol enabling us to write `TestOS` public protocol SargonOSProtocol { var os: SargonOS { get } - + func createAccount( named accountName: DisplayName ) async throws -> Account @@ -19,7 +13,6 @@ public protocol SargonOSProtocol { // MARK: Forward calls to `os` extension SargonOSProtocol { - public func createAccount( named accountName: DisplayName ) async throws -> Account { @@ -34,28 +27,27 @@ extension SargonOSProtocol { try os.currentNetworkId() } } - + public var gateways: SavedGateways { get throws { try os.gateways() } } - + @available(*, deprecated, message: "Consider using faster `accountsForDisplayOnCurrentNetwork` and follow up with ") public var accountsOnCurrentNetwork: [Account] { get throws { try os.accountsOnCurrentNetwork() } } - + public var accountsForDisplayOnCurrentNetwork: [AccountForDisplay] { get throws { try os.accountsForDisplayOnCurrentNetwork() } } - + public func accountByAddress(_ address: AccountAddress) throws -> Account { try os.accountByAddress(address: address) } - } diff --git a/apple/Sources/Sargon/SargonOS/TestOS.swift b/apple/Sources/Sargon/SargonOS/TestOS.swift index a1581d27e..1d236067d 100644 --- a/apple/Sources/Sargon/SargonOS/TestOS.swift +++ b/apple/Sources/Sargon/SargonOS/TestOS.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - import Foundation import SargonUniFFI @@ -26,48 +19,45 @@ extension BIOS { public final class TestOS { public let os: SargonOS - + public init(os: SargonOS) { self.os = os } - + public convenience init(bios: BIOS) async { let os = await SargonOS.boot(bios: bios) self.init(os: os) } - - } + extension TestOS: SargonOSProtocol {} // MARK: Private extension TestOS { private func nextAccountName() -> DisplayName { - let index = (try? accountsForDisplayOnCurrentNetwork.count) ?? 0 - return DisplayName(value: "Unnamed \(index)") + let index = (try? accountsForDisplayOnCurrentNetwork.count) ?? 0 + return DisplayName(value: "Unnamed \(index)") } } // MARK: Public extension TestOS { - @discardableResult public func createAccount( named name: String? = nil ) async throws -> Self { - let accountName = try name.map { try DisplayName( validating: $0 ) } ?? nextAccountName() - + let _ = try await os.createAccount( named: accountName ) return self } - + @discardableResult public func batchCreateAccounts( count: UInt16, @@ -78,5 +68,4 @@ extension TestOS { } } - #endif // DEBUG diff --git a/apple/Sources/Sargon/Util/Buffer+InitializeWithRandomBytes.swift b/apple/Sources/Sargon/Util/Buffer+InitializeWithRandomBytes.swift index fd711ad4c..5211156db 100644 --- a/apple/Sources/Sargon/Util/Buffer+InitializeWithRandomBytes.swift +++ b/apple/Sources/Sargon/Util/Buffer+InitializeWithRandomBytes.swift @@ -40,4 +40,4 @@ extension UnsafeMutableRawBufferPointer { targetPtr = UnsafeMutableRawBufferPointer(rebasing: targetPtr[1...]) } } -} \ No newline at end of file +} diff --git a/apple/Sources/Sargon/Util/Data+Hex.swift b/apple/Sources/Sargon/Util/Data+Hex.swift index 1671a0f6a..126cb854d 100644 --- a/apple/Sources/Sargon/Util/Data+Hex.swift +++ b/apple/Sources/Sargon/Util/Data+Hex.swift @@ -1,6 +1,7 @@ import Foundation import SargonUniFFI +// MARK: - ByteHexEncodingErrors enum ByteHexEncodingErrors: Error { case incorrectHexValue case incorrectString @@ -11,9 +12,9 @@ let char0 = UInt8(UnicodeScalar("0").value) private func htoi(_ value: UInt8) throws -> UInt8 { switch value { - case char0...char0 + 9: + case char0 ... char0 + 9: return value - char0 - case charA...charA + 5: + case charA ... charA + 5: return value - charA + 10 default: throw ByteHexEncodingErrors.incorrectHexValue @@ -21,7 +22,7 @@ private func htoi(_ value: UInt8) throws -> UInt8 { } private func itoh(_ value: UInt8) -> UInt8 { - return (value > 9) ? (charA + value - 10) : (char0 + value) + (value > 9) ? (charA + value - 10) : (char0 + value) } extension DataProtocol { @@ -30,7 +31,7 @@ extension DataProtocol { var hexChars = [UInt8](repeating: 0, count: hexLen) var offset = 0 - self.regions.forEach { (_) in + for _ in self.regions { for i in self { hexChars[Int(offset * 2)] = itoh((i >> 4) & 0xF) hexChars[Int(offset * 2 + 1)] = itoh(i & 0xF) diff --git a/apple/Sources/Sargon/Util/EventPublisher.swift b/apple/Sources/Sargon/Util/EventPublisher.swift index 098832d06..29da77948 100644 --- a/apple/Sources/Sargon/Util/EventPublisher.swift +++ b/apple/Sources/Sargon/Util/EventPublisher.swift @@ -1,15 +1,15 @@ import AsyncExtensions public final actor EventPublisher { - public typealias Subject = AsyncReplaySubject - public typealias Stream = AsyncThrowingReplaySubject + public typealias Subject = AsyncReplaySubject + public typealias Stream = AsyncThrowingReplaySubject - let stream = Stream(bufferSize: 1) - let subject = Subject(bufferSize: 1) + let stream = Stream(bufferSize: 1) + let subject = Subject(bufferSize: 1) - public func eventStream() -> AsyncMulticastSequence { - subject - .multicast(stream) - .autoconnect() - } + public func eventStream() -> AsyncMulticastSequence { + subject + .multicast(stream) + .autoconnect() + } } diff --git a/apple/Sources/Sargon/Util/SargonLiteralCodable.swift b/apple/Sources/Sargon/Util/SargonLiteralCodable.swift index 21ed0bb0c..516a66d77 100644 --- a/apple/Sources/Sargon/Util/SargonLiteralCodable.swift +++ b/apple/Sources/Sargon/Util/SargonLiteralCodable.swift @@ -1,28 +1,22 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation +// MARK: - SargonLiteralCodable public protocol SargonLiteralCodable: Codable { - associatedtype Literal: Codable - - init(jsonAsLiteral: Literal) throws - func jsonLiteral() -> Literal + associatedtype Literal: Codable + + init(jsonAsLiteral: Literal) throws + func jsonLiteral() -> Literal } extension SargonLiteralCodable { - public init(from decoder: any Decoder) throws { - let container = try decoder.singleValueContainer() - let literal = try container.decode(Literal.self) - try self.init(jsonAsLiteral: literal) - } + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + let literal = try container.decode(Literal.self) + try self.init(jsonAsLiteral: literal) + } - public func encode(to encoder: any Encoder) throws { - var container = encoder.singleValueContainer() - try container.encode(jsonLiteral()) - } + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(jsonLiteral()) + } } diff --git a/apple/Sources/Sargon/Util/SargonObjectCodable.swift b/apple/Sources/Sargon/Util/SargonObjectCodable.swift index e433b5124..08e9cd71f 100644 --- a/apple/Sources/Sargon/Util/SargonObjectCodable.swift +++ b/apple/Sources/Sargon/Util/SargonObjectCodable.swift @@ -1,6 +1,7 @@ import Foundation import SwiftyJSON +// MARK: - SargonObjectCodable public protocol SargonObjectCodable: Codable { init(jsonData: some DataProtocol) throws func jsonData() -> Data @@ -12,11 +13,10 @@ extension SargonObjectCodable { let json = try JSON(data: jsonData()) try container.encode(json) } - + public init(from decoder: any Decoder) throws { let container = try decoder.singleValueContainer() let json = try container.decode(JSON.self) try self.init(jsonData: json.rawData()) } } - diff --git a/apple/Sources/Sargon/Util/SargonStringCodable.swift b/apple/Sources/Sargon/Util/SargonStringCodable.swift index fdbee99a1..39aa636fe 100644 --- a/apple/Sources/Sargon/Util/SargonStringCodable.swift +++ b/apple/Sources/Sargon/Util/SargonStringCodable.swift @@ -1,30 +1,23 @@ -// -// File 2.swift -// -// -// Created by Alexander Cyon on 2024-04-19. -// - import Foundation +// MARK: - SargonStringCodable /// A type in Sargon which is always JSON encoded as a String literal, /// e.g. DepositRule public protocol SargonStringCodable: SargonLiteralCodable where Literal == String { - init(jsonStringLiteral: String) throws - func jsonStringLiteral() -> String + init(jsonStringLiteral: String) throws + func jsonStringLiteral() -> String } /// We piggyback on `SargonLiteralCodable` and always use that, /// making it fast for us to add support for e.g. Int literals. + // MARK: SargonLiteralCodable extension SargonStringCodable { - - public init(jsonAsLiteral: Literal) throws { - try self.init(jsonStringLiteral: jsonAsLiteral) - } - - public func jsonLiteral() -> Literal { - jsonStringLiteral() - } -} + public init(jsonAsLiteral: Literal) throws { + try self.init(jsonStringLiteral: jsonAsLiteral) + } + public func jsonLiteral() -> Literal { + jsonStringLiteral() + } +} diff --git a/apple/Sources/Sargon/Util/SharedConstants.swift b/apple/Sources/Sargon/Util/SharedConstants.swift index 336f164c6..36e7c00ee 100644 --- a/apple/Sources/Sargon/Util/SharedConstants.swift +++ b/apple/Sources/Sargon/Util/SharedConstants.swift @@ -1,13 +1,14 @@ +// MARK: - SharedConstants public enum SharedConstants {} extension SharedConstants { - public static let minRequiredXrdForAccountDeletion = constantMinRequiredXrdForAccountDeletion() + public static let minRequiredXrdForAccountDeletion = constantMinRequiredXrdForAccountDeletion() } extension Account { - public static let nameMaxLength = Int(constantEntityNameMaxLength()) + public static let nameMaxLength = Int(constantEntityNameMaxLength()) } extension Persona { - public static let nameMaxLength = Int(constantEntityNameMaxLength()) + public static let nameMaxLength = Int(constantEntityNameMaxLength()) } diff --git a/apple/Tests/IntegrationTests/DriversTests/AppleHostInfoDriverTests.swift b/apple/Tests/IntegrationTests/DriversTests/AppleHostInfoDriverTests.swift index f82869bbe..cc3736e78 100644 --- a/apple/Tests/IntegrationTests/DriversTests/AppleHostInfoDriverTests.swift +++ b/apple/Tests/IntegrationTests/DriversTests/AppleHostInfoDriverTests.swift @@ -11,26 +11,26 @@ extension AppleHostInfoDriver { } } +// MARK: - AppleHostInfoDriverTests class AppleHostInfoDriverTests: DriverTest { - func test_app_version() async throws { let sut = SUT() let info = await sut.hostAppVersion() XCTAssertEqual(info, appVersion) } - + func test_device_name_not_empty() async throws { let sut = SUT() let info = await sut.hostDeviceName() XCTAssertFalse(info.isEmpty) } - + func test_device_os_name_not_empty() async throws { let sut = SUT() let info = await sut.hostOs() XCTAssertFalse(info.name().isEmpty) } - + func test_device_model_not_empty() async throws { let sut = SUT() let info = await sut.hostDeviceModel() diff --git a/apple/Tests/IntegrationTests/DriversTests/DriversTests.swift b/apple/Tests/IntegrationTests/DriversTests/DriversTests.swift index 7de9038b1..3cf0fb168 100644 --- a/apple/Tests/IntegrationTests/DriversTests/DriversTests.swift +++ b/apple/Tests/IntegrationTests/DriversTests/DriversTests.swift @@ -4,7 +4,6 @@ import Sargon import SargonUniFFI import XCTest - #if DEBUG extension Drivers { public static func test() -> Drivers { @@ -16,19 +15,18 @@ extension Drivers { ) ) } - } #endif - +// MARK: - DriversTests final class DriversTests: TestCase { typealias SUT = Drivers func test_log_at_each_level() { rustLoggerLogAtEveryLevel() } - - func test_bios_insecure() async throws { - let _ = await SargonOS.boot(bios: BIOS.insecure()) - } + + func test_bios_insecure() async throws { + let _ = await SargonOS.boot(bios: BIOS.insecure()) + } } diff --git a/apple/Tests/IntegrationTests/DriversTests/EntropyProviderDriverTests.swift b/apple/Tests/IntegrationTests/DriversTests/EntropyProviderDriverTests.swift index ad38b2586..b0ef7fdaa 100644 --- a/apple/Tests/IntegrationTests/DriversTests/EntropyProviderDriverTests.swift +++ b/apple/Tests/IntegrationTests/DriversTests/EntropyProviderDriverTests.swift @@ -5,18 +5,16 @@ import SargonUniFFI import XCTest class EntropyProviderDriverTests: DriverTest { - func test() { let sut = SUT() let n = 10 XCTAssertEqual( - Set((0.. { - func test() async throws { let sut = SUT() - - let expectedEvents = Array([.booted, .profileSaved, .profileSaved, .factorSourceUpdated, .accountAdded, .profileSaved]) + + let expectedEvents = [EventKind]([.booted, .profileSaved, .profileSaved, .factorSourceUpdated, .accountAdded, .profileSaved]) let task = Task { var notifications = Set() for await notification in await sut.notifications().prefix(expectedEvents.count) { @@ -17,7 +17,7 @@ class EventBusDriverTests: DriverTest { } return notifications } - + let bios = BIOS(drivers: .withEventBus(sut)) let os = await TestOS(bios: bios) try await os.os.newWallet(shouldPreDeriveInstances: false) @@ -26,7 +26,6 @@ class EventBusDriverTests: DriverTest { let notifications = await task.value XCTAssertEqual(Set(notifications.map(\.event.kind)), Set(expectedEvents)) } - } extension HostInfoDriver where Self == AppleHostInfoDriver { @@ -42,11 +41,7 @@ extension SecureStorageDriver where Self == Insecure︕!TestOnly︕!Ephemera } } - - - extension Drivers { - static func withNetworking(_ networking: some NetworkingDriver) -> Drivers { Drivers( networking: networking, @@ -60,7 +55,7 @@ extension Drivers { profileStateChangeDriver: .shared ) } - + static func withSecureStorage(_ secureStorage: some SecureStorageDriver) -> Drivers { Drivers( networking: .shared, @@ -72,10 +67,9 @@ extension Drivers { fileSystem: .shared, unsafeStorage: .shared, profileStateChangeDriver: .shared - ) } - + static func withEntropyProvider(_ entropyProvider: some EntropyProviderDriver) -> Drivers { Drivers( networking: .shared, @@ -89,7 +83,7 @@ extension Drivers { profileStateChangeDriver: .shared ) } - + static func withHostInfo(_ hostInfo: some HostInfoDriver) -> Drivers { Drivers( networking: .shared, @@ -103,7 +97,7 @@ extension Drivers { profileStateChangeDriver: .shared ) } - + static func withLogging(_ logging: some LoggingDriver) -> Drivers { Drivers( networking: .shared, @@ -117,7 +111,7 @@ extension Drivers { profileStateChangeDriver: .shared ) } - + static func withEventBus(_ eventBus: some EventBusDriver) -> Drivers { Drivers( networking: .shared, @@ -131,7 +125,7 @@ extension Drivers { profileStateChangeDriver: .shared ) } - + static func withFileSystem(_ fileSystem: some FileSystemDriver) -> Drivers { Drivers( networking: .shared, @@ -145,7 +139,7 @@ extension Drivers { profileStateChangeDriver: .shared ) } - + static func withUnsafeStorage(_ unsafeStorage: some UnsafeStorageDriver) -> Drivers { Drivers( networking: .shared, diff --git a/apple/Tests/IntegrationTests/DriversTests/FileSystemDriverTests.swift b/apple/Tests/IntegrationTests/DriversTests/FileSystemDriverTests.swift index 639cb304d..a1e804204 100644 --- a/apple/Tests/IntegrationTests/DriversTests/FileSystemDriverTests.swift +++ b/apple/Tests/IntegrationTests/DriversTests/FileSystemDriverTests.swift @@ -5,34 +5,33 @@ import SargonUniFFI import XCTest class FileSystemDriverTests: DriverTest { - func test() async throws { let nameOfFile = "delete_me_\(UUID().uuidString).txt" let path = URL.temporaryDirectory.appending(path: nameOfFile, directoryHint: .notDirectory).path() let data = Data("This file is completely safe to delete. It was generated by a unit test.".utf8) - + let sut = SUT() - try await sut.saveToFile(path: path, data: data, isAllowedToOverwrite: true) + try await sut.saveToFile(path: path, data: data, isAllowedToOverwrite: true) let loaded = try await sut.loadFromFile(path: path) XCTAssertEqual(loaded, data) - + XCTAssertTrue(FileManager.default.fileExists(atPath: path)) try await sut.deleteFile(path: path) XCTAssertFalse(FileManager.default.fileExists(atPath: path)) } - - func test_without_overwrite() async throws { - let nameOfFile = "delete_me_\(UUID().uuidString).txt" - let path = URL.temporaryDirectory.appending(path: nameOfFile, directoryHint: .notDirectory).path() - let data = Data("This file is completely safe to delete. It was generated by a unit test.".utf8) - - let sut = SUT() - try await sut.saveToFile(path: path, data: data, isAllowedToOverwrite: true) - do { - try await sut.saveToFile(path: path, data: data, isAllowedToOverwrite: false) - XCTFail("Expected throw") - } catch { - // Good, expected to throw - } - } + + func test_without_overwrite() async throws { + let nameOfFile = "delete_me_\(UUID().uuidString).txt" + let path = URL.temporaryDirectory.appending(path: nameOfFile, directoryHint: .notDirectory).path() + let data = Data("This file is completely safe to delete. It was generated by a unit test.".utf8) + + let sut = SUT() + try await sut.saveToFile(path: path, data: data, isAllowedToOverwrite: true) + do { + try await sut.saveToFile(path: path, data: data, isAllowedToOverwrite: false) + XCTFail("Expected throw") + } catch { + // Good, expected to throw + } + } } diff --git a/apple/Tests/IntegrationTests/DriversTests/InsecureStorageTests.swift b/apple/Tests/IntegrationTests/DriversTests/InsecureStorageTests.swift index bbe604124..6d24c73fe 100644 --- a/apple/Tests/IntegrationTests/DriversTests/InsecureStorageTests.swift +++ b/apple/Tests/IntegrationTests/DriversTests/InsecureStorageTests.swift @@ -5,16 +5,15 @@ import SargonUniFFI import XCTest class InsecureStorageDriverTests: DriverTest { - - func test() async throws { - let sut = SUT.init(keychainService: "test") - let data = Data.sampleAced - let key = SUT.Key.profileSnapshot(profileId: newProfileIdSample()) - try await sut.saveData(key: key, data: data) - let loaded = try await sut.loadData(key: key) - XCTAssertEqual(loaded, data) - try await sut.deleteDataForKey(key: key) - let loadedAfterDelete = try await sut.loadData(key: key) - XCTAssertNil(loadedAfterDelete) - } + func test() async throws { + let sut = SUT(keychainService: "test") + let data = Data.sampleAced + let key = SUT.Key.profileSnapshot(profileId: newProfileIdSample()) + try await sut.saveData(key: key, data: data) + let loaded = try await sut.loadData(key: key) + XCTAssertEqual(loaded, data) + try await sut.deleteDataForKey(key: key) + let loadedAfterDelete = try await sut.loadData(key: key) + XCTAssertNil(loadedAfterDelete) + } } diff --git a/apple/Tests/IntegrationTests/DriversTests/LoggingDriverTests.swift b/apple/Tests/IntegrationTests/DriversTests/LoggingDriverTests.swift index 828a5dabd..aa1c29750 100644 --- a/apple/Tests/IntegrationTests/DriversTests/LoggingDriverTests.swift +++ b/apple/Tests/IntegrationTests/DriversTests/LoggingDriverTests.swift @@ -1,29 +1,28 @@ import CustomDump import Foundation +import os @testable import Sargon import SargonUniFFI import XCTest -import os class LoggingDriverTests: DriverTest { - func test() { let sut = SUT.shared let levels = LogLevel.allCases - levels.forEach { level in + for level in levels { let msg = "Swift Unit test \(#file) \(#line)" sut.log(level: level, msg: msg) sut.swiftLogger.log(level: .init(sargonLogLevel: level), "\(msg)") } } - + func test_setRustLogLevel() { - LogFilter.allCases.forEach { level in + for level in LogFilter.allCases { setRustLogLevel(level) XCTAssertEqual(getRustLogLevel(), level) } } - + func test_os_log_type_from_loglevel() { func doTest(_ from: Sargon.LogLevel, _ expected: OSLogType) { XCTAssertEqual(OSLogType(sargonLogLevel: from), expected) @@ -34,7 +33,7 @@ class LoggingDriverTests: DriverTest { doTest(.debug, .default) doTest(.trace, .debug) } - + func test_os_log_type_from_filter() { func doTest(_ from: Sargon.LogFilter, _ expected: OSLogType) { XCTAssertEqual(OSLogType(sargonFilterLevel: from), expected) diff --git a/apple/Tests/IntegrationTests/DriversTests/NetworkingDriverTests.swift b/apple/Tests/IntegrationTests/DriversTests/NetworkingDriverTests.swift index 12911ad37..6642a20c3 100644 --- a/apple/Tests/IntegrationTests/DriversTests/NetworkingDriverTests.swift +++ b/apple/Tests/IntegrationTests/DriversTests/NetworkingDriverTests.swift @@ -5,7 +5,6 @@ import SargonUniFFI import XCTest class NetworkingDriverTests: DriverTest { - func test() async throws { let sut = SUT.shared as NetworkingDriver let response = try await sut.executeNetworkRequest( @@ -16,7 +15,7 @@ class NetworkingDriverTests: DriverTest { ) XCTAssertEqual(response.statusCode, 200) } - + func test_bad_url() { XCTAssertThrowsError(try URL(validating: "")) } diff --git a/apple/Tests/IntegrationTests/DriversTests/UnsafeStorageDriverTests.swift b/apple/Tests/IntegrationTests/DriversTests/UnsafeStorageDriverTests.swift index 70857ecd5..61c034db8 100644 --- a/apple/Tests/IntegrationTests/DriversTests/UnsafeStorageDriverTests.swift +++ b/apple/Tests/IntegrationTests/DriversTests/UnsafeStorageDriverTests.swift @@ -4,9 +4,7 @@ import Sargon import SargonUniFFI import XCTest - class UnsafeStorageDriverTests: DriverTest { - func test_crud() async throws { let sut = SUT() let key = UnsafeStorage.Key.factorSourceUserHasWrittenDown diff --git a/apple/Tests/IntegrationTests/SargonOS/BIOSTests.swift b/apple/Tests/IntegrationTests/SargonOS/BIOSTests.swift index 4fddf8496..c91108a9b 100644 --- a/apple/Tests/IntegrationTests/SargonOS/BIOSTests.swift +++ b/apple/Tests/IntegrationTests/SargonOS/BIOSTests.swift @@ -8,30 +8,31 @@ extension BIOS { static func creatingShared( bundle: Bundle = .main, userDefaultsSuite: String = "test", - secureStorageDriver: SecureStorageDriver = Insecure︕!TestOnly︕!Ephemeral︕!SecureStorage.init( + secureStorageDriver: SecureStorageDriver = Insecure︕!TestOnly︕!Ephemeral︕!SecureStorage( keychainService: "test" ) ) -> BIOS { - Self.creatingShared(drivers: .init(bundle: bundle, userDefaultsSuite: userDefaultsSuite, secureStorageDriver: secureStorageDriver)) + creatingShared(drivers: .init(bundle: bundle, userDefaultsSuite: userDefaultsSuite, secureStorageDriver: secureStorageDriver)) } } +// MARK: - BIOSTests final class BIOSTests: OSTest { typealias SUT = BIOS - + func test_set_shared() { let sut = SUT.creatingShared() - + XCTAssertTrue(SUT.shared === sut) let new = SUT.settingShared( shared: .test( - secureStorageDriver: Insecure︕!TestOnly︕!Ephemeral︕!SecureStorage.init( + secureStorageDriver: Insecure︕!TestOnly︕!Ephemeral︕!SecureStorage( keychainService: "other" ) ), isEmulatingFreshInstall: true ) - + XCTAssertFalse(sut === new) XCTAssertTrue(SUT.shared === new) } diff --git a/apple/Tests/IntegrationTests/SargonOS/SargonOSTests.swift b/apple/Tests/IntegrationTests/SargonOS/SargonOSTests.swift index bc62d5767..d16305238 100644 --- a/apple/Tests/IntegrationTests/SargonOS/SargonOSTests.swift +++ b/apple/Tests/IntegrationTests/SargonOS/SargonOSTests.swift @@ -6,12 +6,12 @@ import XCTest final class SargonOSTests: OSTest { typealias SUT = SargonOS - + override func setUp() { super.setUp() SUT._shared = nil } - + func test() async throws { let _ = await SUT.boot( bios: .init( @@ -19,7 +19,7 @@ final class SargonOSTests: OSTest { ) ) } - + func test_set_shared() async throws { let sut = try await SUT.creatingShared( bootingWith: BIOS.test( @@ -30,7 +30,7 @@ final class SargonOSTests: OSTest { ) XCTAssertTrue(SUT.shared === sut) } - + func test_boot_twice_throws() async throws { let bios = BIOS.test( secureStorageDriver: Insecure︕!TestOnly︕!Ephemeral︕!SecureStorage( @@ -45,7 +45,7 @@ final class SargonOSTests: OSTest { XCTAssertEqual(err.errorDescription, "Radix Wallet core already initialized, should not have been initialized twice. This is a Radix developer error.") } catch { XCTFail("Wrong error type, expected: \(SargonOSAlreadyBooted.self)") } } - + func test_boot_twice_does_not_throws_when_emulating_fresh_install() async throws { let bios = BIOS.test( secureStorageDriver: Insecure︕!TestOnly︕!Ephemeral︕!SecureStorage( @@ -57,6 +57,4 @@ final class SargonOSTests: OSTest { XCTAssertFalse(first === second) XCTAssertTrue(SUT.shared === second) } - } - diff --git a/apple/Tests/IntegrationTests/SargonOS/TestOSTests.swift b/apple/Tests/IntegrationTests/SargonOS/TestOSTests.swift index f3e269c67..72b59e873 100644 --- a/apple/Tests/IntegrationTests/SargonOS/TestOSTests.swift +++ b/apple/Tests/IntegrationTests/SargonOS/TestOSTests.swift @@ -5,7 +5,6 @@ import SargonUniFFI import XCTest extension TestOS { - public convenience init() async { await self.init( bios: BIOS( @@ -31,15 +30,15 @@ extension TestOS { } } +// MARK: - TestOSTests final class TestOSTests: OSTest { - func test_create_single_account_many_times() async throws { let bus = EventBus() let drivers = Drivers.withEventBus(bus) let sut = await TestOS(bios: .init(drivers: drivers)) try await sut.os.newWallet(shouldPreDeriveInstances: false) let n = 3 - + let task = Task { var values = Set() for await eventNotification in await bus.notifications().filter({ $0.event.addressOfNewAccount != nil }).prefix(n) { @@ -47,48 +46,48 @@ final class TestOSTests: OSTest { } return Array(values).sorted().map(\.event) } - + try await sut .createAccount() .createAccount(named: "Foo") .createAccount() - + let events = await task.value XCTAssertEqual(try sut.accountsForDisplayOnCurrentNetwork.map(\.displayName), ["Unnamed 0", "Foo", "Unnamed 2"]) XCTAssertEqual(try sut.accountsForDisplayOnCurrentNetwork.map(\.address), events.compactMap(\.addressOfNewAccount)) } - + func test_create_account_returned() async throws { - let sut = await TestOS() - try await sut.os.newWallet(shouldPreDeriveInstances: false) + let sut = await TestOS() + try await sut.os.newWallet(shouldPreDeriveInstances: false) let displayName: DisplayName = "New" let account = try await sut.createAccount(named: displayName) XCTAssertEqual(account.displayName, displayName) - XCTAssertEqual(try sut.accountsForDisplayOnCurrentNetwork, [AccountForDisplay(account)]) + XCTAssertEqual(try sut.accountsForDisplayOnCurrentNetwork, [AccountForDisplay(account)]) } - + func test_create_account_returned_can_be_looked_up() async throws { - let sut = await TestOS.init() + let sut = await TestOS() try await sut.os.newWallet(shouldPreDeriveInstances: false) let displayName: DisplayName = "New" let account = try await sut.createAccount(named: displayName) let lookedUp = try sut.accountByAddress(account.address) XCTAssertEqual(lookedUp, account) } - + func test_lookup_throws_for_unknown_accounts() async throws { let sut = await TestOS() try await sut.os.newWallet(shouldPreDeriveInstances: false) XCTAssertThrowsError(try sut.accountByAddress(.sample)) } - + func test_new_profile_has_preset_gateways() async throws { let sut = await TestOS() try await sut.os.newWallet(shouldPreDeriveInstances: false) let gateways = try sut.gateways XCTAssertEqual(gateways, .preset) } - + func test_if_replace_profile_throws() async throws { let sut = await TestOS() try await sut.os.newWallet(shouldPreDeriveInstances: false) @@ -101,7 +100,7 @@ final class TestOSTests: OSTest { /* We expected to throw */ } } - + func test_we_can_mutate_profile_in_swift_and_save_then_profile_is_updated() async throws { let sut = await TestOS() try await sut.os.newWallet(shouldPreDeriveInstances: false) @@ -109,19 +108,19 @@ final class TestOSTests: OSTest { let creatingDevice = profile.header.creatingDevice let newCreatingDevice = DeviceInfo.sampleOther XCTAssertNotEqual(newCreatingDevice, creatingDevice) - profile.header.creatingDevice = newCreatingDevice // mutate profile + profile.header.creatingDevice = newCreatingDevice // mutate profile try await sut.os.setProfile(profile: profile) XCTAssertEqual(try sut.os.profile().header.creatingDevice, newCreatingDevice) // assert change worked } - + func test_batch_create_many_accounts() async throws { let sut = await TestOS() try await sut.os.newWallet(shouldPreDeriveInstances: false) let n: UInt16 = 4 try await sut.batchCreateAccounts(count: n, namePrefix: "Unnamed") - XCTAssertEqual(try sut.accountsOnCurrentNetwork.map(\.displayName.value), (0.. { -} +final class AccessControllerAddressTests: AddressTest {} diff --git a/apple/Tests/TestCases/Address/AccountAddressTests.swift b/apple/Tests/TestCases/Address/AccountAddressTests.swift index ed56c32db..d8d1700eb 100644 --- a/apple/Tests/TestCases/Address/AccountAddressTests.swift +++ b/apple/Tests/TestCases/Address/AccountAddressTests.swift @@ -5,48 +5,46 @@ import SargonUniFFI import XCTest final class AccountAddressTests: AddressTest { - - func testAddress() throws { - - let publicKey = try Ed25519PublicKey( - hex: "3e9b96a2a863f1be4658ea66aa0584d2a8847d4c0f658b20e62e3594d994d73d" - ) - + func testAddress() throws { + let publicKey = try Ed25519PublicKey( + hex: "3e9b96a2a863f1be4658ea66aa0584d2a8847d4c0f658b20e62e3594d994d73d" + ) + let address0 = AccountAddress( - publicKey: publicKey, - networkID: .mainnet - ) - - XCTAssertEqual( + publicKey: publicKey, + networkID: .mainnet + ) + + XCTAssertEqual( address0.address, "account_rdx129qdd2yp9vs8jkkn2uwn6sw0ejwmcwr3r4c3usr2hp0nau67m2kzdm" ) - } - + } + func test_into_fails_for_wrong_address_type() { XCTAssertThrowsError(try SUT.sample.asGeneral.asSpecific(type: IdentityAddress.self)) } - + func test_short() { XCTAssertEqual(SUT.sample.shortFormat, "acco...nvjdwr") } - + func test_formatted() { XCTAssertEqual(SUT.sample.formatted(.full), "account_rdx128y6j78mt0aqv6372evz28hrxp8mn06ccddkr7xppc88hyvynvjdwr") XCTAssertEqual(SUT.sample.formatted(.default), "acco...nvjdwr") } - - func test_from_bech32_on_stokenet() throws { - let address = try SUT( - validatingAddress: "account_tdx_2_1288efhmjt8kzce77par4ex997x2zgnlv5qqv9ltpxqg7ur0xpqm6gk" - ) - XCTAssertEqual(address.networkID, .stokenet) - - XCTAssertEqual( - address, - "account_tdx_2_1288efhmjt8kzce77par4ex997x2zgnlv5qqv9ltpxqg7ur0xpqm6gk" // ExpressibleByStringLiteral - ) - } - + + func test_from_bech32_on_stokenet() throws { + let address = try SUT( + validatingAddress: "account_tdx_2_1288efhmjt8kzce77par4ex997x2zgnlv5qqv9ltpxqg7ur0xpqm6gk" + ) + XCTAssertEqual(address.networkID, .stokenet) + + XCTAssertEqual( + address, + "account_tdx_2_1288efhmjt8kzce77par4ex997x2zgnlv5qqv9ltpxqg7ur0xpqm6gk" // ExpressibleByStringLiteral + ) + } + func test_is_legacy() { XCTAssertTrue(SUT("account_rdx16xlfcpp0vf7e3gqnswv8j9k58n6rjccu58vvspmdva22kf3aplease").isLegacy) diff --git a/apple/Tests/TestCases/Address/AddressOfAccountOrPersonaTests.swift b/apple/Tests/TestCases/Address/AddressOfAccountOrPersonaTests.swift index cb9c4032c..dbec49f83 100644 --- a/apple/Tests/TestCases/Address/AddressOfAccountOrPersonaTests.swift +++ b/apple/Tests/TestCases/Address/AddressOfAccountOrPersonaTests.swift @@ -4,6 +4,4 @@ import Sargon import SargonUniFFI import XCTest -final class AddressOfAccountOrPersonaTests: AddressTest { - -} +final class AddressOfAccountOrPersonaTests: AddressTest {} diff --git a/apple/Tests/TestCases/Address/ComponentAddressTests.swift b/apple/Tests/TestCases/Address/ComponentAddressTests.swift index 354c0de75..d57a210d3 100644 --- a/apple/Tests/TestCases/Address/ComponentAddressTests.swift +++ b/apple/Tests/TestCases/Address/ComponentAddressTests.swift @@ -5,12 +5,11 @@ import SargonUniFFI import XCTest final class ComponentAddressTests: AddressTest { - func test_is_global() { XCTAssertTrue(SUT.sampleMainnet.isGlobal) XCTAssertFalse(SUT.sampleMainnetOther.isGlobal) } - + func test_is_internal() { XCTAssertTrue(SUT.sampleMainnetOther.isInternal) XCTAssertFalse(SUT.sampleMainnet.isInternal) diff --git a/apple/Tests/TestCases/Address/LegacyOlympiaAccountAddressTests.swift b/apple/Tests/TestCases/Address/LegacyOlympiaAccountAddressTests.swift index 4e386f2d7..780c895c2 100644 --- a/apple/Tests/TestCases/Address/LegacyOlympiaAccountAddressTests.swift +++ b/apple/Tests/TestCases/Address/LegacyOlympiaAccountAddressTests.swift @@ -5,32 +5,29 @@ import SargonUniFFI import XCTest final class LegacyOlympiaAccountAddressTests: BaseAddressTest { - func test_isLegacyOfBabylonAddress() { let babylon: AccountAddress = "account_rdx168e8u653alt59xm8ple6khu6cgce9cfx9mlza6wxf7qs3wwdh0pwrf" XCTAssert(SUT.sample.isLegacyOfBabylonAddress(babylon)) XCTAssert(babylon.wasMigratedFromLegacyOlympia(address: SUT.sample)) } - + func test_to_babylon_address() { XCTAssertEqual(SUT.sample.toBabylonAddress(), "account_rdx168e8u653alt59xm8ple6khu6cgce9cfx9mlza6wxf7qs3wwdh0pwrf") } - + func test_from_public_key() { XCTAssertEqual( SUT(publicKey: "026f08db98ef1d0231eb15580da9123db8e25aa1747c8c32e5fd2ec47b8db73d5c"), // ExpressibleByStringLiteral "rdx1qspx7zxmnrh36q33av24srdfzg7m3cj65968erpjuh7ja3rm3kmn6hq4j9842" as SUT // ExpressibleByStringLiteral ) } - + func test_to_string() { XCTAssertNoDifference(SUT.sample, "rdx1qspx7zxmnrh36q33av24srdfzg7m3cj65968erpjuh7ja3rm3kmn6hq4j9842") } - - func test_formatted() { - XCTAssertNoDifference(SUT.sampleOther.formatted(.default), "rdx...0xqm2ylge") - XCTAssertNoDifference(SUT.sampleOther.formatted(.raw), "rdx1qsp8n0nx0muaewav2ksx99wwsu9swq5mlndjmn3gm9vl9q2mzmup0xqm2ylge") - } -} - + func test_formatted() { + XCTAssertNoDifference(SUT.sampleOther.formatted(.default), "rdx...0xqm2ylge") + XCTAssertNoDifference(SUT.sampleOther.formatted(.raw), "rdx1qsp8n0nx0muaewav2ksx99wwsu9swq5mlndjmn3gm9vl9q2mzmup0xqm2ylge") + } +} diff --git a/apple/Tests/TestCases/Address/LockerAddressTests.swift b/apple/Tests/TestCases/Address/LockerAddressTests.swift index 66dc5ea76..378a50d28 100644 --- a/apple/Tests/TestCases/Address/LockerAddressTests.swift +++ b/apple/Tests/TestCases/Address/LockerAddressTests.swift @@ -4,5 +4,4 @@ import Sargon import SargonUniFFI import XCTest -final class LockerAddressTests: AddressTest { -} +final class LockerAddressTests: AddressTest {} diff --git a/apple/Tests/TestCases/Address/ManifestEncounteredAddressTests.swift b/apple/Tests/TestCases/Address/ManifestEncounteredAddressTests.swift index 860b63ec4..78e130a96 100644 --- a/apple/Tests/TestCases/Address/ManifestEncounteredAddressTests.swift +++ b/apple/Tests/TestCases/Address/ManifestEncounteredAddressTests.swift @@ -4,6 +4,4 @@ import Sargon import SargonUniFFI import XCTest -final class ManifestEncounteredComponentAddressTests: AddressTest { - -} +final class ManifestEncounteredComponentAddressTests: AddressTest {} diff --git a/apple/Tests/TestCases/Address/NonFungibleResourceTests.swift b/apple/Tests/TestCases/Address/NonFungibleResourceTests.swift index 27c18e0e1..fa29d5f08 100644 --- a/apple/Tests/TestCases/Address/NonFungibleResourceTests.swift +++ b/apple/Tests/TestCases/Address/NonFungibleResourceTests.swift @@ -4,5 +4,4 @@ import Sargon import SargonUniFFI import XCTest -final class NonFungibleResourceAddressTests: AddressTest { -} +final class NonFungibleResourceAddressTests: AddressTest {} diff --git a/apple/Tests/TestCases/Address/PackageAddressTests.swift b/apple/Tests/TestCases/Address/PackageAddressTests.swift index 26ff8e496..7df4fc97c 100644 --- a/apple/Tests/TestCases/Address/PackageAddressTests.swift +++ b/apple/Tests/TestCases/Address/PackageAddressTests.swift @@ -4,5 +4,4 @@ import Sargon import SargonUniFFI import XCTest -final class PackageAddressTests: AddressTest { -} +final class PackageAddressTests: AddressTest {} diff --git a/apple/Tests/TestCases/Address/ResourceAddressTests.swift b/apple/Tests/TestCases/Address/ResourceAddressTests.swift index 207c259f6..6a9095194 100644 --- a/apple/Tests/TestCases/Address/ResourceAddressTests.swift +++ b/apple/Tests/TestCases/Address/ResourceAddressTests.swift @@ -5,21 +5,20 @@ import SargonUniFFI import XCTest final class ResourceAddressTests: AddressTest { - func test_is_fungible() { XCTAssertTrue(SUT.sampleMainnetXRD.isFungible) XCTAssertFalse(SUT.sampleMainnetNonFungibleGCMembership.isFungible) } - + func test_is_non_fungible() { XCTAssertFalse(SUT.sampleMainnetXRD.isNonFungible) XCTAssertTrue(SUT.sampleMainnetNonFungibleGCMembership.isNonFungible) } - + func test_as_non_fungible() { XCTAssertNotNil(SUT.sampleMainnetNonFungibleGCMembership.asNonFungibleResourceAddress) } - + func test_xrd_on_network() { XCTAssertEqual(SUT.xrd(on: .mainnet), SUT.sampleMainnet) XCTAssertEqual(SUT.xrd(on: .stokenet), SUT.sampleStokenet) @@ -31,36 +30,36 @@ final class ResourceAddressTests: AddressTest { ) XCTAssertEqual(SUT.sampleMainnetXRD.xrdOnSameNetwork, SUT.sampleMainnetXRD) XCTAssertEqual(SUT.sampleStokenetXRD.xrdOnSameNetwork, SUT.sampleStokenetXRD) - + XCTAssertEqual(AccountAddress.sampleMainnet.xrdOnSameNetwork, SUT.sampleMainnetXRD) XCTAssertEqual(AccountAddress.sampleMainnetOther.xrdOnSameNetwork, SUT.sampleMainnetXRD) XCTAssertEqual(AccountAddress.sampleStokenet.xrdOnSameNetwork, SUT.sampleStokenetXRD) XCTAssertEqual(AccountAddress.sampleStokenetOther.xrdOnSameNetwork, SUT.sampleStokenetXRD) - + XCTAssertEqual(IdentityAddress.sampleMainnet.xrdOnSameNetwork, SUT.sampleMainnetXRD) XCTAssertEqual(IdentityAddress.sampleMainnetOther.xrdOnSameNetwork, SUT.sampleMainnetXRD) XCTAssertEqual(IdentityAddress.sampleStokenet.xrdOnSameNetwork, SUT.sampleStokenetXRD) XCTAssertEqual(IdentityAddress.sampleStokenetOther.xrdOnSameNetwork, SUT.sampleStokenetXRD) } - - func test_is_xrd() { - XCTAssertTrue(SUT.sampleMainnetXRD.isXRD) - XCTAssertTrue(SUT.sampleStokenetXRD.isXRD) - XCTAssertFalse(SUT.sampleMainnetCandy.isXRD) - XCTAssertFalse(SUT.sampleMainnetNonFungibleGCMembership.isXRD) - XCTAssertFalse(SUT.sampleStokenetGum.isXRD) - XCTAssertFalse(SUT.sampleStokenetGC.isXRD) - } - + func test_is_xrd() { + XCTAssertTrue(SUT.sampleMainnetXRD.isXRD) + XCTAssertTrue(SUT.sampleStokenetXRD.isXRD) + + XCTAssertFalse(SUT.sampleMainnetCandy.isXRD) + XCTAssertFalse(SUT.sampleMainnetNonFungibleGCMembership.isXRD) + XCTAssertFalse(SUT.sampleStokenetGum.isXRD) + XCTAssertFalse(SUT.sampleStokenetGC.isXRD) + } + func test_is_xrd_on_network() { XCTAssertTrue(SUT.sampleMainnet.isXRD(on: .mainnet)) XCTAssertFalse(SUT.sampleMainnet.isXRD(on: .stokenet)) - + XCTAssertFalse(SUT.sampleStokenet.isXRD(on: .mainnet)) XCTAssertTrue(SUT.sampleStokenet.isXRD(on: .stokenet)) } - + func test_xrd_of_mainnet() { XCTAssertEqual(SUT.mainnetXRD, SUT.sampleMainnet) XCTAssert(SUT.mainnetXRD.isXRD) diff --git a/apple/Tests/TestCases/Address/ValidatorAddressTests.swift b/apple/Tests/TestCases/Address/ValidatorAddressTests.swift index 88d100583..a30bd34a6 100644 --- a/apple/Tests/TestCases/Address/ValidatorAddressTests.swift +++ b/apple/Tests/TestCases/Address/ValidatorAddressTests.swift @@ -4,5 +4,4 @@ import Sargon import SargonUniFFI import XCTest -final class ValidatorAddressTests: AddressTest { -} +final class ValidatorAddressTests: AddressTest {} diff --git a/apple/Tests/TestCases/Address/VaultAddressTests.swift b/apple/Tests/TestCases/Address/VaultAddressTests.swift index c38eecd8b..d9d2bb797 100644 --- a/apple/Tests/TestCases/Address/VaultAddressTests.swift +++ b/apple/Tests/TestCases/Address/VaultAddressTests.swift @@ -9,7 +9,7 @@ final class VaultAddressTests: AddressTest { XCTAssertTrue(SUT.sampleMainnetFungible.isFungible) XCTAssertFalse(SUT.sampleMainnetNonFungible.isFungible) } - + func test_is_non_fungible() { XCTAssertFalse(SUT.sampleMainnetFungible.isNonFungible) XCTAssertTrue(SUT.sampleMainnetNonFungible.isNonFungible) diff --git a/apple/Tests/TestCases/Crypto/AccountPathTests.swift b/apple/Tests/TestCases/Crypto/AccountPathTests.swift index 2ffecce4f..b773292b9 100644 --- a/apple/Tests/TestCases/Crypto/AccountPathTests.swift +++ b/apple/Tests/TestCases/Crypto/AccountPathTests.swift @@ -5,45 +5,45 @@ import SargonUniFFI import XCTest final class AccountPathTests: HDPathProtocolTest { - func test_sample_description() { - XCTAssertNoDifference(SUT.sample.description, "m/44H/1022H/1H/525H/1460H/0H") - } - - func test_sample_from_str() { - XCTAssertNoDifference( - "m/44H/1022H/1H/525H/1460H/0H", - SUT.sample - ) - } - + func test_sample_description() { + XCTAssertNoDifference(SUT.sample.description, "m/44H/1022H/1H/525H/1460H/0H") + } + + func test_sample_from_str() { + XCTAssertNoDifference( + "m/44H/1022H/1H/525H/1460H/0H", + SUT.sample + ) + } + func test_invalid_got_identity() { XCTAssertThrowsError(try SUT(string: "m/44H/1022H/1H/618H/1460H/0H")) } - + func test_invalid_got_bip44_like_legacy_path() { XCTAssertThrowsError(try SUT(string: "m/44H/1022H/0H/0/0H")) } - + func test_init_network_id_key_kind_index() throws { - try XCTAssertEqual( - SUT.sampleOther, - SUT( - networkID: .mainnet, - keyKind: .transactionSigning, - index: .unsecurified(UnsecurifiedHardened(localKeySpace: 1)) - ) - ) + try XCTAssertEqual( + SUT.sampleOther, + SUT( + networkID: .mainnet, + keyKind: .transactionSigning, + index: .unsecurified(UnsecurifiedHardened(localKeySpace: 1)) + ) + ) } - + func test_index() throws { - XCTAssertEqual( - SUT.sample.asGeneral.lastPathComponent, - HdPathComponent(globalKeySpace: 0 + 0x8000_0000) - ) + XCTAssertEqual( + SUT.sample.asGeneral.lastPathComponent, + HdPathComponent(globalKeySpace: 0 + 0x8000_0000) + ) - try XCTAssertEqual( - SUT.sampleOther.asGeneral.lastPathComponent, - HdPathComponent(localKeySpace: 1, keySpace: .unsecurified(isHardened: true)) - ) + try XCTAssertEqual( + SUT.sampleOther.asGeneral.lastPathComponent, + HdPathComponent(localKeySpace: 1, keySpace: .unsecurified(isHardened: true)) + ) } } diff --git a/apple/Tests/TestCases/Crypto/BIP39/BIP39LanguageTests.swift b/apple/Tests/TestCases/Crypto/BIP39/BIP39LanguageTests.swift index feaca0dfd..4e744fd63 100644 --- a/apple/Tests/TestCases/Crypto/BIP39/BIP39LanguageTests.swift +++ b/apple/Tests/TestCases/Crypto/BIP39/BIP39LanguageTests.swift @@ -5,7 +5,7 @@ import SargonUniFFI import XCTest final class BIP39LanguageTests: Test { - func test_wordlist() { - XCTAssertEqual(SUT.english.wordlist().first!.word, "abandon") - } + func test_wordlist() { + XCTAssertEqual(SUT.english.wordlist().first!.word, "abandon") + } } diff --git a/apple/Tests/TestCases/Crypto/BIP39/BIP39WordCountTests.swift b/apple/Tests/TestCases/Crypto/BIP39/BIP39WordCountTests.swift index dca2debc2..e5fd7287b 100644 --- a/apple/Tests/TestCases/Crypto/BIP39/BIP39WordCountTests.swift +++ b/apple/Tests/TestCases/Crypto/BIP39/BIP39WordCountTests.swift @@ -8,41 +8,41 @@ final class BIP39WordCountTests: Test { func test_all_cases() { XCTAssertEqual(SUT.allCases, [.twentyFour, .twentyOne, .eighteen, .fifteen, .twelve]) } - + func test_id_is_raw_value() { eachSample { sut in XCTAssertEqual(sut.id, sut.rawValue) } } - + func test_init_raw_value() { eachSample { sut in - XCTAssertEqual(SUT.init(rawValue: sut.rawValue), sut) + XCTAssertEqual(SUT(rawValue: sut.rawValue), sut) } } - + func test_init_wordCount() { eachSample { sut in - XCTAssertEqual(SUT.init(wordCount: Int(sut.rawValue)), sut) + XCTAssertEqual(SUT(wordCount: Int(sut.rawValue)), sut) } } - + func test_comparable_less_than() { XCTAssertLessThan(SUT.eighteen, SUT.twentyOne) XCTAssertLessThan(SUT.eighteen, SUT.twentyFour) } - + func test_comparable_greater_than() { XCTAssertGreaterThan(SUT.eighteen, SUT.fifteen) XCTAssertGreaterThan(SUT.fifteen, SUT.twelve) } - + func test_decrease() { var sut = SUT.fifteen sut.decreaseBy3() XCTAssertEqual(sut, .twelve) } - + func test_increase() { var sut = SUT.twentyOne sut.increaseBy3() diff --git a/apple/Tests/TestCases/Crypto/BIP39/MnemonicTests.swift b/apple/Tests/TestCases/Crypto/BIP39/MnemonicTests.swift index 4eea0b25c..0829162e6 100644 --- a/apple/Tests/TestCases/Crypto/BIP39/MnemonicTests.swift +++ b/apple/Tests/TestCases/Crypto/BIP39/MnemonicTests.swift @@ -13,44 +13,44 @@ final class MnemonicTests: Test { try XCTAssertEqual(SUT(phrase: string, language: nil), sut) // ok to skip language } } - + func test_words_roundtrip() throws { try eachSample { sut in let words = sut.words try XCTAssertEqual(SUT(words: words), sut) } } - + func test_new_from_generated_entropy() throws { let wordCounts = BIP39WordCount.allCases XCTAssertEqual(wordCounts.count, 5) let language = BIP39Language.english let n = 100 func doTest(_ wordCount: Bip39WordCount) throws { - let mnemonics = try (0.. { - - func test_not_codable_but_lower_level_json_methods_json_data_roundtrip() throws{ + func test_not_codable_but_lower_level_json_methods_json_data_roundtrip() throws { let sut = SUT.sample let json = sut.jsonData() try XCTAssertEqual( @@ -14,7 +13,7 @@ final class MnemonicWithPassphraseTests: Test { sut ) } - + func test_codable() throws { let raw = """ { @@ -22,25 +21,25 @@ final class MnemonicWithPassphraseTests: Test { "passphrase": "" } """.data(using: .utf8)! - + // test decoding let sut = try JSONDecoder().decode(SUT.self, from: raw) XCTAssertNoDifference(sut, SUT.sample) - + // test encoding let encoded = try JSONEncoder().encode(sut) try XCTAssertEqual(JSONDecoder().decode(SUT.self, from: encoded), sut) } - + func test_derive_public_keys() { XCTAssertEqual(SUT.sample.derivePublicKeys(paths: [DerivationPath.sample]), [HierarchicalDeterministicPublicKey.sample]) } - - func test_validate() { - XCTAssertTrue(SUT.sample.validate(publicKeys: [HierarchicalDeterministicPublicKey.sample])) - XCTAssertFalse(SUT.sampleOther.validate(publicKeys: [HierarchicalDeterministicPublicKey.sample])) - } - + + func test_validate() { + XCTAssertTrue(SUT.sample.validate(publicKeys: [HierarchicalDeterministicPublicKey.sample])) + XCTAssertFalse(SUT.sampleOther.validate(publicKeys: [HierarchicalDeterministicPublicKey.sample])) + } + func test_sign_is_valid() { let sut = SUT.sample let path = DerivationPath.sample @@ -50,7 +49,7 @@ final class MnemonicWithPassphraseTests: Test { XCTAssertTrue(publicKey.isValidSignature(signature, for: msg)) } - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { diff --git a/apple/Tests/TestCases/Crypto/BIP44LikePathTests.swift b/apple/Tests/TestCases/Crypto/BIP44LikePathTests.swift index f8475c9d1..3c5fb1800 100644 --- a/apple/Tests/TestCases/Crypto/BIP44LikePathTests.swift +++ b/apple/Tests/TestCases/Crypto/BIP44LikePathTests.swift @@ -5,37 +5,37 @@ import SargonUniFFI import XCTest final class BIP44LikePathTests: HDPathProtocolTest { - func test_sample_description() { - XCTAssertNoDifference(SUT.sampleOther.description, "m/44H/1022H/0H/0/1H") - } - - func test_sample_from_str() { - XCTAssertNoDifference( - "m/44H/1022H/0H/0/1H", // ExpressibleByStringLiteral - SUT.sampleOther - ) - } - + func test_sample_description() { + XCTAssertNoDifference(SUT.sampleOther.description, "m/44H/1022H/0H/0/1H") + } + + func test_sample_from_str() { + XCTAssertNoDifference( + "m/44H/1022H/0H/0/1H", // ExpressibleByStringLiteral + SUT.sampleOther + ) + } + func test_invalid_got_cap26_account() { XCTAssertThrowsError(try SUT(string: "m/44H/1022H/1H/525H/1460H/0H")) } - + func test_index_roundtrip() { eachSample { sut in let index = sut.addressIndex XCTAssertEqual(SUT(index: index), sut) } } - + func test_index() throws { let sut = try SUT(string: "m/44H/1022H/0H/0/42H") - XCTAssertEqual( - sut.addressIndex, - .unsecurifiedComponent( - .hardenedComponent( - try! UnsecurifiedHardened(localKeySpace: 42) - ) - ) - ) + XCTAssertEqual( + sut.addressIndex, + .unsecurifiedComponent( + .hardenedComponent( + try! UnsecurifiedHardened(localKeySpace: 42) + ) + ) + ) } } diff --git a/apple/Tests/TestCases/Crypto/DerivationPathTests.swift b/apple/Tests/TestCases/Crypto/DerivationPathTests.swift index b2bde59ae..a7935d95f 100644 --- a/apple/Tests/TestCases/Crypto/DerivationPathTests.swift +++ b/apple/Tests/TestCases/Crypto/DerivationPathTests.swift @@ -5,80 +5,77 @@ import SargonUniFFI import XCTest final class DerivationPathTests: HDPathProtocolTest { - func test_sample_description() { - XCTAssertNoDifference(SUT.sample.description, "m/44H/1022H/1H/525H/1460H/0H") - } - - func test_cap26_account_path_as_derivation_path() { - let sut = AccountPath.sample - - XCTAssertEqual( - sut.asGeneral, - DerivationPath.account(value: sut) - ) - } - - - func test_get_hd_path() { - eachSample { sut in - XCTAssertEqual(sut.path.components.count, sut.toString().matches(of: "/").count) - } - } - - - - func test_bip44_account_path_as_derivation_path() { - let bip44Path = BIP44LikePath.sample - - XCTAssertEqual( - bip44Path.asGeneral, - DerivationPath.bip44Like(value: bip44Path) - ) - } - - func test_bip44_account_path_to_string() { - let bip44Path = BIP44LikePath.sample - - XCTAssertEqual( - bip44Path.asDerivationPath.toString(), - bip44Path.toString() - ) - } - - func test_bip44_string() throws { - XCTAssertNoDifference( - try SUT(string: "m/44H/1022H/0H/0/1H"), - BIP44LikePath.sampleOther.asGeneral - ) - } - - func test_as_general_is_identity() { - XCTAssertEqual(SUT.sample.asDerivationPath, SUT.sample) - } - - func test_curve() { - XCTAssertEqual(SUT.sample.curve, .curve25519) - XCTAssertEqual(SUT.bip44Like(value: .sample).curve, .secp256k1) - } - - func test_for_entity() throws { - try XCTAssertEqual( - SUT.forEntity( - kind: .account, - networkID: .mainnet, - index: .unsecurified(UnsecurifiedHardened(globalKeySpace: 9 + 0x8000_0000)) - ) - .toString(), - "m/44H/1022H/1H/525H/1460H/9H" - ) - try XCTAssertEqual( - SUT.forEntity( - kind: .persona, - networkID: .stokenet, - index: Hardened.unsecurified(UnsecurifiedHardened(localKeySpace: 42)) - ) - .toString(), - "m/44H/1022H/2H/618H/1460H/42H" - ) - } + func test_sample_description() { + XCTAssertNoDifference(SUT.sample.description, "m/44H/1022H/1H/525H/1460H/0H") + } + + func test_cap26_account_path_as_derivation_path() { + let sut = AccountPath.sample + + XCTAssertEqual( + sut.asGeneral, + DerivationPath.account(value: sut) + ) + } + + func test_get_hd_path() { + eachSample { sut in + XCTAssertEqual(sut.path.components.count, sut.toString().matches(of: "/").count) + } + } + + func test_bip44_account_path_as_derivation_path() { + let bip44Path = BIP44LikePath.sample + + XCTAssertEqual( + bip44Path.asGeneral, + DerivationPath.bip44Like(value: bip44Path) + ) + } + + func test_bip44_account_path_to_string() { + let bip44Path = BIP44LikePath.sample + + XCTAssertEqual( + bip44Path.asDerivationPath.toString(), + bip44Path.toString() + ) + } + + func test_bip44_string() throws { + XCTAssertNoDifference( + try SUT(string: "m/44H/1022H/0H/0/1H"), + BIP44LikePath.sampleOther.asGeneral + ) + } + + func test_as_general_is_identity() { + XCTAssertEqual(SUT.sample.asDerivationPath, SUT.sample) + } + + func test_curve() { + XCTAssertEqual(SUT.sample.curve, .curve25519) + XCTAssertEqual(SUT.bip44Like(value: .sample).curve, .secp256k1) + } + + func test_for_entity() throws { + try XCTAssertEqual( + SUT.forEntity( + kind: .account, + networkID: .mainnet, + index: .unsecurified(UnsecurifiedHardened(globalKeySpace: 9 + 0x8000_0000)) + ) + .toString(), + "m/44H/1022H/1H/525H/1460H/9H" + ) + try XCTAssertEqual( + SUT.forEntity( + kind: .persona, + networkID: .stokenet, + index: Hardened.unsecurified(UnsecurifiedHardened(localKeySpace: 42)) + ) + .toString(), + "m/44H/1022H/2H/618H/1460H/42H" + ) + } } diff --git a/apple/Tests/TestCases/Crypto/Ed25519PublicKeyTests.swift b/apple/Tests/TestCases/Crypto/Ed25519PublicKeyTests.swift index c2acb26cd..d7b8cc15e 100644 --- a/apple/Tests/TestCases/Crypto/Ed25519PublicKeyTests.swift +++ b/apple/Tests/TestCases/Crypto/Ed25519PublicKeyTests.swift @@ -1,5 +1,5 @@ -@testable import Sargon import CryptoKit +@testable import Sargon import CustomDump import Foundation @@ -18,29 +18,29 @@ final class Ed25519PublicKeyTests: PublicKeyTest { // test decoding let sut = try JSONDecoder().decode(SUT.self, from: raw) XCTAssertEqual(sut, SUT.sample) - + // test encoding let encoded = try JSONEncoder().encode(sut) try XCTAssertEqual(JSONDecoder().decode(SUT.self, from: encoded), sut) } func test_wrapped_in_obj() throws { - struct Wrapper: Codable, Equatable { - let myString: String - let publicKey: Ed25519PublicKey - } - let json = """ - { - "myString": "Foo", - "publicKey": "ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf" - } - """.data(using: .utf8)! - - let decoded = try JSONDecoder().decode(Wrapper.self, from: json) - XCTAssertEqual(decoded, try Wrapper.init(myString: "Foo", publicKey: .init(hex: "ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf"))) - } - - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + struct Wrapper: Codable, Equatable { + let myString: String + let publicKey: Ed25519PublicKey + } + let json = """ + { + "myString": "Foo", + "publicKey": "ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf" + } + """.data(using: .utf8)! + + let decoded = try JSONDecoder().decode(Wrapper.self, from: json) + XCTAssertEqual(decoded, try Wrapper(myString: "Foo", publicKey: .init(hex: "ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf"))) + } + + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { diff --git a/apple/Tests/TestCases/Crypto/Ed25519SignatureTests.swift b/apple/Tests/TestCases/Crypto/Ed25519SignatureTests.swift index 16d3c3ce3..4a4c15901 100644 --- a/apple/Tests/TestCases/Crypto/Ed25519SignatureTests.swift +++ b/apple/Tests/TestCases/Crypto/Ed25519SignatureTests.swift @@ -17,7 +17,7 @@ final class Ed25519SignatureTests: SignatureTest { func test_codable() throws { let raw = "\"fc6a4a15516b886b10f26777094cb1abdccb213c9ebdea7a4bceb83b6fcba50fea181b0136ee5659c3dfae5f771e5b6e6f9abbaa3f0435df0be1f732be965103\"" - .data(using: .utf8)! + .data(using: .utf8)! // test decoding let sut = try JSONDecoder().decode(SUT.self, from: raw) @@ -34,21 +34,23 @@ final class Ed25519SignatureTests: SignatureTest { let signature: Ed25519Signature } let json = """ - { - "myString": "Foo", - "signature": "fc6a4a15516b886b10f26777094cb1abdccb213c9ebdea7a4bceb83b6fcba50fea181b0136ee5659c3dfae5f771e5b6e6f9abbaa3f0435df0be1f732be965103" - } - """.data(using: .utf8)! + { + "myString": "Foo", + "signature": "fc6a4a15516b886b10f26777094cb1abdccb213c9ebdea7a4bceb83b6fcba50fea181b0136ee5659c3dfae5f771e5b6e6f9abbaa3f0435df0be1f732be965103" + } + """.data(using: .utf8)! let decoded = try JSONDecoder().decode(Wrapper.self, from: json) XCTAssertEqual( decoded, - try Wrapper.init( + try Wrapper( myString: "Foo", signature: .init( hex: - "fc6a4a15516b886b10f26777094cb1abdccb213c9ebdea7a4bceb83b6fcba50fea181b0136ee5659c3dfae5f771e5b6e6f9abbaa3f0435df0be1f732be965103" - ))) + "fc6a4a15516b886b10f26777094cb1abdccb213c9ebdea7a4bceb83b6fcba50fea181b0136ee5659c3dfae5f771e5b6e6f9abbaa3f0435df0be1f732be965103" + ) + ) + ) } /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more diff --git a/apple/Tests/TestCases/Crypto/HDPathComponentTests/BaseHDPathComponentProtocolTest.swift b/apple/Tests/TestCases/Crypto/HDPathComponentTests/BaseHDPathComponentProtocolTest.swift index a58bd98d6..e119cc2cf 100644 --- a/apple/Tests/TestCases/Crypto/HDPathComponentTests/BaseHDPathComponentProtocolTest.swift +++ b/apple/Tests/TestCases/Crypto/HDPathComponentTests/BaseHDPathComponentProtocolTest.swift @@ -1,16 +1,7 @@ -// -// BaseHDPathComponentProtocolTest.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - -import XCTest import Sargon - +import XCTest class BaseHDPathComponentProtocolTest: Test { - func test_global_roundtrip_using_samples() throws { func test(_ sample: SUT_) throws { let global = sample.indexInGlobalKeySpace() diff --git a/apple/Tests/TestCases/Crypto/HDPathComponentTests/HDPathComponentProtocolTest.swift b/apple/Tests/TestCases/Crypto/HDPathComponentTests/HDPathComponentProtocolTest.swift index 35c45db73..2ce422274 100644 --- a/apple/Tests/TestCases/Crypto/HDPathComponentTests/HDPathComponentProtocolTest.swift +++ b/apple/Tests/TestCases/Crypto/HDPathComponentTests/HDPathComponentProtocolTest.swift @@ -1,32 +1,23 @@ -// -// HDPathComponentProtocolTest.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - -import XCTest import Sargon - +import XCTest class HDPathComponentProtocolTest: BaseHDPathComponentProtocolTest { func test_local() throws { - for local in UInt32(0)...10 { + for local in UInt32(0) ... 10 { let sut = try SUT(localKeySpace: local) let indexInLocal = sut.indexInLocalKeySpace() XCTAssertEqual(local, indexInLocal) XCTAssertEqual(try SUT(localKeySpace: indexInLocal), sut) } } - - + func test_local_to_global() throws { let sut = try SUT(localKeySpace: 42) let global = sut.indexInGlobalKeySpace() let fromGlobal = try SUT(globalKeySpace: global) XCTAssertEqual(fromGlobal, sut) } - + func test_global() throws { for global in SUT.globalOffset ... SUT.globalOffset + 3 { let sut = try SUT(globalKeySpace: global) @@ -36,5 +27,3 @@ class HDPathComponentProtocolTest: BaseHDPathComp } } } - - diff --git a/apple/Tests/TestCases/Crypto/HDPathComponentTests/HDPathComponentTests.swift b/apple/Tests/TestCases/Crypto/HDPathComponentTests/HDPathComponentTests.swift index cb86977a0..9c9175ab3 100644 --- a/apple/Tests/TestCases/Crypto/HDPathComponentTests/HDPathComponentTests.swift +++ b/apple/Tests/TestCases/Crypto/HDPathComponentTests/HDPathComponentTests.swift @@ -1,34 +1,27 @@ -// -// HDPathComponentTests.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-24. -// - import Sargon import XCTest +// MARK: - KeySpace + CaseIterable extension KeySpace: CaseIterable { - public static var allCases: [KeySpace] { - [.securified, .unsecurified(isHardened: false), .unsecurified(isHardened: true)] - } + public static var allCases: [KeySpace] { + [.securified, .unsecurified(isHardened: false), .unsecurified(isHardened: true)] + } } +// MARK: - HDPathComponentTests final class HDPathComponentTests: BaseHDPathComponentProtocolTest { - - func test_local_roundtrip() throws { + func test_local_roundtrip() throws { for keySpace in KeySpace.allCases { - for local in UInt32(0)...3 { + for local in UInt32(0) ... 3 { let sut = try SUT(localKeySpace: local, keySpace: keySpace) let indexInLocal = sut.indexInLocalKeySpace() XCTAssertEqual(local, indexInLocal) XCTAssertEqual(try SUT(localKeySpace: indexInLocal, keySpace: keySpace), sut) } } - - } - - func test_global_roundtrip() throws { + } + + func test_global_roundtrip() throws { struct Param { let keySpace: KeySpace let global: UInt32 @@ -41,17 +34,17 @@ final class HDPathComponentTests: BaseHDPathComponentProtocolTest { -} +final class HardenedTests: Test {} diff --git a/apple/Tests/TestCases/Crypto/HDPathComponentTests/SecurifiedTests.swift b/apple/Tests/TestCases/Crypto/HDPathComponentTests/SecurifiedTests.swift index b2c47ad34..99aa171c7 100644 --- a/apple/Tests/TestCases/Crypto/HDPathComponentTests/SecurifiedTests.swift +++ b/apple/Tests/TestCases/Crypto/HDPathComponentTests/SecurifiedTests.swift @@ -1,12 +1,4 @@ -// -// SecurifiedTestsTests.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - -import XCTest import Sargon - +import XCTest final class SecurifiedTests: HDPathComponentProtocolTest {} diff --git a/apple/Tests/TestCases/Crypto/HDPathComponentTests/UnhardenedTests.swift b/apple/Tests/TestCases/Crypto/HDPathComponentTests/UnhardenedTests.swift index eb6f4bbf0..a46a87e93 100644 --- a/apple/Tests/TestCases/Crypto/HDPathComponentTests/UnhardenedTests.swift +++ b/apple/Tests/TestCases/Crypto/HDPathComponentTests/UnhardenedTests.swift @@ -1,18 +1,9 @@ -// -// UnhardenedTests.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - -import XCTest import Sargon +import XCTest final class UnhardenedTests: HDPathComponentProtocolTest { - func test_fromU31() throws { let sut = try SUT(u31: U31(value: 5)) try XCTAssertEqual(SUT(localKeySpace: 5), sut) } } - diff --git a/apple/Tests/TestCases/Crypto/HDPathComponentTests/UnsecurifiedHardenedTests.swift b/apple/Tests/TestCases/Crypto/HDPathComponentTests/UnsecurifiedHardenedTests.swift index ac99d7ff5..4977511c4 100644 --- a/apple/Tests/TestCases/Crypto/HDPathComponentTests/UnsecurifiedHardenedTests.swift +++ b/apple/Tests/TestCases/Crypto/HDPathComponentTests/UnsecurifiedHardenedTests.swift @@ -1,12 +1,4 @@ -// -// UnsecurifiedHardenedTests.swift -// Sargon -// -// Created by Alexander Cyon on 2024-10-25. -// - -import XCTest import Sargon - +import XCTest final class UnsecurifiedHardenedTests: HDPathComponentProtocolTest {} diff --git a/apple/Tests/TestCases/Crypto/HashTests.swift b/apple/Tests/TestCases/Crypto/HashTests.swift index 119541e86..c2f466c1e 100644 --- a/apple/Tests/TestCases/Crypto/HashTests.swift +++ b/apple/Tests/TestCases/Crypto/HashTests.swift @@ -13,18 +13,18 @@ final class HashTests: Test { doTest("Hello Radix", expected: "48f1bd08444b5e713db9e14caac2faae71836786ac94d645b00679728202a935") doTest("Radix... just imagine", expected: "679dfbbda16d3f9669da8552ab6594d2b0446d03d96c076a0ec9dc550ea41fad") } - + func test_hash_of_hash() { XCTAssertEqual(Data("Hello Radix".utf8).hash().hash().bytes, "0c18fa9b3e94d9b879d631e791ee0699ad2f98d914f16a35a70f6312abe4474a") } - - func test_from_bytes32() { - let bytes32: Exactly32Bytes = "48f1bd08444b5e713db9e14caac2faae71836786ac94d645b00679728202a935" - XCTAssertEqual(SUT(bytes32: bytes32).bytes, bytes32) - } - - func test_from_string() throws { - let hex = "48f1bd08444b5e713db9e14caac2faae71836786ac94d645b00679728202a935" - try XCTAssertEqual(SUT(string: hex).hex, hex) - } + + func test_from_bytes32() { + let bytes32: Exactly32Bytes = "48f1bd08444b5e713db9e14caac2faae71836786ac94d645b00679728202a935" + XCTAssertEqual(SUT(bytes32: bytes32).bytes, bytes32) + } + + func test_from_string() throws { + let hex = "48f1bd08444b5e713db9e14caac2faae71836786ac94d645b00679728202a935" + try XCTAssertEqual(SUT(string: hex).hex, hex) + } } diff --git a/apple/Tests/TestCases/Crypto/HierarchicalDeterministicPublicKeyTests.swift b/apple/Tests/TestCases/Crypto/HierarchicalDeterministicPublicKeyTests.swift index 2fea59562..79b29ef88 100644 --- a/apple/Tests/TestCases/Crypto/HierarchicalDeterministicPublicKeyTests.swift +++ b/apple/Tests/TestCases/Crypto/HierarchicalDeterministicPublicKeyTests.swift @@ -4,6 +4,4 @@ import Sargon import SargonUniFFI import XCTest -final class HierarchicalDeterministicPublicKeyTests: Test { -} - +final class HierarchicalDeterministicPublicKeyTests: Test {} diff --git a/apple/Tests/TestCases/Crypto/IdentityPathTests.swift b/apple/Tests/TestCases/Crypto/IdentityPathTests.swift index a275e7206..8f8f2e823 100644 --- a/apple/Tests/TestCases/Crypto/IdentityPathTests.swift +++ b/apple/Tests/TestCases/Crypto/IdentityPathTests.swift @@ -5,29 +5,29 @@ import SargonUniFFI import XCTest final class IdentityPathTests: HDPathProtocolTest { - func test_sample_description() { - XCTAssertNoDifference(SUT.sample.description, "m/44H/1022H/1H/618H/1460H/0H") - } - - func test_sample_from_str() { - XCTAssertNoDifference( - "m/44H/1022H/1H/618H/1460H/0H", // ExpressibleByStringLiteral - SUT.sample - ) - } - + func test_sample_description() { + XCTAssertNoDifference(SUT.sample.description, "m/44H/1022H/1H/618H/1460H/0H") + } + + func test_sample_from_str() { + XCTAssertNoDifference( + "m/44H/1022H/1H/618H/1460H/0H", // ExpressibleByStringLiteral + SUT.sample + ) + } + func test_invalid_got_account() { XCTAssertThrowsError(try SUT(string: "m/44H/1022H/1H/525H/1460H/0H")) } - + func test_init_network_id_key_kind_index() throws { - try XCTAssertEqual( - SUT.sampleOther, - SUT.init( - networkID: .mainnet, - keyKind: .transactionSigning, - index: Hardened.unsecurified(UnsecurifiedHardened(localKeySpace: 1)) - ) - ) + try XCTAssertEqual( + SUT.sampleOther, + SUT( + networkID: .mainnet, + keyKind: .transactionSigning, + index: Hardened.unsecurified(UnsecurifiedHardened(localKeySpace: 1)) + ) + ) } } diff --git a/apple/Tests/TestCases/Crypto/IntentHashTests.swift b/apple/Tests/TestCases/Crypto/IntentHashTests.swift index b271163a5..f84bc62e5 100644 --- a/apple/Tests/TestCases/Crypto/IntentHashTests.swift +++ b/apple/Tests/TestCases/Crypto/IntentHashTests.swift @@ -8,17 +8,17 @@ final class TransactionIntentHashTests: TransactionHashProtocolTest { - - // with very low probability this will fail - func test_secure_random() { - let n = 10 - let sut = Set( - (0..( + (0 ..< n).map { _ in SUT.secureRandom() } + ) + XCTAssertEqual(sut.count, n) + XCTAssertEqual(Set(sut.map(\.value)).count, n) + } } diff --git a/apple/Tests/TestCases/Crypto/PublicKeyHashTests.swift b/apple/Tests/TestCases/Crypto/PublicKeyHashTests.swift index c199e15e0..dd624ec1e 100644 --- a/apple/Tests/TestCases/Crypto/PublicKeyHashTests.swift +++ b/apple/Tests/TestCases/Crypto/PublicKeyHashTests.swift @@ -5,24 +5,22 @@ import SargonUniFFI import XCTest final class PublicKeyHashTests: Test { - func test_hash_public_key_ed25519() { XCTAssertNoDifference(SUT.hash(publicKey: .ed25519(.sample)), SUT.sample) XCTAssertNoDifference(Ed25519PublicKey.sample.hash(), SUT.sample) } - + func test_hash_public_key_secp256k1() { XCTAssertNoDifference(SUT.hash(publicKey: .secp256k1(.sample)), SUT.sampleOther) XCTAssertNoDifference(Secp256k1PublicKey.sample.hash(), SUT.sampleOther) } - + func test_hashing_init() { XCTAssertNoDifference(SUT(hashing: .secp256k1(.sample)), SUT.sampleOther) } - + func test_data() { XCTAssertEqual(SUT.sample.data.hex, "f4e18c034e069baee91ada4764fdfcf2438b8f976861df00557d4cc9e7") XCTAssertEqual(SUT.sampleOther.data.hex, "4a5004504dbbc08c65ba86fcd7592a3ac48db81d217fe2356e75b37f31") } - } diff --git a/apple/Tests/TestCases/Crypto/PublicKeyTests.swift b/apple/Tests/TestCases/Crypto/PublicKeyTests.swift index 8e8d887a6..9f4150023 100644 --- a/apple/Tests/TestCases/Crypto/PublicKeyTests.swift +++ b/apple/Tests/TestCases/Crypto/PublicKeyTests.swift @@ -1,5 +1,5 @@ -@testable import Sargon import CryptoKit +@testable import Sargon import CustomDump import Foundation @@ -12,20 +12,19 @@ final class PublicKeyTests: PublicKeyTest { XCTAssertNoThrow(try SUT(hex: Curve25519.Signing.PrivateKey().publicKey.rawRepresentation.hex)) XCTAssertNoThrow(try Curve25519.Signing.PublicKey(rawRepresentation: SUT.sample.data)) } - + func test_expressible_by_string_literal() { XCTAssertEqual(SUT.sampleOther, "043083620d1596d3f8988ff3270e42970dd2a031e2b9b6488052a4170ff999f3e8ab3efd3320b8f893cb421ed7ff0aa9ff43b43cad4e00e194f89845c6ac8233a7") - } - + func test_embed_is_identity() { XCTAssertEqual(SUT.sample, SUT.sample.asGeneral) } - + func test_is_valid() { XCTAssertFalse(SUT.sample.isValidSignature(Signature.sample, for: .sample)) } - + func test_curve() { XCTAssertEqual(SUT.sample.curve, .curve25519) XCTAssertEqual(SUT.sampleOther.curve, .secp256k1) diff --git a/apple/Tests/TestCases/Crypto/SLIP10CurveTests.swift b/apple/Tests/TestCases/Crypto/SLIP10CurveTests.swift index fb90a840f..8529c08ed 100644 --- a/apple/Tests/TestCases/Crypto/SLIP10CurveTests.swift +++ b/apple/Tests/TestCases/Crypto/SLIP10CurveTests.swift @@ -9,16 +9,16 @@ final class SLIP10CurveTests: Test { XCTAssertNoDifference(SUT.sample.toString(), SUT.sample.description) XCTAssertNoDifference(SUT.sampleOther.toString(), SUT.sampleOther.description) } - + func test_string_roundtrip() throws { try eachSample { sut in let string = sut.toString() - let fromString = try XCTUnwrap(SUT.init(rawValue: string)) + let fromString = try XCTUnwrap(SUT(rawValue: string)) XCTAssertEqual(fromString, sut) } } - - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { diff --git a/apple/Tests/TestCases/Crypto/Secp256k1PublicKeyTests.swift b/apple/Tests/TestCases/Crypto/Secp256k1PublicKeyTests.swift index d79646d22..aa1bb095b 100644 --- a/apple/Tests/TestCases/Crypto/Secp256k1PublicKeyTests.swift +++ b/apple/Tests/TestCases/Crypto/Secp256k1PublicKeyTests.swift @@ -8,31 +8,30 @@ import SargonUniFFI import XCTest final class Secp256k1PublicKeyTests: PublicKeyTest { - func test_from_compressed() throws { // from K1: https://github.com/Sajjon/K1/blob/main/Tests/K1Tests/TestCases/Keys/PublicKey/PublicKeyImportTests.swift#L48 XCTAssertNoThrow(try SUT(hex: "020202020202020202020202020202020202020202020202020202020202020202")) } - + func test_from_uncompressed() throws { // from K1: https://github.com/Sajjon/K1/blob/main/Tests/K1Tests/TestCases/Keys/PublicKey/PublicKeyImportTests.swift#L48 XCTAssertNoThrow(try SUT(hex: "040202020202020202020202020202020202020202020202020202020202020202415456f0fc01d66476251cab4525d9db70bfec652b2d8130608675674cde64b2")) } - - func test_uncompressed_and_compresses_equals() throws { - try XCTAssertNoDifference( - SUT(hex: "040202020202020202020202020202020202020202020202020202020202020202415456f0fc01d66476251cab4525d9db70bfec652b2d8130608675674cde64b2"), - SUT(hex: "020202020202020202020202020202020202020202020202020202020202020202") - ) - } - - func test_uncompressed_from_compressed() throws { - try XCTAssertNoDifference( - SUT(hex: "020202020202020202020202020202020202020202020202020202020202020202").uncompressedData.hex, - "040202020202020202020202020202020202020202020202020202020202020202415456f0fc01d66476251cab4525d9db70bfec652b2d8130608675674cde64b2" - ) - } - + + func test_uncompressed_and_compresses_equals() throws { + try XCTAssertNoDifference( + SUT(hex: "040202020202020202020202020202020202020202020202020202020202020202415456f0fc01d66476251cab4525d9db70bfec652b2d8130608675674cde64b2"), + SUT(hex: "020202020202020202020202020202020202020202020202020202020202020202") + ) + } + + func test_uncompressed_from_compressed() throws { + try XCTAssertNoDifference( + SUT(hex: "020202020202020202020202020202020202020202020202020202020202020202").uncompressedData.hex, + "040202020202020202020202020202020202020202020202020202020202020202415456f0fc01d66476251cab4525d9db70bfec652b2d8130608675674cde64b2" + ) + } + func test_not_on_curve_33_bytes() throws { XCTAssertThrowsError(try SUT(hex: "99deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")) { anyError in if let sargonError = anyError as? SargonError { @@ -47,7 +46,7 @@ final class Secp256k1PublicKeyTests: PublicKeyTest { } } } - + func test_not_on_curve_65_bytes() throws { XCTAssertThrowsError(try SUT(hex: "040000000000000000000000000000000000000000000000000000000000000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e")) { anyError in if let sargonError = anyError as? SargonError { diff --git a/apple/Tests/TestCases/Crypto/Secp256k1SignatureTests.swift b/apple/Tests/TestCases/Crypto/Secp256k1SignatureTests.swift index 526246f62..c045bfe6c 100644 --- a/apple/Tests/TestCases/Crypto/Secp256k1SignatureTests.swift +++ b/apple/Tests/TestCases/Crypto/Secp256k1SignatureTests.swift @@ -5,11 +5,10 @@ import SargonUniFFI import XCTest final class Secp256k1SignatureTests: SignatureTest { - func test_from_exactly_65_bytes() { XCTAssertEqual(SUT(exactly: SUT.sample.bytes), SUT.sample) } - + func test_as_signature() { let sut = SUT.sample XCTAssertEqual(sut.signature, Signature.secp256k1(value: sut)) diff --git a/apple/Tests/TestCases/Crypto/SignedIntentHashTests.swift b/apple/Tests/TestCases/Crypto/SignedIntentHashTests.swift index 3b722cf71..750fb8d71 100644 --- a/apple/Tests/TestCases/Crypto/SignedIntentHashTests.swift +++ b/apple/Tests/TestCases/Crypto/SignedIntentHashTests.swift @@ -8,17 +8,17 @@ final class SignedTransactionIntentHashTests: TransactionHashProtocolTest() let n = 100 - (0.. {} + +// MARK: - Entropy20BytesTests final class Entropy20BytesTests: ExactlyNBytesTest {} + +// MARK: - Entropy24BytesTests final class Entropy24BytesTests: ExactlyNBytesTest {} + +// MARK: - Entropy28BytesTests final class Entropy28BytesTests: ExactlyNBytesTest {} + +// MARK: - Entropy32BytesTests final class Entropy32BytesTests: ExactlyNBytesTest {} diff --git a/apple/Tests/TestCases/Prelude/Bytes/ExactlyNBytesTests.swift b/apple/Tests/TestCases/Prelude/Bytes/ExactlyNBytesTests.swift index 5fd2f1d36..7ee3f5152 100644 --- a/apple/Tests/TestCases/Prelude/Bytes/ExactlyNBytesTests.swift +++ b/apple/Tests/TestCases/Prelude/Bytes/ExactlyNBytesTests.swift @@ -4,27 +4,29 @@ import Sargon import SargonUniFFI import XCTest +// MARK: - Exactly29BytesTests final class Exactly29BytesTests: ExactlyNBytesTest {} +// MARK: - Exactly32BytesTests final class Exactly32BytesTests: ExactlyNBytesTest { func test_from_array_literal() { - let sut: SUT = [0xde, 0xad, 0xde, 0xad, 0xde, 0xad, 0xde, 0xad, 0xde, 0xad, 0xde, 0xad, 0xde, 0xad, 0xde, 0xad, 0xde, 0xad, 0xde, 0xad, 0xde, 0xad, 0xde, 0xad, 0xde, 0xad, 0xde, 0xad, 0xde, 0xad, 0xde, 0xad] + let sut: SUT = [0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD, 0xDE, 0xAD] XCTAssertNoDifference(sut, SUT.sample) } - + func test_codable() throws { let raw = "\"deaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddead\"".data(using: .utf8)! - + // test decoding let sut = try JSONDecoder().decode(SUT.self, from: raw) XCTAssertEqual(sut, SUT.sample) - + // test encoding let encoded = try JSONEncoder().encode(sut) try XCTAssertEqual(JSONDecoder().decode(SUT.self, from: encoded), sut) } - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { @@ -32,6 +34,11 @@ final class Exactly32BytesTests: ExactlyNBytesTest { } } +// MARK: - Exactly33BytesTests final class Exactly33BytesTests: ExactlyNBytesTest {} + +// MARK: - Exactly64BytesTests final class Exactly64BytesTests: ExactlyNBytesTest {} + +// MARK: - Exactly65BytesTests final class Exactly65BytesTests: ExactlyNBytesTest {} diff --git a/apple/Tests/TestCases/Prelude/DateTests.swift b/apple/Tests/TestCases/Prelude/DateTests.swift index 2c1bf85d9..ce6f0d995 100644 --- a/apple/Tests/TestCases/Prelude/DateTests.swift +++ b/apple/Tests/TestCases/Prelude/DateTests.swift @@ -5,70 +5,68 @@ import SargonUniFFI import XCTest final class DateTests: TestCase { - - func test_date() { - - /// This matches `[bindings.swift.custom_types.Timestamp]` - /// inside `uniffi.toml` with the only difference that we use `$0` here but - /// the toml uses `{}`; - let into_custom: (String) -> Date = { - let stringToDeserialize = $0 - let formatter = ISO8601DateFormatter() - let formatOptionMS = ISO8601DateFormatter.Options.withFractionalSeconds - formatter.formatOptions.insert(formatOptionMS) - - func format() -> Date? { - formatter.date(from: stringToDeserialize) - } - - if let date = format() { - return date - } - - // try without fractional seconds - formatter.formatOptions.remove(formatOptionMS) - return format()! - } - - /// This matches `[bindings.swift.custom_types.Timestamp]` - /// inside `uniffi.toml` - let from_custom: (Date) -> String = { - let dateToSerialize = $0 - let formatter = ISO8601DateFormatter() - formatter.formatOptions.insert(.withFractionalSeconds) - return formatter.string(from: dateToSerialize) - } - - func testIntoThenFrom(_ vector: (String, String?)) { - let sut = vector.0 - let expected = vector.1 ?? sut + func test_date() { + /// This matches `[bindings.swift.custom_types.Timestamp]` + /// inside `uniffi.toml` with the only difference that we use `$0` here but + /// the toml uses `{}`; + let into_custom: (String) -> Date = { + let stringToDeserialize = $0 + let formatter = ISO8601DateFormatter() + let formatOptionMS = ISO8601DateFormatter.Options.withFractionalSeconds + formatter.formatOptions.insert(formatOptionMS) - let string = from_custom(into_custom(sut)) - - XCTAssertEqual(string, expected) - } - - func testFromThenInto(_ vector: (String, String?)) { - let lhs = vector.0 - let rhs = vector.1 ?? lhs - - let lhsString = from_custom(into_custom(lhs)) - let rhsString = from_custom(into_custom(rhs)) - - XCTAssertEqual(rhsString, rhs) - - XCTAssertEqual( - into_custom(lhsString), - into_custom(rhsString) - ) - } - - let vectors = [ - ("2023-12-24T17:13:56.123456Z", "2023-12-24T17:13:56.123Z"), // precision lost (which is OK) - ("2023-12-24T17:13:56.123Z", nil), // unchanged - ("2023-12-24T17:13:56Z", "2023-12-24T17:13:56.000Z") // (000 added, which is OK) - ] - vectors.forEach(testIntoThenFrom) - vectors.forEach(testFromThenInto) - } + func format() -> Date? { + formatter.date(from: stringToDeserialize) + } + + if let date = format() { + return date + } + + // try without fractional seconds + formatter.formatOptions.remove(formatOptionMS) + return format()! + } + + /// This matches `[bindings.swift.custom_types.Timestamp]` + /// inside `uniffi.toml` + let from_custom: (Date) -> String = { + let dateToSerialize = $0 + let formatter = ISO8601DateFormatter() + formatter.formatOptions.insert(.withFractionalSeconds) + return formatter.string(from: dateToSerialize) + } + + func testIntoThenFrom(_ vector: (String, String?)) { + let sut = vector.0 + let expected = vector.1 ?? sut + + let string = from_custom(into_custom(sut)) + + XCTAssertEqual(string, expected) + } + + func testFromThenInto(_ vector: (String, String?)) { + let lhs = vector.0 + let rhs = vector.1 ?? lhs + + let lhsString = from_custom(into_custom(lhs)) + let rhsString = from_custom(into_custom(rhs)) + + XCTAssertEqual(rhsString, rhs) + + XCTAssertEqual( + into_custom(lhsString), + into_custom(rhsString) + ) + } + + let vectors = [ + ("2023-12-24T17:13:56.123456Z", "2023-12-24T17:13:56.123Z"), // precision lost (which is OK) + ("2023-12-24T17:13:56.123Z", nil), // unchanged + ("2023-12-24T17:13:56Z", "2023-12-24T17:13:56.000Z"), // (000 added, which is OK) + ] + vectors.forEach(testIntoThenFrom) + vectors.forEach(testFromThenInto) + } } diff --git a/apple/Tests/TestCases/Prelude/Decimal192Tests.swift b/apple/Tests/TestCases/Prelude/Decimal192Tests.swift index 723034dbb..c06117c50 100644 --- a/apple/Tests/TestCases/Prelude/Decimal192Tests.swift +++ b/apple/Tests/TestCases/Prelude/Decimal192Tests.swift @@ -13,8 +13,8 @@ extension Decimal192: ExpressibleByFloatLiteral { #endif extension Decimal192 { - public static let pi: Self = "3.141592653589793238" - public static let e: Self = "2.718281828459045235" + public static let pi: Self = "3.141592653589793238" + public static let e: Self = "2.718281828459045235" } extension Decimal192 { @@ -33,18 +33,16 @@ extension Decimal192 { Self.eight, Self.nine, Self.ten, - Self(21_000_000) + Self(21_000_000), ] assert(values.sorted() == values) assert(Set(values).count == values.count) // assert no duplicates return values }() - + // Sorted in increasing order: [-10, -9, .. -2, -1] - public static let negative: [Self] = { - positive.map { $0.negate() }.sorted() - }() - + public static let negative: [Self] = positive.map { $0.negate() }.sorted() + public static let nonZero: [Self] = { var nonZero: [Self] = [] nonZero.append(contentsOf: Self.negative) @@ -52,14 +50,15 @@ extension Decimal192 { return nonZero.sorted() }() } + extension Array { var identityPairs: [(Element, Element)] { zip(self, self).map { ($0, $1) } } - + /// [2, 5, 7, 13].slidingWindowPairs == [(2, 5), (5, 7), (7, 13)] var slidingWindowPairs: [(Element, Element)] { - enumerated().compactMap { (offset, element) in + enumerated().compactMap { offset, element in let nextIndex = offset + 1 if nextIndex >= count { return nil @@ -76,35 +75,35 @@ import Sargon import SargonUniFFI import XCTest +// MARK: - Decimal192Tests final class Decimal192Tests: Test { - func test_init_from_string() throws { let s = "3.1415" try XCTAssertNoDifference(SUT(s).debugDescription, s) } - + func test_init_from_i64() { let value: Int64 = -1337 XCTAssertNoDifference(SUT(value).debugDescription, value.description) } - + func test_init_from_u64() { let value: UInt64 = 237 XCTAssertNoDifference(SUT(value).debugDescription, value.description) } - + func test_max_divisibility() { XCTAssertEqual(SUT.maxDivisibility, 18) } - + func test_equal() { - SUT.positive.identityPairs.forEach { lhs, rhs in + for (lhs, rhs) in SUT.positive.identityPairs { XCTAssertEqual(lhs, rhs) } - SUT.negative.identityPairs.forEach { lhs, rhs in + for (lhs, rhs) in SUT.negative.identityPairs { XCTAssertEqual(lhs, rhs) } - + XCTAssertEqual(SUT.zero, SUT.zero) XCTAssertEqual(SUT.max, SUT.max) XCTAssertEqual(SUT.min, SUT.min) @@ -113,7 +112,7 @@ final class Decimal192Tests: Test { XCTAssertEqual(SUT.pi, SUT.pi) XCTAssertEqual(SUT.e, SUT.e) } - + func test_not_equal() { XCTAssertNotEqual(SUT.zero, SUT.max) XCTAssertNotEqual(SUT.zero, SUT.min) @@ -121,7 +120,7 @@ final class Decimal192Tests: Test { XCTAssertNotEqual(SUT.one, SUT.one.negate()) XCTAssertNotEqual(SUT.pi, SUT.e) } - + func test_greater_than() { XCTAssertGreaterThan(SUT.one, SUT.zero) XCTAssertGreaterThan(SUT.max, SUT.ten) @@ -129,21 +128,21 @@ final class Decimal192Tests: Test { XCTAssertGreaterThan(SUT.zero, SUT.min) XCTAssertGreaterThan(SUT.pi, SUT.e) } - + func test_greater_than_or_equal() { - SUT.nonZero.identityPairs.forEach { lhs, rhs in + for (lhs, rhs) in SUT.nonZero.identityPairs { XCTAssertGreaterThanOrEqual(lhs, rhs) } - SUT.nonZero.slidingWindowPairs.forEach { lhs, rhs in + for (lhs, rhs) in SUT.nonZero.slidingWindowPairs { XCTAssertGreaterThanOrEqual(rhs, lhs) } XCTAssertGreaterThanOrEqual(SUT.four, SUT.three) XCTAssertGreaterThanOrEqual(SUT.five, SUT.five) XCTAssertGreaterThanOrEqual(SUT.pi, SUT.e) } - + func test_less_than() { - SUT.nonZero.slidingWindowPairs.forEach { lhs, rhs in + for (lhs, rhs) in SUT.nonZero.slidingWindowPairs { XCTAssertLessThan(lhs, rhs) } XCTAssertLessThan(SUT.nine, SUT.ten) @@ -151,29 +150,29 @@ final class Decimal192Tests: Test { XCTAssertLessThan(SUT.zero, SUT.max) XCTAssertLessThan(SUT.e, SUT.pi) } - + func test_less_than_or_equal() { - SUT.nonZero.identityPairs.forEach { lhs, rhs in + for (lhs, rhs) in SUT.nonZero.identityPairs { XCTAssertLessThanOrEqual(lhs, rhs) } XCTAssertLessThanOrEqual(SUT.seven, SUT.eight) XCTAssertLessThanOrEqual(SUT.six, SUT.six) XCTAssertLessThanOrEqual(SUT.e, SUT.pi) } - + func test_addition() { - SUT.nonZero.slidingWindowPairs.forEach { lhs, rhs in + for (lhs, rhs) in SUT.nonZero.slidingWindowPairs { XCTAssertEqual(lhs + rhs, rhs + lhs) // commutative } - SUT.negative.forEach { - XCTAssertEqual($0 + $0, 2 * $0) + for item in SUT.negative { + XCTAssertEqual(item + item, 2 * item) } - - SUT.nonZero.forEach { + + for item in SUT.nonZero { // zero is identity under addition - XCTAssertEqual($0 + SUT.zero, $0) + XCTAssertEqual(item + SUT.zero, item) } - + XCTAssertEqual(SUT.zero + 0, 0) XCTAssertEqual(SUT.zero + 1, 1) XCTAssertEqual(SUT.one + 1, 2) @@ -184,20 +183,20 @@ final class Decimal192Tests: Test { XCTAssertEqual(SUT.pi + SUT.e, "5.859874482048838473") XCTAssertEqual(SUT.pi + SUT.e, SUT.e + SUT.pi) // commutative } - + func test_subtraction() { - SUT.positive.forEach { - XCTAssertEqual($0 - $0, SUT.zero) // 3 - 3 => 0 + for item in SUT.positive { + XCTAssertEqual(item - item, SUT.zero) // 3 - 3 => 0 } - SUT.negative.forEach { - XCTAssertEqual($0 - $0, SUT.zero) // (-3) - (-3) => (-3) + 3 => 0 + for item in SUT.negative { + XCTAssertEqual(item - item, SUT.zero) // (-3) - (-3) => (-3) + 3 => 0 } - - SUT.nonZero.forEach { + + for item in SUT.nonZero { // zero is identity under subtraction - XCTAssertEqual($0 - SUT.zero, $0) + XCTAssertEqual(item - SUT.zero, item) } - + XCTAssertEqual(SUT.zero - 0, 0) XCTAssertEqual(SUT.zero - 1, -1) XCTAssertEqual(SUT.one - 1, 0) @@ -209,81 +208,80 @@ final class Decimal192Tests: Test { XCTAssertEqual(SUT.max - SUT.max, 0) XCTAssertEqual(SUT.min - SUT.min, 0) } - + func test_multiplication() { - - SUT.nonZero.forEach { + for item in SUT.nonZero { // `1` is identity under multiplication - XCTAssertEqual($0 * SUT.one, $0) + XCTAssertEqual(item * SUT.one, item) } - - SUT.nonZero.slidingWindowPairs.forEach { lhs, rhs in + + for (lhs, rhs) in SUT.nonZero.slidingWindowPairs { XCTAssertEqual(lhs * rhs, rhs * lhs) // commutative } - - SUT.nonZero.forEach { + + for item in SUT.nonZero { // Every number multiplied by zero, is zero... - XCTAssertEqual($0 * SUT.zero, SUT.zero) + XCTAssertEqual(item * SUT.zero, SUT.zero) } // ... incliding `max` and `min` XCTAssertEqual(SUT.max * 0, 0) XCTAssertEqual(SUT.min * 0, 0) - + var sut: SUT = .ten sut *= SUT.five XCTAssertEqual(sut, 50) } - + func test_division() { XCTAssertEqual(SUT.nine / SUT.three, SUT.three) - - SUT.nonZero.forEach { + + for item in SUT.nonZero { // All numbers divided by themselves equals `one`... - XCTAssertEqual($0 / $0, SUT.one) + XCTAssertEqual(item / item, SUT.one) } // ... incliding `max` and `min` XCTAssertEqual(SUT.max / SUT.max, SUT.one) XCTAssertEqual(SUT.min / SUT.min, SUT.one) } - + func test_is_negative() { - SUT.negative.forEach { - XCTAssertTrue($0.isNegative) + for item in SUT.negative { + XCTAssertTrue(item.isNegative) } - SUT.positive.forEach { - XCTAssertFalse($0.isNegative) + for item in SUT.positive { + XCTAssertFalse(item.isNegative) } } - + func test_is_positive() { - SUT.negative.forEach { - XCTAssertFalse($0.isPositive) + for item in SUT.negative { + XCTAssertFalse(item.isPositive) } - SUT.positive.forEach { - XCTAssertTrue($0.isPositive) + for item in SUT.positive { + XCTAssertTrue(item.isPositive) } } - + func test_is_zero() { - SUT.negative.forEach { - XCTAssertFalse($0.isZero) + for item in SUT.negative { + XCTAssertFalse(item.isZero) } - SUT.positive.forEach { - XCTAssertFalse($0.isZero) + for item in SUT.positive { + XCTAssertFalse(item.isZero) } - + XCTAssert(SUT.zero.isZero) } - + func test_clamped() { - SUT.negative.forEach { - XCTAssertEqual($0.clamped, SUT.zero) + for item in SUT.negative { + XCTAssertEqual(item.clamped, SUT.zero) } - SUT.positive.forEach { - XCTAssertEqual($0.clamped, $0) + for item in SUT.positive { + XCTAssertEqual(item.clamped, item) } } - + func test_exponent() { func doTest(exponent: UInt8, expected: SUT) { XCTAssertEqual(SUT(exponent: exponent), expected) @@ -294,18 +292,18 @@ final class Decimal192Tests: Test { doTest(exponent: 3, expected: 1000) doTest(exponent: 4, expected: 10000) } - + func test_negation() { XCTAssertEqual(-SUT.five, SUT.zero - 5) } - + func test_init_source_exactly() { - XCTAssertEqual(SUT(exactly: UInt64(12345678912345678)), 12345678912345678) - XCTAssertEqual(SUT(exactly: Int64(-12345678912345678)), SUT("12345678912345678").negate()) + XCTAssertEqual(SUT(exactly: UInt64(12_345_678_912_345_678)), 12_345_678_912_345_678) + XCTAssertEqual(SUT(exactly: Int64(-12_345_678_912_345_678)), SUT("12345678912345678").negate()) } - + func test_from_and_from_formatted() { - func doTest(_ decimalString: String , line: UInt = #line) { + func doTest(_ decimalString: String, line: UInt = #line) { XCTAssertNoThrow( try SUT( formattedString: decimalString, @@ -326,13 +324,13 @@ final class Decimal192Tests: Test { doTest("0.1234") doTest("1,234.9876") } - + func test_rounded() { func doTest(_ from: SUT, decimalPlaces: UInt8, expected: SUT, line: UInt = #line) { let sut = from.rounded(decimalPlaces: decimalPlaces) XCTAssertEqual(sut, expected, line: line) } - + doTest(0.12345, decimalPlaces: 5, expected: 0.12345) // unchanged doTest(0.12345, decimalPlaces: 4, expected: 0.1235) doTest(0.12345, decimalPlaces: 3, expected: 0.123) @@ -340,14 +338,13 @@ final class Decimal192Tests: Test { doTest(0.12345, decimalPlaces: 1, expected: 0.1) doTest(0.12345, decimalPlaces: 0, expected: 0) } - - + func test_ceil() { func doTest(_ from: SUT, decimalPlaces: UInt8, expected: SUT, line: UInt = #line) { let sut = from.ceil(decimalPlaces: decimalPlaces) XCTAssertEqual(sut, expected, line: line) } - + doTest(0.12345, decimalPlaces: 5, expected: 0.12345) // unchanged doTest(0.12345, decimalPlaces: 4, expected: 0.1235) doTest(0.12345, decimalPlaces: 3, expected: 0.124) @@ -355,25 +352,24 @@ final class Decimal192Tests: Test { doTest(0.12345, decimalPlaces: 1, expected: 0.2) doTest(0.12345, decimalPlaces: 0, expected: 1) } - - + func test_floor() { func doTest(_ from: SUT, decimalPlaces: UInt8, expected: SUT, line: UInt = #line) { let sut = from.floor(decimalPlaces: decimalPlaces) XCTAssertEqual(sut, expected, line: line) } - + doTest(0.12345, decimalPlaces: 5, expected: 0.12345) // unchanged doTest(0.12345, decimalPlaces: 4, expected: 0.1234) doTest(0.12345, decimalPlaces: 3, expected: 0.123) doTest(0.12345, decimalPlaces: 2, expected: 0.12) - + doTest(0.955, decimalPlaces: 3, expected: 0.955) doTest(0.955, decimalPlaces: 2, expected: 0.95) doTest(0.955, decimalPlaces: 1, expected: 0.9) doTest(0.955, decimalPlaces: 0, expected: 0) } - + func test_from_double() throws { func doTest(_ double: Double, _ expected: String) throws { let sut = try SUT(double) @@ -383,21 +379,21 @@ final class Decimal192Tests: Test { try doTest(0.1, "0.1") try doTest(4.012345678901234567895555555, "4.012345678901235") } - + func test_magnitude() { XCTAssertEqual(SUT.min.magnitude, SUT.max) } - + func test_standard_transaction_fee() { XCTAssertEqual(SUT.temporaryStandardFee, 25) } - + func test_decoding_to_SUT() throws { struct TestStruct: Codable, Equatable { let decimal: SUT let optional: SUT? } - + func doTest(_ string: String, decimal expectedDecimal: SUT, optionalIsNil: Bool = false) throws { if let data = string.data(using: .utf8) { let actual = try JSONDecoder().decode(TestStruct.self, from: data) @@ -407,7 +403,7 @@ final class Decimal192Tests: Test { XCTFail() } } - + try doTest("{\"decimal\":\"123.1234\",\"optional\":\"123.1234\"}", decimal: .init("123.1234")) try doTest("{\"decimal\":\"1233434.1234\",\"optional\":\"1233434.1234\"}", decimal: .init("1233434.1234")) try doTest("{\"decimal\":\"124300.1332\",\"optional\":\"124300.1332\"}", decimal: .init("124300.1332")) @@ -420,33 +416,33 @@ final class Decimal192Tests: Test { try doTest("{\"decimal\":\"1234123.4\",\"optional\":\"1234123.4\"}", decimal: .init("1234123.4")) try doTest("{\"decimal\":\"123456.34\",\"optional\":\"123456.34\"}", decimal: .init("123456.34")) try doTest("{\"decimal\":\"12345.234\",\"optional\":\"12345.234\"}", decimal: .init("12345.234")) - + try doTest("{\"decimal\":\"12341234\",\"optional\":\"12341234\"}", decimal: .init("12341234")) try doTest("{\"decimal\":\"1234123412341234\",\"optional\":\"1234123412341234\"}", decimal: .init("1234123412341234")) - + try doTest("{\"decimal\":\"00000123\",\"optional\":\"00000123\"}", decimal: .init("123")) try doTest("{\"decimal\":\"00000123.1234\",\"optional\":\"00000123.1234\"}", decimal: .init("123.1234")) try doTest("{\"decimal\":\"00000123.12340000\",\"optional\":\"00000123.12340000\"}", decimal: .init("123.1234")) try doTest("{\"decimal\":\"123.12340000\",\"optional\":\"123.12340000\"}", decimal: .init("123.1234")) - + try doTest("{\"decimal\":\"123.1234\"}", decimal: .init("123.1234"), optionalIsNil: true) try doTest("{\"decimal\":\"12341234\"}", decimal: .init("12341234"), optionalIsNil: true) } - + func test_roundtrip_coding_SUT() throws { struct TestStruct: Codable, Equatable { let decimal: SUT? } - + func doTest(_ decimal: SUT?) throws { let original = TestStruct(decimal: decimal) let encoded = try JSONEncoder().encode(original) let decoded = try JSONDecoder().decode(TestStruct.self, from: encoded) XCTAssertEqual(original, decoded) } - + try doTest(nil) - + for decimalString in smallDecimalStrings { let sut = try SUT(decimalString) try doTest(sut) @@ -454,7 +450,7 @@ final class Decimal192Tests: Test { XCTAssertNoDifference(sut, fromRawString) } } - + func test_as_double() throws { typealias LargeVector = (string: String, lostPrecision: UInt8) let largeDecimalsStrings: [LargeVector] = [ @@ -464,14 +460,14 @@ final class Decimal192Tests: Test { let numberFormatter = NumberFormatter() numberFormatter.maximumFractionDigits = 18 numberFormatter.locale = .test - + func testSmall(_ string: String) throws { let sut = try SUT(string) let double = sut.asDouble let doubleFormatted = try XCTUnwrap(numberFormatter.string(for: double)) XCTAssertEqual(sut.toRawString(), doubleFormatted) } - + func testLarge(_ vector: LargeVector) throws { let sut = try SUT(vector.string) let double = sut.asDouble @@ -480,15 +476,14 @@ final class Decimal192Tests: Test { let rounded = (sut / scale).rounded(decimalPlaces: 0) * scale XCTAssertEqual(rounded.toRawString(), doubleFormatted) } - - + try smallDecimalStrings.forEach(testSmall) try largeDecimalsStrings.forEach(testLarge) - + XCTAssertLessThan(SUT.min.asDouble, SUT.max.asDouble) - XCTAssertNoThrow(try SUT.init("12345678987654321.000000000000000001").asDouble) + XCTAssertNoThrow(try SUT("12345678987654321.000000000000000001").asDouble) } - + private var smallDecimalStrings: [String] { [ "0.000000000000000001", @@ -532,71 +527,71 @@ final class Decimal192Tests: Test { "1.0", ] } - + func test_from_double_zeroPrice() throws { try doTestFromDouble(0, expected: SUT.zero) } - + func test_from_double_noDecimalPlaces_1() throws { try doTestFromDouble(10, expected: 10) } - + func test_from_double_noDecimalPlaces_2() throws { try doTestFromDouble(10000, expected: 10000) } - + func test_from_double_noDecimalPlaces_3() throws { try doTestFromDouble(10_000_000, expected: 10_000_000) } - + func test_from_double_withDecimalPlaces_1() throws { try doTestFromDouble(1.99, expected: SUT("1.99")) } - + func test_from_double_withDecimalPlaces_2() throws { try doTestFromDouble(1.000099, expected: SUT("1.000099")) } - + func test_from_double_belowOne_1() throws { try doTestFromDouble(0.99, expected: 0.99) } - + func test_from_double_belowOne_2() throws { try doTestFromDouble(0.000099, expected: SUT("0.000099")) } - + func test_from_double_closeToSUTDivisibility() throws { // 17 decimal places try doTestFromDouble( - 1.12345678901234567, + 1.12345678901234567, expected: SUT("1.1234567890123457") ) } - + func test_from_double_maxSUTDivisibility() throws { // 18 decimal places try doTestFromDouble(1.123456789012345678, expected: SUT("1.1234567890123457")) } - + func test_from_double_overMaxSUTDivisibility() throws { // 22 decimal places try doTestFromDouble(1.1234567890123456789012, expected: SUT("1.1234567890123457")) } - + func test_from_double_large_value() throws { try doTestFromDouble( - 70000000000.987654, + 70_000_000_000.987654, expected: SUT("70000000000.98766") ) } - + private func doTestFromDouble( _ double: Double, expected: SUT, file: StaticString = #filePath, line: UInt = #line ) throws { - let fromDouble = try SUT.init(double) + let fromDouble = try SUT(double) XCTAssertEqual( fromDouble, expected, @@ -605,7 +600,4 @@ final class Decimal192Tests: Test { line: line ) } - - } - diff --git a/apple/Tests/TestCases/Prelude/DisplayNameTests.swift b/apple/Tests/TestCases/Prelude/DisplayNameTests.swift index 6ff7dac3a..dfd8bda45 100644 --- a/apple/Tests/TestCases/Prelude/DisplayNameTests.swift +++ b/apple/Tests/TestCases/Prelude/DisplayNameTests.swift @@ -7,17 +7,17 @@ import XCTest final class DisplayNameTests: Test { func test_codable() throws { let raw = "\"Spending Account\"".data(using: .utf8)! - + // test decoding let sut = try JSONDecoder().decode(SUT.self, from: raw) XCTAssertEqual(sut, SUT.sample) - + // test encoding let encoded = try JSONEncoder().encode(sut) try XCTAssertEqual(JSONDecoder().decode(SUT.self, from: encoded), sut) } - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { diff --git a/apple/Tests/TestCases/Prelude/ImageURLTests.swift b/apple/Tests/TestCases/Prelude/ImageURLTests.swift index fb81571d4..c6e42c618 100644 --- a/apple/Tests/TestCases/Prelude/ImageURLTests.swift +++ b/apple/Tests/TestCases/Prelude/ImageURLTests.swift @@ -24,7 +24,7 @@ final class ImageURLTests: XCTestCase { ) } - func test_image_url_with_data_url() throws { + func test_image_url_with_data_url() throws { let size = CGSize(width: 1024, height: 1024) let imageServiceURL = URL(string: "https://image-service-dev.extratools.works")! let svgDataURL = URL(string: "data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%201000%201000%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%0A%3Cpolygon%20fill%3D%22hsla%2890%2C99%25%2C52%25%2C1%29%22%20points%3D%220%2C%200%2C%201000%2C%201000%2C%200%2C%201000%22%20transform%3D%22scale%28-1%2C1%29%20translate%28-1000%29%22%2F%3E%0A%3Cpolygon%20fill%3D%22hsla%28199%2C90%25%2C64%25%2C1%29%22%20points%3D%221000%2C%201000%2C%201000%2C%200%2C%200%2C%200%22%20transform%3D%22scale%28-1%2C1%29%20translate%28-1000%29%22%2F%3E%0A%3Cpath%20d%3D%22M1000%2C229%20A1000%2C1000%2C0%2C0%2C0%2C229%2C1000%20L1000%2C1000%20z%22%20fill%3D%22hsla%28140%2C98%25%2C61%25%2C1%29%22%2F%3E%0A%3Cpath%20d%3D%22M392%2C500%20L608%2C500%20M500%2C392%20L500%2C608%22%20stroke%3D%22hsla%2847%2C92%25%2C61%25%2C1%29%22%20stroke-width%3D%2272%22%2F%3E%0A%3C%2Fsvg%3E")! @@ -34,4 +34,4 @@ final class ImageURLTests: XCTestCase { URL(string: "https://image-service-dev.extratools.works/?imageOrigin=data%3Aimage%2Fsvg%2Bxml%2C%253Csvg%2520viewBox%253D%25220%25200%25201000%25201000%2522%2520xmlns%253D%2522http%253A%252F%252Fwww.w3.org%252F2000%252Fsvg%2522%253E%250A%253Cpolygon%2520fill%253D%2522hsla%252890%252C99%2525%252C52%2525%252C1%2529%2522%2520points%253D%25220%252C%25200%252C%25201000%252C%25201000%252C%25200%252C%25201000%2522%2520transform%253D%2522scale%2528-1%252C1%2529%2520translate%2528-1000%2529%2522%252F%253E%250A%253Cpolygon%2520fill%253D%2522hsla%2528199%252C90%2525%252C64%2525%252C1%2529%2522%2520points%253D%25221000%252C%25201000%252C%25201000%252C%25200%252C%25200%252C%25200%2522%2520transform%253D%2522scale%2528-1%252C1%2529%2520translate%2528-1000%2529%2522%252F%253E%250A%253Cpath%2520d%253D%2522M1000%252C229%2520A1000%252C1000%252C0%252C0%252C0%252C229%252C1000%2520L1000%252C1000%2520z%2522%2520fill%253D%2522hsla%2528140%252C98%2525%252C61%2525%252C1%2529%2522%252F%253E%250A%253Cpath%2520d%253D%2522M392%252C500%2520L608%252C500%2520M500%252C392%2520L500%252C608%2522%2520stroke%253D%2522hsla%252847%252C92%2525%252C61%2525%252C1%2529%2522%2520stroke-width%253D%252272%2522%252F%253E%250A%253C%252Fsvg%253E&imageSize=1024x1024&format=png") ) } -} \ No newline at end of file +} diff --git a/apple/Tests/TestCases/Prelude/NetworkIDTests.swift b/apple/Tests/TestCases/Prelude/NetworkIDTests.swift index 5c91ebc8d..8db1b692a 100644 --- a/apple/Tests/TestCases/Prelude/NetworkIDTests.swift +++ b/apple/Tests/TestCases/Prelude/NetworkIDTests.swift @@ -8,20 +8,20 @@ final class NetworkIDTests: Test { func test_non_existing_throws() { XCTAssertThrowsError(try SUT(discriminant: 237)) } - + func test_from_raw_value() throws { XCTAssertEqual(try SUT(discriminant: 1), SUT.mainnet) } - + func test_description() { XCTAssertNoDifference(SUT.mainnet.description, "mainnet") } - + func test_network_id_all_cases_is_12() { XCTAssertEqual(SUT.allCases.count, 12) } - - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { diff --git a/apple/Tests/TestCases/Prelude/NetworkMethodTests.swift b/apple/Tests/TestCases/Prelude/NetworkMethodTests.swift index 2fa9e3c42..b9d996d2d 100644 --- a/apple/Tests/TestCases/Prelude/NetworkMethodTests.swift +++ b/apple/Tests/TestCases/Prelude/NetworkMethodTests.swift @@ -5,15 +5,14 @@ import SargonUniFFI import XCTest final class NetworkMethodTests: Test { - func test_get_description() { XCTAssertEqual(SUT.get.description, "GET") } - + func test_post_description() { XCTAssertEqual(SUT.post.description, "POST") } - + func test_head_description() { XCTAssertEqual(SUT.head.description, "HEAD") } diff --git a/apple/Tests/TestCases/Prelude/NonFungibleGlobalIDTests.swift b/apple/Tests/TestCases/Prelude/NonFungibleGlobalIDTests.swift index 6f4e03a40..476935ff2 100644 --- a/apple/Tests/TestCases/Prelude/NonFungibleGlobalIDTests.swift +++ b/apple/Tests/TestCases/Prelude/NonFungibleGlobalIDTests.swift @@ -5,53 +5,52 @@ import SargonUniFFI import XCTest final class NonFungibleGlobalIDTests: IdentifiableByStringProtocolTest { - - func test_from_parts() { - XCTAssertEqual( - SUT.sample, - try SUT( - nonFungibleResourceAddress: NonFungibleResourceAddress.sample, + func test_from_parts() { + XCTAssertEqual( + SUT.sample, + try SUT( + nonFungibleResourceAddress: NonFungibleResourceAddress.sample, localID: .stringID("Member_237") - ) - ) - } - - func test_local_id() { - XCTAssertEqual(SUT.sample.localID.formatted(), "Member_237") - } - - func test_expressible_by_string_literal() { - XCTAssertEqual(SUT.sample, "resource_rdx1nfyg2f68jw7hfdlg5hzvd8ylsa7e0kjl68t5t62v3ttamtejc9wlxa:") - } - - func test_valid_from_str() { - XCTAssertEqual( - try SUT.init("resource_rdx1nfyg2f68jw7hfdlg5hzvd8ylsa7e0kjl68t5t62v3ttamtejc9wlxa:"), - SUT.sample - ) - } - - func test_invalid_from_str() { - XCTAssertThrowsError( - try SUT.init("super invalid string!!!!") - ) - } - + ) + ) + } + + func test_local_id() { + XCTAssertEqual(SUT.sample.localID.formatted(), "Member_237") + } + + func test_expressible_by_string_literal() { + XCTAssertEqual(SUT.sample, "resource_rdx1nfyg2f68jw7hfdlg5hzvd8ylsa7e0kjl68t5t62v3ttamtejc9wlxa:") + } + + func test_valid_from_str() { + XCTAssertEqual( + try SUT("resource_rdx1nfyg2f68jw7hfdlg5hzvd8ylsa7e0kjl68t5t62v3ttamtejc9wlxa:"), + SUT.sample + ) + } + + func test_invalid_from_str() { + XCTAssertThrowsError( + try SUT("super invalid string!!!!") + ) + } + func test_id_is_description() { XCTAssertEqual(SUT.sample.id, SUT.sample.description) } - - func test_formatted_ruid() throws { - let sut = try SUT( - nonFungibleResourceAddress: .sample, - localID: .ruid( - value: .init(hex: "deadbeef12345678babecafe87654321fadedeaf01234567ecadabba76543210") - ) - ) - XCTAssertNoDifference(sut.formatted(.raw), "resource_rdx1nfyg2f68jw7hfdlg5hzvd8ylsa7e0kjl68t5t62v3ttamtejc9wlxa:{deadbeef12345678-babecafe87654321-fadedeaf01234567-ecadabba76543210}") + + func test_formatted_ruid() throws { + let sut = try SUT( + nonFungibleResourceAddress: .sample, + localID: .ruid( + value: .init(hex: "deadbeef12345678babecafe87654321fadedeaf01234567ecadabba76543210") + ) + ) + XCTAssertNoDifference(sut.formatted(.raw), "resource_rdx1nfyg2f68jw7hfdlg5hzvd8ylsa7e0kjl68t5t62v3ttamtejc9wlxa:{deadbeef12345678-babecafe87654321-fadedeaf01234567-ecadabba76543210}") XCTAssertNoDifference(sut.formatted(.default), "reso...c9wlxa:{dead...3210}") - } - + } + func test_formatted_string() throws { let sut = try SUT( nonFungibleResourceAddress: .sample, diff --git a/apple/Tests/TestCases/Prelude/NonFungibleLocalIDTests.swift b/apple/Tests/TestCases/Prelude/NonFungibleLocalIDTests.swift index 6780a16ab..1dbf9bb0c 100644 --- a/apple/Tests/TestCases/Prelude/NonFungibleLocalIDTests.swift +++ b/apple/Tests/TestCases/Prelude/NonFungibleLocalIDTests.swift @@ -7,24 +7,23 @@ import SargonUniFFI import XCTest final class NonFungibleLocalIDTests: IdentifiableByStringProtocolTest { - - // MARK: LocalID String - func test_valid_local_id_string_from_string() { - XCTAssertEqual(try SUT.init(""), SUT.str(value: "foo")) - } - - func test_valid_local_id_string_from_integer() { - XCTAssertEqual(try SUT.init("#666#"), SUT.integer(value: 666)) - } - - func test_valid_local_id_string_from_ruid() { - XCTAssertEqual(try SUT.init("{deaddeaddeaddead-deaddeaddeaddead-deaddeaddeaddead-deaddeaddeaddead}"), SUT.ruid(value: .sample)) - } - - func test_valid_local_id_string_from_bytes() { - XCTAssertEqual(try SUT.init("[acedacedacedacedacedacedacedacedacedacedacedacedacedacedacedaced]"), SUT.bytes(value: NonEmptyMax64Bytes(bagOfBytes: Data.sampleAced))) - } - + // MARK: LocalID String + func test_valid_local_id_string_from_string() { + XCTAssertEqual(try SUT(""), SUT.str(value: "foo")) + } + + func test_valid_local_id_string_from_integer() { + XCTAssertEqual(try SUT("#666#"), SUT.integer(value: 666)) + } + + func test_valid_local_id_string_from_ruid() { + XCTAssertEqual(try SUT("{deaddeaddeaddead-deaddeaddeaddead-deaddeaddeaddead-deaddeaddeaddead}"), SUT.ruid(value: .sample)) + } + + func test_valid_local_id_string_from_bytes() { + XCTAssertEqual(try SUT("[acedacedacedacedacedacedacedacedacedacedacedacedacedacedacedaced]"), SUT.bytes(value: NonEmptyMax64Bytes(bagOfBytes: Data.sampleAced))) + } + // MARK: Integer func test_integer_valid() { XCTAssertEqual( @@ -32,11 +31,11 @@ final class NonFungibleLocalIDTests: IdentifiableByStringProtocolTest" ) } - + func test_init_string_fails_when_given_user_facing_string() throws { - XCTAssertThrowsError(try SUT.init("x")) + XCTAssertThrowsError(try SUT("x")) } - + func test_init_string_succeeds_when_given_raw_string() throws { - XCTAssertNoThrow(try SUT.init("")) + XCTAssertNoThrow(try SUT("")) } - + func test_from_stringID_fails_when_given_raw_string() throws { XCTAssertThrowsError(try SUT.stringID("")) } - + func test_from_stringID_succeeds_when_given_user_facing_string() throws { XCTAssertNoThrow(try SUT.stringID("x")) } - + func test_string_valid_max_length() { let s = String(repeating: "z", count: 64) XCTAssertEqual( @@ -68,42 +67,42 @@ final class NonFungibleLocalIDTests: IdentifiableByStringProtocolTest" ) } - + func test_string_invalid_too_long() { XCTAssertThrowsError(try SUT.stringID("much2longmuch2longmuch2longmuch2longmuch2longmuch2longmuch2longmuch2long")) } - + func test_string_invalid_forbidden_chars() { XCTAssertThrowsError(try SUT.stringID("#$^")) } - + // MARK: Bytes func test_bytes_valid_short() { XCTAssertEqual( - try SUT(bytes: [0xde, 0xad, 0xbe, 0xef]).description, + try SUT(bytes: [0xDE, 0xAD, 0xBE, 0xEF]).description, "[deadbeef]" ) XCTAssertEqual( - try SUT(bytes: [0xde, 0xad, 0xbe, 0xef]), - [0xde, 0xad, 0xbe, 0xef] as SUT // ExpressibleByArrayLiteral + try SUT(bytes: [0xDE, 0xAD, 0xBE, 0xEF]), + [0xDE, 0xAD, 0xBE, 0xEF] as SUT // ExpressibleByArrayLiteral ) } - + func test_bytes_valid_max_len() { XCTAssertEqual( - try SUT(bytes: Data(repeating: 0xab, count: 64)).description, + try SUT(bytes: Data(repeating: 0xAB, count: 64)).description, "[abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab]" ) } - + func test_bytes_invalid_empty() { XCTAssertThrowsError(try SUT(bytes: Data([]))) } - + func test_bytes_invalid_too_long() { - XCTAssertThrowsError(try SUT(bytes: Data(repeating: 0xff, count: 128))) + XCTAssertThrowsError(try SUT(bytes: Data(repeating: 0xFF, count: 128))) } - + // MARK: RUID func test_ruid() { XCTAssertEqual( @@ -111,31 +110,31 @@ final class NonFungibleLocalIDTests: IdentifiableByStringProtocolTest") - XCTAssertNoDifference(SUT.sampleOther.formatted(.default), "foobar") - } - + XCTAssertThrowsError(try SUT(ruid: Data(repeating: 0xFF, count: 128))) + } + + func test_to_user_facing_string() { + XCTAssertNoDifference(SUT.sampleOther.toUserFacingString(), "foobar") + } + + func test_formatted() { + XCTAssertNoDifference(SUT.sampleOther.formatted(.raw), "") + XCTAssertNoDifference(SUT.sampleOther.formatted(.default), "foobar") + } + func test_random() { let n = 20 - let set = Set((0.. { - func test_exactly() { XCTAssertEqual(SUT.exactly(1), SUT.sample) } - + func test_atLeast() { XCTAssertEqual(SUT.atLeast(1), SUT.sampleOther) } - + func test_isValid_true() { XCTAssertTrue(SUT.sample.isValid) } - + func test_isValid_false() { let sut = SUT( quantifier: .exactly, @@ -25,16 +24,16 @@ final class RequestedQuantityTests: Test { ) XCTAssertFalse(sut.isValid) } - + func test_is_fulfilled_by_true() { XCTAssertTrue(SUT.atLeast(1).isFulfilled(by: 1)) } - + func test_is_fulfilled_by_false() { XCTAssertFalse(SUT.atLeast(2).isFulfilled(by: 1)) XCTAssertFalse(SUT.exactly(2).isFulfilled(by: 3)) } - + func test_codable() throws { let raw = """ { @@ -42,17 +41,17 @@ final class RequestedQuantityTests: Test { "quantity": 1 } """.data(using: .utf8)! - + // test decoding let sut = try JSONDecoder().decode(SUT.self, from: raw) XCTAssertEqual(sut, SUT.sample) - + // test encoding let encoded = try JSONEncoder().encode(sut) try XCTAssertEqual(JSONDecoder().decode(SUT.self, from: encoded), sut) } - - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { diff --git a/apple/Tests/TestCases/Prelude/SargonBuildInformationTests.swift b/apple/Tests/TestCases/Prelude/SargonBuildInformationTests.swift index f3b5f39ba..ef429c039 100644 --- a/apple/Tests/TestCases/Prelude/SargonBuildInformationTests.swift +++ b/apple/Tests/TestCases/Prelude/SargonBuildInformationTests.swift @@ -5,10 +5,10 @@ import SargonUniFFI import XCTest final class SargonBuildInformationTests: Test { - func test_build_information() { - let info = SargonBuildInformation.get() - XCTAssert(info.sargonVersion.contains(".")) - XCTAssertFalse(String(describing: info.dependencies.radixEngineToolkit).isEmpty) - XCTAssertFalse(String(describing: info.dependencies.scryptoRadixEngine).isEmpty) - } + func test_build_information() { + let info = SargonBuildInformation.get() + XCTAssert(info.sargonVersion.contains(".")) + XCTAssertFalse(String(describing: info.dependencies.radixEngineToolkit).isEmpty) + XCTAssertFalse(String(describing: info.dependencies.scryptoRadixEngine).isEmpty) + } } diff --git a/apple/Tests/TestCases/Prelude/SargonErrorTests.swift b/apple/Tests/TestCases/Prelude/SargonErrorTests.swift index 8b580e0cc..dd75e2f22 100644 --- a/apple/Tests/TestCases/Prelude/SargonErrorTests.swift +++ b/apple/Tests/TestCases/Prelude/SargonErrorTests.swift @@ -5,20 +5,19 @@ import SargonUniFFI import XCTest final class SargonErrorTests: Test { - func test_error_code() { XCTAssertEqual(SUT.UnknownNetworkForId(badValue: 99).errorCode, 10049) } - + func test_error_message() { XCTAssertEqual(SUT.UnknownNetworkForId(badValue: 99).errorMessage, "No network found with id: '99'") } - + func test_description() { let sut = SUT.UnknownNetworkForId(badValue: 99) XCTAssertEqual(sut.description, sut.errorMessage) } - + func test_debug_description() { let sut = SUT.UnknownNetworkForId(badValue: 99) XCTAssertEqual(sut.debugDescription, "10049: No network found with id: '99'") @@ -36,5 +35,5 @@ final class SargonErrorTests: Test { func test_localized_description_for_non_sensitive_error() { let sut = SUT.FailedToDeserializeJsonToValue(jsonByteCount: 100, typeName: "TypeName", serdeMessage: "serdeMessage") XCTAssertEqual(sut.localizedDescription, "Error code: 10070\nError message: Failed deserialize JSON with #100 bytes to value of type TypeName with error: \"serdeMessage\"") - } + } } diff --git a/apple/Tests/TestCases/Profile+Supporting+Types/AccountOrPersonaTests.swift b/apple/Tests/TestCases/Profile+Supporting+Types/AccountOrPersonaTests.swift index a609d88e4..cfb6e2e20 100644 --- a/apple/Tests/TestCases/Profile+Supporting+Types/AccountOrPersonaTests.swift +++ b/apple/Tests/TestCases/Profile+Supporting+Types/AccountOrPersonaTests.swift @@ -8,7 +8,7 @@ final class AccountOrPersonaTests: EntityBaseTest { func test_display_names() { XCTAssertEqual(SUT.sampleValues.map(\.displayName), ["Alice", "Batman", "Carol", "Nadia", "Granger", "Paige"]) } - + func test_as_general_is_self() { eachSample { sut in XCTAssertEqual(sut, sut.asGeneral) diff --git a/apple/Tests/TestCases/Profile+Supporting+Types/AuthorizedDappDetailedTests.swift b/apple/Tests/TestCases/Profile+Supporting+Types/AuthorizedDappDetailedTests.swift index 81a41ccbd..75be6323a 100644 --- a/apple/Tests/TestCases/Profile+Supporting+Types/AuthorizedDappDetailedTests.swift +++ b/apple/Tests/TestCases/Profile+Supporting+Types/AuthorizedDappDetailedTests.swift @@ -10,7 +10,7 @@ final class AuthorizedDappDetailedTests: Test { XCTAssertEqual(sut.id, sut.dappDefinitionAddress) } } - + func test_show_deposits() { var sut = SUT.sample XCTAssertTrue(sut.isDepositsVisible) diff --git a/apple/Tests/TestCases/Profile/Account/AccountTests.swift b/apple/Tests/TestCases/Profile/Account/AccountTests.swift index e72fab6a8..a98dc0e20 100644 --- a/apple/Tests/TestCases/Profile/Account/AccountTests.swift +++ b/apple/Tests/TestCases/Profile/Account/AccountTests.swift @@ -5,37 +5,36 @@ import SargonUniFFI import XCTest final class AccountTests: EntityProtocolTest { - func test_extract_wrong_throws() throws { try eachSample { sut in XCTAssertThrowsError(try sut.asGeneral.extract(as: Persona.self)) } } - + func test_as_general_as_account() throws { try eachSample { sut in XCTAssertEqual(try sut.asGeneral.asAccount(), sut) } } - + func test_display_names() { XCTAssertEqual(SUT.sampleValues.map(\.displayName), ["Alice", "Bob", "Carol", "Nadia", "Olivia", "Paige"]) } - + func test_not_hidden() { XCTAssertEqual(SUT.sampleMainnetAlice.flags, []) } - + func test_hidden() { let sut = SUT.sampleStokenetOlivia.flags XCTAssertEqual(sut, [.hiddenByUser]) } - + func test_appearance_id() { XCTAssertEqual(SUT.sampleMainnetAlice.appearanceID, AppearanceID(value: 0)) XCTAssertEqual(SUT.sampleMainnetBob.appearanceID, AppearanceID(value: 1)) } - + func test_ledger_controlled_account_has_no_device_fs_id() { var sut = SUT.sample var uec = UnsecuredEntityControl.sample @@ -49,11 +48,10 @@ final class AccountTests: EntityProtocolTest { sut.securityState = .unsecured(value: .init(transactionSigning: .sample, authenticationSigning: .sampleOther)) XCTAssertEqual(sut.virtualHierarchicalDeterministicFactorInstances.count, 2) } - + func test_new() { let fi: HierarchicalDeterministicFactorInstance = .sample - let sut = SUT.init(networkID: .sample, factorInstance: fi, displayName: .sample, extraProperties: .sample) + let sut = SUT(networkID: .sample, factorInstance: fi, displayName: .sample, extraProperties: .sample) XCTAssertEqual(sut.virtualHierarchicalDeterministicFactorInstances, [fi]) } - } diff --git a/apple/Tests/TestCases/Profile/Account/AppearanceIDTests.swift b/apple/Tests/TestCases/Profile/Account/AppearanceIDTests.swift index c890c50f2..74d08b666 100644 --- a/apple/Tests/TestCases/Profile/Account/AppearanceIDTests.swift +++ b/apple/Tests/TestCases/Profile/Account/AppearanceIDTests.swift @@ -9,19 +9,18 @@ final class AppearanceIDTests: Test { XCTAssertEqual(SUT.sample.id, 0) XCTAssertEqual(SUT.sampleOther.id, 11) } - + func test_all_cases_returns_actual_values_not_samples() { XCTAssertEqual(SUT.allCases.count, 12) } - - - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { try eachSampleCodableRoundtripTest() } - + func test_from_number_of_accounts() { func doTest(_ count: Int, expected: SUT) { XCTAssertEqual(SUT.fromNumberOfAccounts(count), expected) diff --git a/apple/Tests/TestCases/Profile/Account/ThirdPartyDepositsTests.swift b/apple/Tests/TestCases/Profile/Account/ThirdPartyDepositsTests.swift index 34d728c6b..48c4abd92 100644 --- a/apple/Tests/TestCases/Profile/Account/ThirdPartyDepositsTests.swift +++ b/apple/Tests/TestCases/Profile/Account/ThirdPartyDepositsTests.swift @@ -8,15 +8,14 @@ final class ThirdPartyDepositsTests: Test { func test_default_has_some_assetsExceptionList() { XCTAssertNotNil(SUT.default.assetsExceptionList) } - + func test_default_has_some_depositorsAllowList() { XCTAssertNotNil(SUT.default.depositorsAllowList) } - + func test_isAssetsExceptionsUnknown_false() { XCTAssertFalse(SUT.default.isAssetsExceptionsUnknown) } - func test_accountRecoveryScanned_custom_rule() { func doTest(_ rule: DepositRule) { @@ -27,10 +26,8 @@ final class ThirdPartyDepositsTests: Test { } DepositRule.sampleValues.forEach(doTest) } - + func test_isAllowedDepositorsUnknown_false() { XCTAssertFalse(SUT.default.isAllowedDepositorsUnknown) } - - } diff --git a/apple/Tests/TestCases/Profile/AppPreferencesTests.swift b/apple/Tests/TestCases/Profile/AppPreferencesTests.swift index 95cbf59cc..449ec2273 100644 --- a/apple/Tests/TestCases/Profile/AppPreferencesTests.swift +++ b/apple/Tests/TestCases/Profile/AppPreferencesTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import CustomDump import Foundation import Sargon @@ -15,16 +8,16 @@ final class AppPreferencesTests: Test { func test_default_guarantee_is_99() { XCTAssertEqual(SUT.default.transaction.defaultDepositGuarantee, 0.99) } - + func test_has_gateway_valid() throws { - XCTAssertTrue(SUT.default.hasGateway(with: try .init(urlPath: "https://mainnet.radixdlt.com/"))) - XCTAssertTrue(SUT.default.hasGateway(with: try .init(urlPath: "https://mainnet.radixdlt.com"))) - XCTAssertFalse(SUT.default.hasGateway(with: try .init(urlPath: "https://radixdlt.com/"))) + XCTAssertTrue(try SUT.default.hasGateway(with: .init(urlPath: "https://mainnet.radixdlt.com/"))) + XCTAssertTrue(try SUT.default.hasGateway(with: .init(urlPath: "https://mainnet.radixdlt.com"))) + XCTAssertFalse(try SUT.default.hasGateway(with: .init(urlPath: "https://radixdlt.com/"))) } - + func test_has_gateway_invalid() { let urlPath = "invalid input" - XCTAssertThrowsError(SUT.default.hasGateway(with: try .init(urlPath: urlPath))) { error in + XCTAssertThrowsError(try SUT.default.hasGateway(with: .init(urlPath: urlPath))) { error in guard let commonError = error as? SargonUniFFI.CommonError else { return XCTFail("Expected CommonError") } diff --git a/apple/Tests/TestCases/Profile/AssetExceptionTests.swift b/apple/Tests/TestCases/Profile/AssetExceptionTests.swift index dc541ca9d..b480301ca 100644 --- a/apple/Tests/TestCases/Profile/AssetExceptionTests.swift +++ b/apple/Tests/TestCases/Profile/AssetExceptionTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import CustomDump import Foundation import Sargon diff --git a/apple/Tests/TestCases/Profile/AuthorizedDapp/AuthorizedDappTests.swift b/apple/Tests/TestCases/Profile/AuthorizedDapp/AuthorizedDappTests.swift index 599b1a9c8..31d13c9a3 100644 --- a/apple/Tests/TestCases/Profile/AuthorizedDapp/AuthorizedDappTests.swift +++ b/apple/Tests/TestCases/Profile/AuthorizedDapp/AuthorizedDappTests.swift @@ -5,13 +5,12 @@ import SargonUniFFI import XCTest final class AuthorizedDappTests: Test { - func test_network_ids_mainnet() { - XCTAssertTrue(SUT.sampleValuesMainnet.allSatisfy({ $0.networkID == .mainnet })) + XCTAssertTrue(SUT.sampleValuesMainnet.allSatisfy { $0.networkID == .mainnet }) } func test_network_ids_stokenet() { - XCTAssertTrue(SUT.sampleValuesStokenet.allSatisfy({ $0.networkID == .stokenet })) + XCTAssertTrue(SUT.sampleValuesStokenet.allSatisfy { $0.networkID == .stokenet }) } func test_id_is_dapp_definition() { @@ -19,7 +18,7 @@ final class AuthorizedDappTests: Test { XCTAssertEqual(sut.id, sut.dAppDefinitionAddress) } } - + func test_show_deposits() { var sut = SUT.sample XCTAssertTrue(sut.isDepositsVisible) @@ -29,48 +28,48 @@ final class AuthorizedDappTests: Test { func test_codable() throws { let raw = """ - { - "networkID": 1, - "dAppDefinitionAddress": "account_rdx12xuhw6v30chdkhcu7qznz9vu926vxefr4h4tdvc0mdckg9rq4afx9t", - "displayName": "Gumball Club", - "referencesToAuthorizedPersonas": [ - { - "identityAddress": "identity_rdx12tw6rt9c4l56rz6p866e35tmzp556nymxmpj8hagfewq82kspctdyw", - "lastLogin": "2024-01-31T14:23:45.000Z", - "sharedAccounts": { + { + "networkID": 1, + "dAppDefinitionAddress": "account_rdx12xuhw6v30chdkhcu7qznz9vu926vxefr4h4tdvc0mdckg9rq4afx9t", + "displayName": "Gumball Club", + "referencesToAuthorizedPersonas": [ + { + "identityAddress": "identity_rdx12tw6rt9c4l56rz6p866e35tmzp556nymxmpj8hagfewq82kspctdyw", + "lastLogin": "2024-01-31T14:23:45.000Z", + "sharedAccounts": { + "request": { + "quantifier": "atLeast", + "quantity": 1 + }, + "ids": [ + "account_rdx12y02nen8zjrq0k0nku98shjq7n05kvl3j9m5d3a6cpduqwzgmenjq7" + ] + }, + "sharedPersonaData": { + "name": "00000000-0000-0000-0000-000000000000", + "emailAddresses": { "request": { - "quantifier": "atLeast", + "quantifier": "exactly", "quantity": 1 }, "ids": [ - "account_rdx12y02nen8zjrq0k0nku98shjq7n05kvl3j9m5d3a6cpduqwzgmenjq7" + "00000000-0000-0000-0000-000000000002" ] }, - "sharedPersonaData": { - "name": "00000000-0000-0000-0000-000000000000", - "emailAddresses": { - "request": { - "quantifier": "exactly", - "quantity": 1 - }, - "ids": [ - "00000000-0000-0000-0000-000000000002" - ] + "phoneNumbers": { + "request": { + "quantifier": "exactly", + "quantity": 1 }, - "phoneNumbers": { - "request": { - "quantifier": "exactly", - "quantity": 1 - }, - "ids": [ - "00000000-0000-0000-0000-000000000001" - ] - } + "ids": [ + "00000000-0000-0000-0000-000000000001" + ] } } - ] - } - """.data(using: .utf8)! + } + ] + } + """.data(using: .utf8)! // test decoding let sut = try JSONDecoder().decode(SUT.self, from: raw) diff --git a/apple/Tests/TestCases/Profile/Collection/AccountsForDisplayTests.swift b/apple/Tests/TestCases/Profile/Collection/AccountsForDisplayTests.swift index 7e98b5d3a..fd9af0d2b 100644 --- a/apple/Tests/TestCases/Profile/Collection/AccountsForDisplayTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/AccountsForDisplayTests.swift @@ -5,11 +5,10 @@ import SargonUniFFI import XCTest final class AccountsForDisplayTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } diff --git a/apple/Tests/TestCases/Profile/Collection/AccountsOrPersonasTests.swift b/apple/Tests/TestCases/Profile/Collection/AccountsOrPersonasTests.swift index 6d4d85fa1..e7183f6c2 100644 --- a/apple/Tests/TestCases/Profile/Collection/AccountsOrPersonasTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/AccountsOrPersonasTests.swift @@ -4,13 +4,11 @@ import Sargon import SargonUniFFI import XCTest - final class AccountsOrPersonasTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } diff --git a/apple/Tests/TestCases/Profile/Collection/AccountsTests.swift b/apple/Tests/TestCases/Profile/Collection/AccountsTests.swift index 6c119c806..fa3d706ec 100644 --- a/apple/Tests/TestCases/Profile/Collection/AccountsTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/AccountsTests.swift @@ -2,17 +2,18 @@ import CustomDump import Foundation @testable import Sargon import SargonUniFFI -import XCTest import SwiftyJSON +import XCTest final class AccountsTests: CollectionTest { override class func sample() -> SUT { SUT.sample } + override class func sampleOther() -> SUT { SUT.sampleOther } - + /// Have to omit this test... obviously... since it crashes. /// We can have this test implemented when swift-testing is stable to be used, /// and we will use "exit tests" to test it: @@ -31,7 +32,7 @@ final class AccountsTests: CollectionTest { json["profileNetworks.accounts"] = [Account.sample, Account.sample] XCTAssertThrowsError(try Profile(jsonData: json.rawData())) } - + func test_json_decoding_of_profile_fails_if_accounts_contains_duplicated_ids() throws { var json = JSON(Profile.sample) let a = Account.sample diff --git a/apple/Tests/TestCases/Profile/Collection/AssetsExceptionListTests.swift b/apple/Tests/TestCases/Profile/Collection/AssetsExceptionListTests.swift index 345a5e89d..caab32f6f 100644 --- a/apple/Tests/TestCases/Profile/Collection/AssetsExceptionListTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/AssetsExceptionListTests.swift @@ -5,11 +5,10 @@ import SargonUniFFI import XCTest final class AssetsExceptionListTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } diff --git a/apple/Tests/TestCases/Profile/Collection/AuthorizedDappsTests.swift b/apple/Tests/TestCases/Profile/Collection/AuthorizedDappsTests.swift index 55a74164c..f715df061 100644 --- a/apple/Tests/TestCases/Profile/Collection/AuthorizedDappsTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/AuthorizedDappsTests.swift @@ -5,11 +5,10 @@ import SargonUniFFI import XCTest final class AuthorizedDappsTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } diff --git a/apple/Tests/TestCases/Profile/Collection/DepositorsAllowListTests.swift b/apple/Tests/TestCases/Profile/Collection/DepositorsAllowListTests.swift index e2df4eef0..dbea259b3 100644 --- a/apple/Tests/TestCases/Profile/Collection/DepositorsAllowListTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/DepositorsAllowListTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import CustomDump import Foundation import Sargon @@ -12,11 +5,10 @@ import SargonUniFFI import XCTest final class DepositorsAllowListTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } diff --git a/apple/Tests/TestCases/Profile/Collection/DetailedAuthorizedPersonasTests.swift b/apple/Tests/TestCases/Profile/Collection/DetailedAuthorizedPersonasTests.swift index 576c47efa..e10f82e78 100644 --- a/apple/Tests/TestCases/Profile/Collection/DetailedAuthorizedPersonasTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/DetailedAuthorizedPersonasTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import CustomDump import Foundation import Sargon @@ -12,11 +5,10 @@ import SargonUniFFI import XCTest final class DetailedAuthorizedPersonasTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } diff --git a/apple/Tests/TestCases/Profile/Collection/EntityFlagsTests.swift b/apple/Tests/TestCases/Profile/Collection/EntityFlagsTests.swift index 336606d6c..23d2ad4b5 100644 --- a/apple/Tests/TestCases/Profile/Collection/EntityFlagsTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/EntityFlagsTests.swift @@ -5,11 +5,10 @@ import SargonUniFFI import XCTest final class EntityFlagsTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } diff --git a/apple/Tests/TestCases/Profile/Collection/FactorSourcesTests.swift b/apple/Tests/TestCases/Profile/Collection/FactorSourcesTests.swift index a9865e613..ad95d5c41 100644 --- a/apple/Tests/TestCases/Profile/Collection/FactorSourcesTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/FactorSourcesTests.swift @@ -2,19 +2,18 @@ import CustomDump import Foundation @testable import Sargon import SargonUniFFI -import XCTest import SwiftyJSON +import XCTest final class FactorSourcesTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } - + /// Have to omit this test... obviously... since it crashes. /// We can have this test implemented when swift-testing is stable to be used, /// and we will use "exit tests" to test it: @@ -30,13 +29,13 @@ final class FactorSourcesTests: CollectionTest { json["factorSources"] = [] XCTAssertThrowsError(try Profile(jsonData: json.rawData())) } - + func test_json_decoding_of_profile_fails_if_factorSources_contains_duplicates() throws { var json = JSON(Profile.sample) json["factorSources"] = [FactorSource.sample, FactorSource.sample] XCTAssertThrowsError(try Profile(jsonData: json.rawData())) } - + func test_json_decoding_of_profile_fails_if_factorSources_contains_duplicated_ids() throws { var json = JSON(Profile.sample) let a = FactorSource.sample @@ -46,4 +45,3 @@ final class FactorSourcesTests: CollectionTest { XCTAssertThrowsError(try Profile(jsonData: json.rawData())) } } - diff --git a/apple/Tests/TestCases/Profile/Collection/GatewaysTests.swift b/apple/Tests/TestCases/Profile/Collection/GatewaysTests.swift index 90cd4ad53..cc94b4883 100644 --- a/apple/Tests/TestCases/Profile/Collection/GatewaysTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/GatewaysTests.swift @@ -5,11 +5,10 @@ import SargonUniFFI import XCTest final class GatewaysTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } diff --git a/apple/Tests/TestCases/Profile/Collection/PersonasTests.swift b/apple/Tests/TestCases/Profile/Collection/PersonasTests.swift index a3e099923..1c9410961 100644 --- a/apple/Tests/TestCases/Profile/Collection/PersonasTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/PersonasTests.swift @@ -5,11 +5,10 @@ import SargonUniFFI import XCTest final class PersonasTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } diff --git a/apple/Tests/TestCases/Profile/Collection/ProfileNetworksTests.swift b/apple/Tests/TestCases/Profile/Collection/ProfileNetworksTests.swift index 7adb5230b..3e2c4f0a9 100644 --- a/apple/Tests/TestCases/Profile/Collection/ProfileNetworksTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/ProfileNetworksTests.swift @@ -5,11 +5,10 @@ import SargonUniFFI import XCTest final class ProfileNetworksTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } diff --git a/apple/Tests/TestCases/Profile/Collection/ReferencesToAuthorizedPersonasTests.swift b/apple/Tests/TestCases/Profile/Collection/ReferencesToAuthorizedPersonasTests.swift index 0042b226c..e1fc21dd6 100644 --- a/apple/Tests/TestCases/Profile/Collection/ReferencesToAuthorizedPersonasTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/ReferencesToAuthorizedPersonasTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - import CustomDump import Foundation import Sargon @@ -12,11 +5,10 @@ import SargonUniFFI import XCTest final class ReferencesToAuthorizedPersonasTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } diff --git a/apple/Tests/TestCases/Profile/Collection/SupportedCurvesTests.swift b/apple/Tests/TestCases/Profile/Collection/SupportedCurvesTests.swift index 42dd644a0..621c7600b 100644 --- a/apple/Tests/TestCases/Profile/Collection/SupportedCurvesTests.swift +++ b/apple/Tests/TestCases/Profile/Collection/SupportedCurvesTests.swift @@ -5,11 +5,10 @@ import SargonUniFFI import XCTest final class SupportedCurvesTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } diff --git a/apple/Tests/TestCases/Profile/DepositRuleTests.swift b/apple/Tests/TestCases/Profile/DepositRuleTests.swift index 0f2c0b281..1abbfc03e 100644 --- a/apple/Tests/TestCases/Profile/DepositRuleTests.swift +++ b/apple/Tests/TestCases/Profile/DepositRuleTests.swift @@ -5,42 +5,41 @@ import SargonUniFFI import XCTest final class DepositRuleTests: Test { - - func test_low_level_to_json_string() { - let sut = SUT.sample - let jsonString = depositRuleToJsonString(depositRule: sut) - XCTAssertEqual(jsonString, "acceptKnown") - } + func test_low_level_to_json_string() { + let sut = SUT.sample + let jsonString = depositRuleToJsonString(depositRule: sut) + XCTAssertEqual(jsonString, "acceptKnown") + } + + func test_codable() throws { + let raw = "\"denyAll\"".data(using: .utf8)! + + // test decoding + let sut = try JSONDecoder().decode(SUT.self, from: raw) + XCTAssertEqual(sut, SUT.denyAll) + + // test encoding + let encoded = try JSONEncoder().encode(sut) + try XCTAssertEqual(JSONDecoder().decode(SUT.self, from: encoded), sut) + } + + func test_wrapped_in_obj() throws { + struct Wrapper: Codable, Equatable { + let myString: String + let rule: DepositRule + } + let json = """ + { + "myString": "Foo", + "rule": "acceptAll" + } + """.data(using: .utf8)! + + let decoded = try JSONDecoder().decode(Wrapper.self, from: json) + XCTAssertEqual(decoded, Wrapper(myString: "Foo", rule: .acceptAll)) + } - func test_codable() throws { - let raw = "\"denyAll\"".data(using: .utf8)! - - // test decoding - let sut = try JSONDecoder().decode(SUT.self, from: raw) - XCTAssertEqual(sut, SUT.denyAll) - - // test encoding - let encoded = try JSONEncoder().encode(sut) - try XCTAssertEqual(JSONDecoder().decode(SUT.self, from: encoded), sut) - } - - func test_wrapped_in_obj() throws { - struct Wrapper: Codable, Equatable { - let myString: String - let rule: DepositRule - } - let json = """ - { - "myString": "Foo", - "rule": "acceptAll" - } - """.data(using: .utf8)! - - let decoded = try JSONDecoder().decode(Wrapper.self, from: json) - XCTAssertEqual(decoded, Wrapper.init(myString: "Foo", rule: .acceptAll)) - } - - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { diff --git a/apple/Tests/TestCases/Profile/DeviceInfoTests.swift b/apple/Tests/TestCases/Profile/DeviceInfoTests.swift index 683e1faa3..767be0f04 100644 --- a/apple/Tests/TestCases/Profile/DeviceInfoTests.swift +++ b/apple/Tests/TestCases/Profile/DeviceInfoTests.swift @@ -5,8 +5,7 @@ import SargonUniFFI import XCTest final class DeviceInfoTests: Test { - - func test_not_codable_but_lower_level_json_methods_json_data_roundtrip() throws{ + func test_not_codable_but_lower_level_json_methods_json_data_roundtrip() throws { let sut = SUT.sample let json = sut.jsonData() try XCTAssertEqual( @@ -14,64 +13,61 @@ final class DeviceInfoTests: Test { sut ) } - + func test_codable_lowercase_rust_styled_uuid() throws { - func doTest(_ jsonString: String, expected: SUT? = .sample) throws { - - // No matter which encoding strategy is set on encoder/decoder - // the Date coding should work since it should happen inside of - // sargon - func doDoTest(encoder: JSONEncoder, decoder: JSONDecoder) throws { - let raw = Data(jsonString.utf8) - // test decoding - let sut = try decoder.decode(SUT.self, from: raw) - - if let expected { - XCTAssertEqual(sut, expected) - } - - // test encoding - let encoded = try encoder.encode(sut) - try XCTAssertEqual(decoder.decode(SUT.self, from: encoded), sut) - } - - try doDoTest(encoder: .init(), decoder: .init()) - try doDoTest(encoder: .iso8601, decoder: .iso8601) - try doDoTest(encoder: .init(), decoder: .iso8601) - try doDoTest(encoder: .iso8601, decoder: .init()) - } - - // Rust style: - // * lower UUID - // * date with milliseconds - try doTest(""" - { - "id": "66f07ca2-a9d9-49e5-8152-77aca3d1dd74", - "date": "2023-09-11T16:05:56.000Z", - "description": "iPhone (iPhone)" - } - """) + func doTest(_ jsonString: String, expected: SUT? = .sample) throws { + // No matter which encoding strategy is set on encoder/decoder + // the Date coding should work since it should happen inside of + // sargon + func doDoTest(encoder: JSONEncoder, decoder: JSONDecoder) throws { + let raw = Data(jsonString.utf8) + // test decoding + let sut = try decoder.decode(SUT.self, from: raw) + + if let expected { + XCTAssertEqual(sut, expected) + } + + // test encoding + let encoded = try encoder.encode(sut) + try XCTAssertEqual(decoder.decode(SUT.self, from: encoded), sut) + } + + try doDoTest(encoder: .init(), decoder: .init()) + try doDoTest(encoder: .iso8601, decoder: .iso8601) + try doDoTest(encoder: .init(), decoder: .iso8601) + try doDoTest(encoder: .iso8601, decoder: .init()) + } + + // Rust style: + // * lower UUID + // * date with milliseconds + try doTest(""" + { + "id": "66f07ca2-a9d9-49e5-8152-77aca3d1dd74", + "date": "2023-09-11T16:05:56.000Z", + "description": "iPhone (iPhone)" + } + """) + + // Swift style: + // * uppercase UUID + // * date without milliseconds + try doTest(""" + { + "id": "66F07CA2-A9D9-49E5-8152-77ACA3D1DD74", + "date": "2023-09-11T16:05:56Z", + "description": "iPhone (iPhone)" + } + """) - // Swift style: - // * uppercase UUID - // * date without milliseconds - try doTest(""" - { - "id": "66F07CA2-A9D9-49E5-8152-77ACA3D1DD74", - "date": "2023-09-11T16:05:56Z", - "description": "iPhone (iPhone)" - } - """) - - // Swift style - new. - try doTest(""" - { - "id": "\(UUID().uuidString)", - "date": "\(Date.now.ISO8601Format())", - "description": "iPhone (iPhone)" - } - """, expected: nil) + // Swift style - new. + try doTest(""" + { + "id": "\(UUID().uuidString)", + "date": "\(Date.now.ISO8601Format())", + "description": "iPhone (iPhone)" + } + """, expected: nil) } - - } diff --git a/apple/Tests/TestCases/Profile/EntitySecurityStateTests.swift b/apple/Tests/TestCases/Profile/EntitySecurityStateTests.swift index 57bbfe75e..cf2900863 100644 --- a/apple/Tests/TestCases/Profile/EntitySecurityStateTests.swift +++ b/apple/Tests/TestCases/Profile/EntitySecurityStateTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-27. -// - import CustomDump import Foundation import Sargon diff --git a/apple/Tests/TestCases/Profile/Factor/ArculusCardFactorSourceTests.swift b/apple/Tests/TestCases/Profile/Factor/ArculusCardFactorSourceTests.swift index 892201eb9..cb76cfa76 100644 --- a/apple/Tests/TestCases/Profile/Factor/ArculusCardFactorSourceTests.swift +++ b/apple/Tests/TestCases/Profile/Factor/ArculusCardFactorSourceTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import CustomDump import Foundation import Sargon @@ -17,7 +10,7 @@ final class ArculusCardFactorSourceTests: SpecificFactorSourceTest { func test_id_of_device() { @@ -11,53 +11,53 @@ final class DeviceFactorSourceTests: SpecificFactorSourceTest { func test_babylon_neq_olmypia() { XCTAssertNotEqual(SUT.babylon(), SUT.olympia()) } + func test_babylon_main() { XCTAssertTrue(SUT.babylon(isMain: true).flags.contains(.main)) XCTAssertFalse(SUT.babylon(isMain: false).flags.contains(.main)) diff --git a/apple/Tests/TestCases/Profile/Factor/FactorSourceCryptoParametersTests.swift b/apple/Tests/TestCases/Profile/Factor/FactorSourceCryptoParametersTests.swift index 9cb3005a6..1d5d70e24 100644 --- a/apple/Tests/TestCases/Profile/Factor/FactorSourceCryptoParametersTests.swift +++ b/apple/Tests/TestCases/Profile/Factor/FactorSourceCryptoParametersTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import CustomDump import Foundation import Sargon @@ -12,21 +5,19 @@ import SargonUniFFI import XCTest final class FactorSourceCryptoParametersTests: Test { - func test_supports_olympia() { let f: (SUT) -> Bool = \.supportsOlympia - + XCTAssertTrue(f(.olympia)) XCTAssertTrue(f(.babylonOlympiaCompatible)) XCTAssertFalse(f(.babylon)) } - + func test_supports_babylon() { let f: (SUT) -> Bool = \.supportsBabylon - + XCTAssertFalse(f(.olympia)) XCTAssertTrue(f(.babylonOlympiaCompatible)) XCTAssertTrue(f(.babylon)) } } - diff --git a/apple/Tests/TestCases/Profile/Factor/FactorSourceIDFromAddressTests.swift b/apple/Tests/TestCases/Profile/Factor/FactorSourceIDFromAddressTests.swift index 64b51ad1a..1dd8b665a 100644 --- a/apple/Tests/TestCases/Profile/Factor/FactorSourceIDFromAddressTests.swift +++ b/apple/Tests/TestCases/Profile/Factor/FactorSourceIDFromAddressTests.swift @@ -5,15 +5,13 @@ import SargonUniFFI import XCTest final class FactorSourceIDFromAddressTests: SpecificFactorSourceIDTest { - func test_as_general() { XCTAssertEqual(SUT.sample.asGeneral, FactorSourceID.address(value: SUT.sample)) } - + func test_extract_wrong_throws() throws { try eachSample { sut in XCTAssertThrowsError(try sut.asGeneral.extract(as: FactorSourceIDFromHash.self)) } } } - diff --git a/apple/Tests/TestCases/Profile/Factor/FactorSourceIDFromHashTests.swift b/apple/Tests/TestCases/Profile/Factor/FactorSourceIDFromHashTests.swift index b3b6cdd38..6b2da4b64 100644 --- a/apple/Tests/TestCases/Profile/Factor/FactorSourceIDFromHashTests.swift +++ b/apple/Tests/TestCases/Profile/Factor/FactorSourceIDFromHashTests.swift @@ -5,11 +5,10 @@ import SargonUniFFI import XCTest final class FactorSourceIDFromHashTests: SpecificFactorSourceIDTest { - func test_as_general() { XCTAssertEqual(SUT.sample.asGeneral, FactorSourceID.hash(value: SUT.sample)) } - + func test_from_mnemonic_with_passphrase() { let sut = SUT( kind: .device, @@ -17,11 +16,10 @@ final class FactorSourceIDFromHashTests: SpecificFactorSourceIDTest { } } } - diff --git a/apple/Tests/TestCases/Profile/Factor/FactorSourceTests.swift b/apple/Tests/TestCases/Profile/Factor/FactorSourceTests.swift index 9e77ccdb5..5cb161137 100644 --- a/apple/Tests/TestCases/Profile/Factor/FactorSourceTests.swift +++ b/apple/Tests/TestCases/Profile/Factor/FactorSourceTests.swift @@ -5,26 +5,24 @@ import SargonUniFFI import XCTest final class FactorSourceTests: FactorSourceTest { - func test_factor_source_id() { XCTAssertEqual(SUT.sample.factorSourceID, SUT.sample.id) } - + func test_id_of_device() { XCTAssertEqual(SUT.sample.id.description, DeviceFactorSource.sample.id.description) } - + func test_as_general() { XCTAssertEqual(SUT.sample.asGeneral, SUT.sample) } - + func test_description() { XCTAssertEqual(SUT.sample.toString(), SUT.sample.description) } - + func test_factor_source_kind() { XCTAssertEqual(SUT.sample.factorSourceKind, .device) XCTAssertEqual(SUT.sampleOther.factorSourceKind, .ledgerHqHardwareWallet) } } - diff --git a/apple/Tests/TestCases/Profile/Factor/HierarchicalDeterministicFactorInstanceTests.swift b/apple/Tests/TestCases/Profile/Factor/HierarchicalDeterministicFactorInstanceTests.swift index 5e5c2215b..58d960350 100644 --- a/apple/Tests/TestCases/Profile/Factor/HierarchicalDeterministicFactorInstanceTests.swift +++ b/apple/Tests/TestCases/Profile/Factor/HierarchicalDeterministicFactorInstanceTests.swift @@ -5,19 +5,18 @@ import SargonUniFFI import XCTest final class HierarchicalDeterministicFactorInstanceTests: Test { - func test_factorSourceID() { eachSample { sut in XCTAssertEqual(sut.factorSourceID, sut.factorSourceId) } } - + func test_derivationPath() { eachSample { sut in XCTAssertEqual(sut.derivationPath, sut.publicKey.derivationPath) } } - + func test_factor_instance() { eachSample { sut in let factor = sut.factorInstance diff --git a/apple/Tests/TestCases/Profile/Factor/LedgerHardwareWalletFactorSourceTests.swift b/apple/Tests/TestCases/Profile/Factor/LedgerHardwareWalletFactorSourceTests.swift index 26139f859..607b74e36 100644 --- a/apple/Tests/TestCases/Profile/Factor/LedgerHardwareWalletFactorSourceTests.swift +++ b/apple/Tests/TestCases/Profile/Factor/LedgerHardwareWalletFactorSourceTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-15. -// - import CustomDump import Foundation import Sargon @@ -17,7 +10,7 @@ final class LedgerHardwareWalletFactorSourceTests: SpecificFactorSourceTest { - func test_new_babylon() { let sut = SUT.babylon(isMainBDFS: true, mnemonicWithPassphrase: .sample, hostInfo: .sample) XCTAssertTrue(sut.supportsBabylon) } - + func test_new_olympia() { let sut = SUT.olympia(mnemonicWithPassphrase: .sample, hostInfo: .sample) XCTAssertTrue(sut.supportsOlympia) } - + func test_kind_is_device() { XCTAssertEqual(SUT.olympia(mnemonicWithPassphrase: .sample, hostInfo: .sample).factorSourceKind, .device) XCTAssertEqual(SUT.babylon(isMainBDFS: true, mnemonicWithPassphrase: .sample, hostInfo: .sample).factorSourceKind, .device) } - + func test_is_main_bdfs_true() { let sut = SUT.babylon(isMainBDFS: true, mnemonicWithPassphrase: .sample, hostInfo: .sample) XCTAssertTrue(sut.factorSource.isMainBDFS) } - + func test_is_main_bdfs_false() { let sut = SUT.babylon(isMainBDFS: false, mnemonicWithPassphrase: .sample, hostInfo: .sample) XCTAssertFalse(sut.factorSource.isMainBDFS) diff --git a/apple/Tests/TestCases/Profile/Factor/SecurityQuestionsFactorSourceTests.swift b/apple/Tests/TestCases/Profile/Factor/SecurityQuestionsFactorSourceTests.swift index 77d6d7b54..da80e942a 100644 --- a/apple/Tests/TestCases/Profile/Factor/SecurityQuestionsFactorSourceTests.swift +++ b/apple/Tests/TestCases/Profile/Factor/SecurityQuestionsFactorSourceTests.swift @@ -5,13 +5,12 @@ import SargonUniFFI import XCTest final class SecurityQuestionsFactorSourceTests: SpecificFactorSourceTest { - func test_id_of_security_questions() { eachSample { sut in XCTAssertEqual(sut.id.description, FactorSourceID.hash(value: sut.id).description) } } - + func test_roundtrip() throws { let mnemonic = Mnemonic.sampleSecurityQuestions let qas = newSecurityNOTPRODUCTIONREADYQuestionsAndAnswersSample() @@ -22,8 +21,7 @@ final class SecurityQuestionsFactorSourceTests: SpecificFactorSourceTest { - func test_id_of_trusted_contact() { eachSample { sut in XCTAssertEqual(sut.id.description, FactorSourceID.address(value: sut.id).description) } } - + func test_new() { XCTAssertEqual( SUT(accountAddress: .sample, contact: .sample).id, SUT.sample.id ) } - + func test_as() { eachSample { sut in XCTAssertEqual(sut.asGeneral.asTrustedContact, sut) @@ -28,38 +27,37 @@ final class TrustedContactFactorSourceTests: SpecificFactorSourceTest { + func test_description_is_to_string() { + eachSample { sut in + XCTAssertEqual(sut.description, sut.toString()) + } + } - func test_description_is_to_string() { - eachSample { sut in - XCTAssertEqual(sut.description, sut.toString()) - } - } - - - func test_rawValue_is_to_string() { - eachSample { sut in - XCTAssertEqual(sut.rawValue, sut.toString()) - } - } - - func test_string_roundtrip() { - eachSample { sut in - XCTAssertEqual( - SUT(rawValue: sut.rawValue)!, - sut - ) - } - } + func test_rawValue_is_to_string() { + eachSample { sut in + XCTAssertEqual(sut.rawValue, sut.toString()) + } + } + + func test_string_roundtrip() { + eachSample { sut in + XCTAssertEqual( + SUT(rawValue: sut.rawValue)!, + sut + ) + } + } } diff --git a/apple/Tests/TestCases/Profile/FiatCurrencyTests.swift b/apple/Tests/TestCases/Profile/FiatCurrencyTests.swift index 522b99bf2..e244ce1cd 100644 --- a/apple/Tests/TestCases/Profile/FiatCurrencyTests.swift +++ b/apple/Tests/TestCases/Profile/FiatCurrencyTests.swift @@ -5,7 +5,6 @@ import SargonUniFFI import XCTest final class FiatCurrencyTests: Test { - func test_low_level_to_json_string() { let sut = SUT.sample let jsonString = fiatCurrencyToJsonString(fiatCurrency: sut) @@ -14,16 +13,16 @@ final class FiatCurrencyTests: Test { func test_codable() throws { let raw = "\"usd\"".data(using: .utf8)! - + // test decoding let sut = try JSONDecoder().decode(SUT.self, from: raw) XCTAssertEqual(sut, SUT.usd) - + // test encoding let encoded = try JSONEncoder().encode(sut) try XCTAssertEqual(JSONDecoder().decode(SUT.self, from: encoded), sut) } - + func test_wrapped_in_obj() throws { struct Wrapper: Codable, Equatable { let myString: String @@ -35,18 +34,18 @@ final class FiatCurrencyTests: Test { "sut": "usd" } """.data(using: .utf8)! - + let decoded = try JSONDecoder().decode(Wrapper.self, from: json) - XCTAssertEqual(decoded, Wrapper.init(myString: "Foo", sut: .usd)) + XCTAssertEqual(decoded, Wrapper(myString: "Foo", sut: .usd)) } - - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { try eachSampleCodableRoundtripTest() } - + func test_raw_value_roundtrip() { eachSample { sut in XCTAssertEqual(sut.rawValue, sut.jsonStringLiteral()) diff --git a/apple/Tests/TestCases/Profile/Gateways/GatewayTests.swift b/apple/Tests/TestCases/Profile/Gateways/GatewayTests.swift index 088c12ff1..6d98117eb 100644 --- a/apple/Tests/TestCases/Profile/Gateways/GatewayTests.swift +++ b/apple/Tests/TestCases/Profile/Gateways/GatewayTests.swift @@ -5,53 +5,51 @@ import SargonUniFFI import XCTest final class GatewayTests: Test { - func test_is_wellknown() { - XCTAssertTrue(SUT.mainnet.isWellknown) - XCTAssertTrue(SUT.stokenet.isWellknown) - XCTAssertFalse(SUT.forNetwork(id: .hammunet).isWellknown) - } - - func test_new_url_network_id() throws { - XCTAssertEqual( - SUT.mainnet, - try SUT( - url: "https://mainnet.radixdlt.com", - networkID: .mainnet - ) - ) - } - - func test_id() throws { - XCTAssertEqual(SUT.sample.id, SUT.sample.getID()) - } - - func test_description() throws { - XCTAssertEqual(SUT.sample.description, SUT.sample.toString()) - } - - func test_network_id_of_nebunet() { - XCTAssertEqual(SUT.nebunet.networkID, .nebunet) - } - - func test_network_id_of_kisharnet() { - XCTAssertEqual(SUT.kisharnet.networkID, .kisharnet) - } - - func test_network_id_of_ansharnet() { - XCTAssertEqual(SUT.ansharnet.networkID, .ansharnet) - } - - func test_network_id_of_hammunet() { - XCTAssertEqual(SUT.hammunet.networkID, .hammunet) - } - - func test_network_id_of_enkinet() { - XCTAssertEqual(SUT.enkinet.networkID, .enkinet) - } - - func test_network_id_of_mardunet() { - XCTAssertEqual(SUT.mardunet.networkID, .mardunet) - } - - + func test_is_wellknown() { + XCTAssertTrue(SUT.mainnet.isWellknown) + XCTAssertTrue(SUT.stokenet.isWellknown) + XCTAssertFalse(SUT.forNetwork(id: .hammunet).isWellknown) + } + + func test_new_url_network_id() throws { + XCTAssertEqual( + SUT.mainnet, + try SUT( + url: "https://mainnet.radixdlt.com", + networkID: .mainnet + ) + ) + } + + func test_id() throws { + XCTAssertEqual(SUT.sample.id, SUT.sample.getID()) + } + + func test_description() throws { + XCTAssertEqual(SUT.sample.description, SUT.sample.toString()) + } + + func test_network_id_of_nebunet() { + XCTAssertEqual(SUT.nebunet.networkID, .nebunet) + } + + func test_network_id_of_kisharnet() { + XCTAssertEqual(SUT.kisharnet.networkID, .kisharnet) + } + + func test_network_id_of_ansharnet() { + XCTAssertEqual(SUT.ansharnet.networkID, .ansharnet) + } + + func test_network_id_of_hammunet() { + XCTAssertEqual(SUT.hammunet.networkID, .hammunet) + } + + func test_network_id_of_enkinet() { + XCTAssertEqual(SUT.enkinet.networkID, .enkinet) + } + + func test_network_id_of_mardunet() { + XCTAssertEqual(SUT.mardunet.networkID, .mardunet) + } } diff --git a/apple/Tests/TestCases/Profile/Gateways/SavedGatewaysTests.swift b/apple/Tests/TestCases/Profile/Gateways/SavedGatewaysTests.swift index 9dd1e437a..9f5800888 100644 --- a/apple/Tests/TestCases/Profile/Gateways/SavedGatewaysTests.swift +++ b/apple/Tests/TestCases/Profile/Gateways/SavedGatewaysTests.swift @@ -8,23 +8,23 @@ final class SavedGatewaysTests: Test { func test_preset_is_default() { XCTAssertEqual(SUT.preset, SUT.default) } - + func test_init_current_other() { XCTAssertEqual(SUT(current: Gateway.mainnet, other: [Gateway.stokenet]), SUT.preset) } - + func test_init_current_only() { let sut = SUT(current: Gateway.mainnet) XCTAssertEqual(sut.current, .mainnet) XCTAssertEqual(sut.other, []) } - + func test_change_current_to() throws { var sut = SUT(current: .stokenet, other: [.mainnet]) try sut.changeCurrent(to: .mainnet) XCTAssertEqual(sut, .preset) } - + func test_all() { XCTAssertEqual(SUT.preset.all, [.mainnet, .stokenet]) } diff --git a/apple/Tests/TestCases/Profile/HeaderTests.swift b/apple/Tests/TestCases/Profile/HeaderTests.swift index b599c24f9..d462b9cfe 100644 --- a/apple/Tests/TestCases/Profile/HeaderTests.swift +++ b/apple/Tests/TestCases/Profile/HeaderTests.swift @@ -5,8 +5,7 @@ import SargonUniFFI import XCTest final class HeaderTests: Test
{ - - func test_not_codable_but_lower_level_json_methods_json_data_roundtrip() throws{ + func test_not_codable_but_lower_level_json_methods_json_data_roundtrip() throws { let sut = SUT.sample let json = sut.jsonData() try XCTAssertEqual( @@ -14,7 +13,7 @@ final class HeaderTests: Test
{ sut ) } - + func test_codable() throws { let raw = """ { @@ -38,75 +37,75 @@ final class HeaderTests: Test
{ } } """.data(using: .utf8)! - + // test decoding let sut = try JSONDecoder().decode(SUT.self, from: raw) XCTAssertEqual(sut, SUT.sample) - + // test encoding let encoded = try JSONEncoder().encode(sut) try XCTAssertEqual(JSONDecoder().decode(SUT.self, from: encoded), sut) } - - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { try eachSampleCodableRoundtripTest() } - - func test_header_list_codable() throws { - let raw = """ - [ - { - "snapshotVersion": 100, - "id": "12345678-bbbb-cccc-dddd-abcd12345678", - "creatingDevice": { - "id": "66f07ca2-a9d9-49e5-8152-77aca3d1dd74", - "date": "2023-09-11T16:05:56.000Z", - "description": "iPhone (iPhone)" - }, - "lastUsedOnDevice": { - "id": "66f07ca2-a9d9-49e5-8152-77aca3d1dd74", - "date": "2023-09-11T16:05:56.000Z", - "description": "iPhone (iPhone)" - }, - "lastModified": "2023-09-11T16:05:56.000Z", - "contentHint": { - "numberOfAccountsOnAllNetworksInTotal": 4, - "numberOfPersonasOnAllNetworksInTotal": 0, - "numberOfNetworks": 2 - } - }, - { - "lastUsedOnDevice" : { - "date" : "2023-12-24T17:13:56.123Z", - "description" : "Android (Android)", - "id" : "F07CA662-D9A9-9E45-1582-ACA773D174DD" - }, - "id" : "87654321-bbbb-cccc-dddd-87654321dcba", - "contentHint" : { - "numberOfNetworks" : 0, - "numberOfAccountsOnAllNetworksInTotal" : 0, - "numberOfPersonasOnAllNetworksInTotal" : 0 - }, - "creatingDevice" : { - "description" : "Android (Android)", - "id" : "F07CA662-D9A9-9E45-1582-ACA773D174DD", - "date" : "2023-12-24T17:13:56.123Z" - }, - "snapshotVersion" : 100, - "lastModified" : "2023-12-24T17:13:56.123Z" - } - ] - """.data(using: .utf8)! - - // test decoding - let headerList = try JSONDecoder().decode([SUT].self, from: raw) - XCTAssertNoDifference(headerList, [SUT.sample, SUT.sampleOther]) - - // test encoding - let encoded = try JSONEncoder().encode(headerList) - try XCTAssertEqual(JSONDecoder().decode([SUT].self, from: encoded), headerList) - } + + func test_header_list_codable() throws { + let raw = """ + [ + { + "snapshotVersion": 100, + "id": "12345678-bbbb-cccc-dddd-abcd12345678", + "creatingDevice": { + "id": "66f07ca2-a9d9-49e5-8152-77aca3d1dd74", + "date": "2023-09-11T16:05:56.000Z", + "description": "iPhone (iPhone)" + }, + "lastUsedOnDevice": { + "id": "66f07ca2-a9d9-49e5-8152-77aca3d1dd74", + "date": "2023-09-11T16:05:56.000Z", + "description": "iPhone (iPhone)" + }, + "lastModified": "2023-09-11T16:05:56.000Z", + "contentHint": { + "numberOfAccountsOnAllNetworksInTotal": 4, + "numberOfPersonasOnAllNetworksInTotal": 0, + "numberOfNetworks": 2 + } + }, + { + "lastUsedOnDevice" : { + "date" : "2023-12-24T17:13:56.123Z", + "description" : "Android (Android)", + "id" : "F07CA662-D9A9-9E45-1582-ACA773D174DD" + }, + "id" : "87654321-bbbb-cccc-dddd-87654321dcba", + "contentHint" : { + "numberOfNetworks" : 0, + "numberOfAccountsOnAllNetworksInTotal" : 0, + "numberOfPersonasOnAllNetworksInTotal" : 0 + }, + "creatingDevice" : { + "description" : "Android (Android)", + "id" : "F07CA662-D9A9-9E45-1582-ACA773D174DD", + "date" : "2023-12-24T17:13:56.123Z" + }, + "snapshotVersion" : 100, + "lastModified" : "2023-12-24T17:13:56.123Z" + } + ] + """.data(using: .utf8)! + + // test decoding + let headerList = try JSONDecoder().decode([SUT].self, from: raw) + XCTAssertNoDifference(headerList, [SUT.sample, SUT.sampleOther]) + + // test encoding + let encoded = try JSONEncoder().encode(headerList) + try XCTAssertEqual(JSONDecoder().decode([SUT].self, from: encoded), headerList) + } } diff --git a/apple/Tests/TestCases/Profile/LedgerHardwareWalletModelTests.swift b/apple/Tests/TestCases/Profile/LedgerHardwareWalletModelTests.swift index 315dae1cc..ade408660 100644 --- a/apple/Tests/TestCases/Profile/LedgerHardwareWalletModelTests.swift +++ b/apple/Tests/TestCases/Profile/LedgerHardwareWalletModelTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-22. -// - import CustomDump import Foundation import Sargon @@ -12,27 +5,24 @@ import SargonUniFFI import XCTest final class LedgerHardwareWalletModelTests: Test { + func test_description_is_to_string() { + eachSample { sut in + XCTAssertEqual(sut.description, sut.toString()) + } + } + + func test_rawValue_is_to_string() { + eachSample { sut in + XCTAssertEqual(sut.rawValue, sut.toString()) + } + } - func test_description_is_to_string() { - eachSample { sut in - XCTAssertEqual(sut.description, sut.toString()) - } - } - - - func test_rawValue_is_to_string() { - eachSample { sut in - XCTAssertEqual(sut.rawValue, sut.toString()) - } - } - - - func test_string_roundtrip() throws { - try eachSample { sut in - XCTAssertEqual( - try SUT(string: sut.rawValue), - sut - ) - } - } + func test_string_roundtrip() throws { + try eachSample { sut in + XCTAssertEqual( + try SUT(string: sut.rawValue), + sut + ) + } + } } diff --git a/apple/Tests/TestCases/Profile/MFA/MatrixOfFactorSourcesTests.swift b/apple/Tests/TestCases/Profile/MFA/MatrixOfFactorSourcesTests.swift index 4662a15be..42c6165db 100644 --- a/apple/Tests/TestCases/Profile/MFA/MatrixOfFactorSourcesTests.swift +++ b/apple/Tests/TestCases/Profile/MFA/MatrixOfFactorSourcesTests.swift @@ -4,5 +4,4 @@ import Sargon import SargonUniFFI import XCTest -final class MatrixOfFactorSourcesTests: Test { -} +final class MatrixOfFactorSourcesTests: Test {} diff --git a/apple/Tests/TestCases/Profile/MFA/SecurityStructureMetadataTests.swift b/apple/Tests/TestCases/Profile/MFA/SecurityStructureMetadataTests.swift index 57f8564fa..0eb07dd9c 100644 --- a/apple/Tests/TestCases/Profile/MFA/SecurityStructureMetadataTests.swift +++ b/apple/Tests/TestCases/Profile/MFA/SecurityStructureMetadataTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-06. -// - import CustomDump import Foundation import Sargon @@ -12,8 +5,8 @@ import SargonUniFFI import XCTest final class SecurityStructureMetadataTests: Test { - func test_new_with_name() { - let sut = SUT.init(name: "foo") - XCTAssertEqual(sut.displayName, "foo") - } + func test_new_with_name() { + let sut = SUT(name: "foo") + XCTAssertEqual(sut.displayName, "foo") + } } diff --git a/apple/Tests/TestCases/Profile/MFA/SecurityStructureOfFactorSourcesTests.swift b/apple/Tests/TestCases/Profile/MFA/SecurityStructureOfFactorSourcesTests.swift index 3f75c6c07..00ce01cdf 100644 --- a/apple/Tests/TestCases/Profile/MFA/SecurityStructureOfFactorSourcesTests.swift +++ b/apple/Tests/TestCases/Profile/MFA/SecurityStructureOfFactorSourcesTests.swift @@ -5,18 +5,17 @@ import SargonUniFFI import XCTest final class SecurityStructureOfFactorSourcesTests: Test { - - func test_new_from_auto_in_days() { - let sut = SUT( - metadata: .sample, - numberOfDaysUntilAutoConfirmation: 10, - matrixOfFactors: .sample - ) - XCTAssertEqual(sut.numberOfEpochsUntilAutoConfirmation, 2880) - XCTAssertEqual(sut.metadata, .sample) - XCTAssertEqual(sut.matrixOfFactors, .sample) - } - + func test_new_from_auto_in_days() { + let sut = SUT( + metadata: .sample, + numberOfDaysUntilAutoConfirmation: 10, + matrixOfFactors: .sample + ) + XCTAssertEqual(sut.numberOfEpochsUntilAutoConfirmation, 2880) + XCTAssertEqual(sut.metadata, .sample) + XCTAssertEqual(sut.matrixOfFactors, .sample) + } + func test_id() { eachSample { sut in XCTAssertEqual(sut.id, sut.metadata.id) diff --git a/apple/Tests/TestCases/Profile/NetworkDefinitionTests.swift b/apple/Tests/TestCases/Profile/NetworkDefinitionTests.swift index fa19b03ba..07b48f398 100644 --- a/apple/Tests/TestCases/Profile/NetworkDefinitionTests.swift +++ b/apple/Tests/TestCases/Profile/NetworkDefinitionTests.swift @@ -11,7 +11,7 @@ final class NetworkDefinitionTests: Test { .mainnet ) } - + func test_lookup_stokenet() throws { try XCTAssertEqual( NetworkDefinition.lookupBy(logicalName: "stokenet").id, diff --git a/apple/Tests/TestCases/Profile/Persona/PersonaData/AnyIdentifiedPersonaEntryTests.swift b/apple/Tests/TestCases/Profile/Persona/PersonaData/AnyIdentifiedPersonaEntryTests.swift index 3231c0e1d..b8fb3aae2 100644 --- a/apple/Tests/TestCases/Profile/Persona/PersonaData/AnyIdentifiedPersonaEntryTests.swift +++ b/apple/Tests/TestCases/Profile/Persona/PersonaData/AnyIdentifiedPersonaEntryTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import CustomDump import Foundation import Sargon @@ -12,14 +5,13 @@ import SargonUniFFI import XCTest final class AnyIdentifiedPersonaEntryTests: Test { - func test_PersonaDataIdentifiedEntry_description() { let number = "123456789" let sut = SUT( id: 1, value: PersonaData.PhoneNumber(number: number).embed() ) - + XCTAssertNoDifference( sut.description, """ diff --git a/apple/Tests/TestCases/Profile/Persona/PersonaData/AuthorizedPersonaSimpleTests.swift b/apple/Tests/TestCases/Profile/Persona/PersonaData/AuthorizedPersonaSimpleTests.swift index bced45d5a..f1b044e28 100644 --- a/apple/Tests/TestCases/Profile/Persona/PersonaData/AuthorizedPersonaSimpleTests.swift +++ b/apple/Tests/TestCases/Profile/Persona/PersonaData/AuthorizedPersonaSimpleTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - import CustomDump import Foundation import Sargon @@ -13,10 +6,10 @@ import XCTest final class AuthorizedPersonaSimpleTests: Test { func test_network_ids_mainnet() { - XCTAssertTrue(SUT.sampleValuesMainnet.allSatisfy({ $0.networkID == .mainnet })) + XCTAssertTrue(SUT.sampleValuesMainnet.allSatisfy { $0.networkID == .mainnet }) } - + func test_network_ids_stokenet() { - XCTAssertTrue(SUT.sampleValuesStokenet.allSatisfy({ $0.networkID == .stokenet })) + XCTAssertTrue(SUT.sampleValuesStokenet.allSatisfy { $0.networkID == .stokenet }) } } diff --git a/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataEntryEmailAddressTests.swift b/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataEntryEmailAddressTests.swift index 114483394..b27e349fc 100644 --- a/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataEntryEmailAddressTests.swift +++ b/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataEntryEmailAddressTests.swift @@ -1,11 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - - import CustomDump import Foundation import Sargon @@ -13,14 +5,13 @@ import SargonUniFFI import XCTest final class PersonaDataEntryEmailAddressTests: PersonaDataEntryTest { - func test_kind() { XCTAssertEqual(SUT.kind, .emailAddress) eachSample { sut in XCTAssertEqual(sut.kind, .emailAddress) } } - + func test_extract_wrong_is_nil() { XCTAssertNil(SUT.extract(from: PersonaDataEntryPhoneNumber.sample.embed())) } diff --git a/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataEntryNameTests.swift b/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataEntryNameTests.swift index 1857a7612..43f17af2e 100644 --- a/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataEntryNameTests.swift +++ b/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataEntryNameTests.swift @@ -1,11 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - - import CustomDump import Foundation import Sargon @@ -13,22 +5,21 @@ import SargonUniFFI import XCTest final class PersonaDataEntryNameTests: PersonaDataEntryTest { - func test_kind() { XCTAssertEqual(SUT.kind, .fullName) eachSample { sut in XCTAssertEqual(sut.kind, .fullName) } } - + func test_extract_wrong_is_nil() { XCTAssertNil(SUT.extract(from: PersonaDataEntryEmailAddress.sample.embed())) } - + func test_variants() { XCTAssertEqual(SUT.Variant.allCases, [.eastern, .western]) } - + func test_formatted_eastern() { XCTAssertNoDifference( SUT.sampleOther.description, @@ -38,7 +29,7 @@ final class PersonaDataEntryNameTests: PersonaDataEntryTest { - func test_kind() { XCTAssertEqual(SUT.kind, .phoneNumber) eachSample { sut in XCTAssertEqual(sut.kind, .phoneNumber) } } - + func test_extract_wrong_is_nil() { XCTAssertNil(SUT.extract(from: PersonaDataEntryName.sample.embed())) } - } diff --git a/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataEntryTests.swift b/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataEntryTests.swift index b6e2902d9..e9de69e1b 100644 --- a/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataEntryTests.swift +++ b/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataEntryTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import CustomDump import Foundation import Sargon @@ -17,25 +10,25 @@ final class PersonaDataEntryTests: Test { XCTAssertEqual(SUT.emailAddress(.sample).discriminator, .emailAddress) XCTAssertEqual(SUT.phoneNumber(.sample).discriminator, .phoneNumber) } - + func test_codable_roundtrip() throws { try SUT.sampleValues.forEach(doTestCodableRoundtrip) } - + func test_embed_extract_name() throws { let value: PersonaDataEntryName = .sample let sut: SUT = value.embed() try XCTAssertEqual(sut.extract(), value) XCTAssertThrowsError(try sut.extract(as: PersonaDataEntryPhoneNumber.self)) } - + func test_embed_extract_email() throws { let value: PersonaDataEntryEmailAddress = .sample let sut: SUT = value.embed() try XCTAssertEqual(sut.extract(), value) XCTAssertThrowsError(try sut.extract(as: PersonaDataEntryName.self)) } - + func test_embed_extract_phone() throws { let value: PersonaDataEntryPhoneNumber = .sample let sut: SUT = value.embed() diff --git a/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataTests.swift b/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataTests.swift index 6705784d2..da5887939 100644 --- a/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataTests.swift +++ b/apple/Tests/TestCases/Profile/Persona/PersonaData/PersonaDataTests.swift @@ -1,11 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - - import CustomDump import Foundation import Sargon @@ -13,7 +5,6 @@ import SargonUniFFI import XCTest final class PersonaDataTests: Test { - func test_entries() { XCTAssertEqual( SUT.sample.entries, @@ -26,9 +17,8 @@ final class PersonaDataTests: Test { ] ) } - + func test_default_is_empty() { - XCTAssertEqual(SUT.default, SUT.init()) + XCTAssertEqual(SUT.default, SUT()) } - } diff --git a/apple/Tests/TestCases/Profile/Persona/PersonaData/SharedPersonaDataTests.swift b/apple/Tests/TestCases/Profile/Persona/PersonaData/SharedPersonaDataTests.swift index 0ee082e45..6a5796ef4 100644 --- a/apple/Tests/TestCases/Profile/Persona/PersonaData/SharedPersonaDataTests.swift +++ b/apple/Tests/TestCases/Profile/Persona/PersonaData/SharedPersonaDataTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import CustomDump import Foundation import Sargon @@ -18,11 +11,11 @@ final class SharedPersonaDataTests: Test { [0, 1, 2, 3, 4] ) } - + func test_entryIDs_empty() { XCTAssertEqual(SUT.default.entryIDs, []) } - + func test_default_is_empty() { XCTAssertEqual( SUT.default, @@ -34,4 +27,3 @@ final class SharedPersonaDataTests: Test { ) } } - diff --git a/apple/Tests/TestCases/Profile/Persona/PersonaTests.swift b/apple/Tests/TestCases/Profile/Persona/PersonaTests.swift index 49b78cdc8..b9d37ce84 100644 --- a/apple/Tests/TestCases/Profile/Persona/PersonaTests.swift +++ b/apple/Tests/TestCases/Profile/Persona/PersonaTests.swift @@ -5,38 +5,37 @@ import SargonUniFFI import XCTest final class PersonaTests: EntityProtocolTest { - func test_extract_wrong_throws() throws { try eachSample { sut in XCTAssertThrowsError(try sut.asGeneral.extract(as: Account.self)) } } - + func test_as_general_as_account() throws { try eachSample { sut in XCTAssertEqual(try sut.asGeneral.asPersona(), sut) } } - + func test_display_names() { XCTAssertEqual( SUT.sampleValues.map(\.displayName), ["Satoshi", "Batman", "Ellen Ripley", "Skywalker", "Granger", "Sarah Connor"] ) } - + func test_not_hidden() { XCTAssertEqual(SUT.sampleMainnet.flags, []) } - + func test_hidden() { let sut = SUT.sampleMainnetTuring.flags XCTAssertEqual(sut, [.hiddenByUser]) } - + func test_new() { let fi: HierarchicalDeterministicFactorInstance = .sample - let sut = SUT.init(networkID: .sample, factorInstance: fi, displayName: .sample, extraProperties: .sample) + let sut = SUT(networkID: .sample, factorInstance: fi, displayName: .sample, extraProperties: .sample) XCTAssertEqual(sut.virtualHierarchicalDeterministicFactorInstances, [fi]) } } diff --git a/apple/Tests/TestCases/Profile/ProfileTests.swift b/apple/Tests/TestCases/Profile/ProfileTests.swift index 0c9be2367..366c6b18a 100644 --- a/apple/Tests/TestCases/Profile/ProfileTests.swift +++ b/apple/Tests/TestCases/Profile/ProfileTests.swift @@ -5,10 +5,9 @@ import SargonUniFFI import XCTest final class ProfileTests: Test { - - func test_description_and_debug() { - XCTAssertGreaterThan(SUT.sample.debugDescription, SUT.sample.description) - } + func test_description_and_debug() { + XCTAssertGreaterThan(SUT.sample.debugDescription, SUT.sample.description) + } func test_profile_description_equals() throws { XCTAssertNoDifference(SUT.sample.description, SUT.sample.description) @@ -17,7 +16,8 @@ final class ProfileTests: Test { func test_debug_description_equals() throws { XCTAssertNoDifference(SUT.sample.debugDescription, SUT.sample.debugDescription) XCTAssertNoDifference( - SUT.sampleOther.debugDescription, SUT.sampleOther.debugDescription) + SUT.sampleOther.debugDescription, SUT.sampleOther.debugDescription + ) } func test_id_is_header_id() { @@ -36,7 +36,7 @@ final class ProfileTests: Test { ) XCTAssertNoDifference(decrypted, sut) } - + func test_encryption_roundtrip_string() throws { let password = "ultra secret" let sut = SUT.sample @@ -73,15 +73,14 @@ final class ProfileTests: Test { } var vectors = Array(zip(SUT.sampleValues, SUT.sampleValues.map { $0.toJSONString() })) vectors.append(vector) - + vectors.forEach(doTest) } func test_analyze_file_encrypted_profile() { - var vectors = SUT.sampleValues vectors.append(vector.model) - + let passwords = ["Mellon", "open sesame", "REINDEER FLOTILLA", "swordfish"] func doTest(_ index: Int, _ sut: SUT) { let password = passwords[index % passwords.count] @@ -91,7 +90,7 @@ final class ProfileTests: Test { .encryptedProfile ) } - + vectors.enumerated().forEach(doTest) } @@ -102,7 +101,7 @@ final class ProfileTests: Test { XCTAssertTrue(jsonString.contains("encryptedSnapshot")) XCTAssertTrue(jsonString.contains("version")) } - + func test_json_roundtrip() throws { func doTest(_ sut: SUT, _ json: String) throws { let encoded = sut.toJSONString(prettyPrinted: false) @@ -116,8 +115,7 @@ final class ProfileTests: Test { // vectors.append(vector) try vectors.forEach(doTest) } - - + // Macbook Pro M2: 0.06 (10x speedup vs BagOfBytes) func test_performance_json_encoding_string() throws { let (sut, _) = vector @@ -125,7 +123,7 @@ final class ProfileTests: Test { let _ = sut.toJSONString() } } - + // Macbook Pro M2: 0.1 (2.5x speedup vs BagOfBytes) func test_performance_json_decoding_string() throws { let (_, jsonString) = vector @@ -133,22 +131,20 @@ final class ProfileTests: Test { let _ = try! SUT(jsonString: jsonString) } } - - lazy var vector: (model: Profile, jsonString: String) = { - try! jsonString( - as: SUT.self, - file: "huge_profile_1000_accounts", - decode: { try Profile(jsonString: $0) } - ) - }() - func test_check_if_profile_json_contains_legacy_p2p_links_when_p2p_links_are_not_present() { + lazy var vector: (model: Profile, jsonString: String) = try! jsonString( + as: SUT.self, + file: "huge_profile_1000_accounts", + decode: { try Profile(jsonString: $0) } + ) + + func test_check_if_profile_json_contains_legacy_p2p_links_when_p2p_links_are_not_present() { eachSample { sut in XCTAssertFalse( SUT.checkIfProfileJsonStringContainsLegacyP2PLinks(jsonString: sut.toJSONString()) ) } - } + } func test_check_if_profile_json_contains_legacy_p2p_links_when_p2p_links_are_present() throws { let json = try openFile(subPath: "vector", "only_plaintext_profile_snapshot_version_100", extension: "json") @@ -169,7 +165,7 @@ final class ProfileTests: Test { SUT.checkIfEncryptedProfileJsonContainsLegacyP2PLinks(contents: json, password: "babylon") ) } - + func test_check_if_encrypted_profile_json_string_contains_legacy_p2p_links_when_p2p_links_are_present() throws { let json = try openFile(subPath: "vector", "profile_encrypted_by_password_of_babylon", extension: "json") let jsonString = try XCTUnwrap(String(data: json, encoding: .utf8)) diff --git a/apple/Tests/TestCases/Profile/ResourceOrNonFungibleTests.swift b/apple/Tests/TestCases/Profile/ResourceOrNonFungibleTests.swift index 72d989b6e..f0957bfe9 100644 --- a/apple/Tests/TestCases/Profile/ResourceOrNonFungibleTests.swift +++ b/apple/Tests/TestCases/Profile/ResourceOrNonFungibleTests.swift @@ -10,12 +10,14 @@ final class ResourceOrNonFungibleTests: Test { let sut = SUT.resource(value: resourceAddress) XCTAssertEqual(sut.resourceAddress, resourceAddress) } + func test_resource_address_non_fungible() { let resourceAddress = NonFungibleResourceAddress.sample.asResourceAddress let globalID = NonFungibleGlobalID(resourceAddress: resourceAddress, nonFungibleLocalId: 1) let sut = SUT.nonFungible(value: globalID) XCTAssertEqual(sut.resourceAddress, resourceAddress) } + func test_id_is_self() { eachSample { sut in XCTAssertEqual(sut.id, sut) diff --git a/apple/Tests/TestCases/Profile/ResourcePreferencesTests.swift b/apple/Tests/TestCases/Profile/ResourcePreferencesTests.swift index 486c956a6..c5b60292a 100644 --- a/apple/Tests/TestCases/Profile/ResourcePreferencesTests.swift +++ b/apple/Tests/TestCases/Profile/ResourcePreferencesTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Matias Bzurovski on 13/8/24. -// - import CustomDump import Foundation import Sargon @@ -15,16 +8,16 @@ final class AssetPreferencesTests: TestCase { func test_hidden_resources() { var sut: [ResourceAppPreference] = [] XCTAssertTrue(sut.hiddenResources.isEmpty) - + // Hide assets sut.hideResource(resource: .fungible(.sample)) sut.hideResource(resource: .nonFungible(.sample)) sut.hideResource(resource: .fungible(.sampleOther)) - + XCTAssertEqual(sut.hiddenResources, [.fungible(.sample), .nonFungible(.sample), .fungible(.sampleOther)]) - + // Unhide assets - sut.unhideResource(resource: .fungible(.sampleOther)) + sut.unhideResource(resource: .fungible(.sampleOther)) sut.unhideResource(resource: .nonFungible(.sample)) XCTAssertEqual(sut.hiddenResources, [.fungible(.sample)]) } diff --git a/apple/Tests/TestCases/Profile/UnsecuredEntityControlTests.swift b/apple/Tests/TestCases/Profile/UnsecuredEntityControlTests.swift index 89cd2e5de..409b9393b 100644 --- a/apple/Tests/TestCases/Profile/UnsecuredEntityControlTests.swift +++ b/apple/Tests/TestCases/Profile/UnsecuredEntityControlTests.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-27. -// - import CustomDump import Foundation import Sargon @@ -12,4 +5,3 @@ import SargonUniFFI import XCTest final class UnsecuredEntityControlTests: Test {} - diff --git a/apple/Tests/TestCases/RET/BlobTest.swift b/apple/Tests/TestCases/RET/BlobTest.swift index 172dbd85c..7eac1e64d 100644 --- a/apple/Tests/TestCases/RET/BlobTest.swift +++ b/apple/Tests/TestCases/RET/BlobTest.swift @@ -1,7 +1,6 @@ -@testable import Sargon import CustomDump import Foundation -import Sargon +@testable import Sargon import SargonUniFFI import XCTest diff --git a/apple/Tests/TestCases/RET/BlobsTests.swift b/apple/Tests/TestCases/RET/BlobsTests.swift index 48ec50c5a..0e4a4de55 100644 --- a/apple/Tests/TestCases/RET/BlobsTests.swift +++ b/apple/Tests/TestCases/RET/BlobsTests.swift @@ -5,14 +5,15 @@ import SargonUniFFI import XCTest final class BlobsTests: Test { - func test_blobs() { - XCTAssertEqual( - SUT.sample.blobs, - [ - Blob(data: Data.sampleAced), - Blob(data: Data.sampleBabe), - Blob(data: Data.sampleCafe), - Blob(data: Data.sampleDead) - ]) - } + func test_blobs() { + XCTAssertEqual( + SUT.sample.blobs, + [ + Blob(data: Data.sampleAced), + Blob(data: Data.sampleBabe), + Blob(data: Data.sampleCafe), + Blob(data: Data.sampleDead), + ] + ) + } } diff --git a/apple/Tests/TestCases/RET/IntentSignatureTests.swift b/apple/Tests/TestCases/RET/IntentSignatureTests.swift index 25a74d7e3..84caa32c5 100644 --- a/apple/Tests/TestCases/RET/IntentSignatureTests.swift +++ b/apple/Tests/TestCases/RET/IntentSignatureTests.swift @@ -5,11 +5,11 @@ import SargonUniFFI import XCTest final class IntentSignatureTests: Test { - func test_get_signature_with_public_key() { - let signature = SignatureWithPublicKey.sample - XCTAssertEqual( - SUT(signatureWithPublicKey: signature).signatureWithPublicKey, - signature - ) - } + func test_get_signature_with_public_key() { + let signature = SignatureWithPublicKey.sample + XCTAssertEqual( + SUT(signatureWithPublicKey: signature).signatureWithPublicKey, + signature + ) + } } diff --git a/apple/Tests/TestCases/RET/ManifestBuilding/ManifestBuildingTests.swift b/apple/Tests/TestCases/RET/ManifestBuilding/ManifestBuildingTests.swift index a629a1528..defed944c 100644 --- a/apple/Tests/TestCases/RET/ManifestBuilding/ManifestBuildingTests.swift +++ b/apple/Tests/TestCases/RET/ManifestBuilding/ManifestBuildingTests.swift @@ -1,5 +1,5 @@ -@testable import Sargon import RegexBuilder +@testable import Sargon import CustomDump import Foundation @@ -7,124 +7,119 @@ import Sargon import SargonUniFFI import XCTest +// MARK: - ManifestBuildingTests final class ManifestBuildingTests: Test { - func test_manifest_for_faucet_with_lock_fee() { - - let manifest = SUT.faucet( + let manifest = SUT.faucet( includeLockFeeInstruction: true, addressOfReceivingAccount: AccountAddress.sample ) - + XCTAssert(manifest.description.contains("CALL_METHOD")) XCTAssert(manifest.description.contains(AccountAddress.sample.description)) XCTAssert(manifest.description.contains("lock_fee")) } func test_manifest_for_faucet_without_lock_fee() { - - let manifest = SUT.faucet( + let manifest = SUT.faucet( includeLockFeeInstruction: false, addressOfReceivingAccount: AccountAddress.sampleOther ) - + XCTAssert(manifest.description.contains("CALL_METHOD")) XCTAssert(manifest.description.contains(AccountAddress.sampleOther.description)) XCTAssertFalse(manifest.description.contains("lock_fee")) } - - + func test_manifest_marking_account_as_dapp_definition_type() { func doTest(_ accountAddress: AccountAddress) { - let manifest = SUT.markingAccountAsDappDefinitionType(accountAddress: accountAddress) + let manifest = SUT.markingAccountAsDappDefinitionType(accountAddress: accountAddress) XCTAssert(manifest.description.contains(accountAddress.description)) XCTAssert(manifest.description.contains("SET_METADATA")) XCTAssert(manifest.description.contains("dapp definition")) } AccountAddress.sampleValues.forEach(doTest) } - - - func test_manifest_set_owner_keys_hashes() { - func doTest(_ address: AddressOfAccountOrPersona, keyHashes: [PublicKeyHash]) { - let manifest = SUT.setOwnerKeys(addressOfAccountOrPersona: address, ownerKeyHashes: keyHashes) - XCTAssert(manifest.description.contains(address.description)) - XCTAssert(manifest.description.contains("SET_METADATA")) - XCTAssert(manifest.description.contains("owner_keys")) - } - - AddressOfAccountOrPersona.sampleValues.forEach { - doTest($0, keyHashes: [.sample]) - doTest($0, keyHashes: [.sample, .sampleOther]) - doTest($0, keyHashes: [.sampleOther]) - } - } - - func test_create_single_fungible_token_with_metadata() { - func doTest(_ accountAddress: AccountAddress) { - let metadata = TokenDefinitionMetadata( - name: UUID().uuidString, - description: UUID().uuidString, - symbol: UUID().uuidString, - iconUrl: "https://example.com", - tags: ["swift test"] - ) - let initialSupply: Decimal192 = .pi - let manifest = SUT.createFungibleTokenWithMetadata( - addressOfOwner: accountAddress, - initialSupply: initialSupply, - metadata: metadata - ) - func oneOf(_ needle: String, line: UInt = #line) { - XCTAssertEqual(manifest.description.ranges(of: needle).count, 1, line: line) - } - func oneIn(metadata keyPath: KeyPath, line: UInt = #line) { - let property = metadata[keyPath: keyPath] - oneOf(property.description, line: line) - } - oneIn(metadata: \.name) - oneIn(metadata: \.description) - oneIn(metadata: \.symbol) - oneOf(initialSupply.formattedPlain(locale: .test)) - } + + func test_manifest_set_owner_keys_hashes() { + func doTest(_ address: AddressOfAccountOrPersona, keyHashes: [PublicKeyHash]) { + let manifest = SUT.setOwnerKeys(addressOfAccountOrPersona: address, ownerKeyHashes: keyHashes) + XCTAssert(manifest.description.contains(address.description)) + XCTAssert(manifest.description.contains("SET_METADATA")) + XCTAssert(manifest.description.contains("owner_keys")) + } + + for sampleValue in AddressOfAccountOrPersona.sampleValues { + doTest(sampleValue, keyHashes: [.sample]) + doTest(sampleValue, keyHashes: [.sample, .sampleOther]) + doTest(sampleValue, keyHashes: [.sampleOther]) + } + } + + func test_create_single_fungible_token_with_metadata() { + func doTest(_ accountAddress: AccountAddress) { + let metadata = TokenDefinitionMetadata( + name: UUID().uuidString, + description: UUID().uuidString, + symbol: UUID().uuidString, + iconUrl: "https://example.com", + tags: ["swift test"] + ) + let initialSupply: Decimal192 = .pi + let manifest = SUT.createFungibleTokenWithMetadata( + addressOfOwner: accountAddress, + initialSupply: initialSupply, + metadata: metadata + ) + func oneOf(_ needle: String, line: UInt = #line) { + XCTAssertEqual(manifest.description.ranges(of: needle).count, 1, line: line) + } + func oneIn(metadata keyPath: KeyPath, line: UInt = #line) { + let property = metadata[keyPath: keyPath] + oneOf(property.description, line: line) + } + oneIn(metadata: \.name) + oneIn(metadata: \.description) + oneIn(metadata: \.symbol) + oneOf(initialSupply.formattedPlain(locale: .test)) + } // We are not testing with AccountAddress.sampleValues since sampleMainnet & sampleMainnetOther are used // to build the prefilled the dummy metadata extra fields (so they will appear more than once in the manifest). AccountAddress.sampleValues.forEach(doTest) - } - + } + func test_create_single_fungible_token() { func doTest(_ accountAddress: AccountAddress) { - - let manifest = SUT.createFungibleToken(addressOfOwner: accountAddress) - - XCTAssertEqual(manifest.description.ranges(of: "Stella").count, 1) + let manifest = SUT.createFungibleToken(addressOfOwner: accountAddress) + + XCTAssertEqual(manifest.description.ranges(of: "Stella").count, 1) XCTAssertEqual(manifest.description.ranges(of: "STAR").count, 1) XCTAssertEqual(manifest.description.ranges(of: "The brightest component in the Radix ecosystem.").count, 1) XCTAssert(manifest.description.contains(accountAddress.address)) } AccountAddress.sampleValues.forEach(doTest) } - - func test_create_multiple_fungible_tokens() { - func doTest(_ accountAddress: AccountAddress) { + + func test_create_multiple_fungible_tokens() { + func doTest(_ accountAddress: AccountAddress) { let n: UInt8 = 5 let manifest = SUT.createMultipleFungibleTokens( addressOfOwner: accountAddress, count: n ) - XCTAssertEqual(manifest.description.ranges(of: "symbol").count, Int(n)) + XCTAssertEqual(manifest.description.ranges(of: "symbol").count, Int(n)) XCTAssert(manifest.description.contains(accountAddress.address)) - } - - [ - AccountAddress.sampleStokenet, - AccountAddress.sampleStokenetOther - ].forEach(doTest) - } - + } + + [ + AccountAddress.sampleStokenet, + AccountAddress.sampleStokenetOther, + ].forEach(doTest) + } + func test_create_single_nft_collection() { func doTest(_ accountAddress: AccountAddress) { - let manifest = SUT.createNonFungibleToken(addressOfOwner: accountAddress) + let manifest = SUT.createNonFungibleToken(addressOfOwner: accountAddress) XCTAssertEqual(manifest.description.ranges(of: "An amazingly innovative and rare NFT collection").count, 1) XCTAssertEqual(manifest.description.ranges(of: "nf-number").count, 20) XCTAssert(manifest.description.contains(accountAddress.address)) @@ -134,7 +129,7 @@ final class ManifestBuildingTests: Test { func test_create_multiple_nft_collection() { func doTest(_ accountAddress: AccountAddress) { - let manifest = SUT.createMultipleNonFungibleTokens(addressOfOwner: accountAddress) + let manifest = SUT.createMultipleNonFungibleTokens(addressOfOwner: accountAddress) let collections = 15 let nftsPerCollection = 10 XCTAssertEqual(manifest.description.ranges(of: "An amazingly innovative and rare NFT collection").count, collections) @@ -143,32 +138,32 @@ final class ManifestBuildingTests: Test { } AccountAddress.sampleValues.forEach(doTest) } - + func test_stakes_claim() { func doTest(_ accountAddress: AccountAddress) { - let manifest = SUT.stakesClaim(accountAddress: accountAddress, stakeClaims: StakeClaim.sampleValues) + let manifest = SUT.stakesClaim(accountAddress: accountAddress, stakeClaims: StakeClaim.sampleValues) XCTAssertEqual(manifest.description.ranges(of: StakeClaim.sample.validatorAddress.mapTo(networkID: accountAddress.networkID).address).count, 1) XCTAssertEqual(manifest.description.ranges(of: accountAddress.xrdOnSameNetwork.address).count, 2) XCTAssert(manifest.description.contains(accountAddress.address)) } - + + AccountAddress.sampleValues.forEach(doTest) + } + + func test_update_third_party_deposits() { + func doTest(_ accountAddress: AccountAddress) { + let manifest = SUT.thirdPartyDepositUpdate( + accountAddress: accountAddress, + from: .sample, + to: .sampleOther + ) + XCTAssert(manifest.description.contains(accountAddress.address)) + XCTAssertEqual(manifest.description.ranges(of: ";").count, 3) // 3 instructions + } AccountAddress.sampleValues.forEach(doTest) } - - func test_update_third_party_deposits() { - func doTest(_ accountAddress: AccountAddress) { - let manifest = SUT.thirdPartyDepositUpdate( - accountAddress: accountAddress, - from: .sample, - to: .sampleOther - ) - XCTAssert(manifest.description.contains(accountAddress.address)) - XCTAssertEqual(manifest.description.ranges(of: ";").count, 3) // 3 instructions - } - AccountAddress.sampleValues.forEach(doTest) - } - - func test_modify_manifest_add_lock_fee() throws { + + func test_modify_manifest_add_lock_fee() throws { func doTest(_ addressOfFeePayer: AccountAddress) throws { var manifest = try rtm("create_pool") func hasLockFee() -> Bool { @@ -185,13 +180,13 @@ final class ManifestBuildingTests: Test { AccountAddress.sampleStokenet, AccountAddress.sampleStokenetOther, ].forEach(doTest) - } - + } + func test_modify_manifest_add_guarantee() throws { var manifest = try rtm("transfer_1to2_multiple_nf_and_f_tokens") - + let guarantee = TransactionGuarantee( - amount: 642, + amount: 642, percentage: 0.9, instructionIndex: 12, resourceAddress: .sampleStokenetXRD, @@ -201,34 +196,32 @@ final class ManifestBuildingTests: Test { XCTAssertFalse(manifest.description.contains(guarantee.amount.description)) manifest = try manifest.modify(addGuarantees: [guarantee]) XCTAssertTrue(manifest.description.contains(guarantee.amount.description)) - } - + func test_assets_transfers() throws { let transfers = PerAssetTransfers.sample let manifest = TransactionManifest.assetsTransfers(transfers: transfers) XCTAssert(manifest.description.contains(transfers.fromAccount.address)) - transfers.fungibleResources.forEach { - XCTAssert(manifest.description.contains($0.resource.resourceAddress.address)) - $0.transfers.forEach { - XCTAssert(manifest.description.contains($0.recipient.description)) + for fungibleResource in transfers.fungibleResources { + XCTAssert(manifest.description.contains(fungibleResource.resource.resourceAddress.address)) + for transfer in fungibleResource.transfers { + XCTAssert(manifest.description.contains(transfer.recipient.description)) } } } - func test_account_locker_claim() { - func doTest(_ accountAddress: AccountAddress) { - let manifest = SUT.accountLockerClaim( + func test_account_locker_claim() { + func doTest(_ accountAddress: AccountAddress) { + let manifest = SUT.accountLockerClaim( lockerAddress: LockerAddress.sample, claimant: accountAddress, claimableResources: [AccountLockerClaimableResource.fungible(resourceAddress: ResourceAddress.sample, amount: Decimal192.sample)] ) - XCTAssert(manifest.description.contains(accountAddress.address)) - XCTAssertEqual(manifest.description.ranges(of: ";").count, 3) // 3 instructions - } - AccountAddress.sampleValues.forEach(doTest) - } - + XCTAssert(manifest.description.contains(accountAddress.address)) + XCTAssertEqual(manifest.description.ranges(of: ";").count, 3) // 3 instructions + } + AccountAddress.sampleValues.forEach(doTest) + } } extension TestCase { @@ -236,19 +229,19 @@ extension TestCase { let utf8 = try openTransactionFile(name, extension: "dat") return try XCTUnwrap(String(data: utf8, encoding: .utf8)) } - - func rtm(_ rtmFile: String) throws -> TransactionManifest { - let data = try openTransactionFile(rtmFile, extension: "rtm") - let instructionsString = try XCTUnwrap(String(data: data, encoding: .utf8)) - - return try TransactionManifest( - instructionsString: instructionsString, - networkID: .stokenet, - blobs: [] - ) - } - - private func openTransactionFile(_ fileName: String, extension fileExtension: String) throws -> Data { + + func rtm(_ rtmFile: String) throws -> TransactionManifest { + let data = try openTransactionFile(rtmFile, extension: "rtm") + let instructionsString = try XCTUnwrap(String(data: data, encoding: .utf8)) + + return try TransactionManifest( + instructionsString: instructionsString, + networkID: .stokenet, + blobs: [] + ) + } + + private func openTransactionFile(_ fileName: String, extension fileExtension: String) throws -> Data { try openFile(subPath: "transaction", fileName, extension: fileExtension) - } + } } diff --git a/apple/Tests/TestCases/RET/ResourceSpecifierTests.swift b/apple/Tests/TestCases/RET/ResourceSpecifierTests.swift index 7a7ff1954..fd331fc2a 100644 --- a/apple/Tests/TestCases/RET/ResourceSpecifierTests.swift +++ b/apple/Tests/TestCases/RET/ResourceSpecifierTests.swift @@ -5,12 +5,12 @@ import SargonUniFFI import XCTest final class ResourceSpecifierTests: Test { - func test_resource_address() { - let sut = SUT.sample - switch sut { - case let .fungible(resourceAddress, _): - XCTAssertEqual(resourceAddress, sut.resourceAddress) - case .nonFungible: XCTFail("Expected fungible") - } - } + func test_resource_address() { + let sut = SUT.sample + switch sut { + case let .fungible(resourceAddress, _): + XCTAssertEqual(resourceAddress, sut.resourceAddress) + case .nonFungible: XCTFail("Expected fungible") + } + } } diff --git a/apple/Tests/TestCases/RET/SignedIntentTests.swift b/apple/Tests/TestCases/RET/SignedIntentTests.swift index 0f7c906c8..727771a98 100644 --- a/apple/Tests/TestCases/RET/SignedIntentTests.swift +++ b/apple/Tests/TestCases/RET/SignedIntentTests.swift @@ -7,7 +7,7 @@ import SargonUniFFI import XCTest final class SignedIntentTests: Test { - func test_hash() { - XCTAssertEqual(SUT.sample.hash().description, "signedintent_sim1ul0kjuvd63sslhxy869zdk4k3vcdg9e9244xwpuck4dyndzx9wnqrhxy5d") - } + func test_hash() { + XCTAssertEqual(SUT.sample.hash().description, "signedintent_sim1ul0kjuvd63sslhxy869zdk4k3vcdg9e9244xwpuck4dyndzx9wnqrhxy5d") + } } diff --git a/apple/Tests/TestCases/RET/TransactionIntentTests.swift b/apple/Tests/TestCases/RET/TransactionIntentTests.swift index 71405d662..fac0998c9 100644 --- a/apple/Tests/TestCases/RET/TransactionIntentTests.swift +++ b/apple/Tests/TestCases/RET/TransactionIntentTests.swift @@ -10,7 +10,8 @@ final class TransactionIntentTests: Test { func test_hash() { XCTAssertEqual( SUT.sample.hash().description, - "txid_rdx198k527d5wt4ms5tvrdcu8089v4hptp7ztv388k539uzzvmw25ltsj7u4zz") + "txid_rdx198k527d5wt4ms5tvrdcu8089v4hptp7ztv388k539uzzvmw25ltsj7u4zz" + ) } func test_compile() { diff --git a/apple/Tests/TestCases/RET/TransactionManifestTests.swift b/apple/Tests/TestCases/RET/TransactionManifestTests.swift index f4b8cd0be..a074e5df3 100644 --- a/apple/Tests/TestCases/RET/TransactionManifestTests.swift +++ b/apple/Tests/TestCases/RET/TransactionManifestTests.swift @@ -7,7 +7,6 @@ import SargonUniFFI import XCTest final class TransactionManifestTests: Test { - // func test_manifest_string() { // let manifest = SUT.sample // XCTAssert(manifest.manifestString.contains("CALL_METHOD")) @@ -20,7 +19,7 @@ final class TransactionManifestTests: Test { func test_manifest_network_id() { let manifest = TransactionManifest.sample - XCTAssertNoDifference(manifest.networkId, .mainnet) + XCTAssertNoDifference(manifest.networkId, .mainnet) } func test_manifest_blobs() { @@ -30,7 +29,7 @@ final class TransactionManifestTests: Test { func test_involved_resource_addresses() { XCTAssertNoDifference(SUT.sample.involvedResourceAddresses, [ResourceAddress.sampleMainnetXRD]) - } + } func test_involved_pool_addresses() { XCTAssertNoDifference(SUT.sample.involvedPoolAddresses, []) @@ -39,14 +38,12 @@ final class TransactionManifestTests: Test { func test_manifest_summary() throws { XCTAssertNoDifference(try SUT.sample.summary.addressesOfAccountsWithdrawnFrom, [AccountAddress.sampleMainnet]) } - + func test_from_instructions_string_with_max_sbor_depth_is_ok() throws { let instructionsString = """ -CALL_METHOD - Address("component_tdx_2_1crllllllllllllllllllllllllllllllllllllllllllllllx8navn") - "dummy" - Tuple( - Tuple( + CALL_METHOD + Address("component_tdx_2_1crllllllllllllllllllllllllllllllllllllllllllllllx8navn") + "dummy" Tuple( Tuple( Tuple( @@ -62,7 +59,11 @@ CALL_METHOD Tuple( Tuple( Tuple( - + Tuple( + Tuple( + + ) + ) ) ) ) @@ -78,22 +79,18 @@ CALL_METHOD ) ) ) - ) - ) -; -""" + ; + """ let sut = try SUT(instructionsString: instructionsString, networkID: .stokenet, blobs: []) // should be OK let intent = TransactionIntent(header: .sample, manifest: sut, message: .sample) XCTAssertEqual(intent.hash().description, "txid_rdx1mecs336t36x7rcuyhwa0jtsef08jq5r573nfa63t8f4aq9faxrls2n3u3c") } - + func test_from_instructions_string_with_exceeded_sbor_depth_throws() { let instructionsString = """ -CALL_METHOD - Address("component_tdx_2_1crllllllllllllllllllllllllllllllllllllllllllllllx8navn") - "dummy" - Tuple( - Tuple( + CALL_METHOD + Address("component_tdx_2_1crllllllllllllllllllllllllllllllllllllllllllllllx8navn") + "dummy" Tuple( Tuple( Tuple( @@ -112,7 +109,11 @@ CALL_METHOD Tuple( Tuple( Tuple( - Tuple() + Tuple( + Tuple( + Tuple() + ) + ) ) ) ) @@ -131,10 +132,8 @@ CALL_METHOD ) ) ) - ) - ) -; -""" + ; + """ XCTAssertThrowsError(try SUT(instructionsString: instructionsString, networkID: .stokenet, blobs: [])) } } diff --git a/apple/Tests/TestCases/RET/TransactionManifestV2Tests.swift b/apple/Tests/TestCases/RET/TransactionManifestV2Tests.swift index 52508507f..5071ddaea 100644 --- a/apple/Tests/TestCases/RET/TransactionManifestV2Tests.swift +++ b/apple/Tests/TestCases/RET/TransactionManifestV2Tests.swift @@ -7,7 +7,6 @@ import SargonUniFFI import XCTest final class TransactionManifestV2Tests: Test { - func test_manifest_string() { let manifest = SUT.sample XCTAssert(manifest.manifestString.contains("CALL_METHOD")) diff --git a/apple/Tests/TestCases/RadixConnect/Collection/P2PLinksTests.swift b/apple/Tests/TestCases/RadixConnect/Collection/P2PLinksTests.swift index e4941d0e9..8b511bbb4 100644 --- a/apple/Tests/TestCases/RadixConnect/Collection/P2PLinksTests.swift +++ b/apple/Tests/TestCases/RadixConnect/Collection/P2PLinksTests.swift @@ -5,11 +5,10 @@ import SargonUniFFI import XCTest final class P2PLinksTests: CollectionTest { - override class func sample() -> SUT { SUT.sample } - + override class func sampleOther() -> SUT { SUT.sampleOther } diff --git a/apple/Tests/TestCases/RadixConnect/P2PLinks/LinkConnectionQrDataTests.swift b/apple/Tests/TestCases/RadixConnect/P2PLinks/LinkConnectionQrDataTests.swift index 5221d2e90..75323ca5a 100644 --- a/apple/Tests/TestCases/RadixConnect/P2PLinks/LinkConnectionQrDataTests.swift +++ b/apple/Tests/TestCases/RadixConnect/P2PLinks/LinkConnectionQrDataTests.swift @@ -7,13 +7,13 @@ import XCTest final class LinkConnectionQrDataTests: Test { func test_codable() throws { let raw = """ - { - "purpose": "general", - "password": "deaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddead", - "publicKey": "ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf", - "signature": "fc6a4a15516b886b10f26777094cb1abdccb213c9ebdea7a4bceb83b6fcba50fea181b0136ee5659c3dfae5f771e5b6e6f9abbaa3f0435df0be1f732be965103" - } - """.data(using: .utf8)! + { + "purpose": "general", + "password": "deaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddead", + "publicKey": "ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf", + "signature": "fc6a4a15516b886b10f26777094cb1abdccb213c9ebdea7a4bceb83b6fcba50fea181b0136ee5659c3dfae5f771e5b6e6f9abbaa3f0435df0be1f732be965103" + } + """.data(using: .utf8)! // test decoding let sut = try JSONDecoder().decode(SUT.self, from: raw) diff --git a/apple/Tests/TestCases/RadixConnect/P2PLinks/P2PLinkTests.swift b/apple/Tests/TestCases/RadixConnect/P2PLinks/P2PLinkTests.swift index e8305ec43..9eed12e70 100644 --- a/apple/Tests/TestCases/RadixConnect/P2PLinks/P2PLinkTests.swift +++ b/apple/Tests/TestCases/RadixConnect/P2PLinks/P2PLinkTests.swift @@ -5,7 +5,7 @@ import SargonUniFFI import XCTest final class P2PLinkTests: Test { - func test_codable() throws { + func test_codable() throws { let raw = """ { "connectionPassword": "cafecafecafecafecafecafecafecafecafecafecafecafecafecafecafecafe", @@ -14,27 +14,27 @@ final class P2PLinkTests: Test { "displayName": "Chrome on Macbook" } """.data(using: .utf8)! - + // test decoding let sut = try JSONDecoder().decode(SUT.self, from: raw) XCTAssertEqual(sut, SUT.sample) - + // test encoding let encoded = try JSONEncoder().encode(sut) try XCTAssertEqual(JSONDecoder().decode(SUT.self, from: encoded), sut) } - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { try eachSampleCodableRoundtripTest() } - func testClientID() throws { - try XCTAssertEqual( - SUT.sample.clientID, - Hash(string: "98e140d9c01c069aa927797627b1bca4d25971a76549ca59df8ef9d8397afa97") - ) - } + func testClientID() throws { + try XCTAssertEqual( + SUT.sample.clientID, + Hash(string: "98e140d9c01c069aa927797627b1bca4d25971a76549ca59df8ef9d8397afa97") + ) + } } diff --git a/apple/Tests/TestCases/RadixConnect/P2PLinks/RadixConnectPasswordTests.swift b/apple/Tests/TestCases/RadixConnect/P2PLinks/RadixConnectPasswordTests.swift index bd9ff4116..0370a3382 100644 --- a/apple/Tests/TestCases/RadixConnect/P2PLinks/RadixConnectPasswordTests.swift +++ b/apple/Tests/TestCases/RadixConnect/P2PLinks/RadixConnectPasswordTests.swift @@ -5,30 +5,30 @@ import SargonUniFFI import XCTest final class RadixConnectPasswordTests: Test { - func test_codable() throws { + func test_codable() throws { let raw = "\"deaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddead\"".data(using: .utf8)! - + // test decoding let sut = try JSONDecoder().decode(SUT.self, from: raw) XCTAssertEqual(sut, SUT.sample) - + // test encoding let encoded = try JSONEncoder().encode(sut) try XCTAssertEqual(JSONDecoder().decode(SUT.self, from: encoded), sut) } - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { try eachSampleCodableRoundtripTest() } - func testMessageHash() throws { - let hex = "479ae13d3983de8ab520e519cfba01a25fafbbc1e7438ba52e5ed4a40cd2f56a" - try XCTAssertEqual( - SUT.sample.messageHash, - Hash(string: hex) - ) - } + func testMessageHash() throws { + let hex = "479ae13d3983de8ab520e519cfba01a25fafbbc1e7438ba52e5ed4a40cd2f56a" + try XCTAssertEqual( + SUT.sample.messageHash, + Hash(string: hex) + ) + } } diff --git a/apple/Tests/TestCases/RadixConnect/P2PLinks/RadixConnectPurposeTests.swift b/apple/Tests/TestCases/RadixConnect/P2PLinks/RadixConnectPurposeTests.swift index 42b19eb09..ae37d4d25 100644 --- a/apple/Tests/TestCases/RadixConnect/P2PLinks/RadixConnectPurposeTests.swift +++ b/apple/Tests/TestCases/RadixConnect/P2PLinks/RadixConnectPurposeTests.swift @@ -5,26 +5,26 @@ import SargonUniFFI import XCTest final class RadixConnectPurposeTests: Test { - func test_string_roundtrip() { - XCTAssertEqual( - SUT(rawValue: "general"), - SUT.general - ) - } + func test_string_roundtrip() { + XCTAssertEqual( + SUT(rawValue: "general"), + SUT.general + ) + } - func test_codable() throws { + func test_codable() throws { let raw = "\"general\"".data(using: .utf8)! - + // test decoding let sut = try JSONDecoder().decode(SUT.self, from: raw) XCTAssertEqual(sut, SUT.sample) - + // test encoding let encoded = try JSONEncoder().encode(sut) try XCTAssertEqual(JSONDecoder().decode(SUT.self, from: encoded), sut) } - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { diff --git a/apple/Tests/TestCases/RadixConnect/WalletInteraction/DappToWalletInteractionSubintentExpirationTests.swift b/apple/Tests/TestCases/RadixConnect/WalletInteraction/DappToWalletInteractionSubintentExpirationTests.swift index 20652815c..e677d6a20 100644 --- a/apple/Tests/TestCases/RadixConnect/WalletInteraction/DappToWalletInteractionSubintentExpirationTests.swift +++ b/apple/Tests/TestCases/RadixConnect/WalletInteraction/DappToWalletInteractionSubintentExpirationTests.swift @@ -4,18 +4,18 @@ import XCTest final class DappToWalletInteractionSubintentExpirationTests: TestCase { typealias SUT = DappToWalletInteractionSubintentExpiration - + func testGetStatus() throws { let afterDelay = SUT.afterDelay(.init(expireAfterSeconds: 100)) XCTAssertEqual(afterDelay.getStatus(), .valid) - + let atTimeExpired = SUT.atTime(.init(unixTimestampSeconds: 0)) XCTAssertEqual(atTimeExpired.getStatus(), .expired) - + let now = UInt64(Date.now.timeIntervalSince1970) let atTimeCloseToExpiration = SUT.atTime(.init(unixTimestampSeconds: now + 15)) XCTAssertEqual(atTimeCloseToExpiration.getStatus(), .expirationTooClose) - + let atTimeValid = SUT.atTime(.init(unixTimestampSeconds: now + 60)) XCTAssertEqual(atTimeValid.getStatus(), .valid) } diff --git a/apple/Tests/TestCases/RadixConnect/WalletInteraction/DappToWalletInteractionSubintentExpireAtTimeTests.swift b/apple/Tests/TestCases/RadixConnect/WalletInteraction/DappToWalletInteractionSubintentExpireAtTimeTests.swift index afa5bc426..69942ff58 100644 --- a/apple/Tests/TestCases/RadixConnect/WalletInteraction/DappToWalletInteractionSubintentExpireAtTimeTests.swift +++ b/apple/Tests/TestCases/RadixConnect/WalletInteraction/DappToWalletInteractionSubintentExpireAtTimeTests.swift @@ -4,14 +4,14 @@ import XCTest final class DappToWalletInteractionSubintentExpireAtTimeTests: TestCase { typealias SUT = DappToWalletInteractionSubintentExpireAtTime - + func testDate() throws { - var sut = SUT.init(unixTimestampSeconds: 0) + var sut = SUT(unixTimestampSeconds: 0) XCTAssertEqual(sut.date, Date(timeIntervalSince1970: 0)) - + sut = .init(unixTimestampSeconds: 500) XCTAssertEqual(sut.date, Date(timeIntervalSince1970: 500)) - + sut = .init(unixTimestampSeconds: 1000) XCTAssertEqual(sut.date.timeIntervalSince1970, 1000) } diff --git a/apple/Tests/TestCases/RadixConnect/WalletInteraction/DappToWalletInteractionUnvalidatedTests.swift b/apple/Tests/TestCases/RadixConnect/WalletInteraction/DappToWalletInteractionUnvalidatedTests.swift index 556baa621..5dcb75a2d 100644 --- a/apple/Tests/TestCases/RadixConnect/WalletInteraction/DappToWalletInteractionUnvalidatedTests.swift +++ b/apple/Tests/TestCases/RadixConnect/WalletInteraction/DappToWalletInteractionUnvalidatedTests.swift @@ -12,7 +12,7 @@ final class DappToWalletInteractionUnvalidatedTests: Test { - func testTransactionManifestOnNetwork() throws { - let instance = SUT(manifest: .sample) - let result = try instance.transactionManifest(onNetwork: .sample) - XCTAssertEqual(result, TransactionManifest.sample) - } -} \ No newline at end of file + func testTransactionManifestOnNetwork() throws { + let instance = SUT(manifest: .sample) + let result = try instance.transactionManifest(onNetwork: .sample) + XCTAssertEqual(result, TransactionManifest.sample) + } +} diff --git a/apple/Tests/TestCases/RadixConnect/WalletInteraction/WalletToDappInteractionResponseTests.swift b/apple/Tests/TestCases/RadixConnect/WalletInteraction/WalletToDappInteractionResponseTests.swift index 2eeec0afd..71e5123cd 100644 --- a/apple/Tests/TestCases/RadixConnect/WalletInteraction/WalletToDappInteractionResponseTests.swift +++ b/apple/Tests/TestCases/RadixConnect/WalletInteraction/WalletToDappInteractionResponseTests.swift @@ -12,10 +12,10 @@ final class WalletToDappInteractionResponseTests: Test { - func testGetName() { let sut = SUT.sample @@ -22,5 +21,4 @@ final class HostOSTests: Test { XCTAssertEqual(sut.version(), "iOS 17.4.1") } - } diff --git a/apple/Tests/TestCases/Transaction/AccountOrAddressOfTests.swift b/apple/Tests/TestCases/Transaction/AccountOrAddressOfTests.swift index 9ff1d0725..70508e864 100644 --- a/apple/Tests/TestCases/Transaction/AccountOrAddressOfTests.swift +++ b/apple/Tests/TestCases/Transaction/AccountOrAddressOfTests.swift @@ -5,11 +5,10 @@ import SargonUniFFI import XCTest final class AccountOrAddressOfTests: Test { - func test_id_is_account_address() { XCTAssertEqual(SUT.sample.id, SUT.sample.accountAddress) } - + func test_description_is_account_address() { XCTAssertEqual(SUT.sample.description, SUT.sample.accountAddress.description) } diff --git a/apple/Tests/Utils/AddressProtocolTest.swift b/apple/Tests/Utils/AddressProtocolTest.swift index 39d159cfd..3648a5cb0 100644 --- a/apple/Tests/Utils/AddressProtocolTest.swift +++ b/apple/Tests/Utils/AddressProtocolTest.swift @@ -4,21 +4,20 @@ import Sargon import SargonUniFFI import XCTest +// MARK: - BaseAddressTest class BaseAddressTest: Test { - func test_network_id_of_sample() { XCTAssertNoDifference(SUT.sample.networkID, .mainnet) } - + func test_network_id_of_sampleOther() { XCTAssertNoDifference(SUT.sampleOther.networkID, .mainnet) } - + func test_all_address_different() { XCTAssertEqual(Set(SUT.sampleValues).count, SUT.sampleValues.count) } - - + func test_bech32_roundtrip() throws { try eachSample { address in try XCTAssertNoDifference( @@ -27,7 +26,7 @@ class BaseAddressTest: Test { ) } } - + func test_description_is_bech32() { eachSample { address in XCTAssertNoDifference( @@ -36,28 +35,26 @@ class BaseAddressTest: Test { ) } } - - } +// MARK: - AddressTest class AddressTest: BaseAddressTest { - func test_network_id_of_mainnet_sample() { XCTAssertNoDifference(SUT.sampleMainnet.networkID, .mainnet) } - + func test_network_id_of_mainnet_sampleOther() { XCTAssertNoDifference(SUT.sampleMainnetOther.networkID, .mainnet) } - + func test_network_id_of_stokenet_sample() { XCTAssertNoDifference(SUT.sampleStokenet.networkID, .stokenet) } - + func test_network_id_of_stokenet_sampleOther() { XCTAssertNoDifference(SUT.sampleStokenetOther.networkID, .stokenet) } - + func test_asSpecific_self() throws { func doTestInto(_ sut: SUT) throws { let extracted = try sut.asGeneral.asSpecific(type: SUT.self) @@ -65,23 +62,23 @@ class AddressTest: BaseAddressTest { } try SUT.sampleValues.forEach(doTestInto) } - - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { try eachSampleCodableRoundtripTest() } - - func test_identifiable() { - SUT.sampleValues.forEach { - XCTAssertEqual($0.id, $0.address) - } - } - + + func test_identifiable() { + for sampleValue in SUT.sampleValues { + XCTAssertEqual(sampleValue.id, sampleValue.address) + } + } + func test_formatted_full_is_address() { - SUT.sampleValues.forEach { - XCTAssertEqual($0.formatted(.full), $0.address) + for sampleValue in SUT.sampleValues { + XCTAssertEqual(sampleValue.formatted(.full), sampleValue.address) } } @@ -91,14 +88,14 @@ class AddressTest: BaseAddressTest { XCTAssertEqual(SUT.sampleStokenet.xrdOnSameNetwork, ResourceAddress.sampleStokenetXRD) XCTAssertEqual(SUT.sampleStokenetOther.xrdOnSameNetwork, ResourceAddress.sampleStokenetXRD) } - + func test_is_on_mainnet() { XCTAssertTrue(SUT.sampleMainnet.isOnMainnet) XCTAssertTrue(SUT.sampleMainnetOther.isOnMainnet) - + XCTAssertFalse(SUT.sampleStokenet.isOnMainnet) XCTAssertFalse(SUT.sampleStokenetOther.isOnMainnet) - + let nonMainnets = Set(NetworkID.sampleValues).subtracting(Set([NetworkID.mainnet])) nonMainnets.map(SUT.random(networkID:)).map(\.isOnMainnet).forEach { XCTAssertFalse($0) } } @@ -109,14 +106,14 @@ class AddressTest: BaseAddressTest { address.asGeneral.address, address.address ) - + XCTAssertNoDifference( address.asGeneral.networkID, address.networkID ) } } - + func test_map_to_same_network_does_not_change() { eachSample { address in XCTAssertNoDifference( @@ -125,34 +122,32 @@ class AddressTest: BaseAddressTest { ) } } - - + func test_map_to_other_networks() { eachSample { address in - NetworkID.sampleValues.forEach { - let addressMapped = address.mapTo(networkID: $0) - XCTAssertEqual(addressMapped.networkID, $0) - if address.networkID != $0 { + for sampleValue in NetworkID.sampleValues { + let addressMapped = address.mapTo(networkID: sampleValue) + XCTAssertEqual(addressMapped.networkID, sampleValue) + if address.networkID != sampleValue { XCTAssertNotEqual(addressMapped, address) } } } } - - + func test_asymmetric_type_equality() { - SUT.sampleValues.forEach { - XCTAssertTrue($0.asGeneral == $0) - XCTAssertTrue($0 == $0.asGeneral) + for sampleValue in SUT.sampleValues { + XCTAssertTrue(sampleValue.asGeneral == sampleValue) + XCTAssertTrue(sampleValue == sampleValue.asGeneral) } } - + func test_random() { let n = 10 var set = Set() let networks = NetworkID.sampleValues - networks.forEach { networkID in - (0..: Test { func test_init_from_hex() throws { try XCTAssertNoDifference(SUT(hex: SUT.sample.hex), SUT.sample) try XCTAssertNoDifference(SUT(hex: SUT.sampleOther.hex), SUT.sampleOther) } - + func test_description_is_hex() { XCTAssertNoDifference(SUT.sample.description, SUT.sample.hex) } - + func test_init_from_bytes() throws { try XCTAssertNoDifference(SUT(bytes: SUT.sample.data), SUT.sample) try XCTAssertNoDifference(SUT(bytes: SUT.sampleOther.data), SUT.sampleOther) } - } -class PublicKeyTest: BinaryProtocolTest { - -} +// MARK: - PublicKeyTest +class PublicKeyTest: BinaryProtocolTest {} + +// MARK: - SignatureTest class SignatureTest: BinaryProtocolTest {} +// MARK: - ExactlyNBytesTest class ExactlyNBytesTest: BinaryProtocolTest { - func test_length() throws { - SUT.sampleValues.forEach { - XCTAssertEqual($0.data.count, SUT.length) + for sampleValue in SUT.sampleValues { + XCTAssertEqual(sampleValue.data.count, SUT.length) } } - + func test_hash_inequality() { - SUT.sampleValues.forEach { - XCTAssertNotEqual($0.hash().data, $0.hash().data.hash().data) + for sampleValue in SUT.sampleValues { + XCTAssertNotEqual(sampleValue.hash().data, sampleValue.hash().data.hash().data) } } - + func test_generate_is_indeed_random() { let n = 10 eachSample { sut in - let randomCollections: [SUT] = (0..: TestCase { typealias SUT = [Element] - + class func sample() -> SUT { fatalError("override me") } + class func sampleOther() -> SUT { fatalError("override me") } - + func test_equality() { XCTAssertNoDifference(Self.sample(), Self.sample()) } @@ -21,7 +22,7 @@ class CollectionTest: TestCase { func test_inequality() { XCTAssertNotEqual(Self.sample(), Self.sampleOther()) } - + func test_ids_are_unique() { func doTest(_ sut: SUT) { XCTAssertEqual( @@ -32,6 +33,4 @@ class CollectionTest: TestCase { doTest(Self.sample()) doTest(Self.sampleOther()) } - } - diff --git a/apple/Tests/Utils/EntityProtocolTest.swift b/apple/Tests/Utils/EntityProtocolTest.swift index 393b2a402..3d4ad0426 100644 --- a/apple/Tests/Utils/EntityProtocolTest.swift +++ b/apple/Tests/Utils/EntityProtocolTest.swift @@ -4,8 +4,8 @@ import Sargon import SargonUniFFI import XCTest +// MARK: - EntityProtocolTest class EntityProtocolTest: EntityBaseTest { - func test_extract() throws { try eachSample { sut in let embedded = sut.asGeneral @@ -15,27 +15,26 @@ class EntityProtocolTest: EntityBaseTest { } } - +// MARK: - EntityBaseTest class EntityBaseTest: Test { - func test_network_id_of_mainnet_entities() { - SUT.sampleValuesMainnet.forEach { - XCTAssertNoDifference($0.networkID, .mainnet) + for item in SUT.sampleValuesMainnet { + XCTAssertNoDifference(item.networkID, .mainnet) } } - + func test_network_id_of_stokenet_entities() { - SUT.sampleValuesStokenet.forEach { - XCTAssertNoDifference($0.networkID, .stokenet) + for item in SUT.sampleValuesStokenet { + XCTAssertNoDifference(item.networkID, .stokenet) } } - + func test_id_is_address() { - SUT.sampleValues.forEach { - XCTAssertNoDifference($0.id, $0.address) + for sampleValue in SUT.sampleValues { + XCTAssertNoDifference(sampleValue.id, sampleValue.address) } } - + func test_is_hidden() { XCTAssertFalse(SUT.sample.isHidden) } @@ -43,13 +42,13 @@ class EntityBaseTest: Test { func test_is_deleted() { XCTAssertFalse(SUT.sample.isDeleted) } - + func test_hasAuthenticationSigningKey() { eachSample { sut in XCTAssertFalse(sut.hasAuthenticationSigningKey) } } - + func test_deviceFactorSourceID() { eachSample { sut in XCTAssertTrue( @@ -66,25 +65,25 @@ class EntityBaseTest: Test { } func test_controlled_by_ed25519_factor() { - SUT.sampleValues.forEach { - switch $0.securityState { - case .unsecured(let unsecuredEntityControl): - switch unsecuredEntityControl.transactionSigning.publicKey.publicKey { - case .ed25519: break // good - case .secp256k1: XCTFail("Wrong key kind") - } - // TODO: Handle - // case .securified(value: _): - // XCTFail("Wrong security state") - // } - } + for sampleValue in SUT.sampleValues { + switch sampleValue.securityState { + case let .unsecured(unsecuredEntityControl): + switch unsecuredEntityControl.transactionSigning.publicKey.publicKey { + case .ed25519: break // good + case .secp256k1: XCTFail("Wrong key kind") + } + // TODO: Handle + // case .securified(value: _): + // XCTFail("Wrong security state") + // } + } } } - + func test_all_address_different() { XCTAssertGreaterThanOrEqual(Set(SUT.sampleValues).count, 6) } - + func test_flags() { XCTAssertTrue( SUT.sampleValues.flatMap( diff --git a/apple/Tests/Utils/Extensions/Instant+Date.swift b/apple/Tests/Utils/Extensions/Instant+Date.swift index cb8d1a399..54e67160f 100644 --- a/apple/Tests/Utils/Extensions/Instant+Date.swift +++ b/apple/Tests/Utils/Extensions/Instant+Date.swift @@ -4,14 +4,14 @@ import XCTest final class InstantTests: TestCase { typealias SUT = Instant - + func testDate() throws { - var sut = SUT.init(secondsSinceUnixEpoch: 0) + var sut = SUT(secondsSinceUnixEpoch: 0) XCTAssertEqual(sut.date, Date(timeIntervalSince1970: 0)) - + sut = .init(secondsSinceUnixEpoch: 500) XCTAssertEqual(sut.date, Date(timeIntervalSince1970: 500)) - + sut = .init(secondsSinceUnixEpoch: 1000) XCTAssertEqual(sut.date.timeIntervalSince1970, 1000) } diff --git a/apple/Tests/Utils/Extensions/JSON+ISO8601.swift b/apple/Tests/Utils/Extensions/JSON+ISO8601.swift index d0308cf19..a911c63be 100644 --- a/apple/Tests/Utils/Extensions/JSON+ISO8601.swift +++ b/apple/Tests/Utils/Extensions/JSON+ISO8601.swift @@ -1,24 +1,17 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-31. -// - import Foundation extension JSONEncoder { - static var iso8601: JSONEncoder { - let encoder = JSONEncoder() - encoder.dateEncodingStrategy = .iso8601 - return encoder - } + static var iso8601: JSONEncoder { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + return encoder + } } extension JSONDecoder { - static var iso8601: JSONDecoder { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 - return decoder - } + static var iso8601: JSONDecoder { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + return decoder + } } diff --git a/apple/Tests/Utils/Extensions/UUID+Literals.swift b/apple/Tests/Utils/Extensions/UUID+Literals.swift index 2602a5529..ee674bfd5 100644 --- a/apple/Tests/Utils/Extensions/UUID+Literals.swift +++ b/apple/Tests/Utils/Extensions/UUID+Literals.swift @@ -1,18 +1,13 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-23. -// - import Foundation +// MARK: - UUID + ExpressibleByStringLiteral extension UUID: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self.init(uuidString: value)! } } +// MARK: - UUID + ExpressibleByIntegerLiteral extension UUID: ExpressibleByIntegerLiteral { public init(integerLiteral value: UInt8) { self.init(uuidString: "00000000-0000-0000-0000-0000000000" + String(format: "%02d", value))! diff --git a/apple/Tests/Utils/FactorSourceTest.swift b/apple/Tests/Utils/FactorSourceTest.swift index 87d573024..f2876a085 100644 --- a/apple/Tests/Utils/FactorSourceTest.swift +++ b/apple/Tests/Utils/FactorSourceTest.swift @@ -5,19 +5,18 @@ import SargonUniFFI import XCTest class FactorSourceTest: Test { - func test_as_general_factorSourceID() { eachSample { sut in XCTAssertEqual(sut.asGeneral.factorSourceID, sut.factorSourceID) } } - + func test_as_general_factorSourceKind() { eachSample { sut in XCTAssertEqual(sut.asGeneral.kind, sut.kind) } } - + func test_common_update() { eachSample { sut in let newDate = Date.now @@ -28,8 +27,7 @@ class FactorSourceTest: Test { XCTAssertEqual(sut.lastUsedOn, newDate) } } - - + func test_crypto_params() { eachSample { sut in XCTAssertEqual(sut.cryptoParameters, sut.common.cryptoParameters) @@ -37,7 +35,7 @@ class FactorSourceTest: Test { XCTAssertEqual(sut.cryptoParameters.supportsOlympia, sut.supportsOlympia) } } - + func test_flag_for_deletion() { eachSample { sut in var sut = sut diff --git a/apple/Tests/Utils/HDPathProtocolTest.swift b/apple/Tests/Utils/HDPathProtocolTest.swift index 7a65cd641..d79dfc510 100644 --- a/apple/Tests/Utils/HDPathProtocolTest.swift +++ b/apple/Tests/Utils/HDPathProtocolTest.swift @@ -5,9 +5,9 @@ import SargonUniFFI import XCTest class HDPathProtocolTest: Test { - func test_string_roundtrip() throws { - try SUT.sampleValues.forEach { - XCTAssertNoDifference(try SUT(string: $0.description), $0) - } - } + func test_string_roundtrip() throws { + try SUT.sampleValues.forEach { + XCTAssertNoDifference(try SUT(string: $0.description), $0) + } + } } diff --git a/apple/Tests/Utils/IdentifiableByStringProtocolTest.swift b/apple/Tests/Utils/IdentifiableByStringProtocolTest.swift index 22daf7eb1..46e12532f 100644 --- a/apple/Tests/Utils/IdentifiableByStringProtocolTest.swift +++ b/apple/Tests/Utils/IdentifiableByStringProtocolTest.swift @@ -5,25 +5,23 @@ import SargonUniFFI import XCTest class IdentifiableByStringProtocolTest: Test { - - func test_string_roundtrip_symmetric_with_raw() throws { - try eachSample { sut in - let roundtripped = try SUT(sut.toRawString()) - XCTAssertEqual(sut, roundtripped) - } - } - - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + func test_string_roundtrip_symmetric_with_raw() throws { + try eachSample { sut in + let roundtripped = try SUT(sut.toRawString()) + XCTAssertEqual(sut, roundtripped) + } + } + + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { try eachSampleCodableRoundtripTest() } - - func test_formatted_raw_is_raw() { - eachSample { sut in - XCTAssertEqual(sut.toRawString(), sut.formatted(.raw)) - } - } -} + func test_formatted_raw_is_raw() { + eachSample { sut in + XCTAssertEqual(sut.toRawString(), sut.formatted(.raw)) + } + } +} diff --git a/apple/Tests/Utils/OSTest.swift b/apple/Tests/Utils/OSTest.swift index 04c9dba8a..4bd445b58 100644 --- a/apple/Tests/Utils/OSTest.swift +++ b/apple/Tests/Utils/OSTest.swift @@ -5,11 +5,9 @@ import SargonUniFFI import XCTest class OSTest: TestCase { - override class func shouldEnableRustLog() -> Bool { // BIOS and SargonOS tests will have enabled Rust logging from inside of rust. // we should not enable it twice which will lead to crash. false } - } diff --git a/apple/Tests/Utils/PersonaDataEntryTest.swift b/apple/Tests/Utils/PersonaDataEntryTest.swift index a4d7fd465..bd3fe5d5f 100644 --- a/apple/Tests/Utils/PersonaDataEntryTest.swift +++ b/apple/Tests/Utils/PersonaDataEntryTest.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-04-21. -// - import CustomDump import Foundation import Sargon @@ -12,7 +5,6 @@ import SargonUniFFI import XCTest class PersonaDataEntryTest: Test { - func test_embed_then_extract() throws { try eachSample { sut in let embedded = sut.embed() @@ -20,21 +12,21 @@ class PersonaDataEntryTest: Test { XCTAssertEqual(extracted, sut) } } - - func test_embed_identity() { + + func test_embed_identity() { eachSample { sut in let embedded = sut.embed() XCTAssertEqual(embedded.embed(), embedded) } } - - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { try eachSampleCodableRoundtripTest() } - + func test_formatted_entry() { XCTAssertNoDifference( SUT.sample.embed().description, diff --git a/apple/Tests/Utils/SpecificFactorSourceIDTest.swift b/apple/Tests/Utils/SpecificFactorSourceIDTest.swift index 9111b081c..417abba3b 100644 --- a/apple/Tests/Utils/SpecificFactorSourceIDTest.swift +++ b/apple/Tests/Utils/SpecificFactorSourceIDTest.swift @@ -12,8 +12,8 @@ class SpecificFactorSourceIDTest: FactorSo XCTAssertEqual(extracted, sut) } } - - /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more + + /// Cyon: We might be able remove this function once we have converted to `swift-testing` which has much more /// powerful discovery than XCTest, and maybe `eachSampleCodableRoundtripTest` will be picked up as /// a test directly. func testJSONRoundtripAllSamples() throws { diff --git a/apple/Tests/Utils/SpecificFactorSourceTest.swift b/apple/Tests/Utils/SpecificFactorSourceTest.swift index 689126104..f60e1069a 100644 --- a/apple/Tests/Utils/SpecificFactorSourceTest.swift +++ b/apple/Tests/Utils/SpecificFactorSourceTest.swift @@ -5,7 +5,6 @@ import SargonUniFFI import XCTest class SpecificFactorSourceTest: FactorSourceTest { - func test_get_set_common() { let samples = SUT.sampleValues.map { var factor = $0.asGeneral @@ -13,9 +12,9 @@ class SpecificFactorSourceTest: FactorSourceTest Bool { false } - - class override func setUp() { + + override class func setUp() { // if shouldEnableRustLog() { -// +// // } super.setUp() } - + override func setUp() { self.continueAfterFailure = false } - + func openFile( subPath: String, _ fileName: String, @@ -29,11 +29,10 @@ class TestCase: XCTestCase { let testsDirectory: String = URL(fileURLWithPath: "\(#file)").pathComponents.dropLast(4).joined(separator: "/") let fileURL = try XCTUnwrap(URL(fileURLWithPath: "\(testsDirectory)/crates/sargon/fixtures/\(subPath)/\(fileName).\(fileExtension)")) - + return try Data(contentsOf: fileURL) - } - + func jsonFixture( as: T.Type = T.self, file fileName: String, @@ -43,7 +42,7 @@ class TestCase: XCTestCase { let model: T = try decode(json) return (model, json) } - + func jsonFixture( as: T.Type = T.self, file fileName: String, @@ -53,7 +52,7 @@ class TestCase: XCTestCase { let model: T = try decode(json) return (model, json) } - + func jsonString( as: T.Type = T.self, file fileName: String, @@ -64,18 +63,18 @@ class TestCase: XCTestCase { let model: T = try decode(jsonString) return (model, jsonString) } - } +// MARK: - Test class Test: TestCase { typealias SUT = SUT_ - + func eachSample( _ test: (SUT) throws -> Void ) rethrows { try SUT.sampleValues.forEach(test) } - + func test_equality() throws { XCTAssertNoDifference(SUT.sample, SUT.sample) } @@ -83,11 +82,11 @@ class Test: TestCase { func test_inequality() throws { XCTAssertNotEqual(SUT.sample, SUT.sampleOther) } - + func test_hashable() { XCTAssertNoDifference(Set([SUT.sample, SUT.sample]).count, 1) XCTAssertNoDifference(Set([SUT.sampleOther, SUT.sampleOther]).count, 1) - + var set = Set() SUT.sampleValues.forEach { set.insert($0) } SUT.sampleValues.forEach { set.insert($0) } // duplicates removed. diff --git a/apple/Tests/Utils/TransactionHashProtocolTest.swift b/apple/Tests/Utils/TransactionHashProtocolTest.swift index 408666ba4..92373674f 100644 --- a/apple/Tests/Utils/TransactionHashProtocolTest.swift +++ b/apple/Tests/Utils/TransactionHashProtocolTest.swift @@ -5,10 +5,9 @@ import SargonUniFFI import XCTest class TransactionHashProtocolTest: IdentifiableByStringProtocolTest { - - func test_bech32EncodedTxId_is_raw() { - eachSample { sut in - XCTAssertEqual(sut.bech32EncodedTxId, sut.toRawString()) - } - } + func test_bech32EncodedTxId_is_raw() { + eachSample { sut in + XCTAssertEqual(sut.bech32EncodedTxId, sut.toRawString()) + } + } } diff --git a/crates/sargon-uniffi/src/Package.swift b/crates/sargon-uniffi/src/Package.swift index 9a7fcd3ba..b282883d2 100644 --- a/crates/sargon-uniffi/src/Package.swift +++ b/crates/sargon-uniffi/src/Package.swift @@ -10,4 +10,4 @@ // And: https://github.com/tuist/tuist/pull/2058 import PackageDescription -let package = Package() \ No newline at end of file +let package = Package() diff --git a/crates/sargon-uniffi/tests/Package.swift b/crates/sargon-uniffi/tests/Package.swift index 9a7fcd3ba..b282883d2 100644 --- a/crates/sargon-uniffi/tests/Package.swift +++ b/crates/sargon-uniffi/tests/Package.swift @@ -10,4 +10,4 @@ // And: https://github.com/tuist/tuist/pull/2058 import PackageDescription -let package = Package() \ No newline at end of file +let package = Package() diff --git a/crates/sargon/src/Package.swift b/crates/sargon/src/Package.swift index 9a7fcd3ba..b282883d2 100644 --- a/crates/sargon/src/Package.swift +++ b/crates/sargon/src/Package.swift @@ -10,4 +10,4 @@ // And: https://github.com/tuist/tuist/pull/2058 import PackageDescription -let package = Package() \ No newline at end of file +let package = Package() diff --git a/crates/sargon/tests/Package.swift b/crates/sargon/tests/Package.swift index 9a7fcd3ba..b282883d2 100644 --- a/crates/sargon/tests/Package.swift +++ b/crates/sargon/tests/Package.swift @@ -10,4 +10,4 @@ // And: https://github.com/tuist/tuist/pull/2058 import PackageDescription -let package = Package() \ No newline at end of file +let package = Package() diff --git a/examples/Package.swift b/examples/Package.swift index 9a7fcd3ba..b282883d2 100644 --- a/examples/Package.swift +++ b/examples/Package.swift @@ -10,4 +10,4 @@ // And: https://github.com/tuist/tuist/pull/2058 import PackageDescription -let package = Package() \ No newline at end of file +let package = Package() diff --git a/examples/iOS/Backend/Package.swift b/examples/iOS/Backend/Package.swift index 8d107f20f..556807f94 100644 --- a/examples/iOS/Backend/Package.swift +++ b/examples/iOS/Backend/Package.swift @@ -3,7 +3,7 @@ import PackageDescription let swiftSettings: [SwiftSetting] = [ - .enableExperimentalFeature("StrictConcurrency") + .enableExperimentalFeature("StrictConcurrency"), ] let package = Package( @@ -12,16 +12,19 @@ let package = Package( products: [ .library( name: "Planbok", - targets: ["Planbok"]) + targets: ["Planbok"] + ), ], dependencies: [ .package(name: "Sargon", path: "../../.."), .package( url: "https://github.com/pointfreeco/swift-composable-architecture", - from: "1.11.0"), + from: "1.11.0" + ), .package( url: "https://github.com/tgrapperon/swift-dependencies-additions", - from: "1.0.2"), + from: "1.0.2" + ), .package(url: "https://github.com/kishikawakatsumi/KeychainAccess", from: "4.2.2"), .package(url: "https://github.com/varkrishna/JSONViewer", revision: "df1a57eddc49b168ff400c8595f72acbe33acc9c"), ], @@ -32,10 +35,12 @@ let package = Package( .product(name: "Sargon", package: "Sargon"), .product( name: "ComposableArchitecture", - package: "swift-composable-architecture"), + package: "swift-composable-architecture" + ), .product( name: "DependenciesAdditions", - package: "swift-dependencies-additions"), + package: "swift-dependencies-additions" + ), "KeychainAccess", "JSONViewer", ], diff --git a/examples/iOS/Backend/Sources/Planbok/Dependencies/AccountsClient.swift b/examples/iOS/Backend/Sources/Planbok/Dependencies/AccountsClient.swift index 2437f2b08..803c67e5d 100644 --- a/examples/iOS/Backend/Sources/Planbok/Dependencies/AccountsClient.swift +++ b/examples/iOS/Backend/Sources/Planbok/Dependencies/AccountsClient.swift @@ -1,14 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - -import Foundation -import Sargon import DependenciesMacros +import Foundation import IdentifiedCollections +import Sargon public typealias Accounts = IdentifiedArrayOf extension Array where Element: Identifiable { @@ -17,6 +10,7 @@ extension Array where Element: Identifiable { } } +// MARK: - AccountsClient /// The purpose of this client is to provide WRITE / UPDATE methods of Profile /// relating to Account(s). READING should be done with `@SharedReader(.accountsForDisplay)` /// Shared state! @@ -26,18 +20,18 @@ public struct AccountsClient: Sendable { public typealias CreateAndSaveAccount = @Sendable (DisplayName) async throws -> Account public typealias UpdateAccount = @Sendable (Account) async throws -> Void public typealias BatchCreateManySavedAccounts = @Sendable (_ count: UInt16) async throws -> Void - + public var accountByAddress: AccountByAddress public var createAndSaveAccount: CreateAndSaveAccount public var updateAccount: UpdateAccount public var batchCreateManySavedAccounts: BatchCreateManySavedAccounts } +// MARK: DependencyKey extension AccountsClient: DependencyKey { public static let liveValue = Self.live(os: SargonOS.shared) public static func live(os: SargonOS) -> Self { - - return Self( + Self( accountByAddress: { address in try os.accountByAddress(address: address) }, diff --git a/examples/iOS/Backend/Sources/Planbok/Dependencies/FactorSourcesClient.swift b/examples/iOS/Backend/Sources/Planbok/Dependencies/FactorSourcesClient.swift index d645735c1..f3f41c057 100644 --- a/examples/iOS/Backend/Sources/Planbok/Dependencies/FactorSourcesClient.swift +++ b/examples/iOS/Backend/Sources/Planbok/Dependencies/FactorSourcesClient.swift @@ -1,34 +1,28 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - +import DependenciesMacros import Foundation import Sargon -import DependenciesMacros +// MARK: - FactorSourcesClient @DependencyClient public struct FactorSourcesClient: Sendable { - - public typealias AddFactorSource = @Sendable (FactorSource) async throws -> Void - public typealias UpdateFactorSource = @Sendable (FactorSource) async throws -> Void - public typealias CreateHWFactorSource = @Sendable (MnemonicWithPassphrase, FactorSourceKind) async throws -> FactorSource - public typealias CreateSecurityQuestionsFactor = @Sendable (AnswersToQuestions) throws -> SecurityQuestionsNotProductionReadyFactorSource - public typealias DecryptSecurityQuestionsFactor = @Sendable (AnswersToQuestions, SecurityQuestionsNotProductionReadyFactorSource) throws -> Mnemonic + public typealias AddFactorSource = @Sendable (FactorSource) async throws -> Void + public typealias UpdateFactorSource = @Sendable (FactorSource) async throws -> Void + public typealias CreateHWFactorSource = @Sendable (MnemonicWithPassphrase, FactorSourceKind) async throws -> FactorSource + public typealias CreateSecurityQuestionsFactor = @Sendable (AnswersToQuestions) throws -> SecurityQuestionsNotProductionReadyFactorSource + public typealias DecryptSecurityQuestionsFactor = @Sendable (AnswersToQuestions, SecurityQuestionsNotProductionReadyFactorSource) throws -> Mnemonic public typealias AddAllSampleFactors = @Sendable () async throws -> Void - public var createHWFactorSource: CreateHWFactorSource - public var createSecurityQuestionsFactor: CreateSecurityQuestionsFactor - public var decryptSecurityQuestionsFactor: DecryptSecurityQuestionsFactor - public var addFactorSource: AddFactorSource - public var addAllSampleFactors: AddAllSampleFactors + public var createHWFactorSource: CreateHWFactorSource + public var createSecurityQuestionsFactor: CreateSecurityQuestionsFactor + public var decryptSecurityQuestionsFactor: DecryptSecurityQuestionsFactor + public var addFactorSource: AddFactorSource + public var addAllSampleFactors: AddAllSampleFactors public var updateFactorSource: UpdateFactorSource } +// MARK: DependencyKey extension FactorSourcesClient: DependencyKey { - public static let liveValue = Self.live(os: SargonOS.shared) - public static func live(os: SargonOS) -> Self { + public static let liveValue = Self.live(os: SargonOS.shared) + public static func live(os: SargonOS) -> Self { Self( createHWFactorSource: { mnemonicWithPassphrase, kind -> FactorSource in switch kind { @@ -39,9 +33,8 @@ extension FactorSourcesClient: DependencyKey { isMain: false ) : .olympia ).asGeneral - case .ledgerHqHardwareWallet: - LedgerHardwareWalletFactorSource.init( + LedgerHardwareWalletFactorSource( mnemonicWithPassphrase: mnemonicWithPassphrase, hint: LedgerHardwareWalletHint( name: "Unknown", @@ -51,7 +44,7 @@ extension FactorSourcesClient: DependencyKey { ) .asGeneral case .offDeviceMnemonic: - OffDeviceMnemonicFactorSource.init( + OffDeviceMnemonicFactorSource( mnemonicWithPassphrase: mnemonicWithPassphrase, hint: .init( displayName: "Unknown" @@ -66,40 +59,39 @@ extension FactorSourcesClient: DependencyKey { fatalError( "SecurityQuestions FS not supported here." ) - case .trustedContact: fatalError( "Trusted Contact not supported yet" ) } - + }, createSecurityQuestionsFactor: { questionsAndAnswers in - @Dependency(MnemonicClient.self) var mnemonicClient + @Dependency(MnemonicClient.self) var mnemonicClient - let mnemonic = mnemonicClient.generateNewMnemonic(.twentyFour) + let mnemonic = mnemonicClient.generateNewMnemonic(.twentyFour) log.notice("Creating new SecurityQuestions FactorSource, mnemonic is:\n'\(mnemonic.phrase)'\nAnswers:\n\(questionsAndAnswers.map(\.answer))") - return try SecurityQuestionsNotProductionReadyFactorSource( - mnemonic: mnemonic, - questionsAndAnswers: questionsAndAnswers.elements - ) + return try SecurityQuestionsNotProductionReadyFactorSource( + mnemonic: mnemonic, + questionsAndAnswers: questionsAndAnswers.elements + ) }, decryptSecurityQuestionsFactor: { questionsAndAnswers, factor in try factor.decrypt(questionsAndAnswers: questionsAndAnswers.elements) }, addFactorSource: { factorSource in - log.notice("Adding New factorSource: \(factorSource)") - let _ = try await os.addFactorSource(factorSource: factorSource) + log.notice("Adding New factorSource: \(factorSource)") + _ = try await os.addFactorSource(factorSource: factorSource) log.info("Finished adding new factorSource.") }, addAllSampleFactors: { log.notice("Adding Many Sample factorSources") - let _ = try await os.debugAddAllSampleFactors() + _ = try await os.debugAddAllSampleFactors() log.notice("Finished adding Many Sample factorSources") }, updateFactorSource: { factorSource in log.notice("Updating factorSource: \(factorSource)") - let _ = try await os.updateFactorSource(updated: factorSource) + _ = try await os.updateFactorSource(updated: factorSource) log.info("Finished updating factorSource.") } ) diff --git a/examples/iOS/Backend/Sources/Planbok/Dependencies/GatewaysClient.swift b/examples/iOS/Backend/Sources/Planbok/Dependencies/GatewaysClient.swift index f557d071e..7e715f3bf 100644 --- a/examples/iOS/Backend/Sources/Planbok/Dependencies/GatewaysClient.swift +++ b/examples/iOS/Backend/Sources/Planbok/Dependencies/GatewaysClient.swift @@ -1,27 +1,22 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - +import DependenciesMacros import Foundation import Sargon -import DependenciesMacros +// MARK: - GatewaysClient @DependencyClient public struct GatewaysClient: Sendable { public typealias SwitchGatewayTo = @Sendable (Gateway) async throws -> Void public var switchGatewayTo: SwitchGatewayTo } +// MARK: DependencyKey extension GatewaysClient: DependencyKey { public static let liveValue = Self.live(os: SargonOS.shared) public static func live(os: SargonOS) -> Self { Self( switchGatewayTo: { to in log.notice("Changing current gateway to: \(to)") - let _ = try await os.changeCurrentGateway(to: to) + _ = try await os.changeCurrentGateway(to: to) log.info("Finished changing current gateway.") } ) diff --git a/examples/iOS/Backend/Sources/Planbok/Dependencies/Keychain.swift b/examples/iOS/Backend/Sources/Planbok/Dependencies/Keychain.swift index dccd7c443..a05e36ffc 100644 --- a/examples/iOS/Backend/Sources/Planbok/Dependencies/Keychain.swift +++ b/examples/iOS/Backend/Sources/Planbok/Dependencies/Keychain.swift @@ -1,18 +1,12 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-02-15. -// - +import ComposableArchitecture @_exported import KeychainAccess import Sargon -import ComposableArchitecture - +// MARK: - Keychain + @unchecked Sendable extension Keychain: @unchecked Sendable {} -extension Keychain: SecureStorageDriver { +// MARK: - Keychain + SecureStorageDriver +extension Keychain: SecureStorageDriver { @Sendable public func loadData(key: SecureStorageKey) throws -> Data? { try getData(key.identifier) diff --git a/examples/iOS/Backend/Sources/Planbok/Dependencies/MnemonicClient.swift b/examples/iOS/Backend/Sources/Planbok/Dependencies/MnemonicClient.swift index 8cdfcca0b..f736761f5 100644 --- a/examples/iOS/Backend/Sources/Planbok/Dependencies/MnemonicClient.swift +++ b/examples/iOS/Backend/Sources/Planbok/Dependencies/MnemonicClient.swift @@ -1,23 +1,17 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - +import DependenciesMacros import Foundation import Sargon -import DependenciesMacros +// MARK: - MnemonicClient @DependencyClient public struct MnemonicClient: Sendable { - public typealias LoadMnemonic = @Sendable (FactorSourceIDFromHash) async throws -> PrivateHierarchicalDeterministicFactorSource - public typealias GenerateNewMnemonic = @Sendable (BIP39WordCount) -> Mnemonic - public var loadMnemonic: LoadMnemonic - public var generateNewMnemonic: GenerateNewMnemonic + public typealias LoadMnemonic = @Sendable (FactorSourceIDFromHash) async throws -> PrivateHierarchicalDeterministicFactorSource + public typealias GenerateNewMnemonic = @Sendable (BIP39WordCount) -> Mnemonic + public var loadMnemonic: LoadMnemonic + public var generateNewMnemonic: GenerateNewMnemonic } - +// MARK: DependencyKey extension MnemonicClient: DependencyKey { public static let liveValue = Self.live(os: SargonOS.shared) public static func live(os: SargonOS) -> Self { @@ -25,9 +19,9 @@ extension MnemonicClient: DependencyKey { loadMnemonic: { id in try await os.loadPrivateDeviceFactorSourceById(id: id) }, - generateNewMnemonic: { wordCount in - Mnemonic(wordCount: wordCount, language: .english) - } + generateNewMnemonic: { wordCount in + Mnemonic(wordCount: wordCount, language: .english) + } ) } } diff --git a/examples/iOS/Backend/Sources/Planbok/Dependencies/PasteboardClient.swift b/examples/iOS/Backend/Sources/Planbok/Dependencies/PasteboardClient.swift index ec050d57a..1a942c8e0 100644 --- a/examples/iOS/Backend/Sources/Planbok/Dependencies/PasteboardClient.swift +++ b/examples/iOS/Backend/Sources/Planbok/Dependencies/PasteboardClient.swift @@ -1,27 +1,24 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-12. -// - -import Foundation -import Dependencies import AsyncExtensions +import Dependencies +import Foundation #if canImport(UIKit) import UIKit + public typealias Pasteboard = UIPasteboard extension Pasteboard { @Sendable public func setCopied(string: String) { self.string = string } + @Sendable public func getCopied() -> String? { self.string } } + #elseif canImport(AppKit) import AppKit + public typealias Pasteboard = NSPasteboard extension NSPasteboard: @unchecked Sendable {} @@ -29,22 +26,26 @@ extension Pasteboard { @Sendable public func setCopied(string: String) { self.setString(string, forType: .string) } + @Sendable public func getCopied() -> String? { self.string(forType: .string) } } #endif +// MARK: - PasteboardClient @DependencyClient public struct PasteboardClient: Sendable { public typealias CopyEvents = @Sendable () -> AnyAsyncSequence public typealias CopyString = @Sendable (String) -> Void public typealias GetString = @Sendable () -> String? - + public var copyEvents: CopyEvents public var copyString: CopyString public var getString: GetString } + +// MARK: DependencyKey extension PasteboardClient: DependencyKey { public typealias Value = Self public static let liveValue = Self.live() diff --git a/examples/iOS/Backend/Sources/Planbok/Dependencies/ProfileClient.swift b/examples/iOS/Backend/Sources/Planbok/Dependencies/ProfileClient.swift index 9971e52c3..2ce5db7de 100644 --- a/examples/iOS/Backend/Sources/Planbok/Dependencies/ProfileClient.swift +++ b/examples/iOS/Backend/Sources/Planbok/Dependencies/ProfileClient.swift @@ -1,21 +1,15 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - +import DependenciesMacros import Foundation import Sargon -import DependenciesMacros +// MARK: - ProfileClient @DependencyClient public struct ProfileClient: Sendable { public typealias ActiveProfile = @Sendable () -> Profile public typealias DeleteProfileAndMnemonicsThenCreateNew = @Sendable () async throws -> Void public typealias ImportProfile = @Sendable (Profile) async throws -> Void public typealias DecryptEncryptedProfile = @Sendable (_ encrypted: Data, _ password: String) throws -> Profile - + public typealias EmulateFreshInstallOfAppThenRestart = @Sendable () async throws -> Void public var activeProfile: ActiveProfile @@ -25,15 +19,16 @@ public struct ProfileClient: Sendable { public var emulateFreshInstallOfAppThenRestart: EmulateFreshInstallOfAppThenRestart } +// MARK: DependencyKey extension ProfileClient: DependencyKey { public static let liveValue = Self.live(os: SargonOS.shared) public static func live(os: SargonOS) -> Self { - return Self( + Self( activeProfile: { try! os.profile() }, deleteProfileAndMnemonicsThenCreateNew: { - try await os.deleteWallet() + try await os.deleteWallet() }, importProfile: { try await os.importProfile(profile: $0) @@ -42,8 +37,8 @@ extension ProfileClient: DependencyKey { try Profile(encrypted: $0, decryptionPassword: $1) }, emulateFreshInstallOfAppThenRestart: { - log.warning("TODO Migrate `emulateFreshInstallOfAppThenRestart`, not in Sargon anymore.") - try await os.deleteWallet() + log.warning("TODO Migrate `emulateFreshInstallOfAppThenRestart`, not in Sargon anymore.") + try await os.deleteWallet() } ) } diff --git a/examples/iOS/Backend/Sources/Planbok/Dependencies/ShieldClient.swift b/examples/iOS/Backend/Sources/Planbok/Dependencies/ShieldClient.swift index a437c1f4c..0e0ee2f88 100644 --- a/examples/iOS/Backend/Sources/Planbok/Dependencies/ShieldClient.swift +++ b/examples/iOS/Backend/Sources/Planbok/Dependencies/ShieldClient.swift @@ -1,14 +1,15 @@ +import DependenciesMacros import Foundation import Sargon -import DependenciesMacros +// MARK: - ShieldClient @DependencyClient public struct ShieldClient: Sendable { public typealias SaveSecurityShield = @Sendable (Shield) async throws -> Bool public var saveSecurityShield: SaveSecurityShield } - +// MARK: DependencyKey extension ShieldClient: DependencyKey { public static let liveValue = Self.live(os: SargonOS.shared) public static func live(os: SargonOS) -> Self { diff --git a/examples/iOS/Backend/Sources/Planbok/Exports.swift b/examples/iOS/Backend/Sources/Planbok/Exports.swift index 371440c5e..b85e6f643 100644 --- a/examples/iOS/Backend/Sources/Planbok/Exports.swift +++ b/examples/iOS/Backend/Sources/Planbok/Exports.swift @@ -1,12 +1,5 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-02-14. -// - +@_exported import ComposableArchitecture +@_exported import DependenciesAdditions @_exported import Foundation @_exported import Sargon @_exported import SwiftUI -@_exported import ComposableArchitecture -@_exported import DependenciesAdditions diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Account/AccountDetailsFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Account/AccountDetailsFeature.swift index 0341573d1..0b78a8e90 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Account/AccountDetailsFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Account/AccountDetailsFeature.swift @@ -1,47 +1,40 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture import SwiftUI +// MARK: - AccountDetailsFeature @Reducer public struct AccountDetailsFeature { - @Dependency(AccountsClient.self) var accountsClient - + @Reducer(state: .equatable) public enum Destination { case changeGradient(SelectGradientFeature) } - + @ObservableState public struct State: Equatable { public var accountForDisplay: AccountForDisplay - + @Presents var destination: Destination.State? - + public init(accountForDisplay: AccountForDisplay) { self.accountForDisplay = accountForDisplay } } - + public enum Action: ViewAction { public enum ViewAction { case changeGradientButtonTapped } - + case destination(PresentationAction) case view(ViewAction) } - + public init() {} - + public var body: some ReducerOf { Reduce { state, action in switch action { @@ -54,12 +47,12 @@ public struct AccountDetailsFeature { case let .destination(.presented(.changeGradient(.delegate(.selected(newGradient))))): state.accountForDisplay.appearanceId = newGradient state.destination = nil - return .run { [address = state.accountForDisplay.address] send in + return .run { [address = state.accountForDisplay.address] _ in var account = try accountsClient.accountByAddress(address) account.appearanceId = newGradient try await accountsClient.updateAccount(account) } - + default: return .none } @@ -68,8 +61,8 @@ public struct AccountDetailsFeature { } } +// MARK: AccountDetailsFeature.View extension AccountDetailsFeature { - @ViewAction(for: AccountDetailsFeature.self) public struct View: SwiftUI.View { @Bindable public var store: StoreOf @@ -77,7 +70,7 @@ extension AccountDetailsFeature { NavigationView { VStack { AccountView(accountForDisplay: store.accountForDisplay, format: .full) - + Button("Change Gradient") { send(.changeGradientButtonTapped) } @@ -91,4 +84,3 @@ extension AccountDetailsFeature { } } } - diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Account/AccountsFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Account/AccountsFeature.swift index 6e43fad1c..f7bd7ed36 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Account/AccountsFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Account/AccountsFeature.swift @@ -1,62 +1,61 @@ -import Sargon import ComposableArchitecture +import Sargon - +// MARK: - AccountsFeature @Reducer public struct AccountsFeature { - public init() {} - + @ObservableState public struct State: Equatable { @SharedReader(.network) var network @SharedReader(.accountsForDisplay) var accountsForDisplay } - + public enum Action: ViewAction { public enum ViewAction { case accountCardTapped(AccountForDisplay) case createNewAccountButtonTapped } + public enum DelegateAction { case createNewAccount(index: Int) case showDetailsFor(AccountForDisplay) } + case view(ViewAction) case delegate(DelegateAction) } - - + public var body: some ReducerOf { Reduce { state, action in switch action { - case .view(.createNewAccountButtonTapped): - return .send(.delegate(.createNewAccount(index: state.accountsForDisplay.count))) - + .send(.delegate(.createNewAccount(index: state.accountsForDisplay.count))) + case let .view(.accountCardTapped(account)): - return .send(.delegate(.showDetailsFor(account))) - - default: return .none + .send(.delegate(.showDetailsFor(account))) + + default: .none } } } } +// MARK: AccountsFeature.View extension AccountsFeature { @ViewAction(for: AccountsFeature.self) public struct View: SwiftUI.View { - public let store: StoreOf - + public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { VStack { Text("Accounts").font(.largeTitle) - + if store.state.accountsForDisplay.isEmpty { Text("You dont have any accounts on \(store.state.network.description)") } else { @@ -70,13 +69,12 @@ extension AccountsFeature { } } } - + Spacer() - + Button("Create New Account") { send(.createNewAccountButtonTapped) } - } .padding() } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Account/SelectGradientFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Account/SelectGradientFeature.swift index e2b5aebaa..598a94617 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Account/SelectGradientFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Account/SelectGradientFeature.swift @@ -1,17 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-02-16. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture +// MARK: - SelectGradientFeature @Reducer public struct SelectGradientFeature { - @ObservableState public struct State: Equatable { public var gradient: AppearanceID @@ -21,50 +14,51 @@ public struct SelectGradientFeature { self.gradient = gradient } } - + @CasePathable public enum Action: ViewAction { public enum Delegate { case selected(AppearanceID) } + @CasePathable public enum ViewAction { case selectedGradient(AppearanceID) case confirmedGradientButtonTapped } + case view(ViewAction) case delegate(Delegate) } - + public init() {} - + public var body: some ReducerOf { Reduce { state, action in switch action { - case let .view(.selectedGradient(gradient)): state.gradient = gradient return .none - + case .view(.confirmedGradientButtonTapped): return .send(.delegate(.selected(state.gradient))) - + default: return .none - } } } } +// MARK: SelectGradientFeature.View extension SelectGradientFeature { - @ViewAction(for: SelectGradientFeature.self) public struct View: SwiftUI.View { public let store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack { Text("Select account gradient").font(.title) @@ -77,9 +71,9 @@ extension SelectGradientFeature { Text("Gradient \(String(describing: appearanceID))") .font(isSelected ? .headline : .subheadline) .fontWeight(isSelected ? .bold : .regular) - + Spacer() - + if isSelected { Image(systemName: "checkmark") .resizable() @@ -93,7 +87,6 @@ extension SelectGradientFeature { .padding() .background(appearanceID.gradient) .cornerRadius(height) - } } Button("Confirm Gradient") { diff --git a/examples/iOS/Backend/Sources/Planbok/Features/AppFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/AppFeature.swift index d295a875e..9e260bfe1 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/AppFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/AppFeature.swift @@ -1,91 +1,94 @@ -import Sargon import ComposableArchitecture +import Sargon +// MARK: - ProfileStateChangeDriverClass final class ProfileStateChangeDriverClass { - init() {} - static let shared = ProfileStateChangeDriverClass() + init() {} + static let shared = ProfileStateChangeDriverClass() } + +// MARK: ProfileStateChangeDriver extension ProfileStateChangeDriverClass: ProfileStateChangeDriver { - func handleProfileStateChange(changedProfileState: ProfileState) async { - log.warning("profileStateChangeDriver not used, ignored event") - switch changedProfileState { - case .incompatible(let error): - fatalError("incompatible profile snapshot format, error: \(error)") - case .loaded(let loadedProfile): - log.notice("Loaded profile - id: \(loadedProfile.header.id)") - case .none: - log.notice("Profle changed to `none`.") - } - } + func handleProfileStateChange(changedProfileState: ProfileState) async { + log.warning("profileStateChangeDriver not used, ignored event") + switch changedProfileState { + case let .incompatible(error): + fatalError("incompatible profile snapshot format, error: \(error)") + case let .loaded(loadedProfile): + log.notice("Loaded profile - id: \(loadedProfile.header.id)") + case .none: + log.notice("Profle changed to `none`.") + } + } } +// MARK: - HostInfoDriverClass final class HostInfoDriverClass { - init() {} - static let shared = HostInfoDriverClass() + init() {} + static let shared = HostInfoDriverClass() } + +// MARK: HostInfoDriver extension HostInfoDriverClass: HostInfoDriver { - func hostOs() async -> HostOs { - HostOs.ios(version: "read") - } - - func hostDeviceName() async -> String { - "iPhone wip" - } - - func hostAppVersion() async -> String { - "0.0.1" - } - - func hostDeviceModel() async -> String { - "iPhone wip" - } - - + func hostOs() async -> HostOs { + HostOs.ios(version: "read") + } + + func hostDeviceName() async -> String { + "iPhone wip" + } + + func hostAppVersion() async -> String { + "0.0.1" + } + + func hostDeviceModel() async -> String { + "iPhone wip" + } } +// MARK: - AppFeature @Reducer public struct AppFeature { - @ObservableState public enum State { case splash(SplashFeature.State) case onboarding(OnboardingFeature.State) case main(MainFeature.State) - + public init(isEmulatingFreshInstall: Bool = false) { let drivers = Drivers( networking: URLSession.shared, - secureStorage: Keychain(service: "rdx.works.planbok"), - entropyProvider: EntropyProvider.shared, - hostInfo: HostInfoDriverClass.shared, - logging: Log.shared, - eventBus: EventBus.shared, - fileSystem: FileSystem.shared, - unsafeStorage: UnsafeStorage.init( - userDefaults: .init( - suiteName: "rdx.works" - )! - ), profileStateChangeDriver: ProfileStateChangeDriverClass.shared - ) - + secureStorage: Keychain(service: "rdx.works.planbok"), + entropyProvider: EntropyProvider.shared, + hostInfo: HostInfoDriverClass.shared, + logging: Log.shared, + eventBus: EventBus.shared, + fileSystem: FileSystem.shared, + unsafeStorage: UnsafeStorage( + userDefaults: .init( + suiteName: "rdx.works" + )! + ), profileStateChangeDriver: ProfileStateChangeDriverClass.shared + ) + BIOS.creatingShared(drivers: drivers) - + self = .splash(.init(isEmulatingFreshInstall: true)) } } - + public enum Action { case splash(SplashFeature.Action) case onboarding(OnboardingFeature.Action) case main(MainFeature.Action) } - + public init() {} - + public var body: some ReducerOf { Reduce { state, action in switch action { - case let .splash(.delegate(.booted(hasAnyAccountOnAnyNetwork))): if hasAnyAccountOnAnyNetwork { state = .main(MainFeature.State()) @@ -93,19 +96,19 @@ public struct AppFeature { state = .onboarding(OnboardingFeature.State()) } return .none - + case .onboarding(.delegate(.done)): state = .main(MainFeature.State()) return .none - + case .main(.delegate(.deletedWallet)): state = .onboarding(OnboardingFeature.State()) return .none - + case .main(.delegate(.emulateFreshInstall)): state = AppFeature.State(isEmulatingFreshInstall: true) return .none - + default: return .none } @@ -122,13 +125,14 @@ public struct AppFeature { } } +// MARK: AppFeature.View extension AppFeature { public struct View: SwiftUI.View { public let store: StoreOf public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { switch store.state { case .splash: diff --git a/examples/iOS/Backend/Sources/Planbok/Features/DebugProfileFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/DebugProfileFeature.swift index 476415123..d862de95e 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/DebugProfileFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/DebugProfileFeature.swift @@ -1,41 +1,35 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-12. -// - -import Foundation -import Sargon +import AsyncExtensions import ComposableArchitecture +import Foundation import JSONViewer -import AsyncExtensions - +import Sargon +// MARK: - DebugProfileFeature @Reducer public struct DebugProfileFeature { - @Dependency(ProfileClient.self) var profileClient @Dependency(PasteboardClient.self) var pasteboardClient - + @ObservableState public struct State { public var profileJSONString: String? } - + public enum Action: ViewAction, Sendable { public enum ViewAction: Sendable { case appear case copyNode(String) case copyButtonTapped } + public enum InternalAction: Sendable { case loadedProfileString(String) } + case view(ViewAction) case `internal`(InternalAction) } - + public var body: some ReducerOf { Reduce { state, action in switch action { @@ -51,12 +45,12 @@ public struct DebugProfileFeature { } pasteboardClient.copyString(profileJSONString) return .none - + case let .view(.copyNode(nodeValue)): // this is NOT JSON... pasteboardClient.copyString(nodeValue) return .none - + case let .internal(.loadedProfileString(profileJSONString)): state.profileJSONString = profileJSONString return .none @@ -67,13 +61,14 @@ public struct DebugProfileFeature { extension DebugProfileFeature { public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { public let store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { Group { if let profileJSONString = store.profileJSONString { diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Manage/ManageFactorSourcesFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Manage/ManageFactorSourcesFeature.swift index 26616b787..c4706acff 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Manage/ManageFactorSourcesFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Manage/ManageFactorSourcesFeature.swift @@ -1,138 +1,125 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture import SwiftUI +// MARK: - ManageFactorSourcesFeature @Reducer public struct ManageFactorSourcesFeature { - @Dependency(FactorSourcesClient.self) var factorsClient - - @ObservableState - public struct State: Equatable { + + @ObservableState + public struct State: Equatable { @SharedReader(.factorSources) var factorSources - } - - @CasePathable - public enum Action: ViewAction { - - @CasePathable - public enum ViewAction { + } + + @CasePathable + public enum Action: ViewAction { + @CasePathable + public enum ViewAction { case addAllSampleValuesTapped - - case deviceButtonTapped - case ledgerButtonTapped - case arculusButtonTapped - case offDeviceButtonTapped - case securityQuestionsButtonTapped - case trustedContactButtonTapped - } - - case view(ViewAction) - - @CasePathable - public enum DelegateAction { - case navigate(Navigate) - - @CasePathable - public enum Navigate { + + case deviceButtonTapped + case ledgerButtonTapped + case arculusButtonTapped + case offDeviceButtonTapped + case securityQuestionsButtonTapped + case trustedContactButtonTapped + } + + case view(ViewAction) + + @CasePathable + public enum DelegateAction { + case navigate(Navigate) + + @CasePathable + public enum Navigate { case toFactor(kind: FactorSourceKind) - } - } - - case delegate(DelegateAction) - } - - public init() {} - - public var body: some ReducerOf { - Reduce { state, action in - switch action { + } + } + + case delegate(DelegateAction) + } + + public init() {} + + public var body: some ReducerOf { + Reduce { _, action in + switch action { case .view(.addAllSampleValuesTapped): - return .run { send in + .run { _ in try await factorsClient.addAllSampleFactors() } - - case .view(.deviceButtonTapped): - return .send(.delegate(.navigate(.toFactor(kind: .device)))) - + + case .view(.deviceButtonTapped): + .send(.delegate(.navigate(.toFactor(kind: .device)))) + case .view(.ledgerButtonTapped): - return .send(.delegate(.navigate(.toFactor(kind: .ledgerHqHardwareWallet)))) - + .send(.delegate(.navigate(.toFactor(kind: .ledgerHqHardwareWallet)))) + case .view(.arculusButtonTapped): - return .send(.delegate(.navigate(.toFactor(kind: .arculusCard)))) - + .send(.delegate(.navigate(.toFactor(kind: .arculusCard)))) + case .view(.offDeviceButtonTapped): - return .send(.delegate(.navigate(.toFactor(kind: .offDeviceMnemonic)))) - + .send(.delegate(.navigate(.toFactor(kind: .offDeviceMnemonic)))) + case .view(.securityQuestionsButtonTapped): - return .send(.delegate(.navigate(.toFactor(kind: .securityQuestions)))) - + .send(.delegate(.navigate(.toFactor(kind: .securityQuestions)))) + case .view(.trustedContactButtonTapped): - return .send(.delegate(.navigate(.toFactor(kind: .trustedContact)))) - - default: - return .none - - } - } - } + .send(.delegate(.navigate(.toFactor(kind: .trustedContact)))) + + default: + .none + } + } + } } +// MARK: ManageFactorSourcesFeature.View extension ManageFactorSourcesFeature { - - @ViewAction(for: ManageFactorSourcesFeature.self) - public struct View: SwiftUI.View { - - @Bindable public var store: StoreOf - - public var body: some SwiftUI.View { - VStack { - Text("FactorSources").font(.largeTitle) + @ViewAction(for: ManageFactorSourcesFeature.self) + public struct View: SwiftUI.View { + @Bindable public var store: StoreOf + + public var body: some SwiftUI.View { + VStack { + Text("FactorSources").font(.largeTitle) Text("You have #\(store.state.factorSources.count) factor sources") Text("of #\(Set(store.state.factorSources.map(\.kind)).count) different kinds.") - + Button("ADD ALL SAMPLE FACTORS") { send(.addAllSampleValuesTapped) } - + Spacer() - + Button("Device") { send(.deviceButtonTapped) } - + Button("Ledger") { send(.ledgerButtonTapped) } - + Button("Arculus") { send(.arculusButtonTapped) } - + Button("Off Device Mnemonic") { send(.offDeviceButtonTapped) } - + Button("Security Questions") { send(.securityQuestionsButtonTapped) } - + Button("Trusted Contact") { send(.trustedContactButtonTapped) } - - } - .padding(.bottom, 100) - } - } - + } + .padding(.bottom, 100) + } + } } - diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Manage/ManageSpecificFactorSourcesFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Manage/ManageSpecificFactorSourcesFeature.swift index 4da5e5b4a..bf6df03c7 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Manage/ManageSpecificFactorSourcesFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Manage/ManageSpecificFactorSourcesFeature.swift @@ -1,14 +1,14 @@ +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture import SwiftUI +// MARK: - EditLabelOffDeviceMnemonicFactor @Reducer public struct EditLabelOffDeviceMnemonicFactor { - @Dependency(FactorSourcesClient.self) var factorSourcesClient @Dependency(\.dismiss) var dismiss - + @ObservableState public struct State: Equatable { public let factorSource: OffDeviceMnemonicFactorSource @@ -16,12 +16,13 @@ public struct EditLabelOffDeviceMnemonicFactor { public var displayName: DisplayName? { try? DisplayName(validating: label) } + public init(factorSource: OffDeviceMnemonicFactorSource) { self.factorSource = factorSource self.label = factorSource.hint.displayName.value } } - + @CasePathable public enum Action: ViewAction { @CasePathable @@ -29,9 +30,10 @@ public struct EditLabelOffDeviceMnemonicFactor { case labelChanged(String) case confirmButtonTapped } + case view(ViewAction) } - + public var body: some ReducerOf { Reduce { state, action in switch action { @@ -42,8 +44,8 @@ public struct EditLabelOffDeviceMnemonicFactor { guard let displayName = state.displayName else { return .none } - - return .run { [factorSource = state.factorSource] send in + + return .run { [factorSource = state.factorSource] _ in var factorSource = factorSource factorSource.hint.displayName = displayName try await factorSourcesClient.updateFactorSource(factorSource.asGeneral) @@ -53,15 +55,17 @@ public struct EditLabelOffDeviceMnemonicFactor { } } } + extension EditLabelOffDeviceMnemonicFactor { public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { @Bindable public var store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack { LabeledTextField(label: "", text: $store.label.sending(\.view.labelChanged)) @@ -73,18 +77,17 @@ extension EditLabelOffDeviceMnemonicFactor { } } } - } +// MARK: - ManageSpecificFactorSourcesFeature @Reducer public struct ManageSpecificFactorSourcesFeature { - @Reducer(state: .equatable) public enum Destination { case decryptSecurityQuestions(DecryptSecurityQuestionsFeatureCoordinator) case editLabelOffDeviceMnemonicFactor(EditLabelOffDeviceMnemonicFactor) } - + @ObservableState public struct State { @SharedReader(.factorSources) var factorSources @@ -92,35 +95,34 @@ public struct ManageSpecificFactorSourcesFeature { @Presents var destination: Destination.State? public let kind: FactorSourceKind } - + @CasePathable public enum Action: ViewAction { - @CasePathable public enum ViewAction { case addNewButtonTapped case factorSourceActionButtonTapped(FactorSource) } - + case view(ViewAction) case destination(PresentationAction) - + @CasePathable public enum DelegateAction { case addNew(FactorSourceKind) } - + case delegate(DelegateAction) } - + public init() {} - + public var body: some ReducerOf { Reduce { state, action in switch action { case .view(.addNewButtonTapped): return .send(.delegate(.addNew(state.kind))) - + case let .view(.factorSourceActionButtonTapped(factorSource)): if let securityQuestions = factorSource.asSecurityQuestions { state.destination = .decryptSecurityQuestions( @@ -141,7 +143,6 @@ public struct ManageSpecificFactorSourcesFeature { default: return .none - } } .ifLet(\.$destination, action: \.destination) @@ -150,23 +151,23 @@ public struct ManageSpecificFactorSourcesFeature { extension ManageSpecificFactorSourcesFeature { public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { - @Bindable public var store: StoreOf - + public var kind: FactorSourceKind { store.kind } + public var factors: IdentifiedArrayOf { store.factorSources.filter(kind: kind) } - + public var body: some SwiftUI.View { VStack { Text("\(kind) Factors").font(.largeTitle) - + if factors.isEmpty { Text("You have no factors") } else { @@ -180,9 +181,9 @@ extension ManageSpecificFactorSourcesFeature { } } } - + Spacer() - + Button("Add New") { send(.addNewButtonTapped) } @@ -206,6 +207,4 @@ extension ManageSpecificFactorSourcesFeature { } } } - } - diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/New/InputMnemonicFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/New/InputMnemonicFeature.swift index b8e8936de..4338b49fd 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/New/InputMnemonicFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/New/InputMnemonicFeature.swift @@ -1,21 +1,14 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-01. -// - -import Foundation import ComposableArchitecture +import Foundation import Sargon +// MARK: - InputMnemonicFeature @Reducer public struct InputMnemonicFeature { - @Reducer(state: .equatable) public enum Destination { case prefillMnemonic(AlertState) - + public enum PrefillMnemonicAlert: String, CaseIterable { case device24 case device24Other @@ -31,7 +24,7 @@ public struct InputMnemonicFeature { case arculusOther } } - + @ObservableState public struct State: Equatable { @Presents var destination: Destination.State? @@ -40,12 +33,13 @@ public struct InputMnemonicFeature { public var mnemonic: Mnemonic? { try? Mnemonic(phrase: phrase) } + public var mnemonicWithPassphrase: MnemonicWithPassphrase? { guard let mnemonic else { return nil } return MnemonicWithPassphrase(mnemonic: mnemonic, passphrase: bip39Passphrase) } } - + @CasePathable public enum Action: ViewAction { @CasePathable @@ -54,30 +48,31 @@ public struct InputMnemonicFeature { case prefillButtonTapped case confirmMnemonicButtonTapped } + public enum DelegateAction { case confirmed(MnemonicWithPassphrase) } + case view(ViewAction) case delegate(DelegateAction) case destination(PresentationAction) - } - + public init() {} - + public var body: some ReducerOf { Reduce { state, action in switch action { case let .view(.phraseChanged(phrase)): state.phrase = phrase return .none - + case .view(.prefillButtonTapped): state.destination = .prefillMnemonic(.init( title: TextState("Prefill Mnemonic"), message: TextState("Will fill in the phrase"), buttons: [ - .cancel(TextState("Cancel")) + .cancel(TextState("Cancel")), ] + Destination.PrefillMnemonicAlert.allCases.map { action in ButtonState(action: action, label: { TextState("Prefill \(action.rawValue)") @@ -85,14 +80,14 @@ public struct InputMnemonicFeature { } )) return .none - + case .view(.confirmMnemonicButtonTapped): guard let mnemonicWithPassphrase = state.mnemonicWithPassphrase else { return .none } return .send(.delegate(.confirmed(mnemonicWithPassphrase))) - + case .delegate: return .none - + case let .destination(.presented(.prefillMnemonic(prefillAction))): let mnemonic = switch prefillAction { case .device24: Mnemonic.sampleDevice @@ -109,10 +104,11 @@ public struct InputMnemonicFeature { case .offDeviceOther: Mnemonic.sampleOffDeviceMnemonicOther } return .send(.view(.phraseChanged(mnemonic.phrase))) - + case .destination(.dismiss): state.destination = nil return .none + case .destination: return .none } @@ -121,29 +117,27 @@ public struct InputMnemonicFeature { } } - extension InputMnemonicFeature { public typealias HostingFeature = Self @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { - @Bindable public var store: StoreOf - + public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { VStack { Text("Input Mnemonic").font(.largeTitle) - + LabeledTextField(label: "Phrase", text: $store.phrase.sending(\.view.phraseChanged)) - + Button("Prefill") { send(.prefillButtonTapped) } - + Button("Confirm") { send(.confirmMnemonicButtonTapped) } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/New/NewHWFactorSourceFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/New/NewHWFactorSourceFeature.swift index 8457c72f9..4ead2b9af 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/New/NewHWFactorSourceFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/New/NewHWFactorSourceFeature.swift @@ -1,19 +1,12 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-01. -// - -import Foundation import ComposableArchitecture +import Foundation import Sargon +// MARK: - NewHWFactorSourceFeature @Reducer public struct NewHWFactorSourceFeature { - @Dependency(FactorSourcesClient.self) var factorSourcesClient - + @ObservableState public struct State: Equatable { public let kind: FactorSourceKind @@ -23,7 +16,7 @@ public struct NewHWFactorSourceFeature { self.inputMnemonic = .init() } } - + @CasePathable public enum Action { case `internal`(InternalAction) @@ -32,34 +25,35 @@ public struct NewHWFactorSourceFeature { public enum InternalAction { case inputMnemonic(InputMnemonicFeature.Action) } + @CasePathable public enum DelegateAction { case createdAndSavedNewFactorSource } } - + public var body: some ReducerOf { Scope(state: \.inputMnemonic, action: \.internal.inputMnemonic) { InputMnemonicFeature() } - + Reduce { state, action in switch action { case let .internal(.inputMnemonic(.delegate(.confirmed(mnemonicWithPassphrase)))): - return .run { [kind = state.kind] send in + .run { [kind = state.kind] send in let factorSource = try await factorSourcesClient.createHWFactorSource(mnemonicWithPassphrase, kind) try await factorSourcesClient.addFactorSource(factorSource) await send(.delegate(.createdAndSavedNewFactorSource)) } + case .delegate: - return .none - + .none + case .internal: - return .none + .none } } } - } extension NewHWFactorSourceFeature { @@ -69,6 +63,7 @@ extension NewHWFactorSourceFeature { public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack { Text("New \(store.state.kind) Factor") diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/New/NewTrustedContactFactorSourceFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/New/NewTrustedContactFactorSourceFeature.swift index 9824e3023..db3ef3875 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/New/NewTrustedContactFactorSourceFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/New/NewTrustedContactFactorSourceFeature.swift @@ -1,40 +1,32 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-03. -// - -import Foundation import ComposableArchitecture +import Foundation import Sargon +// MARK: - NewTrustedContactFactorSourceFeature @Reducer public struct NewTrustedContactFactorSourceFeature { - @Dependency(FactorSourcesClient.self) var factorSourcesClient - + @ObservableState public struct State: Equatable { - @SharedReader(.network) var network - + public var email = "" public var name = "" public var accountAddress = "" - + public var emailAddress: EmailAddress? { EmailAddress(email: email) } - + public var displayName: DisplayName? { try? DisplayName(validating: name) } - + public var account: AccountAddress? { try? AccountAddress(validatingAddress: accountAddress) } - + public var contact: TrustedContactFactorSourceContact? { guard let emailAddress, let displayName else { return nil @@ -45,47 +37,49 @@ public struct NewTrustedContactFactorSourceFeature { ) } } - + public enum Action: BindableAction, ViewAction { public enum ViewAction { case addButtonTapped case randomEmailAddressButtonTapped case randomAccountAddressButtonTapped } + public enum DelegateAction { case done } + case binding(BindingAction) case view(ViewAction) case delegate(DelegateAction) } - + public var body: some ReducerOf { BindingReducer() Reduce { state, action in switch action { - case .view(.randomEmailAddressButtonTapped): let wordlist = bip39LanguageWordlist(language: .english) let word0 = wordlist.randomElement()!.word let word1 = wordlist.randomElement()!.word state.email = "\(word0)@\(word1).com" return .none - + case .view(.randomAccountAddressButtonTapped): state.accountAddress = AccountAddress.random(networkID: state.network).address return .none - + case .view(.addButtonTapped): guard let contact = state.contact, - let accountAddress = state.account else { + let accountAddress = state.account + else { return .none } let trustedContact = TrustedContactFactorSource( accountAddress: accountAddress, contact: contact ) - + return .run { send in try await factorSourcesClient.addFactorSource(trustedContact.asGeneral) await send(.delegate(.done)) @@ -93,10 +87,9 @@ public struct NewTrustedContactFactorSourceFeature { case .binding: return .none - + case .delegate: return .none - } } } @@ -104,18 +97,19 @@ public struct NewTrustedContactFactorSourceFeature { extension NewTrustedContactFactorSourceFeature { public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { @Bindable public var store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack { Text("New Trusted Contact") .font(.largeTitle) - + Spacer() LabeledTextField(label: "Name", text: $store.name) @@ -123,13 +117,13 @@ extension NewTrustedContactFactorSourceFeature { LabeledTextField(label: "AccountAddress", text: $store.accountAddress) { buttonRandomize(with: .randomAccountAddressButtonTapped) } - + LabeledTextField(label: "Email", text: $store.email) { buttonRandomize(with: .randomEmailAddressButtonTapped) } - + Spacer() - + Button("Add Factor Source") { send(.addButtonTapped) } @@ -137,7 +131,7 @@ extension NewTrustedContactFactorSourceFeature { .disabled(store.contact == nil || store.account == nil) } } - + @ViewBuilder private func buttonRandomize( with action: HostingFeature.Action.ViewAction @@ -150,7 +144,6 @@ extension NewTrustedContactFactorSourceFeature { .background(Color.blue) .clipShape(.rect(cornerRadius: 10)) }) - } } } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/ManageSecurityShieldsFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/ManageSecurityShieldsFeature.swift index 8e155122c..2a5c29a6b 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/ManageSecurityShieldsFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/ManageSecurityShieldsFeature.swift @@ -1,35 +1,27 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-03. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture +// MARK: - ManageSecurityShieldsFeature @Reducer public struct ManageSecurityShieldsFeature { - - @Reducer(state: .equatable) public enum Destination { case newSecurityShield(NewSecurityShieldCoordinator) } - + @ObservableState public struct State { @SharedReader(.shields) var shields @SharedReader(.factorSources) var factorSources @Presents var destination: Destination.State? - + public init(copyAndEdit preset: Shield? = nil) { if let preset { destination = .newSecurityShield(NewSecurityShieldCoordinator.State(copyAndEdit: preset)) } } - + public var canAddSampleShields: Bool { // FIXME: cleanup var used: [FactorSource] = [] @@ -44,35 +36,39 @@ public struct ManageSecurityShieldsFeature { return Set(factorSources.map(\.id)).isSuperset(of: usedIDs) } } - + public enum Action: ViewAction { public enum InternalAction { case newShield(preset: Shield?) } + public enum ViewAction { case shieldTapped(Shield) case addNewButtonTapped case addSampleShieldButtonTapped case addSampleOtherShieldButtonTapped } + case destination(PresentationAction) public enum DelegateAction { public enum Navigate { case toDetailsForShield(Shield) } + case navigate(Navigate) } + case delegate(DelegateAction) case view(ViewAction) case `internal`(InternalAction) } - + public var body: some ReducerOf { Reduce { state, action in switch action { case let .view(.shieldTapped(shield)): return .send(.delegate(.navigate(.toDetailsForShield(shield)))) - + case .view(.addSampleShieldButtonTapped): return .send(.internal(.newShield(preset: Shield.sample))) @@ -81,17 +77,18 @@ public struct ManageSecurityShieldsFeature { case .view(.addNewButtonTapped): return .send(.internal(.newShield(preset: nil))) - + case let .internal(.newShield(preset)): state.destination = .newSecurityShield(NewSecurityShieldCoordinator.State(copyAndEdit: preset)) return .none - + case .destination(.presented(.newSecurityShield(.delegate(.done)))): state.destination = nil return .none - + case .delegate: return .none + case .destination: return .none } @@ -100,29 +97,26 @@ public struct ManageSecurityShieldsFeature { } } - extension ManageSecurityShieldsFeature { - public typealias HostingFeature = ManageSecurityShieldsFeature - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { @Bindable public var store: StoreOf - + public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack { - Text("Shields").font(.largeTitle) - + ScrollView { - Text("Security shields are a combination of factors you can use to protect your accounts and personas.") - + Text("Here are your current security shields.") - + if store.shields.isEmpty { Text("You have no shields") } else { @@ -135,9 +129,9 @@ extension ManageSecurityShieldsFeature { } } } - + Spacer() - + Button("Add New") { send(.addNewButtonTapped) } @@ -162,12 +156,12 @@ extension ManageSecurityShieldsFeature { ) ) { store in NewSecurityShieldCoordinator.View(store: store) - } } } } +// MARK: - ShieldCardView public struct ShieldCardView: SwiftUI.View { public let shield: Shield public let action: () -> Void diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/FactorSourceExtensions/FactorSourceKind+Extensions.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/FactorSourceExtensions/FactorSourceKind+Extensions.swift index c6cd4e1c3..21279b51a 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/FactorSourceExtensions/FactorSourceKind+Extensions.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/FactorSourceExtensions/FactorSourceKind+Extensions.swift @@ -1,13 +1,7 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-07. -// - import Foundation import Sargon +// MARK: - FactorSourceKind + Identifiable extension FactorSourceKind: Identifiable { public typealias ID = String public var id: ID { @@ -15,23 +9,25 @@ extension FactorSourceKind: Identifiable { } } +// MARK: - FactorSourceKind + CaseIterable extension FactorSourceKind: CaseIterable { // FIXME: MOVE Into Rust Sargon! - public static let allCases: [Self] = [ + public static let allCases: [Self] = [ .device, .arculusCard, .ledgerHqHardwareWallet, .offDeviceMnemonic, .trustedContact, - .securityQuestions + .securityQuestions, ] } +// MARK: - FactorSourceKindUnavailabilityReason // FIXME: MOVE Into Rust Sargon! public enum FactorSourceKindUnavailabilityReason: Hashable, Sendable { case canNeverBeUsedForRole(Role) case exceededLimitOfKindPerRoleReached(exceededLimit: UInt8, Role) - + public func toString(kind: FactorSourceKind) -> String { switch self { case let .canNeverBeUsedForRole(role): "Cannot be used as \(role)" @@ -41,7 +37,6 @@ public enum FactorSourceKindUnavailabilityReason: Hashable, Sendable { } extension FactorSourceKind { - // FIXME: MOVE Into Rust Sargon! public func unavailabilityForRole(_ role: Role, usedFactorsForRole: FactorSources) -> FactorSourceKindUnavailabilityReason? { guard canBeUsedForRole(role) else { @@ -56,47 +51,47 @@ extension FactorSourceKind { return nil // free to use } } - + // FIXME: MOVE Into Rust Sargon! private func limitOfFactorSourceKindFor(role: Role) -> UInt8? { switch self { - case .device: return 1 - default: return nil + case .device: 1 + default: nil } } - + // FIXME: MOVE Into Rust Sargon! private func canBeUsedForRole(_ role: Role) -> Bool { switch self { case .device: - return role == .primary + role == .primary case .securityQuestions: - return role == .confirmation + role == .confirmation case .offDeviceMnemonic: - return role != .primary + role != .primary case .trustedContact: - return role != .primary - default: return true + role != .primary + default: true } } } extension FactorSourceKind { - public var title: String { switch self { - case .device: return "This Phone" - case .arculusCard: return "Arculus Card" - case .ledgerHqHardwareWallet: return "Ledger Hardware Wallet" - case .trustedContact: return "Trusted Contact" - case .securityQuestions: return "Security Questions" - case .offDeviceMnemonic: return "Password" + case .device: "This Phone" + case .arculusCard: "Arculus Card" + case .ledgerHqHardwareWallet: "Ledger Hardware Wallet" + case .trustedContact: "Trusted Contact" + case .securityQuestions: "Security Questions" + case .offDeviceMnemonic: "Password" } } + public var subtitle: String? { switch self { - case .device: return "Face ID / PIN" - default: return nil + case .device: "Face ID / PIN" + default: nil } } } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/IntroWhatIsShieldFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/IntroWhatIsShieldFeature.swift index d5752e755..28090a844 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/IntroWhatIsShieldFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/IntroWhatIsShieldFeature.swift @@ -1,69 +1,64 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-06. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture +// MARK: - IntroWhatIsShieldFeature @Reducer public struct IntroWhatIsShieldFeature { - @ObservableState public struct State: Equatable {} - + @ObservableState public enum Action: ViewAction { public enum ViewAction { case continueButtonTapped } + public enum DelegateAction { case `continue` } + case view(ViewAction) case delegate(DelegateAction) } - + public var body: some ReducerOf { - Reduce { state, action in + Reduce { _, action in switch action { case .view(.continueButtonTapped): - return .send(.delegate(.continue)) + .send(.delegate(.continue)) case .delegate: - return .none + .none } } } } - extension IntroWhatIsShieldFeature { public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { public let store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack { Text("Create a Security Shield").font(.largeTitle) Spacer() Text("Let's make sure you can always access your accounts - even if you lose your phone or buy a new one.") - - Spacer() - + + Spacer() + Button("Create security shield") { send(.continueButtonTapped) } } - .padding() - .navigationTitle("New Shield") + .padding() + .navigationTitle("New Shield") } } } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/NameNewShieldFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/NameNewShieldFeature.swift index 7caa580f0..8da9827b3 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/NameNewShieldFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/NameNewShieldFeature.swift @@ -1,11 +1,11 @@ -import Sargon import ComposableArchitecture +import Sargon +// MARK: - NameNewShieldFeature @Reducer public struct NameNewShieldFeature { - @Dependency(ShieldClient.self) var shieldClient - + @ObservableState public struct State: Equatable { @Shared(.newShieldDraft) var newShieldDraft @@ -14,6 +14,7 @@ public struct NameNewShieldFeature { var copyOf: Shield? { newShieldDraft.copyOf } + public init() { if let copyOf { self.shieldName = "Copy of \(copyOf.metadata.displayName.value)" @@ -22,26 +23,29 @@ public struct NameNewShieldFeature { } } } - + public enum Action: ViewAction { public enum Delegate { case done } + public enum InternalAction { case named(DisplayName) } + @CasePathable public enum ViewAction { case shieldNameChanged(String) case continueButtonTapped } + case delegate(Delegate) case `internal`(InternalAction) case view(ViewAction) } - + public init() {} - + public var body: some ReducerOf { Reduce { state, action in switch action { @@ -49,7 +53,7 @@ public struct NameNewShieldFeature { state.errorMessage = nil state.shieldName = name return .none - + case .view(.continueButtonTapped): state.errorMessage = nil do { @@ -59,7 +63,7 @@ public struct NameNewShieldFeature { state.errorMessage = "Invalid DisplayName, can't be empty or too long." return .none } - + case let .internal(.named(name)): guard let matrixOfFactors = state.newShieldDraft.matrixOfFactors else { return .none @@ -69,34 +73,33 @@ public struct NameNewShieldFeature { numberOfDaysUntilAutoConfirmation: state.newShieldDraft.numberOfDaysUntilAutoConfirmation, matrixOfFactors: matrixOfFactors ) - + return .run { send in try await shieldClient.saveSecurityShield(shield) await send(.delegate(.done)) } - + case .delegate: return .none - } } } } extension NameNewShieldFeature { - public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { @Bindable public var store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack { Text("Name Shield").font(.largeTitle) - + Spacer() LabeledTextField(label: "Shield Name", text: $store.shieldName.sending(\.view.shieldNameChanged)) if let error = store.state.errorMessage { diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/PickFactorSourceCoordinator/Children/PickFactorSelectKindFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/PickFactorSourceCoordinator/Children/PickFactorSelectKindFeature.swift index bead8e097..cceb4545f 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/PickFactorSourceCoordinator/Children/PickFactorSelectKindFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/PickFactorSourceCoordinator/Children/PickFactorSelectKindFeature.swift @@ -1,66 +1,59 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-07. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture +// MARK: - PickFactorSelectKindFeature @Reducer public struct PickFactorSelectKindFeature { - @Dependency(\.dismiss) var dismiss - + @ObservableState public struct State: Equatable { @Shared(.newShieldDraft) var newShieldDraft - + public let role: Role public init(role: Role) { self.role = role } - + public var usedFactorsForRole: FactorSources { matrixOfFactorsForRole.usedFactorSources } - + public var matrixOfFactorsForRole: MatrixOfFactorsForRole { get { newShieldDraft[role] } set { newShieldDraft[role] = newValue } } - - } - + @CasePathable public enum Action: ViewAction { public enum ViewAction { case kindButtonTapped(FactorSourceKind) case dismissButtonTapped } - public enum DelegateAction { - case selectedKind(FactorSourceKind) - } - case view(ViewAction) - case delegate(DelegateAction) + + public enum DelegateAction { + case selectedKind(FactorSourceKind) + } + + case view(ViewAction) + case delegate(DelegateAction) } - + public var body: some ReducerOf { - Reduce { state, action in + Reduce { _, action in switch action { case let .view(.kindButtonTapped(kind)): - return .send(.delegate(.selectedKind(kind))) + .send(.delegate(.selectedKind(kind))) case .view(.dismissButtonTapped): - return .run { _ in + .run { _ in await dismiss() } - case .delegate: - return .none + case .delegate: + .none } } } @@ -68,15 +61,15 @@ public struct PickFactorSelectKindFeature { extension PickFactorSelectKindFeature { public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { public let store: StoreOf - + public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { VStack(alignment: .leading) { ScrollView { @@ -106,7 +99,7 @@ extension PickFactorSelectKindFeature { } } } - .padding() + .padding() } } } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/PickFactorSourceCoordinator/Children/PickFactorSourceFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/PickFactorSourceCoordinator/Children/PickFactorSourceFeature.swift index 98c597ad7..fd3c3f739 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/PickFactorSourceCoordinator/Children/PickFactorSourceFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/PickFactorSourceCoordinator/Children/PickFactorSourceFeature.swift @@ -1,132 +1,124 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-07. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture import SwiftUI +// MARK: - PickFactorSourceFeature @Reducer public struct PickFactorSourceFeature { - - @ObservableState - public struct State: Equatable { - - @SharedReader(.factorSources) var factorSources + @ObservableState + public struct State: Equatable { + @SharedReader(.factorSources) var factorSources @Shared(.newShieldDraft) var newShieldDraft public func isFactorSourceAvailable(id: FactorSourceID) -> Bool { newShieldDraft[role].usedFactorSources.contains(where: { $0.id == id }) == false } - public var idOfSelected: FactorSourceID? = nil + + public var idOfSelected: FactorSourceID? = nil public let role: Role - public let kind: FactorSourceKind - } - - @CasePathable - public enum Action: ViewAction { - @CasePathable - public enum ViewAction { - case tappedFactorSource(id: FactorSourceID) - case confirmSelectedFactorButtonTapped - } - public enum DelegateAction { - case done - } - case view(ViewAction) - case delegate(DelegateAction) - } - - public var body: some ReducerOf { - Reduce { state, action in - switch action { - - case .view(.confirmSelectedFactorButtonTapped): - guard - let selected = state.idOfSelected, - let factor = state.factorSources[id: selected] - else { - return .none - } + public let kind: FactorSourceKind + } + + @CasePathable + public enum Action: ViewAction { + @CasePathable + public enum ViewAction { + case tappedFactorSource(id: FactorSourceID) + case confirmSelectedFactorButtonTapped + } + + public enum DelegateAction { + case done + } + + case view(ViewAction) + case delegate(DelegateAction) + } + + public var body: some ReducerOf { + Reduce { state, action in + switch action { + case .view(.confirmSelectedFactorButtonTapped): + guard + let selected = state.idOfSelected, + let factor = state.factorSources[id: selected] + else { + return .none + } state.newShieldDraft.pickedFactorSource(factor, role: state.role) - return .send(.delegate(.done)) - - case let .view(.tappedFactorSource(id)): - if let selected = state.idOfSelected, - id == selected { - state.idOfSelected = nil - } else { - state.idOfSelected = id - } - return .none - - case .delegate: - return .none - - } - } - } + return .send(.delegate(.done)) + + case let .view(.tappedFactorSource(id)): + if let selected = state.idOfSelected, + id == selected + { + state.idOfSelected = nil + } else { + state.idOfSelected = id + } + return .none + + case .delegate: + return .none + } + } + } } extension FactorSource { - public var displayLabel: String { - switch self { - case let .device(value): "\(value.hint.name) (\(value.hint.model))" - case let .ledger(value):"\(value.hint.name) (\(value.hint.model))" - case let .arculusCard(value): "\(value.hint.name) (\(value.hint.model))" - case let .offDeviceMnemonic(value): "\(value.hint.displayName)" - case let .trustedContact(value): "\(value.contact.name) (\(value.contact.emailAddress.email))" - case let .securityQuestions(value): "Questions: \(value.sealedMnemonic.securityQuestions.map({ q in q.id.description }).joined(separator: ", "))" - } - } + public var displayLabel: String { + switch self { + case let .device(value): "\(value.hint.name) (\(value.hint.model))" + case let .ledger(value): "\(value.hint.name) (\(value.hint.model))" + case let .arculusCard(value): "\(value.hint.name) (\(value.hint.model))" + case let .offDeviceMnemonic(value): "\(value.hint.displayName)" + case let .trustedContact(value): "\(value.contact.name) (\(value.contact.emailAddress.email))" + case let .securityQuestions(value): "Questions: \(value.sealedMnemonic.securityQuestions.map { q in q.id.description }.joined(separator: ", "))" + } + } } extension PickFactorSourceFeature { - public typealias HostingFeature = Self - - @ViewAction(for: HostingFeature.self) - public struct View: SwiftUI.View { - - public let store: StoreOf - - public var kind: FactorSourceKind { - store.kind - } - - public var factors: IdentifiedArrayOf { - store.factorSources.filter(kind: kind) - } - - public init(store: StoreOf) { - self.store = store - } - - public struct SelectableFactorView: SwiftUI.View { - + public typealias HostingFeature = Self + + @ViewAction(for: HostingFeature.self) + public struct View: SwiftUI.View { + public let store: StoreOf + + public var kind: FactorSourceKind { + store.kind + } + + public var factors: IdentifiedArrayOf { + store.factorSources.filter(kind: kind) + } + + public init(store: StoreOf) { + self.store = store + } + + public struct SelectableFactorView: SwiftUI.View { public let factorSource: FactorSource - public let isAvailable: Bool - public let isSelected: Bool - + public let isAvailable: Bool + public let isSelected: Bool + public let action: () -> Void - - public var body: some SwiftUI.View { - Button(action: action, label: { - HStack { - VStack(alignment: .leading) { - Text("\(factorSource.displayLabel)") - Labeled("Last Used", factorSource.lastUsedOn.formatted(.dateTime)) - Labeled("Added", factorSource.addedOn.formatted(.dateTime)) - Labeled("ID", "...\(factorSource.id.description.suffix(6))").font(.footnote) - + + public var body: some SwiftUI.View { + Button(action: action, label: { + HStack { + VStack(alignment: .leading) { + Text("\(factorSource.displayLabel)") + Labeled("Last Used", factorSource.lastUsedOn.formatted(.dateTime)) + Labeled("Added", factorSource.addedOn.formatted(.dateTime)) + Labeled("ID", "...\(factorSource.id.description.suffix(6))").font(.footnote) + if !isAvailable { Text("ALREADY USED IN SHIELD").fontWeight(.bold) } - } - .multilineTextAlignment(.leading) + } + .multilineTextAlignment(.leading) if isAvailable { Circle() @@ -134,55 +126,53 @@ extension PickFactorSourceFeature { .fill(isSelected ? Color.app.gray2 : Color.app.gray5) .frame(width: 20, height: 20) } - } - .padding() - .background(Color.app.white) - .foregroundStyle(Color.app.gray1) - .overlay( - RoundedRectangle(cornerRadius: 15) - .inset(by: 1) - .stroke(.gray, lineWidth: 1) - ) - .padding() - }) + } + .padding() + .background(Color.app.white) + .foregroundStyle(Color.app.gray1) + .overlay( + RoundedRectangle(cornerRadius: 15) + .inset(by: 1) + .stroke(.gray, lineWidth: 1) + ) + .padding() + }) .disabled(!isAvailable) - .buttonStyle(.plain) - - } - } - - public var body: some SwiftUI.View { - VStack { - Text("Select A Factor") - .font(.largeTitle) + .buttonStyle(.plain) + } + } + + public var body: some SwiftUI.View { + VStack { + Text("Select A Factor") + .font(.largeTitle) Text("For \(store.role)") - - Text("You have the the following \(store.kind) factors") - - ScrollView { - VStack { - ForEach(factors) { factorSource in - SelectableFactorView( - factorSource: factorSource, + + Text("You have the the following \(store.kind) factors") + + ScrollView { + VStack { + ForEach(factors) { factorSource in + SelectableFactorView( + factorSource: factorSource, isAvailable: store.state.isFactorSourceAvailable(id: factorSource.id), - isSelected: factorSource.id == store.idOfSelected - ) { - send(.tappedFactorSource(id: factorSource.id)) - } - } - } - - } - - Button("Confirm") { - send(.confirmSelectedFactorButtonTapped) - } - .buttonStyle(.borderedProminent) - .disabled(store.idOfSelected == nil) - } - .background(Color.app.gray5) - .padding() - } - } + isSelected: factorSource.id == store.idOfSelected + ) { + send(.tappedFactorSource(id: factorSource.id)) + } + } + } + } + + Button("Confirm") { + send(.confirmSelectedFactorButtonTapped) + } + .buttonStyle(.borderedProminent) + .disabled(store.idOfSelected == nil) + } + .background(Color.app.gray5) + .padding() + } + } } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/PickFactorSourceCoordinator/PickFactorSourceCoordinator.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/PickFactorSourceCoordinator/PickFactorSourceCoordinator.swift index d47d9168c..6d0a54f82 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/PickFactorSourceCoordinator/PickFactorSourceCoordinator.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/PickFactorSourceCoordinator/PickFactorSourceCoordinator.swift @@ -1,102 +1,93 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-07. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture import SwiftUI +// MARK: - PickFactorSourceCoordinator @Reducer public struct PickFactorSourceCoordinator { - - @Reducer(state: .equatable) - public enum Path { - case pickFactorSource(PickFactorSourceFeature) - } - - @ObservableState - public struct State: Equatable { + @Reducer(state: .equatable) + public enum Path { + case pickFactorSource(PickFactorSourceFeature) + } + + @ObservableState + public struct State: Equatable { public var role: Role { pickKind.role } - public var path = StackState() - public var pickKind: PickFactorSelectKindFeature.State - + + public var path = StackState() + public var pickKind: PickFactorSelectKindFeature.State + public init(role: Role) { self.pickKind = PickFactorSelectKindFeature.State(role: role) - } - } - - @CasePathable - public enum Action { - @CasePathable - public enum DelegateAction { - case done - } - - case path(StackAction) - case pickKind(PickFactorSelectKindFeature.Action) - case delegate(DelegateAction) - } - - public var body: some ReducerOf { - Scope(state: \.pickKind, action: \.pickKind) { - PickFactorSelectKindFeature() - } - Reduce { state, action in - switch action { + } + } + + @CasePathable + public enum Action { + @CasePathable + public enum DelegateAction { + case done + } - case let .pickKind(.delegate(.selectedKind(kind))): + case path(StackAction) + case pickKind(PickFactorSelectKindFeature.Action) + case delegate(DelegateAction) + } + + public var body: some ReducerOf { + Scope(state: \.pickKind, action: \.pickKind) { + PickFactorSelectKindFeature() + } + Reduce { state, action in + switch action { + case let .pickKind(.delegate(.selectedKind(kind))): state.path.append(.pickFactorSource(PickFactorSourceFeature.State( role: state.role, kind: kind ))) - return .none - - case .path(.element(id: _, action: .pickFactorSource(.delegate(.done)))): - return .send(.delegate(.done)) - - case .pickKind: - return .none + return .none - case .path: - return .none + case .path(.element(id: _, action: .pickFactorSource(.delegate(.done)))): + return .send(.delegate(.done)) - case .delegate: - return .none - } - } - .forEach(\.path, action: \.path) - } + case .pickKind: + return .none + + case .path: + return .none + + case .delegate: + return .none + } + } + .forEach(\.path, action: \.path) + } } extension PickFactorSourceCoordinator { public typealias HostingFeature = Self - + public struct View: SwiftUI.View { @Bindable public var store: StoreOf - - public init(store: StoreOf) { + + public init(store: StoreOf) { self.store = store } - - - public var body: some SwiftUI.View { - NavigationStack(path: $store.scope(state: \.path, action: \.path)) { - PickFactorSelectKindFeature.View( - store: store.scope(state: \.pickKind, action: \.pickKind) - ) - } destination: { store in - switch store.case { - case let .pickFactorSource(store): - PickFactorSourceFeature.View(store: store) - } - } - } - + + public var body: some SwiftUI.View { + NavigationStack(path: $store.scope(state: \.path, action: \.path)) { + PickFactorSelectKindFeature.View( + store: store.scope(state: \.pickKind, action: \.pickKind) + ) + } destination: { store in + switch store.case { + case let .pickFactorSource(store): + PickFactorSourceFeature.View(store: store) + } + } + } } } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Features/FactorsBuilderFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Features/FactorsBuilderFeature.swift index a580ec541..be324b783 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Features/FactorsBuilderFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Features/FactorsBuilderFeature.swift @@ -1,34 +1,27 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-07. -// - +import ComposableArchitecture import Foundation -import SwiftUI import Sargon -import ComposableArchitecture +import SwiftUI +// MARK: - FactorsBuilderFeature @Reducer public struct FactorsBuilderFeature { - @ObservableState public struct State: Equatable { public enum Mode: Sendable, Hashable { case threshold, override } - + @Shared(.newShieldDraft) var newShieldDraft - + public let mode: Mode public let role: Role - + public init(mode: Mode, role: Role) { self.mode = mode self.role = role } - + public var threshold: FactorThreshold { get { if mode == .threshold { @@ -43,14 +36,13 @@ public struct FactorsBuilderFeature { } } - public var matrixOfFactorsForRole: MatrixOfFactorsForRole { get { newShieldDraft[role] } set { newShieldDraft[role] = newValue } } - + public var factors: Factors { get { switch mode { @@ -66,9 +58,10 @@ public struct FactorsBuilderFeature { matrixOfFactorsForRole.overrideFactors = newValue case .threshold: matrixOfFactorsForRole.thresholdFactors = newValue - } } + } + } } - + public var pickedFactorID: Factor.ID? { get { newShieldDraft.pendingFactorID @@ -77,7 +70,7 @@ public struct FactorsBuilderFeature { newShieldDraft.pendingFactorID = newValue } } - + public var title: LocalizedStringKey { switch mode { case .override: @@ -86,15 +79,14 @@ public struct FactorsBuilderFeature { "Threshold Factors" } } - + public var canChangeThreshold: Bool { mode == .threshold } } - + @CasePathable public enum Action: ViewAction { - @CasePathable public enum ViewAction { case titleButtonTapped @@ -104,62 +96,61 @@ public struct FactorsBuilderFeature { case changeThresholdButtonTapped case factorsChanged(Factors) } - + public enum DelegateAction { case pickFactor case setThreshold } - + case view(ViewAction) case delegate(DelegateAction) } - + public var body: some ReducerOf { Reduce { state, action in switch action { - case .view(.titleButtonTapped): log.info("Title button tapped, show important info!") return .none - + case .view(.appendFactorButtonTapped): state.factors.append(Factor()) return .none - + case let .view(.pickFactorButtonTapped(factor)): state.pickedFactorID = factor.id return .send(.delegate(.pickFactor)) - + case let .view(.removeButtonTapped(toRemove)): state.newShieldDraft.removeFactor(toRemove, role: state.role) return .none - + case .view(.changeThresholdButtonTapped): assert(state.mode == .threshold) return .send(.delegate(.setThreshold)) - + case let .view(.factorsChanged(new)): state.factors = new return .none - + case .delegate: return .none } } } } + extension FactorsBuilderFeature { public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { - @Bindable public var store: StoreOf - + public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { VStack(spacing: 0) { HStack { @@ -175,9 +166,9 @@ extension FactorsBuilderFeature { Spacer() } .padding() - + Divider().background(Color.app.gray2) - + VStack(spacing: 10) { ForEach(store.factors) { factor in FactorView( @@ -191,7 +182,7 @@ extension FactorsBuilderFeature { } .padding(.horizontal) .padding(.top, 10) - + Button("Add factors") { send(.appendFactorButtonTapped) } @@ -200,10 +191,9 @@ extension FactorsBuilderFeature { } .frame(maxWidth: .infinity, minHeight: 50) .background(Color.app.gray5) - - + Divider().background(Color.app.gray3) - + Button(action: { send(.changeThresholdButtonTapped) }, label: { @@ -218,7 +208,6 @@ extension FactorsBuilderFeature { }) .padding() .disabled(!store.canChangeThreshold) - } .foregroundStyle(Color.app.gray1) .overlay( @@ -232,9 +221,9 @@ extension FactorsBuilderFeature { } } -//#Preview { +// #Preview { // VStack { -// +// // FactorsBuilderView( // factors: .init(get: { [FactorSource.sample].map({ Factor(factorSource: $0) }).asIdentified() }, set: { // print("Preview NOOP set factors sources to: \($0)") @@ -264,5 +253,5 @@ extension FactorsBuilderFeature { // } // ) // } -//} -// +// } +// diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Features/RoleFactorsFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Features/RoleFactorsFeature.swift index 782549b15..9119dfb72 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Features/RoleFactorsFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Features/RoleFactorsFeature.swift @@ -1,18 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-06. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture +// MARK: - RoleFactorsFeature @Reducer public struct RoleFactorsFeature { - - @Reducer(state: .equatable) public enum Destination { case pickFactorSourceCoordinator(PickFactorSourceCoordinator) @@ -26,48 +18,45 @@ public struct RoleFactorsFeature { public var thresholdFactorsBuilder: FactorsBuilderFeature.State public var overrideFactorsBuilder: FactorsBuilderFeature.State public let role: Role - + @Presents var destination: Destination.State? - + public var daysUntilAutoConfirm: UInt16 { newShieldDraft.numberOfDaysUntilAutoConfirmation } - + public init(role: Role) { self.role = role self.thresholdFactorsBuilder = FactorsBuilderFeature.State(mode: .threshold, role: role) self.overrideFactorsBuilder = FactorsBuilderFeature.State(mode: .override, role: role) } - + var canProceed: Bool { newShieldDraft.isValidRole(role) } } - + @CasePathable public enum Action: ViewAction { - @CasePathable public enum ViewAction { case confirmButtonTapped case changeDaysUntilAutoConfirmButtonTapped - } - - public enum DelegateAction { + } + + public enum DelegateAction { case `continue`(role: Role) - } - + } + case destination(PresentationAction) - - - case view(ViewAction) + + case view(ViewAction) case delegate(DelegateAction) - + case thresholdFactorsBuilder(FactorsBuilderFeature.Action) case overrideFactorsBuilder(FactorsBuilderFeature.Action) - } - + public var body: some ReducerOf { Scope(state: \.thresholdFactorsBuilder, action: \.thresholdFactorsBuilder) { FactorsBuilderFeature() @@ -77,44 +66,41 @@ public struct RoleFactorsFeature { } Reduce { state, action in switch action { - case .view(.changeDaysUntilAutoConfirmButtonTapped): state.destination = .setDaysUntilAutoConfirm(SetDaysUntilAutoConfirm.State()) return .none - + case .view(.confirmButtonTapped): return .send(.delegate(.continue(role: state.role))) - + case .thresholdFactorsBuilder(.delegate(.pickFactor)), .overrideFactorsBuilder(.delegate(.pickFactor)): state.destination = .pickFactorSourceCoordinator(PickFactorSourceCoordinator.State(role: state.role)) return .none - - + case .thresholdFactorsBuilder(.delegate(.setThreshold)): state.destination = .setFactorThreshold(SetFactorThresholdFeature.State( role: state.role )) return .none - case .destination(.presented(.setFactorThreshold(.delegate(.confirm)))): state.destination = nil return .none - + case .destination(.presented(.pickFactorSourceCoordinator(.delegate(.done)))): state.destination = nil return .none - + case .destination(.presented(.setDaysUntilAutoConfirm(.delegate(.done)))): state.destination = nil return .none case .thresholdFactorsBuilder: return .none - + case .overrideFactorsBuilder: return .none - + case .destination: return .none @@ -128,31 +114,30 @@ public struct RoleFactorsFeature { extension RoleFactorsFeature { public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { - @Bindable public var store: StoreOf - + public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { ScrollView { VStack(alignment: .center, spacing: 20) { Text("\(store.role.title)").font(.largeTitle) - + Text("These factors are required to \(store.role.actionDetailed)") .foregroundStyle(Color.app.gray2) - + FactorsBuilderFeature.View( store: store.scope( state: \.thresholdFactorsBuilder, action: \.thresholdFactorsBuilder ) ) - + FactorsBuilderFeature.View( store: store.scope( state: \.overrideFactorsBuilder, @@ -191,7 +176,7 @@ extension RoleFactorsFeature { .buttonStyle(.plain) .frame(maxWidth: .infinity) } - + Button("Confirm") { send(.confirmButtonTapped) } @@ -220,9 +205,6 @@ extension RoleFactorsFeature { } } - - - #Preview { RoleFactorsFeature.View( store: Store( diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Features/SetDaysUntilAutoConfirm.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Features/SetDaysUntilAutoConfirm.swift index 877ddecef..fb42d7cd1 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Features/SetDaysUntilAutoConfirm.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Features/SetDaysUntilAutoConfirm.swift @@ -1,14 +1,8 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-09. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture +// MARK: - SetDaysUntilAutoConfirm @Reducer public struct SetDaysUntilAutoConfirm { @ObservableState @@ -18,6 +12,7 @@ public struct SetDaysUntilAutoConfirm { public init() { daysString = daysUntilAutoConfirm.description } + public var daysUntilAutoConfirm: UInt16 { get { newShieldDraft.numberOfDaysUntilAutoConfirmation @@ -26,73 +21,72 @@ public struct SetDaysUntilAutoConfirm { newShieldDraft.numberOfDaysUntilAutoConfirmation = newValue } } - + public var daysFromString: UInt16? { UInt16(daysString) } } - + @CasePathable public enum Action: ViewAction { - public enum DelegateAction { case done } + @CasePathable public enum ViewAction { case confirmButtonTapped case numberOfDaysChanged(String) } + case view(ViewAction) case delegate(DelegateAction) } - - + public var body: some ReducerOf { - Reduce { state, action in switch action { - case let .view(.numberOfDaysChanged(daysString)): state.daysString = daysString if let days = state.daysFromString { state.daysUntilAutoConfirm = days } return .none + case .view(.confirmButtonTapped): return .send(.delegate(.done)) - + case .delegate: return .none } } } - } extension SetDaysUntilAutoConfirm { public typealias HostingFeature = SetDaysUntilAutoConfirm - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { @Bindable public var store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack { Text("Number of days") .font(.largeTitle) - + Spacer() - + Text("Will auto confirm after \(store.daysUntilAutoConfirm.description) days.") - + LabeledTextField(label: "#Days", text: $store.daysUntilAutoConfirm.description.sending(\.view.numberOfDaysChanged)) .keyboardType(.numberPad) - + Spacer() - + Button("Confirm") { send(.confirmButtonTapped) } @@ -103,5 +97,4 @@ extension SetDaysUntilAutoConfirm { .padding() } } - } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Views/FactorView.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Views/FactorView.swift index 5e12c3eb4..d16b845e8 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Views/FactorView.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/Roles/Views/FactorView.swift @@ -1,20 +1,13 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-07. -// - import Foundation -import SwiftUI import Sargon +import SwiftUI +// MARK: - FactorView public struct FactorView: SwiftUI.View { - public let factor: Factor public let pickAction: (() -> Void)? public let removeAction: (() -> Void)? - + public init( factor: Factor, pickAction: (() -> Void)? = nil, @@ -24,13 +17,13 @@ public struct FactorView: SwiftUI.View { self.pickAction = pickAction self.removeAction = removeAction } - + public init( _ factorSource: FactorSource ) { self.init(factor: Factor(factorSource: factorSource)) } - + public var body: some SwiftUI.View { HStack { if let pickAction { @@ -40,10 +33,9 @@ public struct FactorView: SwiftUI.View { } else { label } - - + Spacer() - + if let removeAction { Button(action: removeAction, label: { Image(systemName: "plus").rotationEffect(.degrees(45)) @@ -51,12 +43,11 @@ public struct FactorView: SwiftUI.View { } } } - + @ViewBuilder private var label: some View { HStack(alignment: .top) { if let factorSource = factor.factorSource { - Image(systemName: factorSource.kind.image) .resizable() .imageScale(.large) @@ -64,7 +55,7 @@ public struct FactorView: SwiftUI.View { .frame(width: 40) .rotationEffect(.degrees(factorSource.kind.rotationDegrees)) .offset(y: factorSource.kind.rotationDegrees > 0 ? 10 : 0) - + VStack(alignment: .leading) { Text("\(factorSource.kind.title)") if let subtitle = factorSource.kind.subtitle { @@ -88,21 +79,21 @@ public struct FactorView: SwiftUI.View { extension FactorSourceKind { public var image: String { switch self { - case .device: return "lock.iphone" - case .ledgerHqHardwareWallet: return "mediastick" - case .arculusCard: return "key.radiowaves.forward" - case .trustedContact: return "figure.child.and.lock" - case .securityQuestions: return "person.crop.circle.badge.questionmark" - case .offDeviceMnemonic: return "key" + case .device: "lock.iphone" + case .ledgerHqHardwareWallet: "mediastick" + case .arculusCard: "key.radiowaves.forward" + case .trustedContact: "figure.child.and.lock" + case .securityQuestions: "person.crop.circle.badge.questionmark" + case .offDeviceMnemonic: "key" } } + public var rotationDegrees: CGFloat { switch self { - case .ledgerHqHardwareWallet: return 90 - default: return 0 + case .ledgerHqHardwareWallet: 90 + default: 0 } } - } #Preview { diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/SetFactorThresholdFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/SetFactorThresholdFeature.swift index 766750914..5689a8c32 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/SetFactorThresholdFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Children/SetFactorThresholdFeature.swift @@ -1,38 +1,32 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-07. -// - -import Foundation import ComposableArchitecture +import Foundation import Sargon import SwiftUI +// MARK: - SetFactorThresholdFeature @Reducer public struct SetFactorThresholdFeature { - @ObservableState public struct State: Equatable { @Shared(.newShieldDraft) var newShieldDraft public let role: Role public var threshold: FactorThreshold - + public init(role: Role) { self.role = role self.threshold = .all - + self.threshold = alreadySet } - + public var matrixOfFactorsForRole: MatrixOfFactorsForRole { newShieldDraft[role] } - + public var numberOfFactors: Int { matrixOfFactorsForRole.thresholdFactors.count } + public var options: [FactorThreshold] { var options: [FactorThreshold] = [.any, .all] guard numberOfFactors > 0 else { @@ -40,48 +34,47 @@ public struct SetFactorThresholdFeature { } let exceeding1 = UInt8(numberOfFactors - 1) if exceeding1 > 1 { - options.append(contentsOf: (1...exceeding1).map(FactorThreshold.threshold)) + options.append(contentsOf: (1 ... exceeding1).map(FactorThreshold.threshold)) } return options } - - + public var alreadySet: FactorThreshold { matrixOfFactorsForRole.threshold } + public var recommended: FactorThreshold { .any } - - } - + public enum Action: ViewAction { public enum ViewAction { case changedThreshold(Int) case confirmButtonTapped } + public enum DelegateAction { case confirm } + case view(ViewAction) case delegate(DelegateAction) } - + public var body: some ReducerOf { Reduce { state, action in switch action { - case let .view(.changedThreshold(index)): var index = max(index, 0) index = min(index, state.options.count - 1) state.threshold = state.options[index] return .none - + case .view(.confirmButtonTapped): state.newShieldDraft[state.role].threshold = state.threshold return .send(.delegate(.confirm)) - + case .delegate: return .none } @@ -90,15 +83,15 @@ public struct SetFactorThresholdFeature { } extension SetFactorThresholdFeature { - public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { public let store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack(alignment: .center) { Text("Choose the number of security factors required for \(store.role.title)") @@ -111,7 +104,7 @@ extension SetFactorThresholdFeature { .lineLimit(nil) .padding() } - + var scrollView: some SwiftUI.View { GeometryReader { geo in let cellWidth = max(geo.size.width / 4, 50) // must use `max`, will be `0` initially... @@ -125,7 +118,7 @@ extension SetFactorThresholdFeature { .frame(width: cellWidth) .foregroundStyle(option == store.threshold ? Color.app.blue1 : Color.app.gray5) Group { - if option == store.alreadySet || option == store.recommended { + if option == store.alreadySet || option == store.recommended { Text(option == store.alreadySet ? "Current" : "Recommended") .font(.system(size: 10)) .padding(5) @@ -154,7 +147,7 @@ extension SetFactorThresholdFeature { ) .onPreferenceChange(ViewOffsetKey.self) { let positionX = contentMarginX + $0 - + send(.changedThreshold(Int(CGFloat(positionX / cellWidth).rounded()))) } } @@ -162,14 +155,16 @@ extension SetFactorThresholdFeature { .contentMargins(contentMarginX) } } + private let coordinateSpaceScrollView = "coordinateSpaceScrollView" } } +// MARK: - ViewOffsetKey struct ViewOffsetKey: PreferenceKey { typealias Value = CGFloat static let defaultValue = CGFloat.zero - + static func reduce( value: inout Value, nextValue: () -> Value @@ -181,33 +176,34 @@ struct ViewOffsetKey: PreferenceKey { extension Role { public var title: String { switch self { - case .primary: return "Signing" - case .recovery: return "Wallet lock & recovery" - case .confirmation: return "Confirm Recovery" + case .primary: "Signing" + case .recovery: "Wallet lock & recovery" + case .confirmation: "Confirm Recovery" } } + public var action: String { switch self { - case .primary: return "sign transaction" - case .recovery: return "initiate recovery" - case .confirmation: return "confirm recovery" + case .primary: "sign transaction" + case .recovery: "initiate recovery" + case .confirmation: "confirm recovery" } } + public var actionDetailed: String { switch self { - case .primary: return "withdraw your assets and log in to dApps." - case .recovery: return "initiate recovery" - case .confirmation: return "confirm recovery" + case .primary: "withdraw your assets and log in to dApps." + case .recovery: "initiate recovery" + case .confirmation: "confirm recovery" } } - } -//#Preview { +// #Preview { // let role: Role = .primary // @Shared(.thresholdFactors) var thresholdFactors // thresholdFactors[role] = FactorThreshold.all -//SetFactorThresholdFeature.View( +// SetFactorThresholdFeature.View( // store: Store( // initialState: SetFactorThresholdFeature.State( // role: role, @@ -216,5 +212,5 @@ extension Role { // reducer: { // SetFactorThresholdFeature() // } -//)) -//} +// )) +// } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Models/NewShield+Models.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Models/NewShield+Models.swift index d7fd575f6..d86587459 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Models/NewShield+Models.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Models/NewShield+Models.swift @@ -1,18 +1,13 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-07. -// - import Foundation -import Sargon import IdentifiedCollections +import Sargon +// MARK: - Role public enum Role: Sendable, Hashable { case primary, recovery, confirmation } +// MARK: - Factor public struct Factor: Hashable, Sendable, Identifiable { public let id = UUID() public var factorSource: FactorSource? @@ -23,6 +18,7 @@ public struct Factor: Hashable, Sendable, Identifiable { public typealias Factors = IdentifiedArrayOf +// MARK: - FactorThreshold public enum FactorThreshold: Hashable, Sendable, CustomStringConvertible { init(count: UInt8, thresholdFactorsCount: Int) { let factorCount = UInt8(thresholdFactorsCount) @@ -34,7 +30,7 @@ public enum FactorThreshold: Hashable, Sendable, CustomStringConvertible { self = .threshold(count) } } - + public func isValid(thresholdFactorCount: Int) -> Bool { switch self { case .any: return true @@ -47,7 +43,7 @@ public enum FactorThreshold: Hashable, Sendable, CustomStringConvertible { return isValid } } - + public mutating func decrease() { switch self { case .any, .all: break @@ -58,17 +54,16 @@ public enum FactorThreshold: Hashable, Sendable, CustomStringConvertible { default: fatalError("not possible") } } - + case any case all case threshold(UInt8) - + public var description: String { switch self { - case .any: return "Any" - case .all: return "All" - case let .threshold(threshold): return "\(threshold)" + case .any: "Any" + case .all: "All" + case let .threshold(threshold): "\(threshold)" } } } - diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Models/NewShield+SharedState.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Models/NewShield+SharedState.swift index c04647b66..3134f9a5c 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Models/NewShield+SharedState.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/New/Models/NewShield+SharedState.swift @@ -1,14 +1,8 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-07. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture +// MARK: - MatrixOfFactorsForRole public struct MatrixOfFactorsForRole: Hashable, Sendable { public let role: Role public var thresholdFactors: Factors @@ -20,31 +14,35 @@ public struct MatrixOfFactorsForRole: Hashable, Sendable { self.thresholdFactors = thresholdFactors self.overrideFactors = overrideFactors } + init(roleWithFactors: R) where R: RoleFromDraft { - let thresholdFactors = roleWithFactors.thresholdFactors.map { Factor.init(factorSource: $0) }.asIdentified() + let thresholdFactors = roleWithFactors.thresholdFactors.map { Factor(factorSource: $0) }.asIdentified() self.init( role: R.role, thresholdFactors: thresholdFactors, threshold: .init(count: roleWithFactors.threshold, thresholdFactorsCount: thresholdFactors.count), - overrideFactors: roleWithFactors.overrideFactors.map { Factor.init(factorSource: $0) }.asIdentified() + overrideFactors: roleWithFactors.overrideFactors.map { Factor(factorSource: $0) }.asIdentified() ) } + var usedFactorSources: FactorSources { var all: FactorSources = [] all.append(contentsOf: thresholdFactors.compactMap(\.factorSource)) all.append(contentsOf: overrideFactors.compactMap(\.factorSource)) return all } + var thresholdFactorSources: [FactorSource] { thresholdFactors.compactMap(\.factorSource) } + var overrideFactorsSources: [FactorSource] { overrideFactors.compactMap(\.factorSource) } } +// MARK: - RoleFromDraft public protocol RoleFromDraft { - var thresholdFactors: [FactorSource] { get } /** * How many threshold factors that must be used to perform some function with this role. @@ -56,16 +54,16 @@ public protocol RoleFromDraft { * disregarding of `threshold`. */ var overrideFactors: [FactorSource] { get } - + static var role: Role { get } init(thresholdFactors: [FactorSource], threshold: UInt8, overrideFactors: [FactorSource]) init?(draft: MatrixOfFactorsForRole) } + extension RoleFromDraft { - public init?(draft: MatrixOfFactorsForRole) { precondition(draft.role == Self.role) - if draft.thresholdFactorSources.isEmpty && draft.overrideFactorsSources.isEmpty { + if draft.thresholdFactorSources.isEmpty, draft.overrideFactorsSources.isEmpty { return nil } if !draft.threshold.isValid(thresholdFactorCount: draft.thresholdFactorSources.count) { @@ -84,37 +82,43 @@ extension RoleFromDraft { overrideFactors: draft.overrideFactorsSources ) } - - } + +// MARK: - PrimaryRoleWithFactorSources + RoleFromDraft extension PrimaryRoleWithFactorSources: RoleFromDraft { public static let role: Role = .primary } + +// MARK: - RecoveryRoleWithFactorSources + RoleFromDraft extension RecoveryRoleWithFactorSources: RoleFromDraft { public static let role: Role = .recovery } + +// MARK: - ConfirmationRoleWithFactorSources + RoleFromDraft extension ConfirmationRoleWithFactorSources: RoleFromDraft { public static let role: Role = .confirmation } - - +// MARK: - NewShieldDraft public struct NewShieldDraft: Hashable, Sendable { public let copyOf: Shield? public var numberOfDaysUntilAutoConfirmation: UInt16 = 14 private var primary: MatrixOfFactorsForRole private var recovery: MatrixOfFactorsForRole private var confirmation: MatrixOfFactorsForRole - + private var _primaryRole: PrimaryRoleWithFactorSources? { PrimaryRoleWithFactorSources(draft: primary) } + private var _recoveryRole: RecoveryRoleWithFactorSources? { RecoveryRoleWithFactorSources(draft: recovery) } + private var _confirmationRole: ConfirmationRoleWithFactorSources? { ConfirmationRoleWithFactorSources(draft: confirmation) } + public var matrixOfFactors: MatrixOfFactorSources? { guard let primary = _primaryRole, @@ -137,9 +141,9 @@ public struct NewShieldDraft: Hashable, Sendable { allUsed.append(contentsOf: confirmation.usedFactorSources) return allUsed } - + public var pendingFactorID: Factor.ID? - + public func isValidRole(_ role: Role) -> Bool { switch role { case .confirmation: self._confirmationRole != nil @@ -147,7 +151,7 @@ public struct NewShieldDraft: Hashable, Sendable { case .primary: self._primaryRole != nil } } - + public mutating func removeFactor(_ factor: Factor, role: Role) { if factor.id == pendingFactorID { pendingFactorID = nil // not really possible in UI, but prudent. @@ -162,6 +166,7 @@ public struct NewShieldDraft: Hashable, Sendable { self[role].overrideFactors.remove(factor) } } + public mutating func pickedFactorSource(_ factorSource: FactorSource, role: Role) { guard let pendingFactorID else { assertionFailure("Expected pending...") @@ -176,14 +181,14 @@ public struct NewShieldDraft: Hashable, Sendable { } self.pendingFactorID = nil } - + public init() { self.copyOf = nil self.primary = MatrixOfFactorsForRole(role: .primary) self.recovery = MatrixOfFactorsForRole(role: .recovery) self.confirmation = MatrixOfFactorsForRole(role: .confirmation) } - + public init(copyAndEdit preset: Shield) { self.copyOf = preset self.primary = .init(roleWithFactors: preset.matrixOfFactors.primaryRole) @@ -195,9 +200,9 @@ public struct NewShieldDraft: Hashable, Sendable { public subscript(role: Role) -> MatrixOfFactorsForRole { get { switch role { - case .primary: return self.primary - case .recovery: return self.recovery - case .confirmation: return self.confirmation + case .primary: self.primary + case .recovery: self.recovery + case .confirmation: self.confirmation } } set { @@ -218,6 +223,3 @@ extension PersistenceReaderKey where Self == PersistenceKeyDefault) case intro(IntroWhatIsShieldFeature.Action) - + case delegate(DelegateAction) - + public enum DelegateAction { case done } @@ -54,22 +46,22 @@ public struct NewSecurityShieldCoordinator { ) -> EffectOf { let nextRole: Role? = switch lastRole { case .none: - .primary + .primary case .primary: - .recovery + .recovery case .recovery: - .confirmation + .confirmation case .confirmation: nil } - if let nextRole { + if let nextRole { state.path.append(.roleFactors(RoleFactorsFeature.State(role: nextRole))) } else { state.path.append(.nameShield(NameNewShieldFeature.State())) } return .none } - + public var body: some ReducerOf { Scope(state: \.intro, action: \.intro) { IntroWhatIsShieldFeature() @@ -77,22 +69,22 @@ public struct NewSecurityShieldCoordinator { Reduce { state, action in switch action { case .intro(.delegate(.continue)): - return Self.next(&state) + Self.next(&state) case let .path(.element(id: _, action: .roleFactors(.delegate(.continue(role))))): - return Self.next(lastRole: role, &state) - + Self.next(lastRole: role, &state) + case .path(.element(id: _, action: .nameShield(.delegate(.done)))): - return .send(.delegate(.done)) - + .send(.delegate(.done)) + case .path: - return .none + .none case .intro: - return .none + .none + case .delegate: - return .none - + .none } } .forEach(\.path, action: \.path) @@ -101,12 +93,13 @@ public struct NewSecurityShieldCoordinator { extension NewSecurityShieldCoordinator { public typealias HostingFeature = Self - + public struct View: SwiftUI.View { @Bindable public var store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { NavigationStack(path: $store.scope(state: \.path, action: \.path)) { IntroWhatIsShieldFeature.View( diff --git a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/ShieldDetailsFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/ShieldDetailsFeature.swift index ba758f42c..1e621cc7f 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/ShieldDetailsFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/FactorSource/Shields/ShieldDetailsFeature.swift @@ -1,40 +1,35 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-09. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture +// MARK: - ShieldDetailsFeature @Reducer public struct ShieldDetailsFeature { - @ObservableState public struct State { public let shield: Shield } - + public enum Action: ViewAction { public enum ViewAction { case copyAndEditButtonTapped } + public enum DelegateAction { case copyAndEdit(Shield) } + case view(ViewAction) case delegate(DelegateAction) } - + public var body: some ReducerOf { Reduce { state, action in switch action { case .view(.copyAndEditButtonTapped): - return .send(.delegate(.copyAndEdit(state.shield))) + .send(.delegate(.copyAndEdit(state.shield))) case .delegate: - return .none + .none } } } @@ -42,22 +37,22 @@ public struct ShieldDetailsFeature { extension ShieldDetailsFeature { public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { public let store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack(alignment: .leading) { - ScrollView { VStack(alignment: .leading, spacing: 30) { section(role: store.shield.matrixOfFactors.primaryRole) - + section(role: store.shield.matrixOfFactors.recoveryRole) - + section(role: store.shield.matrixOfFactors.confirmationRole) } .padding() @@ -76,7 +71,7 @@ extension ShieldDetailsFeature { } } } - + func section(role roleWithFactors: R) -> some SwiftUI.View { VStack(alignment: .leading, spacing: 3) { VStack(alignment: .leading) { @@ -98,7 +93,7 @@ extension ShieldDetailsFeature { .foregroundStyle(Color.app.white) .background(Color.app.gray3) .clipShape(.rect(cornerRadius: 10)) - + VStack(alignment: .leading) { Text(role.action.capitalized) .font(.title2) @@ -115,23 +110,22 @@ extension ShieldDetailsFeature { .clipShape(.rect(topLeadingRadius: 10, topTrailingRadius: 10)) } .multilineTextAlignment(.leading) - + sectionFactors( factors: roleWithFactors.thresholdFactors, factorAmount: "Must present **\(roleWithFactors.thresholdAmount)** of the following", emptyFactors: "No threshold factors set", roundCorners: false ) - + sectionFactors( factors: roleWithFactors.overrideFactors, factorAmount: "Or must present **1** of the following", emptyFactors: "No override factors set" ) - } } - + @ViewBuilder func sectionFactors( factors: [FactorSource], @@ -140,13 +134,12 @@ extension ShieldDetailsFeature { roundCorners: Bool = true ) -> some SwiftUI.View { VStack(alignment: .leading) { - if !factors.isEmpty { HStack { Text(factorAmount) Spacer() } - + ForEach(factors) { factorSource in FactorView(factorSource) .foregroundStyle(Color.app.gray1) @@ -172,50 +165,50 @@ extension ShieldDetailsFeature { .shadow(color: Color.app.gray3, radius: 4, x: 0, y: 1) } } - } extension RoleFromDraft { var thresholdAmount: String { - if threshold == thresholdFactors.count { - return "All" + "All" } else if threshold == 1 { - return "Any" + "Any" } else { - return String(describing: threshold) + String(describing: threshold) } - } } extension Role { var detailTitle: String? { switch self { - case .primary: return "Transactions" - case .recovery: return "Recovery Assistance" - case .confirmation: return nil + case .primary: "Transactions" + case .recovery: "Recovery Assistance" + case .confirmation: nil } } + public var actionVeryDetailed: String { switch self { - case .primary: return "withdraw your assets and log in to dApps." - case .recovery: return "lock your account or start recovering your accounts if you lose your phone." - case .confirmation: return "confirm recovery" + case .primary: "withdraw your assets and log in to dApps." + case .recovery: "lock your account or start recovering your accounts if you lose your phone." + case .confirmation: "confirm recovery" } } + var smallIcon: String? { switch self { - case .primary: return "pencil.circle" - case .recovery: return "wrench.and.screwdriver" - case .confirmation: return nil + case .primary: "pencil.circle" + case .recovery: "wrench.and.screwdriver" + case .confirmation: nil } } + var largeIcon: String { switch self { - case .primary: return "pencil.and.list.clipboard" - case .recovery: return "cross.case" - case .confirmation: return "person.badge.shield.checkmark" + case .primary: "pencil.and.list.clipboard" + case .recovery: "cross.case" + case .confirmation: "person.badge.shield.checkmark" } } } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/CreateAccount/CreateAccountFlowFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/CreateAccount/CreateAccountFlowFeature.swift index e2bb04432..b8e556c9f 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/CreateAccount/CreateAccountFlowFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/CreateAccount/CreateAccountFlowFeature.swift @@ -1,40 +1,40 @@ -import Sargon import ComposableArchitecture +import Sargon +// MARK: - CreateAccountFlowFeature @Reducer public struct CreateAccountFlowFeature { - @ObservableState public struct State: Equatable { public var nameAccount: NameNewAccountFeature.State - + public init(index: Int) { self.nameAccount = NameNewAccountFeature.State(index: index) } } - + public enum Action { public enum DelegateAction { case createdAccount } + case nameAccount(NameNewAccountFeature.Action) case delegate(DelegateAction) } - + @Dependency(AccountsClient.self) var accountsClient - + public init() {} - + public var body: some ReducerOf { Scope(state: \.nameAccount, action: \.nameAccount) { NameNewAccountFeature() } - - Reduce { state, action in - switch action { + Reduce { _, action in + switch action { case let .nameAccount(.delegate(.named(name))): - return .run { send in + .run { send in try await accountsClient.createAndSaveAccount(name) await send(.delegate(.createdAccount)) } catch: { error, _ in @@ -42,18 +42,18 @@ public struct CreateAccountFlowFeature { } case .nameAccount: - return .none - + .none + case .delegate: - return .none + .none } } } } +// MARK: CreateAccountFlowFeature.View extension CreateAccountFlowFeature { public struct View: SwiftUI.View { - @Bindable var store: StoreOf public init(store: StoreOf) { self.store = store @@ -65,5 +65,4 @@ extension CreateAccountFlowFeature { ) } } - } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/CreateAccount/Steps/NameAccountFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/CreateAccount/Steps/NameAccountFeature.swift index a131ddce9..7ae66e8b7 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/CreateAccount/Steps/NameAccountFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/CreateAccount/Steps/NameAccountFeature.swift @@ -1,9 +1,9 @@ -import Sargon import ComposableArchitecture +import Sargon +// MARK: - NameNewAccountFeature @Reducer public struct NameNewAccountFeature { - @ObservableState public struct State: Equatable { public var accountName: String @@ -12,22 +12,24 @@ public struct NameNewAccountFeature { self.accountName = "Unnamed \(index)" } } - + public enum Action: ViewAction { public enum Delegate { case named(DisplayName) } + @CasePathable public enum ViewAction { case accountNameChanged(String) case continueButtonTapped } + case delegate(Delegate) case view(ViewAction) } - + public init() {} - + public var body: some ReducerOf { Reduce { state, action in switch action { @@ -35,7 +37,7 @@ public struct NameNewAccountFeature { state.errorMessage = nil state.accountName = name return .none - + case .view(.continueButtonTapped): state.errorMessage = nil do { @@ -45,25 +47,24 @@ public struct NameNewAccountFeature { state.errorMessage = "Invalid DisplayName, can't be empty or too long." return .none } - + case .delegate: return .none - } } } } extension NameNewAccountFeature { - public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { @Bindable public var store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack { Text("Name Account").font(.largeTitle) diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/ImportProfileFlowFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/ImportProfileFlowFeature.swift index 9972ac6b8..e52df40c3 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/ImportProfileFlowFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/ImportProfileFlowFeature.swift @@ -1,67 +1,64 @@ +import ComposableArchitecture +import Foundation import Sargon import UniformTypeIdentifiers -import Foundation -import ComposableArchitecture +// MARK: - ImportProfileFlowFeature @Reducer public struct ImportProfileFlowFeature { - @Dependency(ProfileClient.self) var profileClient - + @Reducer(state: .equatable) public enum Path { case inputDecryptionPassword(InputDecryptionPasswordFeature) } - + @ObservableState public struct State: Equatable { public var path = StackState() public var selectFile: SelectFileFeature.State - + public init() { self.selectFile = SelectFileFeature.State() } } - + public enum Action { public enum DelegateAction { case imported case failed } + case path(StackAction) - + case selectFile(SelectFileFeature.Action) case delegate(DelegateAction) } public init() {} - + public var body: some ReducerOf { Scope(state: \.selectFile, action: \.selectFile) { SelectFileFeature() } - + Reduce { state, action in switch action { - case let .selectFile(.delegate(.analyzedContentsOfFile(contents: data, analysis: profileFileContents))): switch profileFileContents { - case .notProfile: return .send(.delegate(.failed)) - + case .encryptedProfile: state.path.append(.inputDecryptionPassword(InputDecryptionPasswordFeature.State(encryptedProfile: data))) return .none - + case let .plaintextProfile(plaintextProfile): return importProfile(&state, plaintextProfile) - } - case .path(let pathAction): + case let .path(pathAction): switch pathAction { - case let .element( id: _, action: .inputDecryptionPassword(.delegate(.inputtedPassword(encryptedProfile, decryptionPassword))) @@ -73,7 +70,6 @@ public struct ImportProfileFlowFeature { } catch { log.error("Failed to decrypt encrypted profile, error: \(error)") } - case .element(id: _, action: _): return .none case .popFrom(id: _): @@ -85,30 +81,30 @@ public struct ImportProfileFlowFeature { case .selectFile: return .none - + case .delegate: return .none } } .forEach(\.path, action: \.path) } - + func importProfile(_ state: inout State, _ profile: Profile) -> Effect { - return .run { send in + .run { send in try await profileClient.importProfile(profile) await send(.delegate(.imported)) } } } +// MARK: ImportProfileFlowFeature.View extension ImportProfileFlowFeature { public struct View: SwiftUI.View { - @Bindable var store: StoreOf public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { NavigationStack(path: $store.scope(state: \.path, action: \.path)) { SelectFileFeature.View( diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/Steps/FileDocument+Profile.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/Steps/FileDocument+Profile.swift index 9804d8291..c45cac311 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/Steps/FileDocument+Profile.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/Steps/FileDocument+Profile.swift @@ -20,7 +20,6 @@ public enum ExportableProfileFile: FileDocument, Sendable, Hashable { case encrypted(Data) } - extension ExportableProfileFile { public static let readableContentTypes: [UTType] = [.profile] diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/Steps/InputDecryptionPasswordFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/Steps/InputDecryptionPasswordFeature.swift index 26c25d674..0b086ead4 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/Steps/InputDecryptionPasswordFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/Steps/InputDecryptionPasswordFeature.swift @@ -1,11 +1,11 @@ +import ComposableArchitecture +import Foundation import Sargon import UniformTypeIdentifiers -import Foundation -import ComposableArchitecture +// MARK: - InputDecryptionPasswordFeature @Reducer public struct InputDecryptionPasswordFeature { - @CasePathable public enum Action: ViewAction { public enum DelegateAction { @@ -17,10 +17,11 @@ public struct InputDecryptionPasswordFeature { case passwordChanged(String) case confirmPasswordButtonTapped } + case delegate(DelegateAction) case view(ViewAction) } - + @ObservableState public struct State: Equatable { public let encryptedProfile: Data @@ -29,43 +30,40 @@ public struct InputDecryptionPasswordFeature { self.encryptedProfile = encryptedProfile } } - - + public init() {} - + public var body: some ReducerOf { Reduce { state, action in switch action { case let .view(.passwordChanged(password)): state.password = password return .none - + case .view(.confirmPasswordButtonTapped): return .send(.delegate(.inputtedPassword(encryptedProfile: state.encryptedProfile, decryptionPassword: state.password))) - + case .delegate: return .none - } } } } +// MARK: InputDecryptionPasswordFeature.View extension InputDecryptionPasswordFeature { - @ViewAction(for: InputDecryptionPasswordFeature.self) public struct View: SwiftUI.View { - @Bindable public var store: StoreOf - + public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { VStack { LabeledTextField(label: "Decryption password", text: $store.password.sending(\.view.passwordChanged)) - + Button("Confirm") { send(.confirmPasswordButtonTapped) } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/Steps/SelectFileFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/Steps/SelectFileFeature.swift index 1f5ef82b7..0563cb2bd 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/Steps/SelectFileFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/ImportProfileFlowFeature/Steps/SelectFileFeature.swift @@ -1,14 +1,13 @@ +import ComposableArchitecture +import Foundation import Sargon import UniformTypeIdentifiers -import Foundation -import ComposableArchitecture extension UTType { // FIXME: should we declare our own file format? For now we use require `.json` file extension. public static let profile: Self = .json } - extension String { static let profileFileEncryptedPart = "encrypted" private static let filenameProfileBase = "radix_wallet_backup_file" @@ -16,44 +15,46 @@ extension String { static let filenameProfileEncrypted: Self = "\(filenameProfileBase).\(profileFileEncryptedPart).json" } +// MARK: - LackedPermissionToAccessSecurityScopedResource struct LackedPermissionToAccessSecurityScopedResource: Error {} +// MARK: - SelectFileFeature @Reducer public struct SelectFileFeature { - @CasePathable public enum Action: ViewAction { public enum DelegateAction { case analyzedContentsOfFile(contents: Data, analysis: ProfileFileContents) } - + @CasePathable public enum ViewAction { case openFileButtonTapped case profileImportResult(Result) case isPresentingFileImporterChanged(Bool) } + case delegate(DelegateAction) case view(ViewAction) } - + @ObservableState public struct State: Equatable { public var isPresentingFileImporter = false public init() {} } - + public var body: some ReducerOf { Reduce { state, action in switch action { case .view(.openFileButtonTapped): state.isPresentingFileImporter = true return .none - + case let .view(.profileImportResult(.failure(error))): log.error("Failed to read file, error: \(error)") return .none - + case let .view(.profileImportResult(.success(profileURL))): do { guard profileURL.startAccessingSecurityScopedResource() else { @@ -61,20 +62,19 @@ public struct SelectFileFeature { } defer { profileURL.stopAccessingSecurityScopedResource() } let data = try Data(contentsOf: profileURL) - + let analyzed = Profile.analyzeContents(data: data) return .send(.delegate(.analyzedContentsOfFile(contents: data, analysis: analyzed))) - + } catch { log.error("Failed to import profile, error: \(error)") } return .none - - + case let .view(.isPresentingFileImporterChanged(isPresentingFileImporter)): state.isPresentingFileImporter = isPresentingFileImporter return .none - + case .delegate: return .none } @@ -82,21 +82,20 @@ public struct SelectFileFeature { } } +// MARK: SelectFileFeature.View extension SelectFileFeature { - @ViewAction(for: SelectFileFeature.self) public struct View: SwiftUI.View { - @Bindable public var store: StoreOf - + public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { VStack { Text("Select file") - + Button("Open file selector") { send(.openFileButtonTapped) } @@ -109,5 +108,4 @@ extension SelectFileFeature { .navigationTitle("Open Profile file") } } - } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/NewOrImportProfileFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/NewOrImportProfileFeature.swift index d869b530a..0aee1bd7e 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/NewOrImportProfileFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/NewOrImportProfileFeature.swift @@ -1,70 +1,60 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-02-16. -// - -import Foundation import ComposableArchitecture +import Foundation import Sargon import SwiftUI +// MARK: - NewOrImportProfileFeature @Reducer public struct NewOrImportProfileFeature { public init() {} - + @ObservableState public struct State: Equatable { public init() {} } - + public enum Action: ViewAction { - public enum DelegateAction { case createdNewEmptyProfile case importProfile } - + public enum ViewAction { case newProfileButtonTapped case importProfileButtonTapped } - + case delegate(DelegateAction) case view(ViewAction) } - + public var body: some ReducerOf { - Reduce { state, action in + Reduce { _, action in switch action { - case .view(.importProfileButtonTapped): - .send(.delegate(.importProfile)) - - - case .view(.newProfileButtonTapped): - .run { send in - try await SargonOS.shared.newWallet() - await send(.delegate(.createdNewEmptyProfile)) - } catch: { error, _ in - fatalError("Failed to create Profile, error: \(error)") - } - + .send(.delegate(.importProfile)) + + case .view(.newProfileButtonTapped): + .run { send in + try await SargonOS.shared.newWallet() + await send(.delegate(.createdNewEmptyProfile)) + } catch: { error, _ in + fatalError("Failed to create Profile, error: \(error)") + } + case .delegate: - .none - + .none } } } } +// MARK: NewOrImportProfileFeature.View extension NewOrImportProfileFeature { - @ViewAction(for: NewOrImportProfileFeature.self) public struct View: SwiftUI.View { public let store: StoreOf - + public var body: some SwiftUI.View { VStack { Text("Existing or new user?").font(.title) @@ -72,7 +62,7 @@ extension NewOrImportProfileFeature { Button("New Profile") { send(.newProfileButtonTapped) } - + Button("Import Profile") { send(.importProfileButtonTapped) } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/OnboardingFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/OnboardingFeature.swift index ecb74bfc6..a50c1b2a2 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/OnboardingFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/OnboardingFeature.swift @@ -1,99 +1,98 @@ -import SwiftUI -import Sargon import ComposableArchitecture +import Sargon +import SwiftUI +// MARK: - OnboardingFeature @Reducer public struct OnboardingFeature { - @Reducer(state: .equatable) public enum Path { case newOrImportProfile(NewOrImportProfileFeature) case writeDownMnemonic(WriteDownMnemonicFeature) } - + @Reducer(state: .equatable) public enum Destination { case createAccount(CreateAccountFlowFeature) case importProfile(ImportProfileFlowFeature) } - + @ObservableState public struct State: Equatable { public var path = StackState() public var welcome: WelcomeFeature.State - + @Presents var destination: Destination.State? - + public init() { self.welcome = WelcomeFeature.State() } } - + @CasePathable public enum Action { @CasePathable public enum DelegateAction { case done } - + case destination(PresentationAction) case path(StackAction) case welcome(WelcomeFeature.Action) case delegate(DelegateAction) } - + public init() {} - + public var body: some ReducerOf { Scope(state: \.welcome, action: \.welcome) { WelcomeFeature() } Reduce { state, action in switch action { - - case .path(let pathAction): + case let .path(pathAction): switch pathAction { - case .element(id: _, action: .writeDownMnemonic(.delegate(.done))): return .send(.delegate(.done)) case .element(id: _, action: .newOrImportProfile(.delegate(.importProfile))): state.destination = .importProfile(.init()) return .none - + case .element(id: _, action: .newOrImportProfile(.delegate(.createdNewEmptyProfile))): state.destination = .createAccount(CreateAccountFlowFeature.State(index: 0)) return .none - + case .popFrom(id: _): return .none + case .push(id: _, state: _): return .none + default: return .none } - + case .welcome(.delegate(.done)): state.path.append(.newOrImportProfile(.init())) return .none - - + case .welcome: return .none - + case .delegate: return .none - + case .destination(.presented(.importProfile(.delegate(.imported)))): state.destination = nil return .send(.delegate(.done)) - + case .destination(.presented(.createAccount(.delegate(.createdAccount)))): state.destination = nil state.path.append(.writeDownMnemonic(.init())) return .none - + default: return .none } @@ -103,14 +102,15 @@ public struct OnboardingFeature { } } +// MARK: OnboardingFeature.View extension OnboardingFeature { public struct View: SwiftUI.View { @Bindable public var store: StoreOf - + public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { NavigationStack(path: $store.scope(state: \.path, action: \.path)) { WelcomeFeature.View( diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/WelcomeFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/WelcomeFeature.swift index 83798c97a..304dfae69 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/WelcomeFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/WelcomeFeature.swift @@ -1,36 +1,32 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-02-16. -// - -import Foundation import ComposableArchitecture +import Foundation import Sargon +// MARK: - WelcomeFeature @Reducer public struct WelcomeFeature { public init() {} - + @ObservableState public struct State: Equatable { public init() {} } - + public enum Action: ViewAction { public enum DelegateAction { case done } + public enum ViewAction { case continueButtonTapped } + case delegate(DelegateAction) case view(ViewAction) } - + public var body: some ReducerOf { - Reduce { state, action in + Reduce { _, action in switch action { case .view(.continueButtonTapped): .send(.delegate(.done)) @@ -41,26 +37,27 @@ public struct WelcomeFeature { } } +// MARK: WelcomeFeature.View extension WelcomeFeature { @ViewAction(for: WelcomeFeature.self) public struct View: SwiftUI.View { public let store: StoreOf - + public var body: some SwiftUI.View { VStack { Text("Welcome to Sargon demo").font(.title) ScrollView { Text( -""" -This tiny app demonstrates how Sargon written in Rust can be used in an iOS app, thanks to the Swift bindings that we have generated with UniFFI. + """ + This tiny app demonstrates how Sargon written in Rust can be used in an iOS app, thanks to the Swift bindings that we have generated with UniFFI. -The build artifacts of UniFFI are have three major components: -1) A set of binaries we have grouped to together with lipo and put in a .xcframework vendored as a binaryTarget in the Sargon Swift Package. + The build artifacts of UniFFI are have three major components: + 1) A set of binaries we have grouped to together with lipo and put in a .xcframework vendored as a binaryTarget in the Sargon Swift Package. -2) A single HUGE Swift file with Swift models exported from Rust and with function pointers that use the binaryTarget in the Sargon Swift Package + 2) A single HUGE Swift file with Swift models exported from Rust and with function pointers that use the binaryTarget in the Sargon Swift Package -3) A set of Swift extension's on the bindgen generated Swift models, e.g. making `Decimal192` conform to `ExpressibleByIntegerLiteral` which of course is a pure Swift construct. Also marking all types as `Sendable` and `CustomStringConvertible` making use of their `std::fmt::Display` impl in Rust land. -""" + 3) A set of Swift extension's on the bindgen generated Swift models, e.g. making `Decimal192` conform to `ExpressibleByIntegerLiteral` which of course is a pure Swift construct. Also marking all types as `Sendable` and `CustomStringConvertible` making use of their `std::fmt::Display` impl in Rust land. + """ ) .padding() } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/WriteDownMnemonicFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/WriteDownMnemonicFeature.swift index 1f3cd468f..4b4bedb92 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/WriteDownMnemonicFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/Onboarding/WriteDownMnemonicFeature.swift @@ -1,39 +1,34 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-02-16. -// - -import Foundation import ComposableArchitecture +import Foundation import Sargon +// MARK: - WriteDownMnemonicFeature @Reducer public struct WriteDownMnemonicFeature { - @Dependency(MnemonicClient.self) var mnemonicClient - + public init() {} - + @ObservableState public struct State: Equatable { public var mnemonic: String? - public init() { - } + public init() {} } - + public enum Action: ViewAction { public enum DelegateAction { case done } + public enum ViewAction { case revealMnemonicButtonTapped case continueButtonTapped } + public enum InternalAction { case loadedPrivateHDFactor(PrivateHierarchicalDeterministicFactorSource) } + case delegate(DelegateAction) case view(ViewAction) case `internal`(InternalAction) @@ -45,13 +40,12 @@ public struct WriteDownMnemonicFeature { case let .internal(.loadedPrivateHDFactor(privateHDFactor)): state.mnemonic = privateHDFactor.mnemonicWithPassphrase.mnemonic.phrase return .none - case .view(.revealMnemonicButtonTapped): return .run { send in let id = try SargonOS.shared.profile().factorSources.first!.id.extract(as: FactorSourceIdFromHash.self) let privateHDFactor = try await mnemonicClient.loadMnemonic(id) await send(.internal(.loadedPrivateHDFactor(privateHDFactor))) - } catch: { error, send in + } catch: { error, _ in fatalError("error \(error)") } case .view(.continueButtonTapped): @@ -63,12 +57,12 @@ public struct WriteDownMnemonicFeature { } } +// MARK: WriteDownMnemonicFeature.View extension WriteDownMnemonicFeature { - @ViewAction(for: WriteDownMnemonicFeature.self) public struct View: SwiftUI.View { public let store: StoreOf - + public var body: some SwiftUI.View { VStack { Text("Write down your mnemonic on a piece of paper and put it in a safe") @@ -90,5 +84,4 @@ extension WriteDownMnemonicFeature { .padding() } } - } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/DecryptSecurityQuestionsFeature/DecryptSecurityQuestionsFeatureCoordinator.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/DecryptSecurityQuestionsFeature/DecryptSecurityQuestionsFeatureCoordinator.swift index 38fcd4fe1..db46ab856 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/DecryptSecurityQuestionsFeature/DecryptSecurityQuestionsFeatureCoordinator.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/DecryptSecurityQuestionsFeature/DecryptSecurityQuestionsFeatureCoordinator.swift @@ -1,27 +1,27 @@ -import SwiftUI -import Sargon import ComposableArchitecture +import Sargon +import SwiftUI +// MARK: - DecryptSecurityQuestionsFeatureCoordinator @Reducer public struct DecryptSecurityQuestionsFeatureCoordinator { - @Dependency(FactorSourcesClient.self) var factorSourcesClient @Dependency(OverlayWindowClient.self) var overlayWindowClient - + @Reducer(state: .equatable) public enum Path { case answerQuestion(AnswerSecurityQuestionFeature) } - + @ObservableState public struct State: Equatable { @Shared(.questions) var questions @Shared(.pendingAnswers) var pendingAnswers - + public let securityQuestionsFactorSource: SecurityQuestionsNotProductionReadyFactorSource public var firstQuestion: AnswerSecurityQuestionFeature.State public var path = StackState() - + public init(securityQuestionsFactorSource: SecurityQuestionsNotProductionReadyFactorSource) { self.securityQuestionsFactorSource = securityQuestionsFactorSource self.firstQuestion = AnswerSecurityQuestionFeature.State(index: 0, answer: "") @@ -31,21 +31,21 @@ public struct DecryptSecurityQuestionsFeatureCoordinator { self.pendingAnswers = [] } } - + @CasePathable public enum Action { @CasePathable public enum DelegateAction { case done } - + case path(StackAction) case firstQuestion(AnswerSecurityQuestionFeature.Action) case delegate(DelegateAction) } - + public init() {} - + func nextStep(_ state: inout State, nextIndex indexOfNextQuestionToAnswer: Int) -> EffectOf { if indexOfNextQuestionToAnswer < state.questions.count { state.path.append(.answerQuestion( @@ -56,12 +56,12 @@ public struct DecryptSecurityQuestionsFeatureCoordinator { return .none } else { precondition(state.pendingAnswers.count == state.questions.count) - let answersToQuestionsArray = state.pendingAnswers.map({ + let answersToQuestionsArray = state.pendingAnswers.map { let question = state.questions[id: $0.id]! return SecurityNotProductionReadyQuestionAndAnswer(question: question, answer: $0.answer) - }) + } let answersToQuestions = answersToQuestionsArray.asIdentified() - + do { let mnemonic = try factorSourcesClient.decryptSecurityQuestionsFactor( answersToQuestions, @@ -77,51 +77,48 @@ public struct DecryptSecurityQuestionsFeatureCoordinator { } } } - + public var body: some ReducerOf { Scope(state: \.firstQuestion, action: \.firstQuestion) { AnswerSecurityQuestionFeature() } Reduce { state, action in switch action { - - case .path(let pathAction): + case let .path(pathAction): switch pathAction { - case let .element(id: _, action: .answerQuestion(.delegate(.done(index)))): - return nextStep(&state, nextIndex: index + 1) - + nextStep(&state, nextIndex: index + 1) case .popFrom(id: _): - return .none + .none case .push(id: _, state: _): - return .none + .none default: - return .none + .none } - + case let .firstQuestion(.delegate(.done(index))): - return nextStep(&state, nextIndex: index + 1) - + nextStep(&state, nextIndex: index + 1) + case .firstQuestion: - return .none - + .none + case .delegate: - return .none - + .none } } .forEach(\.path, action: \.path) } } +// MARK: DecryptSecurityQuestionsFeatureCoordinator.View extension DecryptSecurityQuestionsFeatureCoordinator { public struct View: SwiftUI.View { @Bindable var store: StoreOf - + public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { NavigationStack(path: $store.scope(state: \.path, action: \.path)) { AnswerSecurityQuestionFeature.View( diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/AnswerSecurityQuestionFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/AnswerSecurityQuestionFeature.swift index 984daa28e..e2440f1e6 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/AnswerSecurityQuestionFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/AnswerSecurityQuestionFeature.swift @@ -1,37 +1,30 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-03. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture +// MARK: - AnswerSecurityQuestionFeature @Reducer public struct AnswerSecurityQuestionFeature { - @ObservableState public struct State: Equatable { - @Shared(.pendingAnswers) var pendingAnswers @Shared(.questions) var questions - + public let index: Int public var answer: String = "" public var trimmed: String { trimSecurityQuestionsAnswer(answer: answer) } + public var question: SecurityNotProductionReadyQuestion { questions[index] } - + public init(index: Int, answer: String) { self.index = index self.answer = answer } - + public init(index: Int) { self.init(index: index, answer: "") self.answer = pendingAnswers[id: questions[index].id]?.answer ?? "" @@ -52,7 +45,7 @@ public struct AnswerSecurityQuestionFeature { case confirmButtonTapped } } - + public var body: some ReducerOf { Reduce { state, action in switch action { @@ -69,36 +62,38 @@ public struct AnswerSecurityQuestionFeature { } } } + extension AnswerSecurityQuestionFeature { public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { @Bindable public var store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack { Text("Question #\(store.state.index)") .font(.largeTitle) - - Spacer() - - Text("\(store.state.question.question)") - .font(.title) - .fontWeight(.bold) - - Spacer() - - if - case let unsafeAnswers = store.state.question.expectedAnswerFormat.unsafeAnswers, - !unsafeAnswers.isEmpty - { - Text("Unsuitable if your answer would be: \(unsafeAnswers.map({ "\"\($0)\"" }).joined(separator: ", "))") - .foregroundStyle(Color.red) - } - + + Spacer() + + Text("\(store.state.question.question)") + .font(.title) + .fontWeight(.bold) + + Spacer() + + if + case let unsafeAnswers = store.state.question.expectedAnswerFormat.unsafeAnswers, + !unsafeAnswers.isEmpty + { + Text("Unsuitable if your answer would be: \(unsafeAnswers.map { "\"\($0)\"" }.joined(separator: ", "))") + .foregroundStyle(Color.red) + } + LabeledTextField( label: "Answer", text: $store.answer.sending(\.view.answerChanged), @@ -106,11 +101,11 @@ extension AnswerSecurityQuestionFeature { hint: "Example: *\"\(store.state.question.expectedAnswerFormat.exampleAnswer)\"*" ) .padding(.vertical, 20) - + Labeled("Used", "'\(store.state.trimmed)'") - + Spacer() - + Button("Confirm") { send(.confirmButtonTapped) } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/SecurityQuestionsReviewAnswersFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/SecurityQuestionsReviewAnswersFeature.swift index e4744db79..ae98340a3 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/SecurityQuestionsReviewAnswersFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/SecurityQuestionsReviewAnswersFeature.swift @@ -1,15 +1,9 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-03. -// - +import ComposableArchitecture import Foundation -import SwiftUI import Sargon -import ComposableArchitecture +import SwiftUI +// MARK: - SecurityNotProductionReadyQuestionAndAnswer + Identifiable extension SecurityNotProductionReadyQuestionAndAnswer: Identifiable { public typealias ID = SecurityNotProductionReadyQuestion.ID public var id: ID { @@ -19,11 +13,11 @@ extension SecurityNotProductionReadyQuestionAndAnswer: Identifiable { public typealias AnswersToQuestions = IdentifiedArrayOf +// MARK: - SecurityQuestionsReviewAnswersFeature @Reducer public struct SecurityQuestionsReviewAnswersFeature { - @Dependency(FactorSourcesClient.self) var factorSourcesClient - + @ObservableState public struct State: Equatable { @Shared(.pendingAnswers) var toWipeAnswers @@ -39,19 +33,17 @@ public struct SecurityQuestionsReviewAnswersFeature { public enum DelegateAction { case factorCreatedAndAdded } - + public enum InternalAction { case factorCreatedAndAdded } - - + @CasePathable public enum ViewAction { case addFactorButtonTapped } - } - + public var body: some ReducerOf { Reduce { state, action in switch action { @@ -60,15 +52,16 @@ public struct SecurityQuestionsReviewAnswersFeature { state.isAdding = true return .run { [qas = state.answersToQuestions] send in let factor = try factorSourcesClient.createSecurityQuestionsFactor(qas) - try await factorSourcesClient.addFactorSource(factor.asGeneral) - await send(.internal(.factorCreatedAndAdded)) + try await factorSourcesClient.addFactorSource(factor.asGeneral) + await send(.internal(.factorCreatedAndAdded)) } + case .internal(.factorCreatedAndAdded): state.toWipeAnswers = [] // IMPORTANT! Since this is shared state (in memory) we SHOULD wipe secrets return .send(.delegate(.factorCreatedAndAdded)) - - case .delegate: - return .none + + case .delegate: + return .none } } } @@ -76,55 +69,58 @@ public struct SecurityQuestionsReviewAnswersFeature { extension SecurityQuestionsReviewAnswersFeature { public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { public let store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack { Text("Review Answers").font(.largeTitle) ScrollView { - ForEach(store.state.answersToQuestions) { answerToQuestion in - let index = store.state.answersToQuestions.firstIndex(of: answerToQuestion)! - AnsweredQuestionCard(answerToQuestion, index) - } - .multilineTextAlignment(.leading) - } - - Button("Add Factor") { - send(.addFactorButtonTapped) - } + ForEach(store.state.answersToQuestions) { answerToQuestion in + let index = store.state.answersToQuestions.firstIndex(of: answerToQuestion)! + AnsweredQuestionCard(answerToQuestion, index) + } + .multilineTextAlignment(.leading) + } + + Button("Add Factor") { + send(.addFactorButtonTapped) + } .disabled(store.state.isAdding) - .buttonStyle(.borderedProminent) - } - .padding() - } + .buttonStyle(.borderedProminent) + } + .padding() + } } } +// MARK: - AnsweredQuestionCard public struct AnsweredQuestionCard: SwiftUI.View { - public let answerToQuestion: AnswersToQuestions.Element - public let index: Int - public init( - _ answerToQuestion: AnswersToQuestions.Element, - _ index: Int - ) { - self.answerToQuestion = answerToQuestion - self.index = index - } - public var body: some View { - VStack(alignment: .leading, spacing: 20) { - Labeled("Question \(index)", answerToQuestion.question.question, axis: .vertical) - Labeled("Answer \(index)", answerToQuestion.answer, axis: .vertical) - } - .fontWeight(.bold) - .foregroundStyle(Color.white) - .frame(maxWidth:. infinity) - .padding() - .background(Color.green) - .clipShape(.rect(cornerRadius: 20)) - } + public let answerToQuestion: AnswersToQuestions.Element + public let index: Int + public init( + _ answerToQuestion: AnswersToQuestions.Element, + _ index: Int + ) { + self.answerToQuestion = answerToQuestion + self.index = index + } + + public var body: some View { + VStack(alignment: .leading, spacing: 20) { + Labeled("Question \(index)", answerToQuestion.question.question, axis: .vertical) + Labeled("Answer \(index)", answerToQuestion.answer, axis: .vertical) + } + .fontWeight(.bold) + .foregroundStyle(Color.white) + .frame(maxWidth: .infinity) + .padding() + .background(Color.green) + .clipShape(.rect(cornerRadius: 20)) + } } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/SelectQuestionsFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/SelectQuestionsFeature.swift index c5203657a..7a12aeabe 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/SelectQuestionsFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/SelectQuestionsFeature.swift @@ -1,93 +1,84 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-03. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture - +// MARK: - SelectQuestionsFeature @Reducer public struct SelectQuestionsFeature { - @Reducer(state: .equatable) public enum Destination { case prefillQuestionsAndAnswersAlert(AlertState) - + public enum PrefillQuestionsAndAnswersAlert: String, CaseIterable { case sample case sampleOther } } - @ObservableState public struct State: Equatable { @Shared(.questions) var questions @Presents var destination: Destination.State? - - public var canProceed: Bool { - // FIXME: change to UniFFI export the `SealedMnemonic::QUESTION_COUNT`... - do { - let _ = try SecurityQuestionsNotProductionReadyFactorSource(mnemonic: .sample, questionsAndAnswers: questions.enumerated().map({ - SecurityNotProductionReadyQuestionAndAnswer.init(question: $0.element, answer: "\($0.offset)") - })) - return true - } catch { - return false - } - } - public var questionCount: Int { - // FIXME: change to UniFFI export the `SealedMnemonic::QUESTION_COUNT`... - 6 // might be wrong, the `canProceed` tells the truth though. - } - + + public var canProceed: Bool { + // FIXME: change to UniFFI export the `SealedMnemonic::QUESTION_COUNT`... + do { + let _ = try SecurityQuestionsNotProductionReadyFactorSource(mnemonic: .sample, questionsAndAnswers: questions.enumerated().map { + SecurityNotProductionReadyQuestionAndAnswer(question: $0.element, answer: "\($0.offset)") + }) + return true + } catch { + return false + } + } + + public var questionCount: Int { + // FIXME: change to UniFFI export the `SealedMnemonic::QUESTION_COUNT`... + 6 // might be wrong, the `canProceed` tells the truth though. + } } - + @CasePathable public enum Action: ViewAction { case delegate(DelegateAction) case view(ViewAction) case destination(PresentationAction) - + public enum DelegateAction { case done(prefillWith: [SecurityNotProductionReadyQuestionAndAnswer]?) } - + @CasePathable public enum ViewAction { case confirmedQuestions case prefillButtonTapped } } - + public var body: some ReducerOf { Reduce { state, action in switch action { - case .view(.prefillButtonTapped): state.destination = .prefillQuestionsAndAnswersAlert(.init( title: TextState("Prefill?"), message: TextState("Will take you to review screen."), buttons: [ - .cancel(TextState("Cancel")) + .cancel(TextState("Cancel")), ] + Destination.PrefillQuestionsAndAnswersAlert.allCases.map { action in ButtonState( action: action, label: { - TextState("Prefill with '\(action.rawValue)'") - }) + TextState("Prefill with '\(action.rawValue)'") + } + ) } )) return .none - + case .view(.confirmedQuestions): - precondition(state.canProceed) + precondition(state.canProceed) return .send(.delegate(.done(prefillWith: nil))) - + case let .destination(.presented(.prefillQuestionsAndAnswersAlert(prefillAction))): let qas = switch prefillAction { case .sample: @@ -95,13 +86,13 @@ public struct SelectQuestionsFeature { case .sampleOther: newSecurityNOTPRODUCTIONREADYQuestionsAndAnswersSampleOther() } - + state.destination = nil return .send(.delegate(.done(prefillWith: qas))) - + case .destination: return .none - + case .delegate: return .none } @@ -110,15 +101,18 @@ public struct SelectQuestionsFeature { } } +// MARK: - SelectQuestionCard public struct SelectQuestionCard: View { @Shared(.questions) var questions public let question: SecurityNotProductionReadyQuestion public var id: SecurityNotProductionReadyQuestion.ID { - question.id - } - public var isSelected: Bool { - questions[id: id] != nil - } + question.id + } + + public var isSelected: Bool { + questions[id: id] != nil + } + public var body: some SwiftUI.View { Button(action: { if isSelected { @@ -129,7 +123,7 @@ public struct SelectQuestionCard: View { }, label: { HStack { Text(isSelected ? "✅" : "☑️").font(.title) - VStack(alignment: .leading) { + VStack(alignment: .leading) { Text("\(question.question)").font(.headline).fontWeight(.bold) if case let unsafeAnswers = question.expectedAnswerFormat.unsafeAnswers, !unsafeAnswers.isEmpty { Text("Unsuitable if: \(unsafeAnswers.joined(separator: ","))") @@ -138,7 +132,7 @@ public struct SelectQuestionCard: View { } } } - .multilineTextAlignment(.leading) + .multilineTextAlignment(.leading) }) .buttonStyle(.plain) .frame(maxWidth: .infinity, alignment: .leading) @@ -148,24 +142,24 @@ public struct SelectQuestionCard: View { extension SelectQuestionsFeature { public typealias HostingFeature = Self - - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { @Bindable public var store: StoreOf public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { VStack { - Text("Pick #\(store.questionCount) questions").font(.title) + Text("Pick #\(store.questionCount) questions").font(.title) Text("Picked: \(store.state.questions.count)") - + Button("Prefill Q + As") { send(.prefillButtonTapped) } .buttonStyle(.borderedProminent) - + ScrollView { ForEach(SecurityNotProductionReadyQuestion.all) { question in SelectQuestionCard(question: question) @@ -173,7 +167,7 @@ extension SelectQuestionsFeature { } } .padding(.vertical, 10) - + Button("Confirm Questions") { send(.confirmedQuestions) } @@ -185,4 +179,3 @@ extension SelectQuestionsFeature { } } } - diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/SharedState+SecurityQuestions.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/SharedState+SecurityQuestions.swift index 51b99fb3e..faa4b31aa 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/SharedState+SecurityQuestions.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/Children/SharedState+SecurityQuestions.swift @@ -1,24 +1,19 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-03. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture +// MARK: - SecurityNotProductionReadyQuestion + Identifiable extension SecurityNotProductionReadyQuestion: Identifiable { public typealias ID = UInt16 } + extension SecurityNotProductionReadyQuestion { public static let all: [SecurityNotProductionReadyQuestion] = securityQuestionsAll() } - extension PersistenceReaderKey -where Self == PersistenceKeyDefault> { + where Self == PersistenceKeyDefault> +{ static var pendingAnswers: Self { PersistenceKeyDefault( .inMemory("pendingAnswers"), @@ -27,18 +22,20 @@ where Self == PersistenceKeyDefault> { } } +// MARK: - PendingAnswerToQuestion public struct PendingAnswerToQuestion: Hashable, Sendable, Identifiable { public typealias ID = SecurityNotProductionReadyQuestion.ID public let questionID: ID public let answer: String - + public var id: ID { questionID } } public typealias PendingAnswersToQuestions = IdentifiedArrayOf extension PersistenceReaderKey -where Self == PersistenceKeyDefault>> { + where Self == PersistenceKeyDefault>> +{ static var questions: Self { PersistenceKeyDefault( .inMemory("questions"), diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/NewSecurityQuestionsFeatureCoordinator.swift b/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/NewSecurityQuestionsFeatureCoordinator.swift index e8d3be757..ea91bf964 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/NewSecurityQuestionsFeatureCoordinator.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Flows/SecurityQuestions/NewSecurityQuestionsFeature/NewSecurityQuestionsFeatureCoordinator.swift @@ -1,45 +1,45 @@ -import SwiftUI -import Sargon import ComposableArchitecture +import Sargon +import SwiftUI +// MARK: - NewSecurityQuestionsFeatureCoordinator @Reducer public struct NewSecurityQuestionsFeatureCoordinator { - @Reducer(state: .equatable) public enum Path { case answerQuestion(AnswerSecurityQuestionFeature) case reviewAnswers(SecurityQuestionsReviewAnswersFeature) } - + @ObservableState public struct State: Equatable { @Shared(.questions) var questions @Shared(.pendingAnswers) var pendingAnswers - + public var selectQuestions: SelectQuestionsFeature.State public var path = StackState() - + public init() { self.selectQuestions = SelectQuestionsFeature.State() questions = .init() pendingAnswers = .init() } } - + @CasePathable public enum Action { @CasePathable public enum DelegateAction { case done } - + case path(StackAction) case selectQuestions(SelectQuestionsFeature.Action) case delegate(DelegateAction) } - + public init() {} - + func nextStep(_ state: inout State, nextIndex indexOfNextQuestionToAnswer: Int) -> EffectOf { if indexOfNextQuestionToAnswer < state.questions.count { state.path.append(.answerQuestion( @@ -49,86 +49,85 @@ public struct NewSecurityQuestionsFeatureCoordinator { )) } else { precondition(state.pendingAnswers.count == state.questions.count) - let answersToQuestionsArray = state.pendingAnswers.map({ + let answersToQuestionsArray = state.pendingAnswers.map { let question = state.questions[id: $0.id]! return SecurityNotProductionReadyQuestionAndAnswer(question: question, answer: $0.answer) - }) + } let answersToQuestions = answersToQuestionsArray.asIdentified() state.path.append(.reviewAnswers(SecurityQuestionsReviewAnswersFeature.State( answersToQuestions: answersToQuestions ))) } - - + return .none } - + public var body: some ReducerOf { Scope(state: \.selectQuestions, action: \.selectQuestions) { SelectQuestionsFeature() } Reduce { state, action in switch action { - - case .path(let pathAction): + case let .path(pathAction): switch pathAction { - case let .element(id: _, action: .answerQuestion(.delegate(.done(index)))): return nextStep(&state, nextIndex: index + 1) - + case .element(id: _, action: .reviewAnswers(.delegate(.factorCreatedAndAdded))): return .send(.delegate(.done)) - + case .popFrom(id: _): return .none + case .push(id: _, state: _): return .none + default: return .none } - + case let .selectQuestions(.delegate(.done(prefillWith))): if let qas = prefillWith { state.questions = qas.map(\.question).asIdentified() - state.pendingAnswers = qas.map({ PendingAnswerToQuestion.init(questionID: $0.question.id, answer: $0.answer) }).asIdentified() + state.pendingAnswers = qas.map { PendingAnswerToQuestion(questionID: $0.question.id, answer: $0.answer) }.asIdentified() state.path = StackState( - (0.. - + public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { NavigationStack(path: $store.scope(state: \.path, action: \.path)) { SelectQuestionsFeature.View( @@ -138,7 +137,7 @@ extension NewSecurityQuestionsFeatureCoordinator { switch store.case { case let .answerQuestion(store): AnswerSecurityQuestionFeature.View(store: store) - + case let .reviewAnswers(store): SecurityQuestionsReviewAnswersFeature.View(store: store) } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/MainFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/MainFeature.swift index 6267e06b4..71b579c02 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/MainFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/MainFeature.swift @@ -1,117 +1,111 @@ -import Sargon import ComposableArchitecture +import Sargon +// MARK: - MainFeature @Reducer public struct MainFeature { - @Dependency(ProfileClient.self) var profileClient @Dependency(AccountsClient.self) var accountsClient - + @Reducer public enum Path { case settings(SettingsFeature) case manageSecurityShields(ManageSecurityShieldsFeature) case shieldDetails(ShieldDetailsFeature) - case manageFactorSources(ManageFactorSourcesFeature) - case manageSpecificFactorSources(ManageSpecificFactorSourcesFeature) + case manageFactorSources(ManageFactorSourcesFeature) + case manageSpecificFactorSources(ManageSpecificFactorSourcesFeature) case accountDetails(AccountDetailsFeature) case profileView(DebugProfileFeature) } - + @Reducer(state: .equatable) public enum Destination { case createAccount(CreateAccountFlowFeature) - + case newHWFactorSource(NewHWFactorSourceFeature) case newTrustedContact(NewTrustedContactFactorSourceFeature) case newSecurityQuestions(NewSecurityQuestionsFeatureCoordinator) case deleteProfileAlert(AlertState) - + public enum DeleteProfileAlert { case confirmedDeleteProfileBDFSThenOnboard case confirmedEmulateFreshInstallThenTerminate } } - + @ObservableState public struct State { @SharedReader(.network) var network @Presents var destination: Destination.State? public var path = StackState() public var accounts: AccountsFeature.State - + public init() { self.accounts = AccountsFeature.State() } - } - + @CasePathable public enum Action: ViewAction { - @CasePathable public enum ViewAction { case settingsButtonTapped case deleteWalletButtonTapped } - + @CasePathable public enum DelegateAction { case deletedWallet case emulateFreshInstall } - + case view(ViewAction) case destination(PresentationAction) case path(StackAction) - + case accounts(AccountsFeature.Action) - + case delegate(DelegateAction) - } - + public init() {} - + public var body: some ReducerOf { Scope(state: \.accounts, action: \.accounts) { AccountsFeature() } Reduce { state, action in switch action { - - case .path(let pathAction): + case let .path(pathAction): switch pathAction { - case let .element(id: _, action: action): switch action { case .settings(.delegate(.navigate(.toProfileView))): state.path.append(.profileView(DebugProfileFeature.State())) return .none - + case .settings(.delegate(.navigate(.toShields))): state.path.append(.manageSecurityShields(ManageSecurityShieldsFeature.State())) return .none - + case .settings(.delegate(.navigate(.toFactorSources))): state.path.append(.manageFactorSources(ManageFactorSourcesFeature.State())) return .none - + case let .shieldDetails(.delegate(.copyAndEdit(preset))): state.path.append(.manageSecurityShields(ManageSecurityShieldsFeature.State(copyAndEdit: preset))) return .none - + case let .manageSecurityShields(.delegate(.navigate(.toDetailsForShield(shield)))): state.path.append(.shieldDetails(ShieldDetailsFeature.State(shield: shield))) return .none - - + case let .manageFactorSources(.delegate(.navigate(.toFactor(kind)))): state.path.append(.manageSpecificFactorSources( ManageSpecificFactorSourcesFeature.State(kind: kind) )) - return .none - + return .none + case let .manageSpecificFactorSources(.delegate(.addNew(kind))): if kind == .securityQuestions { state.destination = .newSecurityQuestions(NewSecurityQuestionsFeatureCoordinator.State()) @@ -121,37 +115,36 @@ public struct MainFeature { state.destination = .newHWFactorSource(NewHWFactorSourceFeature.State(kind: kind)) } return .none - + case .profileView: return .none - + case .settings: return .none - + case .manageSecurityShields: return .none case .manageFactorSources: return .none - + case .manageSpecificFactorSources: return .none - + case .accountDetails: return .none - + case .shieldDetails: return .none - } - + case .popFrom(id: _): return .none - + case .push(id: _, state: _): return .none } - + case .view(.deleteWalletButtonTapped): state.destination = .deleteProfileAlert(.init( title: TextState("Delete wallet?"), @@ -165,39 +158,37 @@ public struct MainFeature { .destructive( TextState("Emulate Fresh Install -> Restart"), action: .send(.confirmedEmulateFreshInstallThenTerminate) - ) + ), ] )) return .none - - + case .view(.settingsButtonTapped): state.path.append(.settings(SettingsFeature.State())) return .none - + case let .accounts(.delegate(.showDetailsFor(accountForDisplay))): state.path.append(.accountDetails(AccountDetailsFeature.State(accountForDisplay: accountForDisplay))) return .none - - + case let .accounts(.delegate(.createNewAccount(index))): state.destination = .createAccount( CreateAccountFlowFeature.State(index: index) ) return .none - + case .destination(.presented(.newSecurityQuestions(.delegate(.done)))): state.destination = nil return .none - + case .destination(.presented(.newTrustedContact(.delegate(.done)))): state.destination = nil return .none - + case .destination(.presented(.newHWFactorSource(.delegate(.createdAndSavedNewFactorSource)))): state.destination = nil return .none - + case .destination(.presented(.deleteProfileAlert(.confirmedEmulateFreshInstallThenTerminate))): log.notice("Confirmed deletion of Profile & BDFS") state.destination = nil @@ -205,7 +196,7 @@ public struct MainFeature { try await profileClient.emulateFreshInstallOfAppThenRestart() await send(.delegate(.emulateFreshInstall)) } - + case .destination(.presented(.deleteProfileAlert(.confirmedDeleteProfileBDFSThenOnboard))): log.notice("Confirmed deletion of Profile & BDFS (will then onboard)") state.destination = nil @@ -213,12 +204,11 @@ public struct MainFeature { try await profileClient.deleteProfileAndMnemonicsThenCreateNew() await send(.delegate(.deletedWallet)) } - case .destination(.presented(.createAccount(.delegate(.createdAccount)))): state.destination = nil return .none - + default: return .none } @@ -226,144 +216,139 @@ public struct MainFeature { .forEach(\.path, action: \.path) .ifLet(\.$destination, action: \.destination) } - } +// MARK: - BannerThisIsNotRadixWallet public struct BannerThisIsNotRadixWallet: View { - public let onMainnet: Bool - public init(onMainnet: Bool) { - self.onMainnet = onMainnet - } - public var body: some View { - VStack(alignment: .center, spacing: 4) { - Text("Demo app, **not** the Radix Wallet app.") - .font(.system(size: 22)) - Text(onMainnet ? "" : "‼️ On Testnet ‼️") - .font(.system(size: 12)) - } - .frame(maxWidth: .infinity, alignment: .center) - .padding(4) - .background(Color.yellow) - .foregroundStyle(Color.red) - .fontWeight(.bold) - } + public let onMainnet: Bool + public init(onMainnet: Bool) { + self.onMainnet = onMainnet + } + public var body: some View { + VStack(alignment: .center, spacing: 4) { + Text("Demo app, **not** the Radix Wallet app.") + .font(.system(size: 22)) + Text(onMainnet ? "" : "‼️ On Testnet ‼️") + .font(.system(size: 12)) + } + .frame(maxWidth: .infinity, alignment: .center) + .padding(4) + .background(Color.yellow) + .foregroundStyle(Color.red) + .fontWeight(.bold) + } } - +// MARK: - MainFeature.View extension MainFeature { @ViewAction(for: MainFeature.self) public struct View: SwiftUI.View { - @Bindable public var store: StoreOf - + public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { VStack(spacing: 0) { - BannerThisIsNotRadixWallet( onMainnet: store.network == .mainnet ) - - mainbody + + mainbody + } + } + + var mainbody: some SwiftUI.View { + NavigationStack(path: $store.scope(state: \.path, action: \.path)) { + VStack { + if let profile = try? SargonOS.shared.profile() { + VStack { + Text("ProfileID:") + Text("\(profile.id)") + } + } else { + Text("NO PROFILE") + } + + AccountsFeature.View( + store: store.scope(state: \.accounts, action: \.accounts) + ) + + Button("Delete Wallet", role: .destructive) { + send(.deleteWalletButtonTapped) + } + } + .toolbar { + ToolbarItem(placement: .primaryAction) { + Button("Settings") { + send(.settingsButtonTapped) + } + } + } + } destination: { store in + destinationView(store: store) + } + .sheet( + item: $store.scope( + state: \.destination?.createAccount, + action: \.destination.createAccount + ) + ) { store in + CreateAccountFlowFeature.View(store: store) + } + .sheet( + item: $store.scope( + state: \.destination?.newHWFactorSource, + action: \.destination.newHWFactorSource + ) + ) { store in + NewHWFactorSourceFeature.View(store: store) + } + .sheet( + item: $store.scope( + state: \.destination?.newTrustedContact, + action: \.destination.newTrustedContact + ) + ) { store in + NewTrustedContactFactorSourceFeature.View(store: store) + } + .sheet( + item: $store.scope( + state: \.destination?.newSecurityQuestions, + action: \.destination.newSecurityQuestions + ) + ) { store in + NewSecurityQuestionsFeatureCoordinator.View(store: store) + } + .alert($store.scope(state: \.destination?.deleteProfileAlert, action: \.destination.deleteProfileAlert)) + } + + @ViewBuilder + func destinationView(store: StoreOf) -> some SwiftUI.View { + switch store.case { + case let .settings(store): + SettingsFeature.View(store: store) + + case let .manageSecurityShields(store): + ManageSecurityShieldsFeature.View(store: store) + + case let .manageFactorSources(store): + ManageFactorSourcesFeature.View(store: store) + + case let .manageSpecificFactorSources(store): + ManageSpecificFactorSourcesFeature.View(store: store) + + case let .accountDetails(store): + AccountDetailsFeature.View(store: store) + + case let .shieldDetails(store): + ShieldDetailsFeature.View(store: store) + + case let .profileView(store): + DebugProfileFeature.View(store: store) } } - - - var mainbody: some SwiftUI.View { - NavigationStack(path: $store.scope(state: \.path, action: \.path)) { - VStack { - if let profile = try? SargonOS.shared.profile() { - VStack { - Text("ProfileID:") - Text("\(profile.id )") - } - } else { - Text("NO PROFILE") - } - - AccountsFeature.View( - store: store.scope(state: \.accounts, action: \.accounts) - ) - - Button("Delete Wallet", role: .destructive) { - send(.deleteWalletButtonTapped) - } - } - .toolbar { - ToolbarItem(placement: .primaryAction) { - Button("Settings") { - send(.settingsButtonTapped) - } - } - } - } destination: { store in - destinationView(store: store) - } - .sheet( - item: $store.scope( - state: \.destination?.createAccount, - action: \.destination.createAccount - ) - ) { store in - CreateAccountFlowFeature.View(store: store) - } - .sheet( - item: $store.scope( - state: \.destination?.newHWFactorSource, - action: \.destination.newHWFactorSource - ) - ) { store in - NewHWFactorSourceFeature.View(store: store) - } - .sheet( - item: $store.scope( - state: \.destination?.newTrustedContact, - action: \.destination.newTrustedContact - ) - ) { store in - NewTrustedContactFactorSourceFeature.View(store: store) - } - .sheet( - item: $store.scope( - state: \.destination?.newSecurityQuestions, - action: \.destination.newSecurityQuestions - ) - ) { store in - NewSecurityQuestionsFeatureCoordinator.View(store: store) - } - .alert($store.scope(state: \.destination?.deleteProfileAlert, action: \.destination.deleteProfileAlert)) - - } - - @ViewBuilder - func destinationView(store: StoreOf) -> some SwiftUI.View { - switch store.case { - - case let .settings(store): - SettingsFeature.View(store: store) - - case let .manageSecurityShields(store): - ManageSecurityShieldsFeature.View(store: store) - - case let .manageFactorSources(store): - ManageFactorSourcesFeature.View(store: store) - - case let .manageSpecificFactorSources(store): - ManageSpecificFactorSourcesFeature.View(store: store) - - case let .accountDetails(store): - AccountDetailsFeature.View(store: store) - - case let .shieldDetails(store): - ShieldDetailsFeature.View(store: store) - - case let .profileView(store): - DebugProfileFeature.View(store: store) - } - } } } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/AppDelegate.swift b/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/AppDelegate.swift index d6d641220..39bcb6bff 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/AppDelegate.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/AppDelegate.swift @@ -2,13 +2,13 @@ import ComposableArchitecture import SwiftUI public final class AppDelegate: NSObject, UIApplicationDelegate { - public func application( - _ application: UIApplication, - configurationForConnecting connectingSceneSession: UISceneSession, - options: UIScene.ConnectionOptions - ) -> UISceneConfiguration { - let sceneConfig = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role) - sceneConfig.delegateClass = SceneDelegate.self - return sceneConfig - } + public func application( + _ application: UIApplication, + configurationForConnecting connectingSceneSession: UISceneSession, + options: UIScene.ConnectionOptions + ) -> UISceneConfiguration { + let sceneConfig = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role) + sceneConfig.delegateClass = SceneDelegate.self + return sceneConfig + } } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/HUDFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/HUDFeature.swift index b0c961656..740232c95 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/HUDFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/HUDFeature.swift @@ -1,52 +1,46 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-11. -// - -import Foundation import ComposableArchitecture +import Foundation +// MARK: - HUDFeature @Reducer public struct HUDFeature { - @Dependency(\.continuousClock) var clock - + @ObservableState public struct State: Equatable { static let hiddenOffset: CGFloat = -128.0 static let autoDismissDelay: Double = 1.0 - + let content: HUDMessage var offset = Self.hiddenOffset - } - + public enum Action: ViewAction, Sendable { public enum ViewAction: Sendable { case onAppear case animationCompletion } + public enum DelegateAction: Sendable { case dismiss } + public enum InternalAction: Sendable { case autoDismiss } + case view(ViewAction) case delegate(DelegateAction) case `internal`(InternalAction) } - + public var body: some ReducerOf { Reduce { state, action in switch action { - case .internal(.autoDismiss): state.offset = State.hiddenOffset return .none - + case .view(.animationCompletion): if state.offset == State.hiddenOffset { /// Notify the delegate only after the animation did complete. @@ -57,13 +51,13 @@ public struct HUDFeature { await send(.internal(.autoDismiss), animation: .hudAnimation) } } + case .view(.onAppear): state.offset = 0 return .none - + case .delegate: return .none - } } } @@ -71,14 +65,14 @@ public struct HUDFeature { extension HUDFeature { public typealias HostingFeature = Self - + @ViewAction(for: HostingFeature.self) public struct View: SwiftUI.View { public let store: StoreOf public init(store: StoreOf) { self.store = store } - + public var body: some SwiftUI.View { VStack { Group { @@ -117,16 +111,16 @@ extension HUDFeature { send(.animationCompletion) } Spacer() - } } } } +// MARK: - HitTargetSize public enum HitTargetSize: CGFloat { /// 24 case smallest = 24 - + public var frame: CGSize { .init(width: rawValue, height: rawValue) } @@ -139,7 +133,7 @@ extension View { } } -// MARK: - SwiftUI.Animation + Sendable +// MARK: - SwiftUI.Animation + @unchecked Sendable extension SwiftUI.Animation: @unchecked Sendable {} extension SwiftUI.Animation { @@ -161,6 +155,7 @@ extension View { ) } } + // MARK: - OnAnimationCompletedViewModifier /// A view modifier allowing to observe the completion of a given value animation private struct OnAnimationCompletedViewModifier: Animatable, ViewModifier { @@ -173,16 +168,16 @@ private struct OnAnimationCompletedViewModifier some View { content } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/HUDMessage.swift b/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/HUDMessage.swift index c9c89d72b..a1a77811e 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/HUDMessage.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/HUDMessage.swift @@ -1,52 +1,46 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-11. -// - import Foundation public struct HUDMessage: Sendable, Hashable, Identifiable { - public let id = UUID() - public let text: String - public let icon: Icon? - - public struct Icon: Hashable, Sendable { - public let systemName: String - public let foregroundColor: Color - - public init( - systemName: String, - foregroundColor: Color - ) { - self.systemName = systemName - self.foregroundColor = foregroundColor - } - + public let id = UUID() + public let text: String + public let icon: Icon? + + public struct Icon: Hashable, Sendable { + public let systemName: String + public let foregroundColor: Color + + public init( + systemName: String, + foregroundColor: Color + ) { + self.systemName = systemName + self.foregroundColor = foregroundColor + } + public static let success = Self( systemName: "checkmark.circle.fill", foregroundColor: Color.app.green1 ) - + public static let fail = Self( systemName: "exclamationmark.triangle.fill", foregroundColor: Color.app.red1 ) - } - - public init( - text: String, - icon: Icon? - ) { - self.text = text - self.icon = icon - } - + } + + public init( + text: String, + icon: Icon? + ) { + self.text = text + self.icon = icon + } + public static func success(text: String, icon: Icon? = .success) -> Self { - Self.init(text: text, icon: icon) + Self(text: text, icon: icon) } + public static func failure(text: String, icon: Icon? = .fail) -> Self { - Self.init(text: text, icon: icon) + Self(text: text, icon: icon) } } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/OverlayFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/OverlayFeature.swift index 01792b6a3..8cb934480 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/OverlayFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/OverlayFeature.swift @@ -1,129 +1,130 @@ import ComposableArchitecture import SwiftUI - +// MARK: - OverlayFeature @Reducer struct OverlayFeature { - - @Dependency(OverlayWindowClient.self) var overlayWindowClient - @Dependency(\.continuousClock) var clock - - @Reducer(state: .equatable) - public enum Destination: Sendable { - case hud(HUDFeature) - } - - @ObservableState - struct State: Equatable { - var itemsQueue: IdentifiedArrayOf = [] - - var isPresenting: Bool { - destination != nil - } - - @Presents - public var destination: Destination.State? - } - - @CasePathable - public enum Action: ViewAction, Sendable { - @CasePathable - public enum ViewAction { - case task - } - enum InternalAction { - case scheduleItem(HUDMessage) - case showNextItemIfPossible - } - case `internal`(InternalAction) - case view(ViewAction) - case destination(PresentationAction) - } - - public var body: some ReducerOf { - Reduce { state, action in - - switch action { - case .view(.task): - return .run { send in - for try await item in overlayWindowClient.getScheduledItems() { - guard !Task.isCancelled else { return } - await send(.internal(.scheduleItem(item))) - } - } - case let .internal(.scheduleItem(hudMessage)): - state.itemsQueue.append(hudMessage) - return showItemIfPossible(state: &state) - case .internal(.showNextItemIfPossible): - return showItemIfPossible(state: &state) - - case .destination(.presented(.hud(.delegate(.dismiss)))): - return dismiss(&state) - - case .destination: - return .none - } - } - .ifLet(\.$destination, action: \.destination) - } - - private func showItemIfPossible(state: inout State) -> Effect { - guard !state.itemsQueue.isEmpty else { - return .none - } - - if state.isPresenting { - guard let presentedItem = state.itemsQueue.first else { - return .none - } - - // A HUD is force dismissed when next item comes in, AKA it is a lower priority. - state.destination = nil - state.itemsQueue.removeFirst() - return .run { send in - // Hacky - A very minor delay is needed before showing the next item is a HUD. - try await clock.sleep(for: .milliseconds(200)) - await send(.internal(.showNextItemIfPossible)) - } - } - - let nextItem = state.itemsQueue[0] - - state.destination = .hud(.init(content: nextItem)) - return .none - } - - - private func dismiss(_ state: inout State) -> Effect { - state.destination = nil - state.itemsQueue.removeFirst() - return showItemIfPossible(state: &state) - } + @Dependency(OverlayWindowClient.self) var overlayWindowClient + @Dependency(\.continuousClock) var clock + + @Reducer(state: .equatable) + public enum Destination: Sendable { + case hud(HUDFeature) + } + + @ObservableState + struct State: Equatable { + var itemsQueue: IdentifiedArrayOf = [] + + var isPresenting: Bool { + destination != nil + } + + @Presents + public var destination: Destination.State? + } + + @CasePathable + public enum Action: ViewAction, Sendable { + @CasePathable + public enum ViewAction { + case task + } + + enum InternalAction { + case scheduleItem(HUDMessage) + case showNextItemIfPossible + } + + case `internal`(InternalAction) + case view(ViewAction) + case destination(PresentationAction) + } + + public var body: some ReducerOf { + Reduce { state, action in + + switch action { + case .view(.task): + return .run { send in + for try await item in overlayWindowClient.getScheduledItems() { + guard !Task.isCancelled else { return } + await send(.internal(.scheduleItem(item))) + } + } + + case let .internal(.scheduleItem(hudMessage)): + state.itemsQueue.append(hudMessage) + return showItemIfPossible(state: &state) + case .internal(.showNextItemIfPossible): + return showItemIfPossible(state: &state) + + case .destination(.presented(.hud(.delegate(.dismiss)))): + return dismiss(&state) + + case .destination: + return .none + } + } + .ifLet(\.$destination, action: \.destination) + } + + private func showItemIfPossible(state: inout State) -> Effect { + guard !state.itemsQueue.isEmpty else { + return .none + } + + if state.isPresenting { + guard let presentedItem = state.itemsQueue.first else { + return .none + } + + // A HUD is force dismissed when next item comes in, AKA it is a lower priority. + state.destination = nil + state.itemsQueue.removeFirst() + return .run { send in + // Hacky - A very minor delay is needed before showing the next item is a HUD. + try await clock.sleep(for: .milliseconds(200)) + await send(.internal(.showNextItemIfPossible)) + } + } + + let nextItem = state.itemsQueue[0] + + state.destination = .hud(.init(content: nextItem)) + return .none + } + + private func dismiss(_ state: inout State) -> Effect { + state.destination = nil + state.itemsQueue.removeFirst() + return showItemIfPossible(state: &state) + } } extension OverlayFeature { - public typealias HostingFeature = Self - - @ViewAction(for: HostingFeature.self) - public struct View: SwiftUI.View { - @Bindable public var store: StoreOf - public init(store: StoreOf) { - self.store = store - } - public var body: some SwiftUI.View { - + public typealias HostingFeature = Self + + @ViewAction(for: HostingFeature.self) + public struct View: SwiftUI.View { + @Bindable public var store: StoreOf + public init(store: StoreOf) { + self.store = store + } + + public var body: some SwiftUI.View { Color.clear - .task { send(.task) } - .fullScreenCover( - item: $store.scope( - state: \.destination?.hud, - action: \.destination.hud - ) - ) { store in - HUDFeature.View(store: store) + .task { send(.task) } + .fullScreenCover( + item: $store.scope( + state: \.destination?.hud, + action: \.destination.hud + ) + ) { store in + HUDFeature.View(store: store) .background(TransparentBackground()) - } - } - } + } + } + } } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/OverlayWindowClient.swift b/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/OverlayWindowClient.swift index a7b43b0c5..4857fdd3f 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/OverlayWindowClient.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/OverlayWindowClient.swift @@ -1,39 +1,33 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-11. -// - -import Foundation -import SwiftUI -import Dependencies +import AsyncExtensions import ComposableArchitecture +import Dependencies +import Foundation import Sargon -import AsyncExtensions +import SwiftUI +// MARK: - OverlayWindowClient @DependencyClient public struct OverlayWindowClient: Sendable { - public typealias GetScheduledItems = @Sendable () -> AnyAsyncSequence - public typealias ScheduleHUDMessage = @Sendable (HUDMessage) -> Void + public typealias GetScheduledItems = @Sendable () -> AnyAsyncSequence + public typealias ScheduleHUDMessage = @Sendable (HUDMessage) -> Void - public var getScheduledItems: GetScheduledItems - - /// Schedule a HUD message to be shown in the Overlay Window. - /// Usually to be called from the Main Window. - public var scheduleHUDMessage: ScheduleHUDMessage + public var getScheduledItems: GetScheduledItems + /// Schedule a HUD message to be shown in the Overlay Window. + /// Usually to be called from the Main Window. + public var scheduleHUDMessage: ScheduleHUDMessage } +// MARK: DependencyKey extension OverlayWindowClient: DependencyKey { - public static let liveValue: Self = { + public static let liveValue: Self = { @Dependency(PasteboardClient.self) var pasteboardClient - let items = AsyncPassthroughSubject() - + let items = AsyncPassthroughSubject() + let scheduleHUDMessage: ScheduleHUDMessage = { message in items.send(message) } - + Task { for await event in await EventBus.shared.notifications() { scheduleHUDMessage( @@ -47,26 +41,25 @@ extension OverlayWindowClient: DependencyKey { ) } } - + Task { for try await _ in pasteboardClient.copyEvents() { scheduleHUDMessage( HUDMessage.success(text: "Copied") ) - } } - - return Self( - getScheduledItems: { items.eraseToAnyAsyncSequence() }, - scheduleHUDMessage: scheduleHUDMessage - ) - }() - - public static let testValue = OverlayWindowClient( - getScheduledItems: { AsyncLazySequence([]).eraseToAnyAsyncSequence() }, - scheduleHUDMessage: { _ in } - ) + + return Self( + getScheduledItems: { items.eraseToAnyAsyncSequence() }, + scheduleHUDMessage: scheduleHUDMessage + ) + }() + + public static let testValue = OverlayWindowClient( + getScheduledItems: { AsyncLazySequence([]).eraseToAnyAsyncSequence() }, + scheduleHUDMessage: { _ in } + ) } extension HUDMessage { diff --git a/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/SceneDelegate.swift b/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/SceneDelegate.swift index f63e57eff..7833fde26 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/SceneDelegate.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/OverlayWindow/SceneDelegate.swift @@ -1,43 +1,44 @@ import ComposableArchitecture import SwiftUI +// MARK: - SceneDelegate public final class SceneDelegate: NSObject, UIWindowSceneDelegate, ObservableObject { - public weak var windowScene: UIWindowScene? - public var overlayWindow: UIWindow? + public weak var windowScene: UIWindowScene? + public var overlayWindow: UIWindow? - public func scene( - _ scene: UIScene, - willConnectTo session: UISceneSession, - options connectionOptions: UIScene.ConnectionOptions - ) { - windowScene = scene as? UIWindowScene - if - let windowScene, - !_XCTIsTesting - { - overlayWindow(in: windowScene) - } - } + public func scene( + _ scene: UIScene, + willConnectTo session: UISceneSession, + options connectionOptions: UIScene.ConnectionOptions + ) { + windowScene = scene as? UIWindowScene + if + let windowScene, + !_XCTIsTesting + { + overlayWindow(in: windowScene) + } + } - func overlayWindow(in scene: UIWindowScene) { - let overlayView = OverlayFeature.View( - store: .init( - initialState: .init(), - reducer: OverlayFeature.init + func overlayWindow(in scene: UIWindowScene) { + let overlayView = OverlayFeature.View( + store: .init( + initialState: .init(), + reducer: OverlayFeature.init )) - let overlayWindow = UIWindow(windowScene: scene) - overlayWindow.rootViewController = UIHostingController(rootView: overlayView) - overlayWindow.rootViewController?.view.backgroundColor = .clear - overlayWindow.windowLevel = .normal + 1 - overlayWindow.isUserInteractionEnabled = false + let overlayWindow = UIWindow(windowScene: scene) + overlayWindow.rootViewController = UIHostingController(rootView: overlayView) + overlayWindow.rootViewController?.view.backgroundColor = .clear + overlayWindow.windowLevel = .normal + 1 + overlayWindow.isUserInteractionEnabled = false overlayWindow.backgroundColor = .clear overlayWindow.makeKeyAndVisible() - self.overlayWindow = overlayWindow - } + self.overlayWindow = overlayWindow + } } - +// MARK: - TransparentBackground struct TransparentBackground: UIViewRepresentable { func makeUIView(context: Context) -> UIView { let view = UIView() diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Settings/GatewaysFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Settings/GatewaysFeature.swift index dde21e77f..049d36fdb 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Settings/GatewaysFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Settings/GatewaysFeature.swift @@ -1,93 +1,96 @@ -import Sargon import ComposableArchitecture +import Sargon +// MARK: - GatewaysFeature @Reducer public struct GatewaysFeature { - - @Dependency(GatewaysClient.self) var gatewaysClient - - @ObservableState - public struct State: Equatable { - @SharedReader(.savedGateways) var savedGateways - } - - @CasePathable - public enum Action: ViewAction { - @CasePathable - public enum ViewAction { - case gatewayTapped(Gateway, isCurrent: Bool) - } - case view(ViewAction) - } - - public var body: some ReducerOf { - Reduce { state, action in - switch action { - case let .view(.gatewayTapped(gateway, isCurrent)): - if isCurrent { - log.debug("Tapped \(gateway), but not switching since it is already current.") - return .none - } else { - return .run { _ in - try await gatewaysClient.switchGatewayTo(gateway) - } - } - } - } - } + @Dependency(GatewaysClient.self) var gatewaysClient + + @ObservableState + public struct State: Equatable { + @SharedReader(.savedGateways) var savedGateways + } + + @CasePathable + public enum Action: ViewAction { + @CasePathable + public enum ViewAction { + case gatewayTapped(Gateway, isCurrent: Bool) + } + + case view(ViewAction) + } + + public var body: some ReducerOf { + Reduce { _, action in + switch action { + case let .view(.gatewayTapped(gateway, isCurrent)): + if isCurrent { + log.debug("Tapped \(gateway), but not switching since it is already current.") + return .none + } else { + return .run { _ in + try await gatewaysClient.switchGatewayTo(gateway) + } + } + } + } + } } + +// MARK: GatewaysFeature.View extension GatewaysFeature { - @ViewAction(for: GatewaysFeature.self) - public struct View: SwiftUI.View { - - @Bindable public var store: StoreOf - public var body: some SwiftUI.View { - VStack { - Text("Saved gateways").font(.title) - - ScrollView { - ForEach(store.state.savedGateways.all.sorted()) { gateway in - let isCurrent = gateway == store.state.savedGateways.current - VStack { - GatewayView(gateway: gateway, isCurrent: isCurrent) { - send(.gatewayTapped(gateway, isCurrent: isCurrent)) - } - .padding(.bottom, 10) - } - } - } - } - .padding([.leading, .trailing], 20) - } - } + @ViewAction(for: GatewaysFeature.self) + public struct View: SwiftUI.View { + @Bindable public var store: StoreOf + public var body: some SwiftUI.View { + VStack { + Text("Saved gateways").font(.title) + + ScrollView { + ForEach(store.state.savedGateways.all.sorted()) { gateway in + let isCurrent = gateway == store.state.savedGateways.current + VStack { + GatewayView(gateway: gateway, isCurrent: isCurrent) { + send(.gatewayTapped(gateway, isCurrent: isCurrent)) + } + .padding(.bottom, 10) + } + } + } + } + .padding([.leading, .trailing], 20) + } + } } +// MARK: - Gateway + Comparable extension Gateway: Comparable { - public static func < (lhs: Self, rhs: Self) -> Bool { - if lhs.networkID == .mainnet { return true } - if rhs.networkID == .mainnet { return false } - return lhs.networkID.rawValue < rhs.networkID.rawValue && lhs.url.absoluteString < rhs.url.absoluteString - } + public static func < (lhs: Self, rhs: Self) -> Bool { + if lhs.networkID == .mainnet { return true } + if rhs.networkID == .mainnet { return false } + return lhs.networkID.rawValue < rhs.networkID.rawValue && lhs.url.absoluteString < rhs.url.absoluteString + } } +// MARK: - GatewayView public struct GatewayView: SwiftUI.View { - public let gateway: Gateway - public let isCurrent: Bool - public let action: () -> Void - - public var body: some SwiftUI.View { - - Button.init(action: action, label: { - HStack { - Text(isCurrent ? "✅" : "☑️").font(.title) - VStack { - Text("\(gateway.network.displayDescription)").font(.body) - Text("\(gateway.networkID.toString())") - } - } - }) - .buttonStyle(.plain) - .frame(maxWidth: .infinity, alignment: .leading) - .cornerRadius(.small1) - } + public let gateway: Gateway + public let isCurrent: Bool + public let action: () -> Void + + public var body: some SwiftUI.View { + Button(action: action, label: { + HStack { + Text(isCurrent ? "✅" : "☑️").font(.title) + VStack { + Text("\(gateway.network.displayDescription)").font(.body) + Text("\(gateway.networkID.toString())") + } + } + }) + .buttonStyle(.plain) + .frame(maxWidth: .infinity, alignment: .leading) + .cornerRadius(.small1) + } } diff --git a/examples/iOS/Backend/Sources/Planbok/Features/Settings/SettingsFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/Settings/SettingsFeature.swift index 03cd81109..aec028cc5 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/Settings/SettingsFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/Settings/SettingsFeature.swift @@ -1,23 +1,17 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-05. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture import SwiftUI +// MARK: - SettingsFeature @Reducer public struct SettingsFeature { @Dependency(AccountsClient.self) var accountsClient - + @Reducer(state: .equatable) public enum Destination { case createManyAccountsAlert(AlertState) - + public enum CreateManyAccountsAlert: Int, CaseIterable { case create10 = 10 case create20 = 20 @@ -28,123 +22,117 @@ public struct SettingsFeature { case create1000 = 1000 } } - + @ObservableState public struct State: Equatable { @Presents var destination: Destination.State? } - + @CasePathable public enum Action: ViewAction { - @CasePathable public enum ViewAction { case createManyAccountsButtonTapped - case factorSourcesButtonTapped + case factorSourcesButtonTapped case shieldsButtonTapped case profileViewButtonTapped } - + case view(ViewAction) case destination(PresentationAction) - - - @CasePathable - public enum DelegateAction { - case navigate(Navigate) - - @CasePathable - public enum Navigate { - case toFactorSources + + @CasePathable + public enum DelegateAction { + case navigate(Navigate) + + @CasePathable + public enum Navigate { + case toFactorSources case toShields case toProfileView - } - } - - case delegate(DelegateAction) + } + } + + case delegate(DelegateAction) } - + public init() {} - + public var body: some ReducerOf { Reduce { state, action in switch action { - case .view(.profileViewButtonTapped): return .send(.delegate(.navigate(.toProfileView))) - + case .view(.createManyAccountsButtonTapped): state.destination = .createManyAccountsAlert(.init( title: TextState("How many?"), message: TextState("Will batch create many accounts and then perform one single save action."), buttons: [ - .cancel(TextState("Cancel")) + .cancel(TextState("Cancel")), ] + Destination.CreateManyAccountsAlert.allCases.map { action in - ButtonState.init(action: action, label: { + ButtonState(action: action, label: { TextState("Create \(action.rawValue)") }) } )) return .none - - case .view(.factorSourcesButtonTapped): - return .send(.delegate(.navigate(.toFactorSources))) - + + case .view(.factorSourcesButtonTapped): + return .send(.delegate(.navigate(.toFactorSources))) + case .view(.shieldsButtonTapped): return .send(.delegate(.navigate(.toShields))) - + case let .destination(.presented(.createManyAccountsAlert(action))): state.destination = nil let count = UInt16(action.rawValue) - return .run { send in + return .run { _ in try await accountsClient.batchCreateManySavedAccounts(count) } - + default: return .none - } } .ifLet(\.$destination, action: \.destination) } } +// MARK: SettingsFeature.View extension SettingsFeature { - @ViewAction(for: SettingsFeature.self) public struct View: SwiftUI.View { - @Bindable public var store: StoreOf - - public var body: some SwiftUI.View { + + public var body: some SwiftUI.View { VStack { Text("Settings").font(.largeTitle) - - Spacer() - - GatewaysFeature.View( + + Spacer() + + GatewaysFeature.View( store: Store( initialState: GatewaysFeature.State() ) { GatewaysFeature() } ) - - Spacer() - + + Spacer() + Button("Profile View (Debug)") { send(.profileViewButtonTapped) } - - - Button("Handle Factor Sources") { - send(.factorSourcesButtonTapped) - } - + + Button("Handle Factor Sources") { + send(.factorSourcesButtonTapped) + } + Button("Handle Security Shields") { send(.shieldsButtonTapped) } - + VStack { Button("Create Many Accounts") { send(.createManyAccountsButtonTapped) @@ -158,6 +146,4 @@ extension SettingsFeature { .alert($store.scope(state: \.destination?.createManyAccountsAlert, action: \.destination.createManyAccountsAlert)) } } - } - diff --git a/examples/iOS/Backend/Sources/Planbok/Features/SplashFeature.swift b/examples/iOS/Backend/Sources/Planbok/Features/SplashFeature.swift index 9e590ed77..dfb93328d 100644 --- a/examples/iOS/Backend/Sources/Planbok/Features/SplashFeature.swift +++ b/examples/iOS/Backend/Sources/Planbok/Features/SplashFeature.swift @@ -1,9 +1,8 @@ -@testable import Sargon import ComposableArchitecture +@testable import Sargon @Reducer public struct SplashFeature { - @Dependency(\.continuousClock) var clock @ObservableState public struct State { @@ -17,12 +16,13 @@ public struct SplashFeature { public enum DelegateAction: Sendable { case booted(hasAnyAccountOnAnyNetwork: Bool) } + public enum ViewAction: Sendable { case appear } + case delegate(DelegateAction) case view(ViewAction) - } @ViewAction(for: SplashFeature.self) @@ -31,9 +31,10 @@ public struct SplashFeature { public init(store: StoreOf) { self.store = store } + public var body: some SwiftUI.View { - Text("Swift Sargon") - .font(.largeTitle) + Text("Swift Sargon") + .font(.largeTitle) .ignoresSafeArea(edges: [.top, .bottom]) .onAppear { send(.appear) @@ -47,18 +48,17 @@ public struct SplashFeature { public var body: some ReducerOf { Reduce { state, - action in + action in switch action { - case .view(.appear): - struct SplashID: Hashable { } + struct SplashID: Hashable {} return .run { [isEmulatingFreshInstall = state.isEmulatingFreshInstall] send in - + let os = try await SargonOS._creatingShared( bootingWith: BIOS.shared, isEmulatingFreshInstall: isEmulatingFreshInstall ) - let hasAnyAccountOnAnyNetwork = (try? os.hasAnyAccountOnAnyNetwork()) ?? false + let hasAnyAccountOnAnyNetwork = (try? os.hasAnyAccountOnAnyNetwork()) ?? false await send( .delegate(.booted( hasAnyAccountOnAnyNetwork: hasAnyAccountOnAnyNetwork @@ -66,11 +66,10 @@ public struct SplashFeature { ) } .debounce(id: SplashID(), for: 0.8, scheduler: mainQueue) - + case .delegate: return .none } } } } - diff --git a/examples/iOS/Backend/Sources/Planbok/SargonExtensions/Sargon+Extensions.swift b/examples/iOS/Backend/Sources/Planbok/SargonExtensions/Sargon+Extensions.swift index 7c64b46b0..f9e452d39 100644 --- a/examples/iOS/Backend/Sources/Planbok/SargonExtensions/Sargon+Extensions.swift +++ b/examples/iOS/Backend/Sources/Planbok/SargonExtensions/Sargon+Extensions.swift @@ -1,17 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-26. -// - import Foundation import Sargon public typealias AccountsForDisplay = IdentifiedArrayOf extension IdentifiedArray where Element: Identifiable, Element.ID == ID { - public static var `default`: Self { IdentifiedArrayOf.init() } + public static var `default`: Self { IdentifiedArrayOf() } } extension NetworkID { @@ -19,9 +12,7 @@ extension NetworkID { } extension SargonOS { - public var accountsForDisplayOnCurrentNetworkIdentified: AccountsForDisplay { try! accountsForDisplayOnCurrentNetwork.asIdentified() } - } diff --git a/examples/iOS/Backend/Sources/Planbok/SharedState/SargonKey.swift b/examples/iOS/Backend/Sources/Planbok/SharedState/SargonKey.swift index dbf61ac8b..a1af8cb8e 100644 --- a/examples/iOS/Backend/Sources/Planbok/SharedState/SargonKey.swift +++ b/examples/iOS/Backend/Sources/Planbok/SharedState/SargonKey.swift @@ -1,10 +1,14 @@ -import Foundation import ComposableArchitecture +import Foundation import Sargon +// MARK: - PersistenceKeyDefault + @unchecked Sendable extension PersistenceKeyDefault: @unchecked Sendable where Base: Sendable {} + +// MARK: - KeyPath + @unchecked Sendable extension KeyPath: @unchecked Sendable where Root: Sendable, Value: Sendable {} +// MARK: - SargonKey /// A `PersistenceReaderKey` that listens to relevant event notifications emitted /// by the SargonOS to which `SargonKey` subscribes using an `EventBus` and /// based on `shouldFetch` we fetch the latest `Value` from the SargonOS @@ -27,155 +31,151 @@ extension KeyPath: @unchecked Sendable where Root: Sendable, Value: Sendable {} /// ) /// ``` public struct SargonKey: Hashable, PersistenceReaderKey, Sendable { - public typealias FetchValueFromSargonOS = @Sendable () -> Value? - public typealias ShouldFetch = @Sendable (EventKind) -> Bool - - /// A closure which we invoke if `shouldFetch` returns `true` for a received `EventNotification`, - /// which fetches a new value from SargonOS. The closure has already been translated from a `(SargonOS) -> Value?` - /// closure in the initializer of `SargonKey` into a `() -> Value?`. - private let fetchValueFromSargonOS: FetchValueFromSargonOS - - /// A predicate which returns `true` given an received `EventNotification` of a certain kind - /// (`EventKind`) if we should call `fetchValueFromSargonOS` else `false`, if the - /// event kind is not relevant for the `Value` of this `SargonKey`. E.g. the EventKind `.addedAccount`, - /// does not affect the current network, so a `SargonKey` should return `false` for - /// a received `EventNotification` of kind `.addedAccount`. - /// - /// However, we SHOULD not make our own decisions here on the Swift side if a certain event is - /// relevant or not, better to use the functions `affectsX` which we have wrapped as computed - /// properties on `EventKind`, e.g. `eventKind.affectsCurrentAccounts`. - private let shouldFetch: ShouldFetch - - /// Owned (retained) by SargonOS - private unowned let eventBus: EventBus - - public init( - sargonOS: SargonOS = .shared, - eventBus: EventBus = .shared, - fetchValueFromSargonOS: @escaping @Sendable (SargonOS) throws -> Value?, - shouldFetch: @escaping ShouldFetch - ) { - self.eventBus = eventBus - self.fetchValueFromSargonOS = { [weak sargonOS] in - guard let sargonOS else { - return nil - } - return try? fetchValueFromSargonOS(sargonOS) - } - self.shouldFetch = shouldFetch - } -} + public typealias FetchValueFromSargonOS = @Sendable () -> Value? + public typealias ShouldFetch = @Sendable (EventKind) -> Bool + + /// A closure which we invoke if `shouldFetch` returns `true` for a received `EventNotification`, + /// which fetches a new value from SargonOS. The closure has already been translated from a `(SargonOS) -> Value?` + /// closure in the initializer of `SargonKey` into a `() -> Value?`. + private let fetchValueFromSargonOS: FetchValueFromSargonOS + + /// A predicate which returns `true` given an received `EventNotification` of a certain kind + /// (`EventKind`) if we should call `fetchValueFromSargonOS` else `false`, if the + /// event kind is not relevant for the `Value` of this `SargonKey`. E.g. the EventKind `.addedAccount`, + /// does not affect the current network, so a `SargonKey` should return `false` for + /// a received `EventNotification` of kind `.addedAccount`. + /// + /// However, we SHOULD not make our own decisions here on the Swift side if a certain event is + /// relevant or not, better to use the functions `affectsX` which we have wrapped as computed + /// properties on `EventKind`, e.g. `eventKind.affectsCurrentAccounts`. + private let shouldFetch: ShouldFetch + /// Owned (retained) by SargonOS + private unowned let eventBus: EventBus + + public init( + sargonOS: SargonOS = .shared, + eventBus: EventBus = .shared, + fetchValueFromSargonOS: @escaping @Sendable (SargonOS) throws -> Value?, + shouldFetch: @escaping ShouldFetch + ) { + self.eventBus = eventBus + self.fetchValueFromSargonOS = { [weak sargonOS] in + guard let sargonOS else { + return nil + } + return try? fetchValueFromSargonOS(sargonOS) + } + self.shouldFetch = shouldFetch + } +} extension SargonKey { - - /// Create a new `SargonKey` with `KeyPath` based API, instead of closure based. - /// - /// This allows use to write: - /// - /// ``` - /// SargonKey( - /// accessing: \.accountsForDisplayOnCurrentNetworkIdentified, - /// fetchIf: \.affectsCurrentAccounts - /// ) - /// ``` - /// - /// Instead of more verbose: - /// - /// ``` - /// SargonKey( - /// fetchValueFromSargonOS: { os in os[keyPath: \.accountsForDisplayOnCurrentNetworkIdentified] }, - /// shouldFetch: { eventKind in eventKind[keyPath: \.affectsCurrentAccounts] } - /// ) - /// ``` - public init( - accessing lastValueWithOSKeyPath: KeyPath, - fetchIf fetchIfKeyPath: KeyPath - ) { - self.init( - fetchValueFromSargonOS: { $0[keyPath: lastValueWithOSKeyPath] }, - shouldFetch: { $0[keyPath: fetchIfKeyPath] } - ) - } - - public init( - mapping fetchValueFromSargonOS: @escaping @Sendable (SargonOS) throws -> Value?, - fetchIf fetchIfKeyPath: KeyPath - ) { - self.init( - fetchValueFromSargonOS: fetchValueFromSargonOS, - shouldFetch: { $0[keyPath: fetchIfKeyPath] } - ) - } + /// Create a new `SargonKey` with `KeyPath` based API, instead of closure based. + /// + /// This allows use to write: + /// + /// ``` + /// SargonKey( + /// accessing: \.accountsForDisplayOnCurrentNetworkIdentified, + /// fetchIf: \.affectsCurrentAccounts + /// ) + /// ``` + /// + /// Instead of more verbose: + /// + /// ``` + /// SargonKey( + /// fetchValueFromSargonOS: { os in os[keyPath: \.accountsForDisplayOnCurrentNetworkIdentified] }, + /// shouldFetch: { eventKind in eventKind[keyPath: \.affectsCurrentAccounts] } + /// ) + /// ``` + public init( + accessing lastValueWithOSKeyPath: KeyPath, + fetchIf fetchIfKeyPath: KeyPath + ) { + self.init( + fetchValueFromSargonOS: { $0[keyPath: lastValueWithOSKeyPath] }, + shouldFetch: { $0[keyPath: fetchIfKeyPath] } + ) + } + + public init( + mapping fetchValueFromSargonOS: @escaping @Sendable (SargonOS) throws -> Value?, + fetchIf fetchIfKeyPath: KeyPath + ) { + self.init( + fetchValueFromSargonOS: fetchValueFromSargonOS, + shouldFetch: { $0[keyPath: fetchIfKeyPath] } + ) + } } // MARK: PersistenceReaderKey extension SargonKey { - - /// Loads the freshest value from storage (SargonOS). Returns `nil` if there is no value in storage. - /// - /// - Parameter initialValue: An initial value assigned to the `@Shared` property. - /// - Returns: An initial value provided by an external system, or `nil`. - public func load(initialValue: Value?) -> Value? { - fetchValueFromSargonOS() ?? initialValue - } - - - /// Subscribes to external updates, we do it by subscribing to `EventBus.notifications()`. - /// - /// - Parameters: - /// - initialValue: An initial value assigned to the `@Shared` property. - /// - didSet: A closure that is invoked with new values from an external system, or `nil` if the - /// external system no longer holds a value. - /// - Returns: A subscription to updates from an external system. If it is cancelled or - /// deinitialized, the `didSet` closure will no longer be invoked. - public func subscribe( - initialValue: Value?, - didSet: @Sendable @escaping (_ newValue: Value?) -> Void - ) -> Shared.Subscription { - let task = Task { [shouldFetch = self.shouldFetch] in - for await _ in await eventBus.notifications().map(\.event.kind).filter({ - shouldFetch($0) - }) { - guard !Task.isCancelled else { return } - - // The call `fetchValueFromSargonOS` might be costly - // we SHOULD try to use as fast and cheap calls as possible - // i.e. it is best to call `os.currentNetwork()` which is near instant - // compared to `os.profile().gateways.current.network.id` which is - // costly, since the whole of Profile has to pass across the UniFFI - // boundary - let newValue = fetchValueFromSargonOS() - - didSet(newValue) - } - } - return .init { - task.cancel() - } - } + /// Loads the freshest value from storage (SargonOS). Returns `nil` if there is no value in storage. + /// + /// - Parameter initialValue: An initial value assigned to the `@Shared` property. + /// - Returns: An initial value provided by an external system, or `nil`. + public func load(initialValue: Value?) -> Value? { + fetchValueFromSargonOS() ?? initialValue + } + + /// Subscribes to external updates, we do it by subscribing to `EventBus.notifications()`. + /// + /// - Parameters: + /// - initialValue: An initial value assigned to the `@Shared` property. + /// - didSet: A closure that is invoked with new values from an external system, or `nil` if the + /// external system no longer holds a value. + /// - Returns: A subscription to updates from an external system. If it is cancelled or + /// deinitialized, the `didSet` closure will no longer be invoked. + public func subscribe( + initialValue: Value?, + didSet: @Sendable @escaping (_ newValue: Value?) -> Void + ) -> Shared.Subscription { + let task = Task { [shouldFetch = self.shouldFetch] in + for await _ in await eventBus.notifications().map(\.event.kind).filter({ + shouldFetch($0) + }) { + guard !Task.isCancelled else { return } + + // The call `fetchValueFromSargonOS` might be costly + // we SHOULD try to use as fast and cheap calls as possible + // i.e. it is best to call `os.currentNetwork()` which is near instant + // compared to `os.profile().gateways.current.network.id` which is + // costly, since the whole of Profile has to pass across the UniFFI + // boundary + let newValue = fetchValueFromSargonOS() + + didSet(newValue) + } + } + return .init { + task.cancel() + } + } } extension SargonKey { - /// A String representation of `Self.Value`, used for `Equatable` and `Hashable` - /// conformance. - private var valueKind: String { - String(describing: Value.self) - } + /// A String representation of `Self.Value`, used for `Equatable` and `Hashable` + /// conformance. + private var valueKind: String { + String(describing: Value.self) + } } // MARK: Equatable extension SargonKey { - public static func == (lhs: SargonKey, rhs: SargonKey) -> Bool { - lhs.valueKind == rhs.valueKind && /* this aint pretty, but I guess it works */ EventKind.allCases.map(lhs.shouldFetch) == EventKind.allCases.map(rhs.shouldFetch) - } + public static func == (lhs: SargonKey, rhs: SargonKey) -> Bool { + lhs.valueKind == rhs.valueKind && /* this aint pretty, but I guess it works */ EventKind.allCases.map(lhs.shouldFetch) == EventKind.allCases.map(rhs.shouldFetch) + } } // MARK: Hashable extension SargonKey { - public func hash(into hasher: inout Hasher) { - hasher.combine(valueKind) - /* this aint pretty, but I guess it works */ - hasher.combine(EventKind.allCases.map(shouldFetch)) - } + public func hash(into hasher: inout Hasher) { + hasher.combine(valueKind) + /* this aint pretty, but I guess it works */ + hasher.combine(EventKind.allCases.map(shouldFetch)) + } } diff --git a/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+Accounts.swift b/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+Accounts.swift index dbd06dcc3..29b709c5b 100644 --- a/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+Accounts.swift +++ b/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+Accounts.swift @@ -1,17 +1,10 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-26. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture extension PersistenceReaderKey where Self == PersistenceKeyDefault> { public static var accountsForDisplay: Self { - Self.sharedAccountsForDisplay + sharedAccountsForDisplay } } diff --git a/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+FactorSources.swift b/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+FactorSources.swift index 1e6fab8f7..b30c84128 100644 --- a/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+FactorSources.swift +++ b/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+FactorSources.swift @@ -1,30 +1,27 @@ +import ComposableArchitecture import Foundation +import IdentifiedCollections import Sargon import SargonUniFFI -import ComposableArchitecture -import IdentifiedCollections public typealias FactorSources = IdentifiedArrayOf public typealias Shield = SecurityStructureOfFactorSources public typealias Shields = IdentifiedArrayOf - - public typealias ShieldReference = SecurityStructureOfFactorSourceIDs public typealias ShieldReferences = IdentifiedArrayOf - extension FactorSources { public func compactMap(as kind: F.Type = F.self) -> IdentifiedArrayOf where F: FactorSourceProtocol { - self.elements.compactMap({ $0.extract(F.self) }).asIdentified() + self.elements.compactMap { $0.extract(F.self) }.asIdentified() } + public func filter(kind: FactorSourceKind) -> Self { - self.elements.filter({ $0.kind == kind }).asIdentified() + self.elements.filter { $0.kind == kind }.asIdentified() } } - public typealias DeviceFactorSources = IdentifiedArrayOf public typealias LedgerHWWalletFactorSources = IdentifiedArrayOf public typealias ArculusCardFactorSources = IdentifiedArrayOf @@ -32,26 +29,27 @@ public typealias OffDeviceMnemonicFactorSources = IdentifiedArrayOf extension PersistenceReaderKey where Self == PersistenceKeyDefault> { - public static var factorSources: Self { - Self.sharedFactorSources - } + public static var factorSources: Self { + sharedFactorSources + } } extension PersistenceKeyDefault> { - public static let sharedFactorSources = Self( - SargonKey( - accessing: \.factorSources, - fetchIf: \.affectsFactorSources - ), + public static let sharedFactorSources = Self( + SargonKey( + accessing: \.factorSources, + fetchIf: \.affectsFactorSources + ), [] - ) + ) } extension PersistenceReaderKey where Self == PersistenceKeyDefault> { public static var shields: Self { - Self.sharedShields + sharedShields } } + extension PersistenceKeyDefault> { public static let sharedShields = Self( SargonKey( @@ -63,46 +61,44 @@ extension PersistenceKeyDefault> { } extension SargonOS { - - public var factorSources: FactorSources { - try! factorSources().asIdentified() - } - + public var factorSources: FactorSources { + try! factorSources().asIdentified() + } + public var shieldReferences: ShieldReferences { - try! securityStructuresOfFactorSourceIds().asIdentified() + try! securityStructuresOfFactorSourceIds().asIdentified() } - + public var shields: Shields { - shieldReferences.compactMap({ try? self.securityStructureOfFactorSourcesFromSecurityStructureOfFactorSourceIds(structureOfIds: $0) }).asIdentified() + shieldReferences.compactMap { try? self.securityStructureOfFactorSourcesFromSecurityStructureOfFactorSourceIds(structureOfIds: $0) }.asIdentified() } - + public var deviceFactorSources: DeviceFactorSources { - factorSources.compactMap({ $0.extract(DeviceFactorSource.self)}).asIdentified() + factorSources.compactMap { $0.extract(DeviceFactorSource.self) }.asIdentified() } - + public var ledgerFactorSources: LedgerHWWalletFactorSources { - factorSources.compactMap({ $0.extract(LedgerHardwareWalletFactorSource.self)}).asIdentified() + factorSources.compactMap { $0.extract(LedgerHardwareWalletFactorSource.self) }.asIdentified() } - + public var arculusCardFactorSources: ArculusCardFactorSources { - factorSources.compactMap({ $0.extract(ArculusCardFactorSource.self)}).asIdentified() + factorSources.compactMap { $0.extract(ArculusCardFactorSource.self) }.asIdentified() } - + public var offDeviceMnemonicFactorSources: OffDeviceMnemonicFactorSources { - factorSources.compactMap({ $0.extract(OffDeviceMnemonicFactorSource.self)}).asIdentified() + factorSources.compactMap { $0.extract(OffDeviceMnemonicFactorSource.self) }.asIdentified() } - + public var securityQuestionsFactorSources: SecurityQuestionsFactorSources { - factorSources.compactMap({ $0.extract(SecurityQuestionsNotProductionReadyFactorSource.self)}).asIdentified() + factorSources.compactMap { $0.extract(SecurityQuestionsNotProductionReadyFactorSource.self) }.asIdentified() } } extension EventKind { - - public var affectsFactorSources: Bool { - eventKindAffectsFactorSources(eventKind: self) - } - + public var affectsFactorSources: Bool { + eventKindAffectsFactorSources(eventKind: self) + } + public var affectsShields: Bool { eventKindAffectsSecurityStructures(eventKind: self) } diff --git a/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+NetworkID.swift b/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+NetworkID.swift index 08843e154..9e54330a9 100644 --- a/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+NetworkID.swift +++ b/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+NetworkID.swift @@ -1,21 +1,20 @@ -import Sargon +import ComposableArchitecture import Dependencies import Foundation -import ComposableArchitecture +import Sargon extension PersistenceReaderKey where Self == PersistenceKeyDefault> { public static var network: Self { - Self.sharedNetwork + sharedNetwork } } extension PersistenceKeyDefault> { public static let sharedNetwork = Self( SargonKey( - mapping: { try $0.currentNetworkID }, + mapping: { try $0.currentNetworkID }, fetchIf: \.affectsCurrentNetwork ), .default ) } - diff --git a/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+SavedGateways.swift b/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+SavedGateways.swift index 63a99f13c..e03cf081d 100644 --- a/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+SavedGateways.swift +++ b/examples/iOS/Backend/Sources/Planbok/SharedState/SharedState+SavedGateways.swift @@ -1,27 +1,19 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-05-26. -// - +import ComposableArchitecture import Foundation import Sargon -import ComposableArchitecture extension PersistenceReaderKey where Self == PersistenceKeyDefault> { public static var savedGateways: Self { - Self.sharedSavedGateways + sharedSavedGateways } } extension PersistenceKeyDefault> { public static let sharedSavedGateways = Self( SargonKey( - mapping: { try $0.gateways }, + mapping: { try $0.gateways }, fetchIf: \.affectsSavedGateways ), - .default + .default ) - } diff --git a/examples/iOS/Backend/Sources/Planbok/View/DesignSystem/Color.swift b/examples/iOS/Backend/Sources/Planbok/View/DesignSystem/Color.swift index 7a29a8c57..9a19ad020 100644 --- a/examples/iOS/Backend/Sources/Planbok/View/DesignSystem/Color.swift +++ b/examples/iOS/Backend/Sources/Planbok/View/DesignSystem/Color.swift @@ -1,6 +1,5 @@ import SwiftUI - #if os(iOS) typealias PlatformSpecificColor = UIColor extension UIColor { @@ -227,8 +226,4 @@ extension Color { opacity: opacity ) } - - - } - diff --git a/examples/iOS/Backend/Sources/Planbok/View/DesignSystem/Constants.swift b/examples/iOS/Backend/Sources/Planbok/View/DesignSystem/Constants.swift index 76d85fadc..096540fd9 100644 --- a/examples/iOS/Backend/Sources/Planbok/View/DesignSystem/Constants.swift +++ b/examples/iOS/Backend/Sources/Planbok/View/DesignSystem/Constants.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-02-16. -// - import Foundation public typealias Grid = CGFloat diff --git a/examples/iOS/Backend/Sources/Planbok/View/DesignSystem/Gradient.swift b/examples/iOS/Backend/Sources/Planbok/View/DesignSystem/Gradient.swift index 5d4249a64..d60ad177e 100644 --- a/examples/iOS/Backend/Sources/Planbok/View/DesignSystem/Gradient.swift +++ b/examples/iOS/Backend/Sources/Planbok/View/DesignSystem/Gradient.swift @@ -4,7 +4,6 @@ extension AppearanceID { } } - extension LinearGradient { public init(appearanceID: AppearanceID) { self.init( @@ -15,9 +14,6 @@ extension LinearGradient { } } - - - extension LinearGradient { /// Namespace only public struct App { fileprivate init() {} } diff --git a/examples/iOS/Backend/Sources/Planbok/View/LabelStyleFlip.swift b/examples/iOS/Backend/Sources/Planbok/View/LabelStyleFlip.swift index 6614dfc0a..f512cc9f7 100644 --- a/examples/iOS/Backend/Sources/Planbok/View/LabelStyleFlip.swift +++ b/examples/iOS/Backend/Sources/Planbok/View/LabelStyleFlip.swift @@ -1,13 +1,6 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-07. -// - import Foundation - +// MARK: - LabelStyleFlip public struct LabelStyleFlip: LabelStyle { let imageColor: Color public func makeBody(configuration: Configuration) -> some View { @@ -17,6 +10,7 @@ public struct LabelStyleFlip: LabelStyle { } } } + extension LabelStyle where Self == LabelStyleFlip { public static func flipped(imageColor: Color = .gray) -> Self { LabelStyleFlip(imageColor: imageColor) } } diff --git a/examples/iOS/Backend/Sources/Planbok/View/Views/AccountView.swift b/examples/iOS/Backend/Sources/Planbok/View/Views/AccountView.swift index 538092e84..ad8fe1916 100644 --- a/examples/iOS/Backend/Sources/Planbok/View/Views/AccountView.swift +++ b/examples/iOS/Backend/Sources/Planbok/View/Views/AccountView.swift @@ -1,13 +1,13 @@ -import Sargon import ComposableArchitecture +import Sargon +// MARK: - AccountCardView public struct AccountCardView: SwiftUI.View { public let accountForDisplay: AccountForDisplay public let action: () -> Void - + public var body: some SwiftUI.View { - - Button.init(action: action, label: { + Button(action: action, label: { AccountView(accountForDisplay: accountForDisplay) }) .buttonStyle(.plain) @@ -15,30 +15,28 @@ public struct AccountCardView: SwiftUI.View { } } +// MARK: - AccountView public struct AccountView: SwiftUI.View { public let accountForDisplay: AccountForDisplay public let format: AddressFormat - + init(accountForDisplay: AccountForDisplay, format: AddressFormat = .default) { self.accountForDisplay = accountForDisplay self.format = format } - + public var body: some SwiftUI.View { - - VStack(alignment: .leading, spacing: .zero) { - Text(accountForDisplay.displayName.value) - .lineLimit(1) - .foregroundColor(.white) - .frame(maxWidth: .infinity, alignment: .leading) - - AddressView(accountForDisplay.address, format: format) - .foregroundColor(.app.whiteTransparent) - } - .padding(.horizontal, .medium1) - .padding(.vertical, .medium2) - .background(accountForDisplay.appearanceId.gradient) - - + VStack(alignment: .leading, spacing: .zero) { + Text(accountForDisplay.displayName.value) + .lineLimit(1) + .foregroundColor(.white) + .frame(maxWidth: .infinity, alignment: .leading) + + AddressView(accountForDisplay.address, format: format) + .foregroundColor(.app.whiteTransparent) + } + .padding(.horizontal, .medium1) + .padding(.vertical, .medium2) + .background(accountForDisplay.appearanceId.gradient) } } diff --git a/examples/iOS/Backend/Sources/Planbok/View/Views/AddressView.swift b/examples/iOS/Backend/Sources/Planbok/View/Views/AddressView.swift index e3fccbcb4..7ddf4fea5 100644 --- a/examples/iOS/Backend/Sources/Planbok/View/Views/AddressView.swift +++ b/examples/iOS/Backend/Sources/Planbok/View/Views/AddressView.swift @@ -1,5 +1,5 @@ -import SargonUniFFI import Sargon +import SargonUniFFI // MARK: - AddressView public struct AddressView: SwiftUI.View { @@ -17,5 +17,4 @@ public struct AddressView: SwiftUI.View { .multilineTextAlignment(.leading) .minimumScaleFactor(0.5) } - } diff --git a/examples/iOS/Backend/Sources/Planbok/View/Views/FactorSourceCardView.swift b/examples/iOS/Backend/Sources/Planbok/View/Views/FactorSourceCardView.swift index 1db1bdd26..65e516e2c 100644 --- a/examples/iOS/Backend/Sources/Planbok/View/Views/FactorSourceCardView.swift +++ b/examples/iOS/Backend/Sources/Planbok/View/Views/FactorSourceCardView.swift @@ -1,29 +1,21 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-01. -// - import Foundation import SwiftUI public struct FactorSourceCardView: SwiftUI.View { - public let factorSource: FactorSource public let action: @Sendable () -> Void - public init( - factorSource: FactorSource, - action: @escaping @Sendable () -> Void = {} - ) { + public init( + factorSource: FactorSource, + action: @escaping @Sendable () -> Void = {} + ) { self.factorSource = factorSource self.action = action } - public var body: some SwiftUI.View { + public var body: some SwiftUI.View { VStack(alignment: .leading) { - Labeled("Kind", factorSource.kind) + Labeled("Kind", factorSource.kind) Labeled("ID", "...\(factorSource.id.description.suffix(6))") Labeled("Added", factorSource.addedOn.formatted(.dateTime)) Labeled("Last Used", factorSource.lastUsedOn.formatted(.dateTime)) @@ -36,4 +28,3 @@ public struct FactorSourceCardView: SwiftUI.View { .padding() } } - diff --git a/examples/iOS/Backend/Sources/Planbok/View/Views/FactorSourceHintView.swift b/examples/iOS/Backend/Sources/Planbok/View/Views/FactorSourceHintView.swift index 3241e4119..5298743e1 100644 --- a/examples/iOS/Backend/Sources/Planbok/View/Views/FactorSourceHintView.swift +++ b/examples/iOS/Backend/Sources/Planbok/View/Views/FactorSourceHintView.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-01. -// - import Foundation import Sargon import SwiftUI @@ -45,6 +38,7 @@ extension TrustedContactFactorSourceContact { .frame(maxWidth: .infinity) } } + extension SecurityQuestionsSealedNotProductionReadyMnemonic { public func display( action: (() -> Void)? @@ -59,6 +53,7 @@ extension SecurityQuestionsSealedNotProductionReadyMnemonic { .frame(maxWidth: .infinity) } } + extension OffDeviceMnemonicHint { public func display( action: (() -> Void)? = nil @@ -73,6 +68,7 @@ extension OffDeviceMnemonicHint { .frame(maxWidth: .infinity) } } + extension ArculusCardHint { public func display() -> some SwiftUI.View { VStack(alignment: .leading) { @@ -83,6 +79,7 @@ extension ArculusCardHint { .frame(maxWidth: .infinity) } } + extension DeviceFactorSourceHint { public func display() -> some SwiftUI.View { VStack(alignment: .leading) { diff --git a/examples/iOS/Backend/Sources/Planbok/View/Views/Labeled.swift b/examples/iOS/Backend/Sources/Planbok/View/Views/Labeled.swift index 4983ac70e..194c519e3 100644 --- a/examples/iOS/Backend/Sources/Planbok/View/Views/Labeled.swift +++ b/examples/iOS/Backend/Sources/Planbok/View/Views/Labeled.swift @@ -1,60 +1,53 @@ -// -// File.swift -// -// -// Created by Alexander Cyon on 2024-06-01. -// - import Foundation import SwiftUI public struct Labeled: SwiftUI.View { public let title: String public let value: String - public let axis: Axis - - public init( - _ title: String, - _ value: V, - axis: Axis = .horizontal - ) where V: CustomStringConvertible { - self.axis = axis - self.title = title + public let axis: Axis + + public init( + _ title: String, + _ value: some CustomStringConvertible, + axis: Axis = .horizontal + ) { + self.axis = axis + self.title = title self.value = value.description } - - public var textTitle: some SwiftUI.View { - Text("**\(title)**") - } - public var textValue: some SwiftUI.View { - Text("`\(value)`") - } - public var body: some SwiftUI.View { - Group { - if axis == .horizontal { - HStack { - textTitle - textValue - Spacer() - } - } else { - VStack(alignment: .leading) { - HStack { - textTitle - Spacer() - } - .frame(maxWidth: .infinity) - HStack { - textValue - Spacer() - } - .frame(maxWidth: .infinity) - } - } - } - .multilineTextAlignment(.leading) - .padding(.horizontal, 10) - } - + public var textTitle: some SwiftUI.View { + Text("**\(title)**") + } + + public var textValue: some SwiftUI.View { + Text("`\(value)`") + } + + public var body: some SwiftUI.View { + Group { + if axis == .horizontal { + HStack { + textTitle + textValue + Spacer() + } + } else { + VStack(alignment: .leading) { + HStack { + textTitle + Spacer() + } + .frame(maxWidth: .infinity) + HStack { + textValue + Spacer() + } + .frame(maxWidth: .infinity) + } + } + } + .multilineTextAlignment(.leading) + .padding(.horizontal, 10) + } } diff --git a/examples/iOS/Backend/Sources/Planbok/View/Views/LabeledTextField.swift b/examples/iOS/Backend/Sources/Planbok/View/Views/LabeledTextField.swift index 127c36a66..d7a425091 100644 --- a/examples/iOS/Backend/Sources/Planbok/View/Views/LabeledTextField.swift +++ b/examples/iOS/Backend/Sources/Planbok/View/Views/LabeledTextField.swift @@ -1,12 +1,11 @@ - +// MARK: - LabeledTextField public struct LabeledTextField: SwiftUI.View { - public let label: LocalizedStringKey public let placeholder: LocalizedStringKey @Binding public var text: String public let hint: LocalizedStringKey? public let trailingView: Trailing - + init( label: LocalizedStringKey, text: Binding, @@ -21,6 +20,7 @@ public struct LabeledTextField: SwiftUI.View { self.trailingView = trailingView() } } + extension LabeledTextField where Trailing == EmptyView { public init( label: LocalizedStringKey, @@ -37,7 +37,7 @@ extension LabeledTextField { VStack(alignment: .leading) { Text(label) .padding(.leading, 5) - + HStack { TextField(placeholder, text: $text) .autocorrectionDisabled() @@ -46,7 +46,7 @@ extension LabeledTextField { trailingView } - + Text(hint ?? "") .font(.footnote) .padding(.leading, 5) diff --git a/examples/iOS/Backend/Tests/PlanbokTests/PlanbokTests.swift b/examples/iOS/Backend/Tests/PlanbokTests/PlanbokTests.swift index a15c72cd4..6ad1c07b9 100644 --- a/examples/iOS/Backend/Tests/PlanbokTests/PlanbokTests.swift +++ b/examples/iOS/Backend/Tests/PlanbokTests/PlanbokTests.swift @@ -1,23 +1,22 @@ -import XCTest @testable import Planbok @testable import Sargon +import XCTest +// MARK: - TestCase class TestCase: XCTestCase { - override func setUp() async throws { try await super.setUp() let _ = try await SargonOS._creatingShared(bootingWith: BIOS.insecure(), isEmulatingFreshInstall: true) } } +// MARK: - PlanbokTests final class PlanbokTests: TestCase { - - func test_shared_reader_network_is_on_mainnet_for_new_profile() { @SharedReader(.network) var network XCTAssertEqual(network, .mainnet) } - + func test_shared_reader_network_updates_when_gateway_switches() async throws { let os = try await SargonOS._creatingShared( bootingWith: BIOS.insecure(), @@ -28,7 +27,7 @@ final class PlanbokTests: TestCase { await Task.megaYield() XCTAssertEqual(network, .stokenet) } - + func test_shared_reader_accounts_switches_updates_when_gateway_switches() async throws { let os = try await SargonOS._creatingShared( bootingWith: BIOS.insecure(), diff --git a/examples/iOS/Frontend/PlanbokApp/PlanbokApp.swift b/examples/iOS/Frontend/PlanbokApp/PlanbokApp.swift index ecc868aa6..5a7b0d3a9 100644 --- a/examples/iOS/Frontend/PlanbokApp/PlanbokApp.swift +++ b/examples/iOS/Frontend/PlanbokApp/PlanbokApp.swift @@ -1,17 +1,10 @@ -// -// PlanbokApp.swift -// Planbok -// -// Created by Alexander Cyon on 2024-02-14. -// - -import SwiftUI -import Planbok import ComposableArchitecture +import Planbok +import SwiftUI @main struct PlanbokApp: App { - @UIApplicationDelegateAdaptor var delegate: AppDelegate + @UIApplicationDelegateAdaptor var delegate: AppDelegate var body: some Scene { WindowGroup { @@ -26,5 +19,5 @@ struct PlanbokApp: App { .buttonStyle(.borderedProminent) .environment(\.colorScheme, .light) } - } + } } diff --git a/jvm/Package.swift b/jvm/Package.swift index 9a7fcd3ba..b282883d2 100644 --- a/jvm/Package.swift +++ b/jvm/Package.swift @@ -10,4 +10,4 @@ // And: https://github.com/tuist/tuist/pull/2058 import PackageDescription -let package = Package() \ No newline at end of file +let package = Package() diff --git a/scripts/Package.swift b/scripts/Package.swift index 9a7fcd3ba..b282883d2 100644 --- a/scripts/Package.swift +++ b/scripts/Package.swift @@ -10,4 +10,4 @@ // And: https://github.com/tuist/tuist/pull/2058 import PackageDescription -let package = Package() \ No newline at end of file +let package = Package()