From eed97f307df483603206f677a9fabc4f66005bef Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 31 Aug 2022 09:54:51 +0200 Subject: [PATCH 1/4] extend pairing on request response - savepoint --- Sources/Auth/AuthClientFactory.swift | 2 +- .../Services/App/AppRespondSubscriber.swift | 35 +++++++++++++++---- .../AuthTests/AppRespondSubscriberTests.swift | 5 ++- .../Mocks/WCPairingStorageMock.swift | 1 - 4 files changed, 34 insertions(+), 9 deletions(-) rename Tests/{WalletConnectSignTests => TestingUtils}/Mocks/WCPairingStorageMock.swift (95%) diff --git a/Sources/Auth/AuthClientFactory.swift b/Sources/Auth/AuthClientFactory.swift index 6be615528..3dc48fbea 100644 --- a/Sources/Auth/AuthClientFactory.swift +++ b/Sources/Auth/AuthClientFactory.swift @@ -24,7 +24,7 @@ public struct AuthClientFactory { let appPairService = AppPairService(networkingInteractor: networkingInteractor, kms: kms, pairingStorage: pairingStore) let appRequestService = AppRequestService(networkingInteractor: networkingInteractor, kms: kms, appMetadata: metadata, logger: logger) let messageSigner = MessageSigner(signer: Signer()) - let appRespondSubscriber = AppRespondSubscriber(networkingInteractor: networkingInteractor, logger: logger, rpcHistory: history, signatureVerifier: messageSigner, messageFormatter: messageFormatter) + let appRespondSubscriber = AppRespondSubscriber(networkingInteractor: networkingInteractor, logger: logger, rpcHistory: history, signatureVerifier: messageSigner, messageFormatter: messageFormatter, pairingStorage: pairingStore) let walletPairService = WalletPairService(networkingInteractor: networkingInteractor, kms: kms, pairingStorage: pairingStore) let walletRequestSubscriber = WalletRequestSubscriber(networkingInteractor: networkingInteractor, logger: logger, kms: kms, messageFormatter: messageFormatter, address: account?.address) let walletRespondService = WalletRespondService(networkingInteractor: networkingInteractor, logger: logger, kms: kms, rpcHistory: history) diff --git a/Sources/Auth/Services/App/AppRespondSubscriber.swift b/Sources/Auth/Services/App/AppRespondSubscriber.swift index 21708bd73..84a0d241f 100644 --- a/Sources/Auth/Services/App/AppRespondSubscriber.swift +++ b/Sources/Auth/Services/App/AppRespondSubscriber.swift @@ -2,9 +2,11 @@ import Combine import Foundation import WalletConnectUtils import JSONRPC +import WalletConnectPairing class AppRespondSubscriber { private let networkingInteractor: NetworkInteracting + private let pairingStorage: WCPairingStorage private let logger: ConsoleLogging private let rpcHistory: RPCHistory private let signatureVerifier: MessageSignatureVerifying @@ -17,12 +19,14 @@ class AppRespondSubscriber { logger: ConsoleLogging, rpcHistory: RPCHistory, signatureVerifier: MessageSignatureVerifying, - messageFormatter: SIWEMessageFormatting) { + messageFormatter: SIWEMessageFormatting, + pairingStorage: WCPairingStorage) { self.networkingInteractor = networkingInteractor self.logger = logger self.rpcHistory = rpcHistory self.signatureVerifier = signatureVerifier self.messageFormatter = messageFormatter + self.pairingStorage = pairingStorage subscribeForResponse() } @@ -35,13 +39,10 @@ class AppRespondSubscriber { let requestParams = request.params, request.method == "wc_authRequest" else { return } + activatePairingIfNeeded(id: requestId) networkingInteractor.unsubscribe(topic: subscriptionPayload.topic) - if let errorResponse = response.error, - let error = AuthError(code: errorResponse.code) { - onResponse?(requestId, .failure(error)) - return - } + handleIfError(response: response) guard let cacao = try? response.result?.get(Cacao.self), @@ -62,4 +63,26 @@ class AppRespondSubscriber { }.store(in: &publishers) } + + + private func activatePairingIfNeeded(id: RPCID) { + guard let record = rpcHistory.get(recordId: id) else { return } + let pairingTopic = record.topic + print(pairingTopic) + guard var pairing = pairingStorage.getPairing(forTopic: pairingTopic) else { return } + if !pairing.active { + pairing.activate() + } else { + try? pairing.updateExpiry() + } + } + + private func handleIfError(response: RPCResponse) { + if let errorResponse = response.error, + let id = response.id, + let error = AuthError(code: errorResponse.code) { + onResponse?(id, .failure(error)) + return + } + } } diff --git a/Tests/AuthTests/AppRespondSubscriberTests.swift b/Tests/AuthTests/AppRespondSubscriberTests.swift index d7baec010..a5eb20c2f 100644 --- a/Tests/AuthTests/AppRespondSubscriberTests.swift +++ b/Tests/AuthTests/AppRespondSubscriberTests.swift @@ -15,6 +15,7 @@ class AppRespondSubscriberTests: XCTestCase { let walletAccount = Account(chainIdentifier: "eip155:1", address: "0x724d0D2DaD3fbB0C168f947B87Fa5DBe36F1A8bf")! let prvKey = Data(hex: "462c1dad6832d7d96ccf87bd6a686a4110e114aaaebd5512e552c0e3a87b480f") var messageSigner: MessageSigner! + var pairingStorage: WCPairingStorageMock! override func setUp() { networkingInteractor = NetworkingInteractorMock() @@ -22,12 +23,14 @@ class AppRespondSubscriberTests: XCTestCase { messageSigner = MessageSigner() let historyStorage = CodableStore(defaults: RuntimeKeyValueStorage(), identifier: StorageDomainIdentifiers.jsonRpcHistory.rawValue) rpcHistory = RPCHistory(keyValueStore: historyStorage) + pairingStorage = WCPairingStorageMock() sut = AppRespondSubscriber( networkingInteractor: networkingInteractor, logger: ConsoleLoggerMock(), rpcHistory: rpcHistory, signatureVerifier: messageSigner, - messageFormatter: messageFormatter) + messageFormatter: messageFormatter, + pairingStorage: pairingStorage) } func testMessageCompromisedFailure() { diff --git a/Tests/WalletConnectSignTests/Mocks/WCPairingStorageMock.swift b/Tests/TestingUtils/Mocks/WCPairingStorageMock.swift similarity index 95% rename from Tests/WalletConnectSignTests/Mocks/WCPairingStorageMock.swift rename to Tests/TestingUtils/Mocks/WCPairingStorageMock.swift index f3c11550e..664d206e2 100644 --- a/Tests/WalletConnectSignTests/Mocks/WCPairingStorageMock.swift +++ b/Tests/TestingUtils/Mocks/WCPairingStorageMock.swift @@ -1,5 +1,4 @@ import WalletConnectPairing -@testable import WalletConnectSign final class WCPairingStorageMock: WCPairingStorage { From 65c8fa31b6b864d1f133f451f2454a85e084d293 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 31 Aug 2022 10:12:20 +0200 Subject: [PATCH 2/4] update testing utils package dependencies --- Package.swift | 2 +- .../Mocks/WCPairingStorageMock.swift | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Package.swift b/Package.swift index 22c22aac8..9c3cd5b68 100644 --- a/Package.swift +++ b/Package.swift @@ -85,7 +85,7 @@ let package = Package( dependencies: ["WalletConnectKMS", "WalletConnectUtils", "TestingUtils"]), .target( name: "TestingUtils", - dependencies: ["WalletConnectUtils", "WalletConnectKMS", "JSONRPC"], + dependencies: ["WalletConnectUtils", "WalletConnectKMS", "JSONRPC", "WalletConnectPairing"], path: "Tests/TestingUtils"), .testTarget( name: "WalletConnectUtilsTests", diff --git a/Tests/TestingUtils/Mocks/WCPairingStorageMock.swift b/Tests/TestingUtils/Mocks/WCPairingStorageMock.swift index 664d206e2..35e737082 100644 --- a/Tests/TestingUtils/Mocks/WCPairingStorageMock.swift +++ b/Tests/TestingUtils/Mocks/WCPairingStorageMock.swift @@ -1,32 +1,32 @@ import WalletConnectPairing -final class WCPairingStorageMock: WCPairingStorage { +public final class WCPairingStorageMock: WCPairingStorage { - var onPairingExpiration: ((WCPairing) -> Void)? + public var onPairingExpiration: ((WCPairing) -> Void)? private(set) var pairings: [String: WCPairing] = [:] - func hasPairing(forTopic topic: String) -> Bool { + public func hasPairing(forTopic topic: String) -> Bool { pairings[topic] != nil } - func setPairing(_ pairing: WCPairing) { + public func setPairing(_ pairing: WCPairing) { pairings[pairing.topic] = pairing } - func getPairing(forTopic topic: String) -> WCPairing? { + public func getPairing(forTopic topic: String) -> WCPairing? { pairings[topic] } - func getAll() -> [WCPairing] { + public func getAll() -> [WCPairing] { Array(pairings.values) } - func delete(topic: String) { + public func delete(topic: String) { pairings[topic] = nil } - func deleteAll() { + public func deleteAll() { pairings = [:] } } From 97754f5e12b5229f22839b9c64d9aa0d4f461314 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 31 Aug 2022 10:22:24 +0200 Subject: [PATCH 3/4] run lint --- Example/DApp/Auth/AuthView.swift | 1 - Example/DApp/Auth/AuthViewModel.swift | 4 +- Example/DApp/SceneDelegate.swift | 2 +- Example/IntegrationTests/Auth/AuthTests.swift | 6 +- .../ApplicationLayer/SceneDelegate.swift | 2 +- .../Wallet/Scan/Views/ScanQR.swift | 16 +++--- .../Wallet/Scan/Views/ScanQRView.swift | 56 +++++++++---------- Sources/Auth/Auth.swift | 2 +- Sources/Auth/AuthClient.swift | 2 - .../Services/App/AppRespondSubscriber.swift | 2 - .../Common/NetworkingInteractor.swift | 2 +- Sources/Auth/Types/Errors/Reason.swift | 1 - .../WalletConnectSign/Sign/SignClient.swift | 1 - Tests/AuthTests/Mocks/AppMetadata.swift | 1 - .../Mocks/NetworkingInteractorMock.swift | 2 +- .../Mocks/BackgroundTaskRegistrarMock.swift | 4 +- .../Mocks/AppMetadata.swift | 1 - Tests/WalletConnectSignTests/Stub/Stubs.swift | 1 - .../WCPairingTests.swift | 10 ++-- 19 files changed, 53 insertions(+), 63 deletions(-) diff --git a/Example/DApp/Auth/AuthView.swift b/Example/DApp/Auth/AuthView.swift index f120f1871..5acdaf08c 100644 --- a/Example/DApp/Auth/AuthView.swift +++ b/Example/DApp/Auth/AuthView.swift @@ -98,4 +98,3 @@ struct CircleButtonStyle: ButtonStyle { .cornerRadius(8.0) } } - diff --git a/Example/DApp/Auth/AuthViewModel.swift b/Example/DApp/Auth/AuthViewModel.swift index 037e5131a..8c59d2a19 100644 --- a/Example/DApp/Auth/AuthViewModel.swift +++ b/Example/DApp/Auth/AuthViewModel.swift @@ -35,7 +35,7 @@ final class AuthViewModel: ObservableObject { } func walletDidPressed() { - + } func deeplinkPressed() { @@ -47,7 +47,7 @@ final class AuthViewModel: ObservableObject { private extension AuthViewModel { func setupSubscriptions() { - Auth.instance.authResponsePublisher.sink { [weak self] (id, result) in + Auth.instance.authResponsePublisher.sink { [weak self] (_, result) in switch result { case .success(let cacao): self?.state = .signed(cacao) diff --git a/Example/DApp/SceneDelegate.swift b/Example/DApp/SceneDelegate.swift index 163421bcc..eeaaf2369 100644 --- a/Example/DApp/SceneDelegate.swift +++ b/Example/DApp/SceneDelegate.swift @@ -18,7 +18,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { private let authCoordinator = AuthCoordinator() func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - Relay.configure(projectId: "8ba9ee138960775e5231b70cc5ef1c3a",socketFactory: SocketFactory()) + Relay.configure(projectId: "8ba9ee138960775e5231b70cc5ef1c3a", socketFactory: SocketFactory()) setupWindow(scene: scene) } diff --git a/Example/IntegrationTests/Auth/AuthTests.swift b/Example/IntegrationTests/Auth/AuthTests.swift index 1c2deff7d..43d56d372 100644 --- a/Example/IntegrationTests/Auth/AuthTests.swift +++ b/Example/IntegrationTests/Auth/AuthTests.swift @@ -72,7 +72,7 @@ final class AuthTests: XCTestCase { } } .store(in: &publishers) - app.authResponsePublisher.sink { (id, result) in + app.authResponsePublisher.sink { (_, result) in guard case .success = result else { XCTFail(); return } responseExpectation.fulfill() } @@ -90,7 +90,7 @@ final class AuthTests: XCTestCase { } } .store(in: &publishers) - app.authResponsePublisher.sink { (id, result) in + app.authResponsePublisher.sink { (_, result) in guard case .failure(let error) = result else { XCTFail(); return } XCTAssertEqual(error, .userRejeted) responseExpectation.fulfill() @@ -111,7 +111,7 @@ final class AuthTests: XCTestCase { } } .store(in: &publishers) - app.authResponsePublisher.sink { (id, result) in + app.authResponsePublisher.sink { (_, result) in guard case .failure(let error) = result else { XCTFail(); return } XCTAssertEqual(error, .signatureVerificationFailed) responseExpectation.fulfill() diff --git a/Example/Showcase/Classes/ApplicationLayer/SceneDelegate.swift b/Example/Showcase/Classes/ApplicationLayer/SceneDelegate.swift index 8660ed4c5..43335bd7d 100644 --- a/Example/Showcase/Classes/ApplicationLayer/SceneDelegate.swift +++ b/Example/Showcase/Classes/ApplicationLayer/SceneDelegate.swift @@ -12,7 +12,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { MigrationConfigurator(app: app), ThirdPartyConfigurator(), ApplicationConfigurator(app: app), - AppearanceConfigurator(), + AppearanceConfigurator() ] } diff --git a/Example/Showcase/Classes/PresentationLayer/Wallet/Scan/Views/ScanQR.swift b/Example/Showcase/Classes/PresentationLayer/Wallet/Scan/Views/ScanQR.swift index 0bb3369d6..8b78b3098 100644 --- a/Example/Showcase/Classes/PresentationLayer/Wallet/Scan/Views/ScanQR.swift +++ b/Example/Showcase/Classes/PresentationLayer/Wallet/Scan/Views/ScanQR.swift @@ -1,28 +1,28 @@ import SwiftUI struct ScanQR: UIViewRepresentable { - + class Coordinator: ScanQRViewDelegate { private let onValue: (String) -> Void private let onError: (Error) -> Void - + init(onValue: @escaping (String) -> Void, onError: @escaping (Error) -> Void) { self.onValue = onValue self.onError = onError } - + func scanDidDetect(value: String) { onValue(value) } - + func scanDidFail(with error: Error) { onError(error) } } - + let onValue: (String) -> Void let onError: (Error) -> Void - + func makeUIView(context: Context) -> ScanQRView { let view = ScanQRView() view.delegate = context.coordinator @@ -30,9 +30,9 @@ struct ScanQR: UIViewRepresentable { } func updateUIView(_ uiView: ScanQRView, context: Context) { - + } - + func makeCoordinator() -> Coordinator { return Coordinator(onValue: onValue, onError: onError) } diff --git a/Example/Showcase/Classes/PresentationLayer/Wallet/Scan/Views/ScanQRView.swift b/Example/Showcase/Classes/PresentationLayer/Wallet/Scan/Views/ScanQRView.swift index c3c8327b4..2d9db1056 100644 --- a/Example/Showcase/Classes/PresentationLayer/Wallet/Scan/Views/ScanQRView.swift +++ b/Example/Showcase/Classes/PresentationLayer/Wallet/Scan/Views/ScanQRView.swift @@ -10,17 +10,17 @@ final class ScanQRView: UIView { enum Errors: Error { case deviceNotFound } - + weak var delegate: ScanQRViewDelegate? - + private let targetSize = CGSize( width: UIScreen.main.bounds.width - 32.0, height: UIScreen.main.bounds.width - 32.0 ) - + private var videoPreviewLayer: AVCaptureVideoPreviewLayer? private var captureSession: AVCaptureSession? - + private lazy var borderView: UIView = { let borderView = ScanTargetView(radius: 24.0, color: .white, strokeWidth: 2.0, length: 36.0) borderView.alpha = 0.85 @@ -34,21 +34,21 @@ final class ScanQRView: UIView { bluredView.layer.mask = createMaskLayer() return bluredView }() - + override init(frame: CGRect) { super.init(frame: frame) - + setupView() startCaptureSession() } - + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } - + override func layoutSubviews() { super.layoutSubviews() - + updateFrames() updateOrientation() } @@ -61,7 +61,7 @@ final class ScanQRView: UIView { // MARK: AVCaptureMetadataOutputObjectsDelegate extension ScanQRView: AVCaptureMetadataOutputObjectsDelegate { - + func metadataOutput(_ metadataOutput: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { guard let metadataObject = metadataObjects.first as? AVMetadataMachineReadableCodeObject, @@ -76,14 +76,14 @@ extension ScanQRView: AVCaptureMetadataOutputObjectsDelegate { // MARK: Privates private extension ScanQRView { - + private func setupView() { backgroundColor = .black addSubview(bluredView) addSubview(borderView) } - + private func createMaskLayer() -> CAShapeLayer { let maskPath = UIBezierPath(rect: bounds) let rect = UIBezierPath( @@ -98,62 +98,62 @@ private extension ScanQRView { ) maskPath.append(rect) maskPath.usesEvenOddFillRule = true - + let maskLayer = CAShapeLayer() maskLayer.path = maskPath.cgPath maskLayer.fillRule = .evenOdd return maskLayer } - + private func startCaptureSession() { DispatchQueue.global().async { [weak self] in guard let self = self else { return } - + do { let session = try self.createCaptureSession() session.startRunning() self.captureSession = session - + DispatchQueue.main.async { self.setupVideoPreviewLayer(with: session) } } catch { DispatchQueue.main.async { self.delegate?.scanDidFail(with: error) } } } } - + private func createCaptureSession() throws -> AVCaptureSession { guard let captureDevice = AVCaptureDevice.default(for: .video) else { throw Errors.deviceNotFound } - + let input = try AVCaptureDeviceInput(device: captureDevice) - + let session = AVCaptureSession() session.addInput(input) - + let captureMetadataOutput = AVCaptureMetadataOutput() captureMetadataOutput.setMetadataObjectsDelegate(self, queue: .main) session.addOutput(captureMetadataOutput) - + captureMetadataOutput.metadataObjectTypes = [.qr] - + return session } - + private func stopCaptureSession() { captureSession?.stopRunning() captureSession = nil } - + private func setupVideoPreviewLayer(with session: AVCaptureSession) { let previewLayer = AVCaptureVideoPreviewLayer(session: session) previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill previewLayer.frame = layer.bounds videoPreviewLayer = previewLayer - + layer.insertSublayer(previewLayer, at: 0) } - + private func updateFrames() { borderView.frame.size = targetSize borderView.center = center @@ -161,13 +161,13 @@ private extension ScanQRView { bluredView.layer.mask = createMaskLayer() videoPreviewLayer?.frame = layer.bounds } - + private func updateOrientation() { guard let connection = videoPreviewLayer?.connection else { return } let previewLayerConnection: AVCaptureConnection = connection - + guard previewLayerConnection.isVideoOrientationSupported else { return } diff --git a/Sources/Auth/Auth.swift b/Sources/Auth/Auth.swift index 002671891..b209104bd 100644 --- a/Sources/Auth/Auth.swift +++ b/Sources/Auth/Auth.swift @@ -25,7 +25,7 @@ public class Auth { account: config.account, relayClient: Relay.instance) }() - + private static var config: Config? private init() { } diff --git a/Sources/Auth/AuthClient.swift b/Sources/Auth/AuthClient.swift index f4da23fa5..6b45e3183 100644 --- a/Sources/Auth/AuthClient.swift +++ b/Sources/Auth/AuthClient.swift @@ -4,7 +4,6 @@ import WalletConnectUtils import WalletConnectPairing import WalletConnectRelay - /// WalletConnect Auth Client /// /// Cannot be instantiated outside of the SDK @@ -41,7 +40,6 @@ public class AuthClient { /// An object that loggs SDK's errors and info messages public let logger: ConsoleLogging - // MARK: - Private Properties private var authResponsePublisherSubject = PassthroughSubject<(id: RPCID, result: Result), Never>() diff --git a/Sources/Auth/Services/App/AppRespondSubscriber.swift b/Sources/Auth/Services/App/AppRespondSubscriber.swift index 84a0d241f..a0daf9e1d 100644 --- a/Sources/Auth/Services/App/AppRespondSubscriber.swift +++ b/Sources/Auth/Services/App/AppRespondSubscriber.swift @@ -64,11 +64,9 @@ class AppRespondSubscriber { }.store(in: &publishers) } - private func activatePairingIfNeeded(id: RPCID) { guard let record = rpcHistory.get(recordId: id) else { return } let pairingTopic = record.topic - print(pairingTopic) guard var pairing = pairingStorage.getPairing(forTopic: pairingTopic) else { return } if !pairing.active { pairing.activate() diff --git a/Sources/Auth/Services/Common/NetworkingInteractor.swift b/Sources/Auth/Services/Common/NetworkingInteractor.swift index 24419b295..e66e97a77 100644 --- a/Sources/Auth/Services/Common/NetworkingInteractor.swift +++ b/Sources/Auth/Services/Common/NetworkingInteractor.swift @@ -11,7 +11,7 @@ protocol NetworkInteracting { func subscribe(topic: String) async throws func unsubscribe(topic: String) func request(_ request: RPCRequest, topic: String, tag: Int, envelopeType: Envelope.EnvelopeType) async throws - func requestNetworkAck(_ request: RPCRequest, topic: String, tag: Int) async throws + func requestNetworkAck(_ request: RPCRequest, topic: String, tag: Int) async throws func respond(topic: String, response: RPCResponse, tag: Int, envelopeType: Envelope.EnvelopeType) async throws func respondError(topic: String, requestId: RPCID, tag: Int, reason: Reason, envelopeType: Envelope.EnvelopeType) async throws } diff --git a/Sources/Auth/Types/Errors/Reason.swift b/Sources/Auth/Types/Errors/Reason.swift index bbf491fdd..4822fe64c 100644 --- a/Sources/Auth/Types/Errors/Reason.swift +++ b/Sources/Auth/Types/Errors/Reason.swift @@ -4,4 +4,3 @@ protocol Reason { var code: Int { get } var message: String { get } } - diff --git a/Sources/WalletConnectSign/Sign/SignClient.swift b/Sources/WalletConnectSign/Sign/SignClient.swift index d00e54242..72fa56e24 100644 --- a/Sources/WalletConnectSign/Sign/SignClient.swift +++ b/Sources/WalletConnectSign/Sign/SignClient.swift @@ -308,7 +308,6 @@ public final class SignClient { return WalletConnectUtils.JsonRpcRecord(id: record.id, topic: record.topic, request: request, response: record.response, chainId: record.chainId) } - #if DEBUG /// Delete all stored data such as: pairings, sessions, keys /// diff --git a/Tests/AuthTests/Mocks/AppMetadata.swift b/Tests/AuthTests/Mocks/AppMetadata.swift index 2f8d6a558..75d48acb1 100644 --- a/Tests/AuthTests/Mocks/AppMetadata.swift +++ b/Tests/AuthTests/Mocks/AppMetadata.swift @@ -1,4 +1,3 @@ - import Foundation import WalletConnectPairing diff --git a/Tests/AuthTests/Mocks/NetworkingInteractorMock.swift b/Tests/AuthTests/Mocks/NetworkingInteractorMock.swift index a3364de40..1a9c03790 100644 --- a/Tests/AuthTests/Mocks/NetworkingInteractorMock.swift +++ b/Tests/AuthTests/Mocks/NetworkingInteractorMock.swift @@ -33,7 +33,7 @@ struct NetworkingInteractorMock: NetworkInteracting { } func respondError(topic: String, requestId: RPCID, tag: Int, reason: Reason, envelopeType: Envelope.EnvelopeType) async throws { - + } func requestNetworkAck(_ request: RPCRequest, topic: String, tag: Int) async throws { diff --git a/Tests/RelayerTests/Mocks/BackgroundTaskRegistrarMock.swift b/Tests/RelayerTests/Mocks/BackgroundTaskRegistrarMock.swift index d8f895242..52d49d774 100644 --- a/Tests/RelayerTests/Mocks/BackgroundTaskRegistrarMock.swift +++ b/Tests/RelayerTests/Mocks/BackgroundTaskRegistrarMock.swift @@ -3,12 +3,12 @@ import Foundation class BackgroundTaskRegistrarMock: BackgroundTaskRegistering { var completion: (() -> Void)? - + func register(name: String, completion: @escaping () -> Void) { self.completion = completion } func invalidate() { - + } } diff --git a/Tests/WalletConnectSignTests/Mocks/AppMetadata.swift b/Tests/WalletConnectSignTests/Mocks/AppMetadata.swift index 2f8d6a558..75d48acb1 100644 --- a/Tests/WalletConnectSignTests/Mocks/AppMetadata.swift +++ b/Tests/WalletConnectSignTests/Mocks/AppMetadata.swift @@ -1,4 +1,3 @@ - import Foundation import WalletConnectPairing diff --git a/Tests/WalletConnectSignTests/Stub/Stubs.swift b/Tests/WalletConnectSignTests/Stub/Stubs.swift index 7f80b8da9..a17ad98a8 100644 --- a/Tests/WalletConnectSignTests/Stub/Stubs.swift +++ b/Tests/WalletConnectSignTests/Stub/Stubs.swift @@ -5,7 +5,6 @@ import WalletConnectUtils import TestingUtils import WalletConnectPairing - extension Pairing { static func stub(expiryDate: Date = Date(timeIntervalSinceNow: 10000), topic: String = String.generateTopic()) -> Pairing { Pairing(topic: topic, peer: nil, expiryDate: expiryDate) diff --git a/Tests/WalletConnectSignTests/WCPairingTests.swift b/Tests/WalletConnectSignTests/WCPairingTests.swift index ca6872e24..6dcad44a0 100644 --- a/Tests/WalletConnectSignTests/WCPairingTests.swift +++ b/Tests/WalletConnectSignTests/WCPairingTests.swift @@ -41,7 +41,7 @@ final class WCPairingTests: XCTestCase { try? pairing.updateExpiry() XCTAssertEqual(pairing.expiryDate, activeExpiry) } - + func testUpdateExpiryForUri() { var pairing = WCPairing(uri: WalletConnectURI.stub()) let activeExpiry = referenceDate.advanced(by: WCPairing.timeToLiveActive) @@ -57,7 +57,7 @@ final class WCPairingTests: XCTestCase { XCTAssertTrue(pairing.active) XCTAssertEqual(pairing.expiryDate, activeExpiry) } - + func testActivateURI() { var pairing = WCPairing(uri: WalletConnectURI.stub()) let activeExpiry = referenceDate.advanced(by: WCPairing.timeToLiveActive) @@ -66,14 +66,14 @@ final class WCPairingTests: XCTestCase { XCTAssertTrue(pairing.active) XCTAssertEqual(pairing.expiryDate, activeExpiry) } - + func testUpdateExpiryWhenValueIsGreaterThanMax() { var pairing = WCPairing(topic: "", relay: .stub(), peerMetadata: .stub(), expiryDate: referenceDate) XCTAssertThrowsError(try pairing.updateExpiry(40 * .day)) { error in XCTAssertEqual(error as! WCPairing.Errors, WCPairing.Errors.invalidUpdateExpiryValue) } } - + func testUpdateExpiryWhenNewExpiryDateIsLessThanExpiryDate() { let expiryDate = referenceDate.advanced(by: 40 * .day) var pairing = WCPairing(topic: "", relay: .stub(), peerMetadata: .stub(), expiryDate: expiryDate) @@ -89,7 +89,7 @@ final class WCPairingTests: XCTestCase { XCTAssertTrue(pairing.active) XCTAssertEqual(referenceDate.advanced(by: 30 * .day), pairing.expiryDate) } - + func testActivateWhenUpdateExpiryIsInvalid() { let expiryDate = referenceDate.advanced(by: 40 * .day) var pairing = WCPairing(topic: "", relay: .stub(), peerMetadata: .stub(), expiryDate: expiryDate) From 50ed654506db0977f1817319248ae9ad552b7e70 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 31 Aug 2022 10:48:48 +0200 Subject: [PATCH 4/4] fix test --- .../Auth/Services/App/AppRespondSubscriber.swift | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/Sources/Auth/Services/App/AppRespondSubscriber.swift b/Sources/Auth/Services/App/AppRespondSubscriber.swift index a0daf9e1d..3a501b718 100644 --- a/Sources/Auth/Services/App/AppRespondSubscriber.swift +++ b/Sources/Auth/Services/App/AppRespondSubscriber.swift @@ -42,7 +42,11 @@ class AppRespondSubscriber { activatePairingIfNeeded(id: requestId) networkingInteractor.unsubscribe(topic: subscriptionPayload.topic) - handleIfError(response: response) + if let errorResponse = response.error, + let error = AuthError(code: errorResponse.code) { + onResponse?(requestId, .failure(error)) + return + } guard let cacao = try? response.result?.get(Cacao.self), @@ -74,13 +78,4 @@ class AppRespondSubscriber { try? pairing.updateExpiry() } } - - private func handleIfError(response: RPCResponse) { - if let errorResponse = response.error, - let id = response.id, - let error = AuthError(code: errorResponse.code) { - onResponse?(id, .failure(error)) - return - } - } }