Skip to content

Commit

Permalink
Merge pull request #1187 from WalletConnect/dapp-extend-session
Browse files Browse the repository at this point in the history
[Sign] Dapp extend session exp
  • Loading branch information
alexander-lsvk authored Oct 25, 2023
2 parents 6c7c129 + 20a5f59 commit f7ffc79
Show file tree
Hide file tree
Showing 12 changed files with 216 additions and 113 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ import SwiftUI

struct ConnectionDetailsView: View {
@EnvironmentObject var presenter: ConnectionDetailsPresenter


private var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss E, d MMM y"
return formatter
}

var body: some View {
ZStack {
Color.grey100
Expand Down Expand Up @@ -145,6 +151,39 @@ struct ConnectionDetailsView: View {
.padding(.top, 30)
}

VStack(alignment: .leading) {
Text("Expiry")
.font(.system(size: 15, weight: .semibold, design: .rounded))
.foregroundColor(.whiteBackground)
.padding(.horizontal, 8)
.padding(.vertical, 5)
.background(Color.grey70)
.cornerRadius(28, corners: .allCorners)
.padding(.leading, 15)
.padding(.top, 9)

VStack(spacing: 0) {
TagsView(items: [dateFormatter.string(from: presenter.session.expiryDate)]) {
Text($0)
.foregroundColor(.cyanBackround)
.font(.system(size: 13, weight: .semibold, design: .rounded))
.padding(.horizontal, 8)
.padding(.vertical, 3)
.background(Color.cyanBackround.opacity(0.2))
.cornerRadius(10, corners: .allCorners)
}
.padding(10)
}
.background(Color.whiteBackground)
.cornerRadius(20, corners: .allCorners)
.padding(.horizontal, 5)
.padding(.bottom, 5)
}
.background(Color("grey95"))
.cornerRadius(25, corners: .allCorners)
.padding(.horizontal, 20)
.padding(.top, 30)

Button {
presenter.onDelete()
} label: {
Expand Down
4 changes: 2 additions & 2 deletions Sources/WalletConnectSign/Engine/Common/SessionEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ final class SessionEngine {
func hasSession(for topic: String) -> Bool {
return sessionStore.hasSession(forTopic: topic)
}

func getSessions() -> [Session] {
sessionStore.getAll().map {$0.publicRepresentation()}
sessionStore.getAll().map { $0.publicRepresentation() }
}

func request(_ request: Request) async throws {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import Foundation
import Combine

final class SessionExtendRequestSubscriber {
var onExtend: ((String, Date) -> Void)?

private let sessionStore: WCSessionStorage
private let networkingInteractor: NetworkInteracting
private var publishers = [AnyCancellable]()
private let logger: ConsoleLogging

init(
networkingInteractor: NetworkInteracting,
sessionStore: WCSessionStorage,
logger: ConsoleLogging
) {
self.networkingInteractor = networkingInteractor
self.sessionStore = sessionStore
self.logger = logger

setupSubscriptions()
}
}

// MARK: - Private functions
extension SessionExtendRequestSubscriber {
private func setupSubscriptions() {
networkingInteractor.requestSubscription(on: SessionExtendProtocolMethod())
.sink { [unowned self] (payload: RequestSubscriptionPayload<SessionType.UpdateExpiryParams>) in
onSessionUpdateExpiry(payload: payload, updateExpiryParams: payload.request)
}.store(in: &publishers)
}

private func onSessionUpdateExpiry(payload: SubscriptionPayload, updateExpiryParams: SessionType.UpdateExpiryParams) {
let protocolMethod = SessionExtendProtocolMethod()
let topic = payload.topic
guard var session = sessionStore.getSession(forTopic: topic) else {
return respondError(payload: payload, reason: .noSessionForTopic, protocolMethod: protocolMethod)
}
guard session.peerIsController else {
return respondError(payload: payload, reason: .unauthorizedExtendRequest, protocolMethod: protocolMethod)
}
do {
try session.updateExpiry(to: updateExpiryParams.expiry)
} catch {
return respondError(payload: payload, reason: .invalidExtendRequest, protocolMethod: protocolMethod)
}
sessionStore.setSession(session)

Task(priority: .high) {
try await networkingInteractor.respondSuccess(topic: payload.topic, requestId: payload.id, protocolMethod: protocolMethod)
}

onExtend?(session.topic, session.expiryDate)
}

private func respondError(payload: SubscriptionPayload, reason: SignReasonCode, protocolMethod: ProtocolMethod) {
Task(priority: .high) {
do {
try await networkingInteractor.respondError(topic: payload.topic, requestId: payload.id, protocolMethod: protocolMethod, reason: reason)
} catch {
logger.error("Respond Error failed with: \(error.localizedDescription)")
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import Foundation

final class SessionExtendRequester {
private let sessionStore: WCSessionStorage
private let networkingInteractor: NetworkInteracting

init(
sessionStore: WCSessionStorage,
networkingInteractor: NetworkInteracting
) {
self.sessionStore = sessionStore
self.networkingInteractor = networkingInteractor
}

func extend(topic: String, by ttl: Int64) async throws {
guard var session = sessionStore.getSession(forTopic: topic) else {
throw WalletConnectError.noSessionMatchingTopic(topic)
}

let protocolMethod = SessionExtendProtocolMethod()
try session.updateExpiry(by: ttl)
let newExpiry = Int64(session.expiryDate.timeIntervalSince1970)
sessionStore.setSession(session)
let request = RPCRequest(method: protocolMethod.method, params: SessionType.UpdateExpiryParams(expiry: newExpiry))
try await networkingInteractor.request(request, topic: topic, protocolMethod: protocolMethod)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import Foundation
import Combine

final class SessionExtendResponseSubscriber {
var onExtend: ((String, Date) -> Void)?

private let sessionStore: WCSessionStorage
private let networkingInteractor: NetworkInteracting
private var publishers = [AnyCancellable]()
private let logger: ConsoleLogging

init(
networkingInteractor: NetworkInteracting,
sessionStore: WCSessionStorage,
logger: ConsoleLogging
) {
self.networkingInteractor = networkingInteractor
self.sessionStore = sessionStore
self.logger = logger

setupSubscriptions()
}

// MARK: - Handle Response
private func setupSubscriptions() {
networkingInteractor.responseSubscription(on: SessionExtendProtocolMethod())
.sink { [unowned self] (payload: ResponseSubscriptionPayload<SessionType.UpdateExpiryParams, RPCResult>) in
handleUpdateExpiryResponse(payload: payload)
}
.store(in: &publishers)
}

private func handleUpdateExpiryResponse(payload: ResponseSubscriptionPayload<SessionType.UpdateExpiryParams, RPCResult>) {
guard var session = sessionStore.getSession(forTopic: payload.topic) else { return }
switch payload.response {
case .response:
do {
try session.updateExpiry(to: payload.request.expiry)
sessionStore.setSession(session)
onExtend?(session.topic, session.expiryDate)
} catch {
logger.error("Update expiry error: \(error.localizedDescription)")
}
case .error:
logger.error("Peer failed to extend session")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import Foundation
import Combine

final class ControllerSessionStateMachine {

var onNamespacesUpdate: ((String, [String: SessionNamespace]) -> Void)?
var onExtend: ((String, Date) -> Void)?

private let sessionStore: WCSessionStorage
private let networkingInteractor: NetworkInteracting
Expand Down Expand Up @@ -35,31 +33,13 @@ final class ControllerSessionStateMachine {
try await networkingInteractor.request(request, topic: topic, protocolMethod: protocolMethod)
}

func extend(topic: String, by ttl: Int64) async throws {
var session = try getSession(for: topic)
let protocolMethod = SessionExtendProtocolMethod()
try validateController(session)
try session.updateExpiry(by: ttl)
let newExpiry = Int64(session.expiryDate.timeIntervalSince1970 )
sessionStore.setSession(session)
let request = RPCRequest(method: protocolMethod.method, params: SessionType.UpdateExpiryParams(expiry: newExpiry))
try await networkingInteractor.request(request, topic: topic, protocolMethod: protocolMethod)
}

// MARK: - Handle Response

private func setupSubscriptions() {
networkingInteractor.responseSubscription(on: SessionUpdateProtocolMethod())
.sink { [unowned self] (payload: ResponseSubscriptionPayload<SessionType.UpdateParams, RPCResult>) in
handleUpdateResponse(payload: payload)
}
.store(in: &publishers)

networkingInteractor.responseSubscription(on: SessionExtendProtocolMethod())
.sink { [unowned self] (payload: ResponseSubscriptionPayload<SessionType.UpdateExpiryParams, RPCResult>) in
handleUpdateExpiryResponse(payload: payload)
}
.store(in: &publishers)
}

private func handleUpdateResponse(payload: ResponseSubscriptionPayload<SessionType.UpdateParams, RPCResult>) {
Expand All @@ -80,22 +60,6 @@ final class ControllerSessionStateMachine {
}
}

private func handleUpdateExpiryResponse(payload: ResponseSubscriptionPayload<SessionType.UpdateExpiryParams, RPCResult>) {
guard var session = sessionStore.getSession(forTopic: payload.topic) else { return }
switch payload.response {
case .response:
do {
try session.updateExpiry(to: payload.request.expiry)
sessionStore.setSession(session)
onExtend?(session.topic, session.expiryDate)
} catch {
logger.error("Update expiry error: \(error.localizedDescription)")
}
case .error:
logger.error("Peer failed to extend session")
}
}

// MARK: - Private
private func getSession(for topic: String) throws -> WCSession {
if let session = sessionStore.getSession(forTopic: topic) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ import Foundation
import Combine

final class NonControllerSessionStateMachine {

var onNamespacesUpdate: ((String, [String: SessionNamespace]) -> Void)?
var onExtend: ((String, Date) -> Void)?

private let sessionStore: WCSessionStorage
private let networkingInteractor: NetworkInteracting
private let kms: KeyManagementServiceProtocol
private var publishers = [AnyCancellable]()
private let logger: ConsoleLogging

init(networkingInteractor: NetworkInteracting,
kms: KeyManagementServiceProtocol,
sessionStore: WCSessionStorage,
logger: ConsoleLogging) {
init(
networkingInteractor: NetworkInteracting,
kms: KeyManagementServiceProtocol,
sessionStore: WCSessionStorage,
logger: ConsoleLogging
) {
self.networkingInteractor = networkingInteractor
self.kms = kms
self.sessionStore = sessionStore
Expand All @@ -28,11 +28,6 @@ final class NonControllerSessionStateMachine {
.sink { [unowned self] (payload: RequestSubscriptionPayload<SessionType.UpdateParams>) in
onSessionUpdateNamespacesRequest(payload: payload, updateParams: payload.request)
}.store(in: &publishers)

networkingInteractor.requestSubscription(on: SessionExtendProtocolMethod())
.sink { [unowned self] (payload: RequestSubscriptionPayload<SessionType.UpdateExpiryParams>) in
onSessionUpdateExpiry(payload: payload, updateExpiryParams: payload.request)
}.store(in: &publishers)
}

private func respondError(payload: SubscriptionPayload, reason: SignReasonCode, protocolMethod: ProtocolMethod) {
Expand Down Expand Up @@ -72,27 +67,4 @@ final class NonControllerSessionStateMachine {

onNamespacesUpdate?(session.topic, updateParams.namespaces)
}

private func onSessionUpdateExpiry(payload: SubscriptionPayload, updateExpiryParams: SessionType.UpdateExpiryParams) {
let protocolMethod = SessionExtendProtocolMethod()
let topic = payload.topic
guard var session = sessionStore.getSession(forTopic: topic) else {
return respondError(payload: payload, reason: .noSessionForTopic, protocolMethod: protocolMethod)
}
guard session.peerIsController else {
return respondError(payload: payload, reason: .unauthorizedExtendRequest, protocolMethod: protocolMethod)
}
do {
try session.updateExpiry(to: updateExpiryParams.expiry)
} catch {
return respondError(payload: payload, reason: .invalidExtendRequest, protocolMethod: protocolMethod)
}
sessionStore.setSession(session)

Task(priority: .high) {
try await networkingInteractor.respondSuccess(topic: payload.topic, requestId: payload.id, protocolMethod: protocolMethod)
}

onExtend?(session.topic, session.expiryDate)
}
}
Loading

0 comments on commit f7ffc79

Please sign in to comment.