diff --git a/Package.resolved b/Package.resolved index 5a36027..c99dfff 100644 --- a/Package.resolved +++ b/Package.resolved @@ -15,8 +15,8 @@ "repositoryURL": "https://github.com/tkey/curvelib.swift", "state": { "branch": null, - "revision": "9f88bd5e56d1df443a908f7a7e81ae4f4d9170ea", - "version": "1.0.1" + "revision": "432bf1abe7ff505fc2ac9fcf697341ff5b2dc6d0", + "version": "2.0.0" } }, { @@ -33,8 +33,8 @@ "repositoryURL": "https://github.com/Web3Auth/session-manager-swift.git", "state": { "branch": null, - "revision": "20cc7bff065d7fe53164d17e7714a3f17d4cea2a", - "version": "4.0.2" + "revision": "d86cd2a7f6d8095531ed609c728d851820fe85be", + "version": "6.0.1" } } ] diff --git a/Package.swift b/Package.swift index 1c29ee3..984e192 100644 --- a/Package.swift +++ b/Package.swift @@ -14,8 +14,8 @@ let package = Package( ], dependencies: [ .package(name: "KeychainSwift", url: "https://github.com/evgenyneu/keychain-swift.git", from: "20.0.0"), - .package(name:"SessionManager",url: "https://github.com/Web3Auth/session-manager-swift.git",from: "5.0.0"), - .package(name: "curvelib.swift", url: "https://github.com/tkey/curvelib.swift", from: "1.0.1"), + .package(name:"SessionManager",url: "https://github.com/Web3Auth/session-manager-swift.git",from: "6.0.1"), + .package(name: "curvelib.swift", url: "https://github.com/tkey/curvelib.swift", from: "2.0.0"), .package(url: "https://github.com/attaswift/BigInt.git", from: "5.3.0"), ], targets: [ diff --git a/Sources/Web3Auth/AnyEncodable.swift b/Sources/Web3Auth/AnyEncodable.swift deleted file mode 100644 index bbbff7a..0000000 --- a/Sources/Web3Auth/AnyEncodable.swift +++ /dev/null @@ -1,293 +0,0 @@ -#if canImport(Foundation) - import Foundation -#endif - -// Taken from https://github.com/Flight-School/AnyCodable - -/** - A type-erased `Encodable` value. - - The `AnyEncodable` type forwards encoding responsibilities - to an underlying value, hiding its specific underlying type. - - You can encode mixed-type values in dictionaries - and other collections that require `Encodable` conformance - by declaring their contained type to be `AnyEncodable`: - - let dictionary: [String: AnyEncodable] = [ - "boolean": true, - "integer": 42, - "double": 3.141592653589793, - "string": "string", - "array": [1, 2, 3], - "nested": [ - "a": "alpha", - "b": "bravo", - "c": "charlie" - ], - "null": nil - ] - - let encoder = JSONEncoder() - let json = try! encoder.encode(dictionary) - */ -@frozen public struct AnyEncodable: Encodable { - public let value: Any - - public init(_ value: T?) { - self.value = value ?? () - } -} - -@usableFromInline -protocol _AnyEncodable { - var value: Any { get } - init(_ value: T?) -} - -extension AnyEncodable: _AnyEncodable {} - -// MARK: - Encodable - -extension _AnyEncodable { - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch value { - #if canImport(Foundation) - case let number as NSNumber: - try encode(nsnumber: number, into: &container) - case is NSNull: - try container.encodeNil() - #endif - case is Void: - try container.encodeNil() - case let bool as Bool: - try container.encode(bool) - case let int as Int: - try container.encode(int) - case let int8 as Int8: - try container.encode(int8) - case let int16 as Int16: - try container.encode(int16) - case let int32 as Int32: - try container.encode(int32) - case let int64 as Int64: - try container.encode(int64) - case let uint as UInt: - try container.encode(uint) - case let uint8 as UInt8: - try container.encode(uint8) - case let uint16 as UInt16: - try container.encode(uint16) - case let uint32 as UInt32: - try container.encode(uint32) - case let uint64 as UInt64: - try container.encode(uint64) - case let float as Float: - try container.encode(float) - case let double as Double: - try container.encode(double) - case let string as String: - try container.encode(string) - #if canImport(Foundation) - case let date as Date: - try container.encode(date) - case let url as URL: - try container.encode(url) - #endif - case let array as [Any?]: - try container.encode(array.map { AnyEncodable($0) }) - case let dictionary as [String: Any?]: - try container.encode(dictionary.mapValues { AnyEncodable($0) }) - case let encodable as Encodable: - try encodable.encode(to: encoder) - default: - let context = EncodingError.Context(codingPath: container.codingPath, debugDescription: "AnyEncodable value cannot be encoded") - throw EncodingError.invalidValue(value, context) - } - } - - #if canImport(Foundation) - private func encode(nsnumber: NSNumber, into container: inout SingleValueEncodingContainer) throws { - switch Character(Unicode.Scalar(UInt8(nsnumber.objCType.pointee))) { - case "c", "C": - try container.encode(nsnumber.boolValue) - case "s": - try container.encode(nsnumber.int8Value) - case "i": - try container.encode(nsnumber.int16Value) - case "l": - try container.encode(nsnumber.int32Value) - case "q": - try container.encode(nsnumber.int64Value) - case "S": - try container.encode(nsnumber.uint8Value) - case "I": - try container.encode(nsnumber.uint16Value) - case "L": - try container.encode(nsnumber.uint32Value) - case "Q": - try container.encode(nsnumber.uint64Value) - case "f": - try container.encode(nsnumber.floatValue) - case "d": - try container.encode(nsnumber.doubleValue) - default: - let context = EncodingError.Context(codingPath: container.codingPath, debugDescription: "NSNumber cannot be encoded because its type is not handled") - throw EncodingError.invalidValue(nsnumber, context) - } - } - #endif -} - -extension AnyEncodable: Equatable { - public static func == (lhs: AnyEncodable, rhs: AnyEncodable) -> Bool { - switch (lhs.value, rhs.value) { - case is (Void, Void): - return true - case let (lhs as Bool, rhs as Bool): - return lhs == rhs - case let (lhs as Int, rhs as Int): - return lhs == rhs - case let (lhs as Int8, rhs as Int8): - return lhs == rhs - case let (lhs as Int16, rhs as Int16): - return lhs == rhs - case let (lhs as Int32, rhs as Int32): - return lhs == rhs - case let (lhs as Int64, rhs as Int64): - return lhs == rhs - case let (lhs as UInt, rhs as UInt): - return lhs == rhs - case let (lhs as UInt8, rhs as UInt8): - return lhs == rhs - case let (lhs as UInt16, rhs as UInt16): - return lhs == rhs - case let (lhs as UInt32, rhs as UInt32): - return lhs == rhs - case let (lhs as UInt64, rhs as UInt64): - return lhs == rhs - case let (lhs as Float, rhs as Float): - return lhs == rhs - case let (lhs as Double, rhs as Double): - return lhs == rhs - case let (lhs as String, rhs as String): - return lhs == rhs - case let (lhs as [String: AnyEncodable], rhs as [String: AnyEncodable]): - return lhs == rhs - case let (lhs as [AnyEncodable], rhs as [AnyEncodable]): - return lhs == rhs - default: - return false - } - } -} - -extension AnyEncodable: CustomStringConvertible { - public var description: String { - switch value { - case is Void: - return String(describing: nil as Any?) - case let value as CustomStringConvertible: - return value.description - default: - return String(describing: value) - } - } -} - -extension AnyEncodable: CustomDebugStringConvertible { - public var debugDescription: String { - switch value { - case let value as CustomDebugStringConvertible: - return "AnyEncodable(\(value.debugDescription))" - default: - return "AnyEncodable(\(description))" - } - } -} - -extension AnyEncodable: ExpressibleByNilLiteral {} -extension AnyEncodable: ExpressibleByBooleanLiteral {} -extension AnyEncodable: ExpressibleByIntegerLiteral {} -extension AnyEncodable: ExpressibleByFloatLiteral {} -extension AnyEncodable: ExpressibleByStringLiteral {} -extension AnyEncodable: ExpressibleByStringInterpolation {} -extension AnyEncodable: ExpressibleByArrayLiteral {} -extension AnyEncodable: ExpressibleByDictionaryLiteral {} - -extension _AnyEncodable { - public init(nilLiteral _: ()) { - self.init(nil as Any?) - } - - public init(booleanLiteral value: Bool) { - self.init(value) - } - - public init(integerLiteral value: Int) { - self.init(value) - } - - public init(floatLiteral value: Double) { - self.init(value) - } - - public init(extendedGraphemeClusterLiteral value: String) { - self.init(value) - } - - public init(stringLiteral value: String) { - self.init(value) - } - - public init(arrayLiteral elements: Any...) { - self.init(elements) - } - - public init(dictionaryLiteral elements: (AnyHashable, Any)...) { - self.init([AnyHashable: Any](elements, uniquingKeysWith: { first, _ in first })) - } -} - -extension AnyEncodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyEncodable]: - hasher.combine(value) - case let value as [AnyEncodable]: - hasher.combine(value) - default: - break - } - } -} diff --git a/Sources/Web3Auth/BuildEnv.swift b/Sources/Web3Auth/BuildEnv.swift index 5e32674..a5cc426 100644 --- a/Sources/Web3Auth/BuildEnv.swift +++ b/Sources/Web3Auth/BuildEnv.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Gaurav Goel on 15/09/23. -// - import Foundation public enum BuildEnv: String, Codable { @@ -12,4 +5,3 @@ public enum BuildEnv: String, Codable { case staging case testing } - diff --git a/Sources/Web3Auth/Data+extensions.swift b/Sources/Web3Auth/Data+extensions.swift index 057494d..e0ecc6e 100644 --- a/Sources/Web3Auth/Data+extensions.swift +++ b/Sources/Web3Auth/Data+extensions.swift @@ -1,14 +1,6 @@ -// -// File.swift -// -// -// Created by Michael Lee on 8/3/2022. -// - import Foundation -extension Data { - +internal extension Data { static func fromBase64URL(_ str: String) -> Data? { var base64 = str base64 = base64.replacingOccurrences(of: "-", with: "+") @@ -23,7 +15,7 @@ extension Data { } func toBase64URL() -> String { - var result = self.base64EncodedString() + var result = base64EncodedString() result = result.replacingOccurrences(of: "+", with: "-") result = result.replacingOccurrences(of: "/", with: "_") result = result.replacingOccurrences(of: "=", with: "") @@ -31,7 +23,7 @@ extension Data { } } -extension Data { +internal extension Data { init?(hexString: String) { let length = hexString.count / 2 var data = Data(capacity: length) @@ -47,8 +39,4 @@ extension Data { } self = data } - - func addLeading0sForLength64() -> Data { - Data(hexString: hexString.padStart(toLength: 64, padString: "0")) ?? Data() - } } diff --git a/Sources/Web3Auth/ECDSASig.swift b/Sources/Web3Auth/ECDSASig.swift index 694eb05..3d50212 100644 --- a/Sources/Web3Auth/ECDSASig.swift +++ b/Sources/Web3Auth/ECDSASig.swift @@ -1,12 +1,6 @@ -// -// File.swift -// -// -// Created by Dhruv Jaiswal on 25/08/22. -// import BigInt -import Foundation import curveSecp256k1 +import Foundation class SECP256K1 { static func sign(privkey: String, messageData: String) throws -> Signature { diff --git a/Sources/Web3Auth/KeychainManager.swift b/Sources/Web3Auth/KeychainManager.swift index e423eaa..a5b27d7 100644 --- a/Sources/Web3Auth/KeychainManager.swift +++ b/Sources/Web3Auth/KeychainManager.swift @@ -1,15 +1,6 @@ -// -// File.swift -// -// -// Created by Dhruv Jaiswal on 18/07/22. -// - import SessionManager - extension KeychainManager { - func saveDappShare(userInfo: Web3AuthUserInfo) { guard let verifer = userInfo.verifier, let veriferID = userInfo.verifierId, let dappShare = userInfo.dappShare else { return } let key = verifer + " | " + veriferID diff --git a/Sources/Web3Auth/Language.swift b/Sources/Web3Auth/Language.swift index a17f90c..e0e76b5 100644 --- a/Sources/Web3Auth/Language.swift +++ b/Sources/Web3Auth/Language.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Gaurav Goel on 05/10/23. -// - import Foundation public enum Language: String, Codable { diff --git a/Sources/Web3Auth/OSLog.swift b/Sources/Web3Auth/OSLog.swift index 43d3e2d..d5c8fda 100644 --- a/Sources/Web3Auth/OSLog.swift +++ b/Sources/Web3Auth/OSLog.swift @@ -1,9 +1,3 @@ -// -// File.swift -// -// -// Created by Dhruv Jaiswal on 12/10/22. -// import OSLog public let subsystem = Bundle.main.bundleIdentifier ?? "com.torus.Web3Auth" diff --git a/Sources/Web3Auth/Provider.swift b/Sources/Web3Auth/Provider.swift index 464426a..7b977a1 100644 --- a/Sources/Web3Auth/Provider.swift +++ b/Sources/Web3Auth/Provider.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Michael Lee on 15/12/2021. -// - import Foundation public enum Web3AuthProvider: String, Codable { diff --git a/Sources/Web3Auth/String+extensions.swift b/Sources/Web3Auth/String+extensions.swift index 60c0629..e331ce8 100644 --- a/Sources/Web3Auth/String+extensions.swift +++ b/Sources/Web3Auth/String+extensions.swift @@ -1,12 +1,6 @@ -// -// File.swift -// -// -// Created by Michael Lee on 8/3/2022. -// - import Foundation -extension String { + +internal extension String { func fromBase64URL() -> String? { var base64 = self base64 = base64.replacingOccurrences(of: "-", with: "+") @@ -27,36 +21,7 @@ extension String { result = result.replacingOccurrences(of: "=", with: "") return result } -} - -extension String { - func fromBase64() -> String? { - guard let data = Data(base64Encoded: self) else { - return nil - } - return String(data: data, encoding: .utf8) - } - - func toBase64() -> String { - return Data(utf8).base64EncodedString() - } - - func strip04Prefix() -> String { - if hasPrefix("04") { - let indexStart = index(startIndex, offsetBy: 2) - return String(self[indexStart...]) - } - return self - } - - func strip0xPrefix() -> String { - if hasPrefix("0x") { - let indexStart = index(startIndex, offsetBy: 2) - return String(self[indexStart...]) - } - return self - } - + func padStart(toLength: Int, padString: String = " ") -> String { var stringLength = count if stringLength < toLength { @@ -76,19 +41,3 @@ extension String { } } } - -extension StringProtocol { - var hexa: [UInt8] { - var startIndex = self.startIndex - return (0 ..< count / 2).compactMap { _ in - let endIndex = index(after: startIndex) - defer { startIndex = index(after: endIndex) } - return UInt8(self[startIndex ... endIndex], radix: 16) - } - } -} - -extension Sequence where Element == UInt8 { - var data: Data { .init(self) } - var hexa: String { map { .init(format: "%02x", $0) }.joined() } -} diff --git a/Sources/Web3Auth/ThemeModes.swift b/Sources/Web3Auth/ThemeModes.swift index 3af88f9..2d2dd31 100644 --- a/Sources/Web3Auth/ThemeModes.swift +++ b/Sources/Web3Auth/ThemeModes.swift @@ -1,10 +1,3 @@ -// -// File.swift -// -// -// Created by Gaurav Goel on 05/10/23. -// - import Foundation public enum ThemeModes: String, Codable { diff --git a/Sources/Web3Auth/Types.swift b/Sources/Web3Auth/Types.swift index 0d563bd..0e9b2b2 100644 --- a/Sources/Web3Auth/Types.swift +++ b/Sources/Web3Auth/Types.swift @@ -1,3 +1,5 @@ +//TODO: Split up this file. + import Foundation public struct Signature: Codable { @@ -46,7 +48,7 @@ public struct SignResponse: Codable { public let success: Bool public let result: String? public let error: String? - + public init(success: Bool, result: String?, error: String?) { self.success = success self.result = result @@ -181,15 +183,15 @@ public struct W3AInitParams: Codable { self.network = network self.buildEnv = buildEnv if sdkUrl != nil { - self.sdkUrl = sdkUrl - } else { - self.sdkUrl = URL(string: getSdkUrl(buildEnv: self.buildEnv)) - } + self.sdkUrl = sdkUrl + } else { + self.sdkUrl = URL(string: getSdkUrl(buildEnv: self.buildEnv)) + } if walletSdkUrl != nil { - self.walletSdkUrl = walletSdkUrl - } else { - self.walletSdkUrl = URL(string: getWalletSdkUrl(buildEnv: self.buildEnv)) - } + self.walletSdkUrl = walletSdkUrl + } else { + self.walletSdkUrl = URL(string: getWalletSdkUrl(buildEnv: self.buildEnv)) + } self.redirectUrl = redirectUrl self.loginConfig = loginConfig self.whiteLabel = whiteLabel @@ -205,7 +207,7 @@ public struct W3AInitParams: Codable { self.network = network buildEnv = BuildEnv.production sdkUrl = URL(string: getSdkUrl(buildEnv: buildEnv)) - walletSdkUrl = URL(string: getWalletSdkUrl(buildEnv: self.buildEnv)) + walletSdkUrl = URL(string: getWalletSdkUrl(buildEnv: buildEnv)) self.redirectUrl = redirectUrl loginConfig = nil whiteLabel = nil @@ -290,7 +292,6 @@ public func getWalletSdkUrl(buildEnv: BuildEnv?) -> String { } public struct W3ALoginParams: Codable { - public init(loginProvider: Web3AuthProvider, dappShare: String? = nil, extraLoginOptions: ExtraLoginOptions? = nil, redirectUrl: String? = nil, appState: String? = nil, mfaLevel: MFALevel? = nil, curve: SUPPORTED_KEY_CURVES = .SECP256K1, dappUrl: String? = nil) { @@ -342,7 +343,7 @@ public struct W3ALoginParams: Codable { public struct ExtraLoginOptions: Codable { public init(display: String? = nil, prompt: String? = nil, max_age: String? = nil, ui_locales: String? = nil, id_token_hint: String? = nil, id_token: String? = nil, login_hint: String? = nil, acr_values: String? = nil, scope: String? = nil, - audience: String? = nil, connection: String? = nil, domain: String? = nil, client_id: String? = nil, redirect_uri: String? = nil, leeway: Int? = 0, verifierIdField: String? = nil, isVerifierIdCaseSensitive: Bool? = false, additionalParams: [String : String]? = nil) { + audience: String? = nil, connection: String? = nil, domain: String? = nil, client_id: String? = nil, redirect_uri: String? = nil, leeway: Int? = 0, verifierIdField: String? = nil, isVerifierIdCaseSensitive: Bool? = false, additionalParams: [String: String]? = nil) { self.display = display self.prompt = prompt self.max_age = max_age @@ -380,7 +381,7 @@ public struct ExtraLoginOptions: Codable { let leeway: Int? let verifierIdField: String? let isVerifierIdCaseSensitive: Bool? - let additionalParams: [String : String]? + let additionalParams: [String: String]? public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) @@ -401,13 +402,13 @@ public struct ExtraLoginOptions: Codable { leeway = try values.decodeIfPresent(Int.self, forKey: .leeway) verifierIdField = try values.decodeIfPresent(String.self, forKey: .verifierIdField) isVerifierIdCaseSensitive = try values.decodeIfPresent(Bool.self, forKey: .isVerifierIdCaseSensitive) - additionalParams = try values.decodeIfPresent([String : String].self, forKey: .additionalParams) + additionalParams = try values.decodeIfPresent([String: String].self, forKey: .additionalParams) } } public struct MfaSettings: Codable { public init(deviceShareFactor: MfaSetting? = nil, backUpShareFactor: MfaSetting? = nil, socialBackupFactor: MfaSetting? = nil, passwordFactor: MfaSetting? = nil, passkeysFactor: MfaSetting? = nil, - authenticatorFactor: MfaSetting? = nil) { + authenticatorFactor: MfaSetting? = nil) { self.deviceShareFactor = deviceShareFactor self.backUpShareFactor = backUpShareFactor self.socialBackupFactor = socialBackupFactor @@ -496,7 +497,7 @@ struct SdkUrlParams: Codable { let actionType: String enum CodingKeys: String, CodingKey { - case options = "options" + case options case params case actionType } @@ -507,8 +508,8 @@ struct WalletServicesParams: Codable { let appState: String? enum CodingKeys: String, CodingKey { - case options = "options" - case appState = "appState" + case options + case appState } } @@ -519,7 +520,7 @@ struct SetUpMFAParams: Codable { let sessionId: String enum CodingKeys: String, CodingKey { - case options = "options" + case options case params case actionType case sessionId diff --git a/Sources/Web3Auth/Util.swift b/Sources/Web3Auth/Util.swift index edf638a..fcdac2e 100644 --- a/Sources/Web3Auth/Util.swift +++ b/Sources/Web3Auth/Util.swift @@ -22,71 +22,17 @@ func plistValues(_ bundle: Bundle) -> (clientId: String, network: Network, redir return (clientId: clientId, network: network, redirectUrl) } -func decodedBase64(_ base64URLSafe: String) -> Data? { - var base64 = base64URLSafe - .replacingOccurrences(of: "-", with: "+") - .replacingOccurrences(of: "_", with: "/") - if base64.count % 4 != 0 { - base64.append(String(repeating: "=", count: 4 - base64.count % 4)) - } - return Data(base64Encoded: base64) -} - -func tupleToArray(_ tuple: Any) -> [UInt8] { - // var result = [UInt8]() - let tupleMirror = Mirror(reflecting: tuple) - let tupleElements = tupleMirror.children.map({ $0.value as! UInt8 }) - return tupleElements -} - -func array32toTuple(_ arr: [UInt8]) -> (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) { - return (arr[0] as UInt8, arr[1] as UInt8, arr[2] as UInt8, arr[3] as UInt8, arr[4] as UInt8, arr[5] as UInt8, arr[6] as UInt8, arr[7] as UInt8, arr[8] as UInt8, arr[9] as UInt8, arr[10] as UInt8, arr[11] as UInt8, arr[12] as UInt8, arr[13] as UInt8, arr[14] as UInt8, arr[15] as UInt8, arr[16] as UInt8, arr[17] as UInt8, arr[18] as UInt8, arr[19] as UInt8, arr[20] as UInt8, arr[21] as UInt8, arr[22] as UInt8, arr[23] as UInt8, arr[24] as UInt8, arr[25] as UInt8, arr[26] as UInt8, arr[27] as UInt8, arr[28] as UInt8, arr[29] as UInt8, arr[30] as UInt8, arr[31] as UInt8, arr[32] as UInt8, arr[33] as UInt8, arr[34] as UInt8, arr[35] as UInt8, arr[36] as UInt8, arr[37] as UInt8, arr[38] as UInt8, arr[39] as UInt8, arr[40] as UInt8, arr[41] as UInt8, arr[42] as UInt8, arr[43] as UInt8, arr[44] as UInt8, arr[45] as UInt8, arr[46] as UInt8, arr[47] as UInt8, arr[48] as UInt8, arr[49] as UInt8, arr[50] as UInt8, arr[51] as UInt8, arr[52] as UInt8, arr[53] as UInt8, arr[54] as UInt8, arr[55] as UInt8, arr[56] as UInt8, arr[57] as UInt8, arr[58] as UInt8, arr[59] as UInt8, arr[60] as UInt8, arr[61] as UInt8, arr[62] as UInt8, arr[63] as UInt8) -} - -extension Array where Element == UInt8 { - func uint8Reverse() -> Array { - var revArr = [Element]() - for arrayIndex in stride(from: self.count - 1, through: 0, by: -1) { - revArr.append(self[arrayIndex]) - } - return revArr - } -} - extension W3AWhiteLabelData { func merge(with other: W3AWhiteLabelData) -> W3AWhiteLabelData { return W3AWhiteLabelData( - appName: self.appName ?? other.appName, - logoLight: self.logoLight ?? other.logoLight, - logoDark: self.logoDark ?? other.logoDark, - defaultLanguage: self.defaultLanguage ?? other.defaultLanguage, - mode: self.mode ?? other.mode, - theme: self.theme ?? other.theme, - appUrl: self.appUrl ?? other.appUrl, - useLogoLoader: self.useLogoLoader ?? other.useLogoLoader + appName: appName ?? other.appName, + logoLight: logoLight ?? other.logoLight, + logoDark: logoDark ?? other.logoDark, + defaultLanguage: defaultLanguage ?? other.defaultLanguage, + mode: mode ?? other.mode, + theme: theme ?? other.theme, + appUrl: appUrl ?? other.appUrl, + useLogoLoader: useLogoLoader ?? other.useLogoLoader ) } } - -extension Dictionary where Key == String, Value == String { - func mergeMaps(other: [String: String]?) -> [String: String]? { - if self.isEmpty && other == nil { - return nil - } else if self.isEmpty { - return other - } else if other == nil { - return self - } - - var mergedMap = [String: String]() - mergedMap.merge(self) { (_, new) in new } - - other?.forEach { (key, value) in - if !mergedMap.keys.contains(key) { - mergedMap[key] = value - } - } - - return mergedMap - } -} diff --git a/Sources/Web3Auth/Web3Auth.swift b/Sources/Web3Auth/Web3Auth.swift index 332624f..abf01c5 100644 --- a/Sources/Web3Auth/Web3Auth.swift +++ b/Sources/Web3Auth/Web3Auth.swift @@ -1,4 +1,5 @@ import AuthenticationServices +import curveSecp256k1 import OSLog import SessionManager @@ -10,21 +11,21 @@ public class Web3Auth: NSObject { private var initParams: W3AInitParams private var authSession: ASWebAuthenticationSession? // You can check the state variable before logging the user in, if the user - // has an active session the state variable will already have all the values you + // has an active session the state variable will already have all the values you // get from login so the user does not have to re-login public var state: Web3AuthState? var sessionManager: SessionManager - var webViewController: WebViewController = DispatchQueue.main.sync{ WebViewController(onSignResponse: {_ in })} + var webViewController: WebViewController = DispatchQueue.main.sync { WebViewController(onSignResponse: { _ in }) } private var w3ALoginParams: W3ALoginParams? private static var signResponse: SignResponse? - + let SIGNER_MAP: [Network: String] = [ - .mainnet: "https://signer.web3auth.io", - .testnet: "https://signer.web3auth.io", - .cyan: "https://signer-polygon.web3auth.io", - .aqua: "https://signer-polygon.web3auth.io", - .sapphire_mainnet: "https://signer.web3auth.io", - .sapphire_devnet: "https://signer.web3auth.io" + .mainnet: "https://signer.web3auth.io", + .testnet: "https://signer.web3auth.io", + .cyan: "https://signer-polygon.web3auth.io", + .aqua: "https://signer-polygon.web3auth.io", + .sapphire_mainnet: "https://signer.web3auth.io", + .sapphire_devnet: "https://signer.web3auth.io", ] /** Web3Auth component for authenticating with web-based flow. @@ -44,14 +45,14 @@ public class Web3Auth: NSObject { super.init() do { let fetchConfigResult = try await fetchProjectConfig() - if(fetchConfigResult) { - do { + if fetchConfigResult { + let sessionId = SessionManager.getSessionIdFromStorage() + if sessionId != nil { + sessionManager.setSessionId(sessionId: sessionId!) let loginDetailsDict = try await sessionManager.authorizeSession(origin: params.redirectUrl) - guard let loginDetails = Web3AuthState(dict: loginDetailsDict, sessionID: sessionManager.getSessionID() ?? "", - network: initParams.network) else { throw Web3AuthError.decodingError } + guard let loginDetails = Web3AuthState(dict: loginDetailsDict, sessionID: sessionManager.getSessionId(), + network: initParams.network) else { throw Web3AuthError.decodingError } state = loginDetails - } catch let error { - os_log("%s", log: getTorusLogger(log: Web3AuthLogger.core, type: .error), type: .error, error.localizedDescription) } } } catch let error { @@ -61,22 +62,25 @@ public class Web3Auth: NSObject { } public func logout() async throws { - guard let state = state else {throw Web3AuthError.noUserFound} - let _ = try await sessionManager.invalidateSession() + guard let state = state else { throw Web3AuthError.noUserFound } + try await sessionManager.invalidateSession() + SessionManager.deleteSessionIdFromStorage() if let verifer = state.userInfo?.verifier, let dappShare = KeychainManager.shared.getDappShare(verifier: verifer) { KeychainManager.shared.delete(key: .custom(dappShare)) } self.state = nil } - + public func getLoginId(data: T) async throws -> String? { + let sessionId = try SessionManager.generateRandomSessionID()! + sessionManager.setSessionId(sessionId: sessionId) return try await sessionManager.createSession(data: data) } - + private func getLoginDetails(_ callbackURL: URL) async throws -> Web3AuthState { let loginDetailsDict = try await sessionManager.authorizeSession(origin: initParams.redirectUrl) guard - let loginDetails = Web3AuthState(dict: loginDetailsDict, sessionID: sessionManager.getSessionID() ?? "",network: initParams.network) + let loginDetails = Web3AuthState(dict: loginDetailsDict, sessionID: sessionManager.getSessionId(), network: initParams.network) else { throw Web3AuthError.decodingError } @@ -152,23 +156,23 @@ public class Web3Auth: NSObject { let redirectURL = URL(string: "\(bundleId)://auth") else { throw Web3AuthError.noBundleIdentifierFound } w3ALoginParams = loginParams - //assign loginParams redirectUrl from intiParamas redirectUrl + // assign loginParams redirectUrl from intiParamas redirectUrl w3ALoginParams?.redirectUrl = "\(bundleId)://auth" if let loginConfig = initParams.loginConfig?.values.first, let savedDappShare = KeychainManager.shared.getDappShare(verifier: loginConfig.verifier) { w3ALoginParams?.dappShare = savedDappShare } - + let sdkUrlParams = SdkUrlParams(options: initParams, params: w3ALoginParams!, actionType: "login") let loginId = try await getLoginId(data: sdkUrlParams) - + let jsonObject: [String: String?] = [ - "loginId": loginId + "loginId": loginId, ] let url = try Web3Auth.generateAuthSessionURL(initParams: initParams, jsonObject: jsonObject, sdkUrl: initParams.sdkUrl?.absoluteString, path: "start") - + return try await withCheckedThrowingContinuation({ (continuation: CheckedContinuation) in authSession = ASWebAuthenticationSession( @@ -187,15 +191,17 @@ public class Web3Auth: NSObject { } return } - - self.sessionManager.setSessionID(sessionResponse.sessionId) + + let sessionId = sessionResponse.sessionId + self.sessionManager.setSessionId(sessionId: sessionId) + SessionManager.saveSessionIdToStorage(sessionId) + Task { do { let loginDetails = try await self.getLoginDetails(callbackURL) if let safeUserInfo = loginDetails.userInfo { KeychainManager.shared.saveDappShare(userInfo: safeUserInfo) } - self.sessionManager.setSessionID(loginDetails.sessionId ?? "") self.state = loginDetails return continuation.resume(returning: loginDetails) @@ -203,62 +209,59 @@ public class Web3Auth: NSObject { continuation.resume(throwing: Web3AuthError.unknownError) } } - } + } - authSession?.presentationContextProvider = self + self.authSession?.presentationContextProvider = self - if !(authSession?.start() ?? false) { + if !(self.authSession?.start() ?? false) { continuation.resume(throwing: Web3AuthError.unknownError) } }) } - - public func enableMFA(_ loginParams: W3ALoginParams? = nil) async throws -> Bool{ - if(state?.userInfo?.isMfaEnabled == true) { + + public func enableMFA(_ loginParams: W3ALoginParams? = nil) async throws -> Bool { + if state?.userInfo?.isMfaEnabled == true { throw Web3AuthError.mfaAlreadyEnabled } - let sessionId = self.sessionManager.getSessionID() - if !(sessionId ?? "").isEmpty { + let sessionId = sessionManager.getSessionId() + if !sessionId.isEmpty { guard let bundleId = Bundle.main.bundleIdentifier, let redirectURL = URL(string: "\(bundleId)://auth") else { throw Web3AuthError.noBundleIdentifierFound } - + var extraLoginOptions: ExtraLoginOptions? = ExtraLoginOptions() - if(loginParams?.extraLoginOptions != nil) { + if loginParams?.extraLoginOptions != nil { extraLoginOptions = loginParams?.extraLoginOptions } else { extraLoginOptions = w3ALoginParams?.extraLoginOptions } extraLoginOptions?.login_hint = state?.userInfo?.verifierId - + let jsonData = try? JSONEncoder().encode(extraLoginOptions) let _extraLoginOptions = String(data: jsonData!, encoding: .utf8) - + let params: [String: String?] = [ "loginProvider": state?.userInfo?.typeOfLogin, "mfaLevel": MFALevel.MANDATORY.rawValue, "redirectUrl": redirectURL.absoluteString, - "extraLoginOptions" : _extraLoginOptions + "extraLoginOptions": _extraLoginOptions, ] - - let setUpMFAParams = SetUpMFAParams(options: initParams, params: params, actionType: "enable_mfa", sessionId: sessionId ?? "") - - let _sessionId = sessionManager.getSessionID() ?? "" + + let setUpMFAParams = SetUpMFAParams(options: initParams, params: params, actionType: "enable_mfa", sessionId: sessionId) let loginId = try await getLoginId(data: setUpMFAParams) - self.sessionManager.setSessionID(_sessionId) - + let jsonObject: [String: String?] = [ - "loginId": loginId + "loginId": loginId, ] - + let url = try Web3Auth.generateAuthSessionURL(initParams: initParams, jsonObject: jsonObject, sdkUrl: initParams.sdkUrl?.absoluteString, path: "start") - + return try await withCheckedThrowingContinuation({ (continuation: CheckedContinuation) in - + authSession = ASWebAuthenticationSession( url: url, callbackURLScheme: redirectURL.scheme) { callbackURL, authError in - + guard authError == nil, let callbackURL = callbackURL, @@ -272,15 +275,17 @@ public class Web3Auth: NSObject { } return } - - self.sessionManager.setSessionID(sessionResponse.sessionId) + + let sessionId = sessionResponse.sessionId + self.sessionManager.setSessionId(sessionId: sessionId) + SessionManager.saveSessionIdToStorage(sessionId) + Task { do { let loginDetails = try await self.getLoginDetails(callbackURL) if let safeUserInfo = loginDetails.userInfo { KeychainManager.shared.saveDappShare(userInfo: safeUserInfo) } - self.sessionManager.setSessionID(loginDetails.sessionId ?? "") self.state = loginDetails return continuation.resume(returning: true) } catch { @@ -288,65 +293,58 @@ public class Web3Auth: NSObject { } } } - authSession?.presentationContextProvider = self - + if !(authSession?.start() ?? false) { continuation.resume(throwing: Web3AuthError.unknownError) } }) - } - else { + } else { throw Web3AuthError.runtimeError("SessionId not found. Please login first.") } } - + public func launchWalletServices(chainConfig: ChainConfig, path: String? = "wallet") async throws { - let sessionId = self.sessionManager.getSessionID() - if !(sessionId ?? "").isEmpty { + let sessionId = SessionManager.getSessionIdFromStorage()! + if !sessionId.isEmpty { guard let bundleId = Bundle.main.bundleIdentifier, let _ = URL(string: "\(bundleId)://auth") else { throw Web3AuthError.noBundleIdentifierFound } - + initParams.chainConfig = chainConfig let walletServicesParams = WalletServicesParams(options: initParams, appState: nil) - - let _sessionId = sessionManager.getSessionID() ?? "" + let loginId = try await getLoginId(data: walletServicesParams) - self.sessionManager.setSessionID(_sessionId) - + let jsonObject: [String: String?] = [ "loginId": loginId, "sessionId": sessionId, - "platform": "ios" + "platform": "ios", ] - + let url = try Web3Auth.generateAuthSessionURL(initParams: initParams, jsonObject: jsonObject, sdkUrl: initParams.walletSdkUrl?.absoluteString, path: path) - //open url in webview - await UIApplication.shared.keyWindow?.rootViewController?.present(webViewController, animated: true, completion: nil) + // open url in webview + await UIApplication.shared.windows.filter { $0.isKeyWindow }.first?.rootViewController?.present(webViewController, animated: true, completion: nil) await webViewController.webView.load(URLRequest(url: url)) - } - else { + } else { throw Web3AuthError.runtimeError("SessionId not found. Please login first.") } } - + public func request(chainConfig: ChainConfig, method: String, requestParams: [Any], path: String? = "wallet/request", appState: String? = nil) async throws -> SignResponse { - let sessionId = self.sessionManager.getSessionID() - if !(sessionId ?? "").isEmpty { + let sessionId = SessionManager.getSessionIdFromStorage()! + if !sessionId.isEmpty { guard let bundleId = Bundle.main.bundleIdentifier, let _ = URL(string: "\(bundleId)://auth") else { throw Web3AuthError.noBundleIdentifierFound } initParams.chainConfig = chainConfig - + let walletServicesParams = WalletServicesParams(options: initParams, appState: appState) - - let _sessionId = sessionManager.getSessionID() ?? "" + let loginId = try await getLoginId(data: walletServicesParams) - self.sessionManager.setSessionID(_sessionId) - + var signMessageMap: [String: String] = [:] signMessageMap["loginId"] = loginId signMessageMap["sessionId"] = sessionId @@ -363,31 +361,28 @@ public class Web3Auth: NSObject { } let url = try Web3Auth.generateAuthSessionURL(initParams: initParams, jsonObject: signMessageMap, sdkUrl: initParams.walletSdkUrl?.absoluteString, path: path) - - //open url in webview + + // open url in webview return await withCheckedContinuation { continuation in Task { let webViewController = await MainActor.run { - return WebViewController(redirectUrl: initParams.redirectUrl, onSignResponse: {_ in }) - } - - webViewController.onSignResponse = { signResponse in - continuation.resume(returning: signResponse) + WebViewController(redirectUrl: initParams.redirectUrl, onSignResponse: { signResponse in + continuation.resume(returning: signResponse) + }) } DispatchQueue.main.async { - UIApplication.shared.keyWindow?.rootViewController?.present(webViewController, animated: true) { + UIApplication.shared.windows.filter { $0.isKeyWindow }.first?.rootViewController?.present(webViewController, animated: true) { webViewController.webView.load(URLRequest(url: url)) } } } } - } - else { + } else { throw Web3AuthError.runtimeError("SessionId not found. Please login first.") } } - + static func generateAuthSessionURL(initParams: W3AInitParams, jsonObject: [String: String?], sdkUrl: String?, path: String?) throws -> URL { let jsonEncoder = JSONEncoder() jsonEncoder.outputFormatting.insert(.sortedKeys) @@ -415,7 +410,7 @@ public class Web3Auth: NSObject { guard let host = callbackURL.host, let fragment = callbackURL.fragment, - let component = URLComponents.init(string: host + "?" + fragment), + let component = URLComponents(string: host + "?" + fragment), let queryItems = component.queryItems, let b64ParamsItem = queryItems.first(where: { $0.name == "b64Params" }), let callbackFragment = b64ParamsItem.value, @@ -426,13 +421,13 @@ public class Web3Auth: NSObject { } return callbackState } - + static func decodeSessionStringfromCallbackURL(_ callbackURL: URL) throws -> String? { let callbackFragment = callbackURL.fragment return callbackFragment?.components(separatedBy: "&")[0].components(separatedBy: "=")[1] } - - public func fetchProjectConfig() async throws -> Bool { + + public func fetchProjectConfig() async throws -> Bool { var response: Bool = false let api = Router.get([.init(name: "project_id", value: initParams.clientId), .init(name: "network", value: initParams.network.rawValue), .init(name: "whitelist", value: "true")]) let result = await Service.request(router: api) @@ -441,8 +436,8 @@ public class Web3Auth: NSObject { do { let decoder = JSONDecoder() let result = try decoder.decode(ProjectConfigResponse.self, from: data) - //os_log("fetchProjectConfig API response is: %@", log: getTorusLogger(log: Web3AuthLogger.network, type: .info), type: .info, "\(String(describing: result))") - initParams.originData = result.whitelist.signedUrls.mergeMaps(other: initParams.originData) + // os_log("fetchProjectConfig API response is: %@", log: getTorusLogger(log: Web3AuthLogger.network, type: .info), type: .info, "\(String(describing: result))") + initParams.originData = result.whitelist.signedUrls.merging(initParams.originData ?? [:]) { _, new in new } if let whiteLabelData = result.whiteLabelData { if initParams.whiteLabel == nil { initParams.whiteLabel = whiteLabelData @@ -473,19 +468,19 @@ public class Web3Auth: NSObject { return "" } let ed25519Key: String = initParams.useCoreKitKey == true ? - state?.coreKitEd25519PrivKey ?? "" : state?.ed25519PrivKey ?? "" + state?.coreKitEd25519PrivKey ?? "" : state?.ed25519PrivKey ?? "" return ed25519Key } public func getUserInfo() throws -> Web3AuthUserInfo { - guard let state = state, let userInfo = state.userInfo else { throw Web3AuthError.noUserFound} + guard let state = state, let userInfo = state.userInfo else { throw Web3AuthError.noUserFound } return userInfo } - + public func getWeb3AuthResponse() throws -> Web3AuthState { guard let state = state else { - throw Web3AuthError.noUserFound - } + throw Web3AuthError.noUserFound + } return state } } diff --git a/Sources/Web3Auth/Web3AuthError.swift b/Sources/Web3Auth/Web3AuthError.swift index 0b66a3d..70d1ba3 100644 --- a/Sources/Web3Auth/Web3AuthError.swift +++ b/Sources/Web3Auth/Web3AuthError.swift @@ -26,7 +26,7 @@ extension Web3AuthError: LocalizedError { return "App cancelled" case .unknownError: return "Unknown error" - case .runtimeError(let msg): + case let .runtimeError(msg): return "Runtime error \(msg)" case .decodingError: return "Decoding Error" diff --git a/Sources/Web3Auth/Web3AuthState.swift b/Sources/Web3Auth/Web3AuthState.swift index fe64860..6f591a5 100644 --- a/Sources/Web3Auth/Web3AuthState.swift +++ b/Sources/Web3Auth/Web3AuthState.swift @@ -60,7 +60,7 @@ public struct Web3AuthState: Codable { } extension Web3AuthState { - init?(dict: [String: Any], sessionID: String,network:Network) { + init?(dict: [String: Any], sessionID: String, network: Network) { guard let privKey = dict["privKey"] as? String, let ed25519PrivKey = dict["ed25519PrivKey"] as? String, let userInfoDict = dict["userInfo"] as? [String: Any], @@ -69,18 +69,18 @@ extension Web3AuthState { let error = dict["error"] as? String self.privKey = privKey self.ed25519PrivKey = ed25519PrivKey - self.sessionId = sessionID + sessionId = sessionID self.userInfo = userInfo self.error = error - self.coreKitKey = dict["coreKitKey"] as? String ?? "" - self.coreKitEd25519PrivKey = dict["coreKitEd25519PrivKey"] as? String ?? "" - self.factorKey = dict["factorKey"] as? String - self.signatures = dict["signatures"] as? [String] - self.tssShareIndex = dict["tssShareIndex"] as? Int - self.tssPubKey = dict["tssPubKey"] as? String - self.tssShare = dict["tssShare"] as? String - self.tssNonce = dict["tssShare"] as? Int - self.nodeIndexes = dict["nodeIndexes"] as? [Int] - self.keyMode = dict["keyMode"] as? String + coreKitKey = dict["coreKitKey"] as? String ?? "" + coreKitEd25519PrivKey = dict["coreKitEd25519PrivKey"] as? String ?? "" + factorKey = dict["factorKey"] as? String + signatures = dict["signatures"] as? [String] + tssShareIndex = dict["tssShareIndex"] as? Int + tssPubKey = dict["tssPubKey"] as? String + tssShare = dict["tssShare"] as? String + tssNonce = dict["tssShare"] as? Int + nodeIndexes = dict["nodeIndexes"] as? [Int] + keyMode = dict["keyMode"] as? String } } diff --git a/Sources/Web3Auth/WebViewController.swift b/Sources/Web3Auth/WebViewController.swift index 73005a7..850a160 100644 --- a/Sources/Web3Auth/WebViewController.swift +++ b/Sources/Web3Auth/WebViewController.swift @@ -1,40 +1,31 @@ -// -// ViewController.swift -// -// -// Created by Gaurav Goel on 12/01/24. -// - import UIKit -import WebKit - - +@preconcurrency import WebKit + class WebViewController: UIViewController, WKScriptMessageHandler { - - var webView : WKWebView! + var webView: WKWebView! var popupWebView: WKWebView? let activityIndicator = UIActivityIndicatorView(style: .large) var redirectUrl: String? var onSignResponse: (SignResponse) -> Void - + init(redirectUrl: String? = nil, onSignResponse: @escaping (SignResponse) -> Void) { self.redirectUrl = redirectUrl self.onSignResponse = onSignResponse super.init(nibName: nil, bundle: nil) } - + required init?(coder aDecoder: NSCoder) { - self.onSignResponse = { _ in } + onSignResponse = { _ in } super.init(coder: aDecoder) } - + override func viewDidLoad() { super.viewDidLoad() setupWebView() activityIndicator.startAnimating() activityIndicator.stopAnimating() } - + func setupWebView() { let preferences = WKPreferences() preferences.javaScriptEnabled = true @@ -52,25 +43,25 @@ class WebViewController: UIViewController, WKScriptMessageHandler { view.addSubview(webView) } - + func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { - if let redirectUrl = redirectUrl, !redirectUrl.isEmpty { - if let url = navigationAction.request.url, url.absoluteString.contains(redirectUrl) { - let host = url.host ?? "" - let fragment = url.fragment ?? "" - let component = URLComponents.init(string: host + "?" + fragment) - let queryItems = component?.queryItems - let b64ParamsItem = queryItems?.first(where: { $0.name == "b64Params" }) - let callbackFragment = (b64ParamsItem?.value)! - let b64ParamString = Data.fromBase64URL(callbackFragment) - let signResponse = try? JSONDecoder().decode(SignResponse.self, from: b64ParamString!) - onSignResponse(signResponse!) - dismiss(animated: true, completion: nil) - } + if let redirectUrl = redirectUrl, !redirectUrl.isEmpty { + if let url = navigationAction.request.url, url.absoluteString.contains(redirectUrl) { + let host = url.host ?? "" + let fragment = url.fragment ?? "" + let component = URLComponents(string: host + "?" + fragment) + let queryItems = component?.queryItems + let b64ParamsItem = queryItems?.first(where: { $0.name == "b64Params" }) + let callbackFragment = (b64ParamsItem?.value)! + let b64ParamString = Data.fromBase64URL(callbackFragment) + let signResponse = try? JSONDecoder().decode(SignResponse.self, from: b64ParamString!) + onSignResponse(signResponse!) + dismiss(animated: true, completion: nil) } - decisionHandler(.allow) } - + decisionHandler(.allow) + } + func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if message.name == "JSBridge", let messageBody = message.body as? String { switch messageBody { @@ -82,32 +73,31 @@ class WebViewController: UIViewController, WKScriptMessageHandler { } } } - - -extension WebViewController : WKNavigationDelegate { + +extension WebViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { activityIndicator.startAnimating() } - + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { activityIndicator.stopAnimating() } } extension WebViewController: WKUIDelegate { -func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { - popupWebView = WKWebView(frame: view.bounds, configuration: configuration) - popupWebView!.autoresizingMask = [.flexibleWidth, .flexibleHeight] - popupWebView!.navigationDelegate = self - popupWebView!.uiDelegate = self - view.addSubview(popupWebView!) - return popupWebView! -} + func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { + popupWebView = WKWebView(frame: view.bounds, configuration: configuration) + popupWebView!.autoresizingMask = [.flexibleWidth, .flexibleHeight] + popupWebView!.navigationDelegate = self + popupWebView!.uiDelegate = self + view.addSubview(popupWebView!) + return popupWebView! + } -func webViewDidClose(_ webView: WKWebView) { - if webView == popupWebView { - popupWebView?.removeFromSuperview() - popupWebView = nil + func webViewDidClose(_ webView: WKWebView) { + if webView == popupWebView { + popupWebView?.removeFromSuperview() + popupWebView = nil + } } } -} diff --git a/Web3Auth.podspec b/Web3Auth.podspec index da04bae..c0577c3 100644 --- a/Web3Auth.podspec +++ b/Web3Auth.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |spec| spec.name = "Web3Auth" - spec.version = "9.0.0" + spec.version = "10.0.0" spec.platform = :ios, "14.0" spec.summary = "Torus Web3Auth SDK for iOS applications" spec.homepage = "https://github.com/web3auth/web3auth-swift-sdk" @@ -11,8 +11,8 @@ Pod::Spec.new do |spec| spec.source = { :git => "https://github.com/web3auth/web3auth-swift-sdk.git", :tag => spec.version } spec.source_files = "Sources/Web3Auth/**/*.{swift}" spec.dependency 'KeychainSwift', '~> 20.0.0' - spec.dependency 'curvelib.swift', '~> 1.0.1' - spec.dependency 'TorusSessionManager', '~> 4.0.2' + spec.dependency 'curvelib.swift', '~> 2.0.0' + spec.dependency 'TorusSessionManager', '~> 6.0.1' spec.dependency 'BigInt', '~> 5.2.0' spec.exclude_files = [ 'docs/**' ] end diff --git a/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 7cf591a..09cd73b 100644 --- a/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -15,8 +15,8 @@ "repositoryURL": "https://github.com/tkey/curvelib.swift", "state": { "branch": null, - "revision": "9f88bd5e56d1df443a908f7a7e81ae4f4d9170ea", - "version": "1.0.1" + "revision": "432bf1abe7ff505fc2ac9fcf697341ff5b2dc6d0", + "version": "2.0.0" } }, { @@ -51,8 +51,8 @@ "repositoryURL": "https://github.com/Web3Auth/session-manager-swift.git", "state": { "branch": null, - "revision": "67d5f7db655d02778861057fb280ecf47c923b09", - "version": "5.0.0" + "revision": "d86cd2a7f6d8095531ed609c728d851820fe85be", + "version": "6.0.1" } }, { diff --git a/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/ContentView.swift b/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/ContentView.swift index bdb5ccc..7197a80 100644 --- a/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/ContentView.swift +++ b/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/ContentView.swift @@ -1,10 +1,3 @@ -// -// ContentView.swift -// Web3AuthPodSample -// -// Created by Dhruv Jaiswal on 03/10/22. -// - import SwiftUI import Web3Auth diff --git a/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/LoginView.swift b/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/LoginView.swift index 24a89b6..06582b9 100644 --- a/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/LoginView.swift +++ b/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/LoginView.swift @@ -1,10 +1,3 @@ -// -// LoginView.swift -// Web3authSwiftSdkDemo -// -// Created by Dhruv Jaiswal on 18/10/22. -// - import SwiftUI struct LoginView: View { diff --git a/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/UserDetailView.swift b/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/UserDetailView.swift index 550e851..9b3343c 100644 --- a/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/UserDetailView.swift +++ b/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/UserDetailView.swift @@ -1,10 +1,3 @@ -// -// LoggedInView.swift -// Web3AuthPodSample -// -// Created by Dhruv Jaiswal on 10/10/22. -// - import SwiftUI struct UserDetailView: View { @@ -25,7 +18,7 @@ struct UserDetailView: View { Text("ED25519 Key") } Section { - Text("Name \( vm.userInfo?.name ?? "")") + Text("Name \(vm.userInfo?.name ?? "")") Text("Email \(vm.userInfo?.email ?? "")") } header: { diff --git a/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/ViewModel.swift b/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/ViewModel.swift index f084a4a..ed3f953 100644 --- a/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/ViewModel.swift +++ b/Web3authSwiftSdkDemo/Web3authSwiftSdkDemo/ViewModel.swift @@ -1,10 +1,3 @@ -// -// ViewModel.swift -// Web3authSwiftSdkDemo -// -// Created by Dhruv Jaiswal on 18/10/22. -// - import Foundation import web3 import Web3Auth @@ -38,7 +31,7 @@ class ViewModel: ObservableObject { typeOfLogin: TypeOfLogin.jwt, clientId: "d84f6xvbdV75VTGmHiMWfZLeSPk8M07C" ) - + func setup() async throws { guard web3Auth == nil else { return } await MainActor.run(body: { @@ -46,10 +39,10 @@ class ViewModel: ObservableObject { navigationTitle = "Loading" }) web3Auth = try await Web3Auth(.init(clientId: clientID, network: network, buildEnv: buildEnv, redirectUrl: "com.web3auth.sdkapp://auth", - // sdkUrl: URL(string: "https://auth.mocaverse.xyz"), - // walletSdkUrl: URL(string: "https://lrc-mocaverse.web3auth.io"), - // loginConfig: ["loginConfig": loginConfig], - useCoreKitKey: useCoreKit)) + // sdkUrl: URL(string: "https://auth.mocaverse.xyz"), + // walletSdkUrl: URL(string: "https://lrc-mocaverse.web3auth.io"), + // loginConfig: ["loginConfig": loginConfig], + useCoreKitKey: useCoreKit)) await MainActor.run(body: { if self.web3Auth?.state != nil { handleUserDetails() @@ -59,7 +52,7 @@ class ViewModel: ObservableObject { navigationTitle = loggedIn ? "UserInfo" : "SignIn" }) } - + @MainActor func handleUserDetails() { do { loggedIn = true @@ -71,7 +64,7 @@ class ViewModel: ObservableObject { showError = true } } - + func login(provider: Web3AuthProvider) { Task { do { @@ -79,14 +72,14 @@ class ViewModel: ObservableObject { extraLoginOptions: ExtraLoginOptions(display: nil, prompt: nil, max_age: nil, ui_locales: nil, id_token_hint: nil, id_token: nil, login_hint: "hello@tor.us", acr_values: nil, scope: nil, audience: nil, connection: nil, domain: nil, client_id: nil, redirect_uri: nil, leeway: nil, verifierIdField: nil, isVerifierIdCaseSensitive: nil, additionalParams: nil), mfaLevel: .DEFAULT, curve: .SECP256K1 - )) + )) await handleUserDetails() } catch { print("Error") } } } - + func loginWithGoogle(provider: Web3AuthProvider) { Task { do { @@ -101,14 +94,14 @@ class ViewModel: ObservableObject { _ = try await web3Auth?.login(W3ALoginParams(loginProvider: provider, mfaLevel: .DEFAULT, curve: .SECP256K1 - )) + )) await handleUserDetails() } catch { print("Error") } } } - + func loginWithGoogleCustomVerifier() { Task { do { @@ -119,13 +112,13 @@ class ViewModel: ObservableObject { redirectUrl: redirectUrl, loginConfig: [ "random": - .init( - verifier: "w3a-agg-example", - typeOfLogin: .google, - name: "Web3Auth-Aggregate-Verifier-Google-Example", - clientId: "774338308167-q463s7kpvja16l4l0kko3nb925ikds2p.apps.googleusercontent.com", - verifierSubIdentifier: "w3a-google" - ) + .init( + verifier: "w3a-agg-example", + typeOfLogin: .google, + name: "Web3Auth-Aggregate-Verifier-Google-Example", + clientId: "774338308167-q463s7kpvja16l4l0kko3nb925ikds2p.apps.googleusercontent.com", + verifierSubIdentifier: "w3a-google" + ), ] ) ) @@ -143,7 +136,7 @@ class ViewModel: ObservableObject { } } } - + @MainActor func logout() { Task { do { @@ -155,7 +148,7 @@ class ViewModel: ObservableObject { } } } - + @MainActor func launchWalletServices() { Task { do { @@ -166,15 +159,15 @@ class ViewModel: ObservableObject { } } } - + @MainActor func enableMFA() { Task { do { web3Auth = try await Web3Auth(W3AInitParams(clientId: clientID, - network: network, - buildEnv: buildEnv, - redirectUrl: redirectUrl, - whiteLabel: W3AWhiteLabelData(appName: "Web3Auth Stub", defaultLanguage: .en, mode: .dark, theme: ["primary": "#123456"]))) + network: network, + buildEnv: buildEnv, + redirectUrl: redirectUrl, + whiteLabel: W3AWhiteLabelData(appName: "Web3Auth Stub", defaultLanguage: .en, mode: .dark, theme: ["primary": "#123456"]))) _ = try await self.web3Auth?.enableMFA() } catch { errorMessage = error.localizedDescription @@ -182,7 +175,7 @@ class ViewModel: ObservableObject { } } } - + @MainActor func request() { Task { do { @@ -208,7 +201,7 @@ class ViewModel: ObservableObject { } } } - + func whitelabelLogin() { Task.detached { [unowned self] in do {