diff --git a/Sources/WalletConnectUtils/RPCHistory/RPCHistory.swift b/Sources/WalletConnectUtils/RPCHistory/RPCHistory.swift index 84f93768f..b310586d0 100644 --- a/Sources/WalletConnectUtils/RPCHistory/RPCHistory.swift +++ b/Sources/WalletConnectUtils/RPCHistory/RPCHistory.swift @@ -35,14 +35,14 @@ public final class RPCHistory { try? storage.get(key: recordId.string) } - public func set(_ request: RPCRequest, forTopic topic: String, emmitedBy origin: Record.Origin) throws { + public func set(_ request: RPCRequest, forTopic topic: String, emmitedBy origin: Record.Origin, time: TimeProvider = DefaultTimeProvider()) throws { guard let id = request.id else { throw HistoryError.unidentifiedRequest } guard get(recordId: id) == nil else { throw HistoryError.requestDuplicateNotAllowed } - let record = Record(id: id, topic: topic, origin: origin, request: request, response: nil, timestamp: Date()) + let record = Record(id: id, topic: topic, origin: origin, request: request, response: nil, timestamp: time.currentDate) storage.set(record, forKey: "\(record.id)") } diff --git a/Sources/WalletConnectUtils/TimeProvider.swift b/Sources/WalletConnectUtils/TimeProvider.swift new file mode 100644 index 000000000..86732b6f0 --- /dev/null +++ b/Sources/WalletConnectUtils/TimeProvider.swift @@ -0,0 +1,12 @@ +import Foundation + +public protocol TimeProvider { + var currentDate: Date { get } +} + +public struct DefaultTimeProvider: TimeProvider { + public init() {} + public var currentDate: Date { + return Date() + } +} diff --git a/Tests/WalletConnectUtilsTests/RPCHistoryTests.swift b/Tests/WalletConnectUtilsTests/RPCHistoryTests.swift index 82becd7b8..b4023eaff 100644 --- a/Tests/WalletConnectUtilsTests/RPCHistoryTests.swift +++ b/Tests/WalletConnectUtilsTests/RPCHistoryTests.swift @@ -105,4 +105,27 @@ final class RPCHistoryTests: XCTestCase { XCTAssertEqual(expectedError, error as? RPCHistory.HistoryError) } } + + func testRemoveOutdated() throws { + let request1 = RPCRequest.stub() + let request2 = RPCRequest.stub() + + let time1 = TestTimeProvider(currentDate: .distantPast) + let time2 = TestTimeProvider(currentDate: Date()) + + try sut.set(request1, forTopic: .randomTopic(), emmitedBy: .local, time: time1) + try sut.set(request2, forTopic: .randomTopic(), emmitedBy: .local, time: time2) + + XCTAssertEqual(sut.get(recordId: request1.id!)?.request, request1) + XCTAssertEqual(sut.get(recordId: request2.id!)?.request, request2) + + sut.removeOutdated() + + XCTAssertEqual(sut.get(recordId: request1.id!)?.request, nil) + XCTAssertEqual(sut.get(recordId: request2.id!)?.request, request2) + } + + struct TestTimeProvider: TimeProvider { + var currentDate: Date + } }