Skip to content

Commit

Permalink
Merge branch 'develop' of github.com:WalletConnect/WalletConnectSwift…
Browse files Browse the repository at this point in the history
…V2 into reorder-propose-response-and-settle-request

# Conflicts:
#	Sources/WalletConnectSign/Engine/Common/ApproveEngine.swift
  • Loading branch information
llbartekll committed Aug 23, 2024
2 parents 794ed31 + b9246a5 commit f4d4ba4
Show file tree
Hide file tree
Showing 34 changed files with 393 additions and 138 deletions.
2 changes: 1 addition & 1 deletion Example/DApp/SceneDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
imageUrl: "https://avatars.githubusercontent.com/u/37784886?s=200&v=4",
order: 1,
mobileLink: "rn-web3wallet://",
linkMode: "https://lab.web3modal.com/walletkit_rn"
linkMode: "https://lab.web3modal.com/rn_walletkit"
),
.init(
id: "flutter-sample",
Expand Down
4 changes: 0 additions & 4 deletions Example/ExampleApp.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,6 @@
C5DD5BE1294E09E3008FD3A4 /* Web3Wallet in Frameworks */ = {isa = PBXBuildFile; productRef = C5DD5BE0294E09E3008FD3A4 /* Web3Wallet */; };
C5F32A2C2954814200A6476E /* ConnectionDetailsModule.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5F32A2B2954814200A6476E /* ConnectionDetailsModule.swift */; };
C5F32A2E2954814A00A6476E /* ConnectionDetailsRouter.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5F32A2D2954814A00A6476E /* ConnectionDetailsRouter.swift */; };
C5F32A302954816100A6476E /* ConnectionDetailsInteractor.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5F32A2F2954816100A6476E /* ConnectionDetailsInteractor.swift */; };
C5F32A322954816C00A6476E /* ConnectionDetailsPresenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5F32A312954816C00A6476E /* ConnectionDetailsPresenter.swift */; };
C5F32A342954817600A6476E /* ConnectionDetailsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5F32A332954817600A6476E /* ConnectionDetailsView.swift */; };
C5F32A362954FE3C00A6476E /* Colors.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C5F32A352954FE3C00A6476E /* Colors.xcassets */; };
Expand Down Expand Up @@ -654,7 +653,6 @@
C5BE021A2AF79B960064FC88 /* SessionAccountModule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionAccountModule.swift; sourceTree = "<group>"; };
C5F32A2B2954814200A6476E /* ConnectionDetailsModule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionDetailsModule.swift; sourceTree = "<group>"; };
C5F32A2D2954814A00A6476E /* ConnectionDetailsRouter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionDetailsRouter.swift; sourceTree = "<group>"; };
C5F32A2F2954816100A6476E /* ConnectionDetailsInteractor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionDetailsInteractor.swift; sourceTree = "<group>"; };
C5F32A312954816C00A6476E /* ConnectionDetailsPresenter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionDetailsPresenter.swift; sourceTree = "<group>"; };
C5F32A332954817600A6476E /* ConnectionDetailsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionDetailsView.swift; sourceTree = "<group>"; };
C5F32A352954FE3C00A6476E /* Colors.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Colors.xcassets; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1805,7 +1803,6 @@
children = (
C5F32A2B2954814200A6476E /* ConnectionDetailsModule.swift */,
C5F32A2D2954814A00A6476E /* ConnectionDetailsRouter.swift */,
C5F32A2F2954816100A6476E /* ConnectionDetailsInteractor.swift */,
C5F32A312954816C00A6476E /* ConnectionDetailsPresenter.swift */,
C5F32A332954817600A6476E /* ConnectionDetailsView.swift */,
);
Expand Down Expand Up @@ -2533,7 +2530,6 @@
C55D34AF2965FB750004314A /* SessionProposalPresenter.swift in Sources */,
A5D610D22AB35B1100C20083 /* Listings.swift in Sources */,
A5B4F7C82ABB21190099AF7C /* CacheAsyncImage.swift in Sources */,
C5F32A302954816100A6476E /* ConnectionDetailsInteractor.swift in Sources */,
847BD1E8298A806800076C90 /* NotificationsView.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ final class ConnectionDetailsModule {
@discardableResult
static func create(app: Application, session: Session) -> UIViewController {
let router = ConnectionDetailsRouter(app: app)
let interactor = ConnectionDetailsInteractor()
let presenter = ConnectionDetailsPresenter(
interactor: interactor,
router: router,
session: session
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,16 @@ import Combine
import Web3Wallet

final class ConnectionDetailsPresenter: ObservableObject {
private let interactor: ConnectionDetailsInteractor
private let router: ConnectionDetailsRouter

let session: Session

private var disposeBag = Set<AnyCancellable>()

init(
interactor: ConnectionDetailsInteractor,
router: ConnectionDetailsRouter,
session: Session
) {
self.interactor = interactor
self.router = router
self.session = session
}
Expand All @@ -25,7 +22,7 @@ final class ConnectionDetailsPresenter: ObservableObject {
Task {
do {
ActivityIndicatorManager.shared.start()
try await interactor.disconnectSession(session: session)
try await Web3Wallet.instance.disconnect(topic: session.topic)
ActivityIndicatorManager.shared.stop()
DispatchQueue.main.async {
self.router.dismiss()
Expand All @@ -36,10 +33,26 @@ final class ConnectionDetailsPresenter: ObservableObject {
}
}
}



func accountReferences(namespace: String) -> [String] {
session.namespaces[namespace]?.accounts.map { "\($0.namespace):\(($0.reference))" } ?? []
}

func changeForMainnet() {
Task {
do {
ActivityIndicatorManager.shared.start()

try await Web3Wallet.instance.emit(topic: session.topic, event: Session.Event(name: "chainChanged", data: AnyCodable("1")), chainId: Blockchain("eip155:1")!)

ActivityIndicatorManager.shared.stop()
} catch {
ActivityIndicatorManager.shared.stop()
print(error)
}
}
}
}

// MARK: - Private functions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,15 @@ struct ConnectionDetailsView: View {
.padding(.horizontal, 20)
.padding(.top, 30)

Button {
presenter.changeForMainnet()
} label: {
Text("Change for Mainnet")
.foregroundColor(.grey50)
.font(.system(size: 20, weight: .semibold, design: .rounded))
}
.padding(.top, 20)

Button {
presenter.onDelete()
} label: {
Expand Down
19 changes: 0 additions & 19 deletions Sources/Events/Event.swift

This file was deleted.

18 changes: 9 additions & 9 deletions Sources/Events/EventStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@
import Foundation

protocol EventStorage {
func saveErrorEvent(_ event: Event)
func fetchErrorEvents() -> [Event]
func saveErrorEvent(_ event: TraceEvent)
func fetchErrorEvents() -> [TraceEvent]
func clearErrorEvents()
}

class UserDefaultsEventStorage: EventStorage {
class UserDefaultsTraceEventStorage: EventStorage {
private let errorEventsKey = "com.walletconnect.sdk.errorEvents"
private let maxEvents = 30

func saveErrorEvent(_ event: Event) {
func saveErrorEvent(_ event: TraceEvent) {
var existingEvents = fetchErrorEvents()
existingEvents.append(event)
// Ensure we keep only the last 30 events
Expand All @@ -23,9 +23,9 @@ class UserDefaultsEventStorage: EventStorage {
}
}

func fetchErrorEvents() -> [Event] {
func fetchErrorEvents() -> [TraceEvent] {
if let data = UserDefaults.standard.data(forKey: errorEventsKey),
let events = try? JSONDecoder().decode([Event].self, from: data) {
let events = try? JSONDecoder().decode([TraceEvent].self, from: data) {
// Return only the last 30 events
return Array(events.suffix(maxEvents))
}
Expand All @@ -39,13 +39,13 @@ class UserDefaultsEventStorage: EventStorage {

#if DEBUG
class MockEventStorage: EventStorage {
private(set) var savedEvents: [Event] = []
private(set) var savedEvents: [TraceEvent] = []

func saveErrorEvent(_ event: Event) {
func saveErrorEvent(_ event: TraceEvent) {
savedEvents.append(event)
}

func fetchErrorEvents() -> [Event] {
func fetchErrorEvents() -> [TraceEvent] {
return savedEvents
}

Expand Down
46 changes: 36 additions & 10 deletions Sources/Events/EventsClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,31 @@ import Foundation

public protocol EventsClientProtocol {
func startTrace(topic: String)
func saveEvent(_ event: TraceEvent)
func saveTraceEvent(_ event: TraceEventItem)
func setTopic(_ topic: String)
func setTelemetryEnabled(_ enabled: Bool)
func saveMessageEvent(_ event: MessageEventType)
}

public class EventsClient: EventsClientProtocol {
private let eventsCollector: EventsCollector
private let eventsDispatcher: EventsDispatcher
private let logger: ConsoleLogging
private var stateStorage: TelemetryStateStorage
private let messageEventsStorage: MessageEventsStorage

init(
eventsCollector: EventsCollector,
eventsDispatcher: EventsDispatcher,
logger: ConsoleLogging,
stateStorage: TelemetryStateStorage
stateStorage: TelemetryStateStorage,
messageEventsStorage: MessageEventsStorage
) {
self.eventsCollector = eventsCollector
self.eventsDispatcher = eventsDispatcher
self.logger = logger
self.stateStorage = stateStorage
self.messageEventsStorage = messageEventsStorage

if stateStorage.telemetryEnabled {
Task { await sendStoredEvents() }
Expand All @@ -48,12 +52,17 @@ public class EventsClient: EventsClientProtocol {
}

// Public method to save event
public func saveEvent(_ event: TraceEvent) {
public func saveTraceEvent(_ event: TraceEventItem) {
guard stateStorage.telemetryEnabled else { return }
logger.debug("Will store an event: \(event)")
logger.debug("Will store a trace event: \(event)")
eventsCollector.saveEvent(event)
}

public func saveMessageEvent(_ event: MessageEventType) {
logger.debug("Will store a message event: \(event)")
messageEventsStorage.saveMessageEvent(event)
}

// Public method to set telemetry enabled or disabled
public func setTelemetryEnabled(_ enabled: Bool) {
stateStorage.telemetryEnabled = enabled
Expand All @@ -66,15 +75,27 @@ public class EventsClient: EventsClientProtocol {

private func sendStoredEvents() async {
guard stateStorage.telemetryEnabled else { return }
let events = eventsCollector.storage.fetchErrorEvents()
guard !events.isEmpty else { return }

logger.debug("Will send events")
let traceEvents = eventsCollector.storage.fetchErrorEvents()
let messageEvents = messageEventsStorage.fetchMessageEvents()

guard !traceEvents.isEmpty || !messageEvents.isEmpty else { return }

var combinedEvents: [AnyCodable] = []

// Wrap trace events
combinedEvents.append(contentsOf: traceEvents.map { AnyCodable($0) })

// Wrap message events
combinedEvents.append(contentsOf: messageEvents.map { AnyCodable($0) })

logger.debug("Will send combined events")
do {
let success: Bool = try await eventsDispatcher.executeWithRetry(events: events)
let success: Bool = try await eventsDispatcher.executeWithRetry(events: combinedEvents)
if success {
logger.debug("Events sent successfully")
logger.debug("Combined events sent successfully")
self.eventsCollector.storage.clearErrorEvents()
self.messageEventsStorage.clearMessageEvents()
}
} catch {
logger.debug("Failed to send events after multiple attempts: \(error)")
Expand All @@ -96,12 +117,17 @@ public class MockEventsClient: EventsClientProtocol {

public func setTopic(_ topic: String) {}

public func saveEvent(_ event: TraceEvent) {
public func saveTraceEvent(_ event: TraceEventItem) {
saveEventCalled = true
}

public func setTelemetryEnabled(_ enabled: Bool) {
telemetryEnabled = enabled
}

public func saveMessageEvent(_ event: MessageEventType) {

}

}
#endif
5 changes: 3 additions & 2 deletions Sources/Events/EventsClientFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ public class EventsClientFactory {
static func create(
projectId: String,
sdkVersion: String,
storage: EventStorage = UserDefaultsEventStorage()
storage: EventStorage = UserDefaultsTraceEventStorage()
) -> EventsClient {
let networkingService = NetworkingService(
projectId: projectId,
Expand All @@ -18,7 +18,8 @@ public class EventsClientFactory {
eventsCollector: eventsCollector,
eventsDispatcher: eventsDispatcher,
logger: logger,
stateStorage: UserDefaultsTelemetryStateStorage()
stateStorage: UserDefaultsTelemetryStateStorage(),
messageEventsStorage: UserDefaultsMessageEventsStorage()
)
}
}
Expand Down
12 changes: 6 additions & 6 deletions Sources/Events/EventsCollector.swift
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import Foundation

// Protocol for TraceEvent
public protocol TraceEvent: CustomStringConvertible {
public protocol TraceEventItem: CustomStringConvertible {
var description: String { get }
}

// Protocol for ErrorEvent
protocol ErrorEvent: TraceEvent {}
protocol ErrorEvent: TraceEventItem {}


class EventsCollector {
Expand Down Expand Up @@ -34,7 +34,7 @@ class EventsCollector {
}

// Function to save event
func saveEvent(_ event: TraceEvent) {
func saveEvent(_ event: TraceEventItem) {
trace.append(event.description)
if let errorEvent = event as? ErrorEvent {
saveErrorEvent(errorEvent)
Expand All @@ -51,14 +51,14 @@ class EventsCollector {
// Private function to save error event
private func saveErrorEvent(_ errorEvent: ErrorEvent) {
let bundleId = Bundle.main.bundleIdentifier ?? "Unknown"
let event = Event(
let event = TraceEvent(
eventId: UUID().uuidString,
bundleId: bundleId,
timestamp: Int64(Date().timeIntervalSince1970 * 1000),
props: Props(
props: TraceEvent.Props(
event: "ERROR",
type: errorEvent.description,
properties: Properties(
properties: TraceEvent.Properties(
topic: topic,
trace: trace
)
Expand Down
2 changes: 1 addition & 1 deletion Sources/Events/EventsDispatcher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class EventsDispatcher {
self.retryPolicy = retryPolicy
}

func executeWithRetry(events: [Event]) async throws -> Bool {
func executeWithRetry<T: Encodable>(events: [T]) async throws -> Bool {
var attempts = 0
var delay = retryPolicy.initialDelay

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

import Foundation

public enum PairingExecutionTraceEvents: String, TraceEvent {
public enum PairingExecutionTraceEvents: String, TraceEventItem {
case pairingUriValidationSuccess = "pairing_uri_validation_success"
case pairingStarted = "pairing_started"
case noWssConnection = "no_wss_connection"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

import Foundation

public enum SessionApproveExecutionTraceEvents: String, TraceEvent {
public enum SessionApproveExecutionTraceEvents: String, TraceEventItem {
case approvingSessionProposal = "approving_session_proposal"
case sessionNamespacesValidationStarted = "session_namespaces_validation_started"
case sessionNamespacesValidationSuccess = "session_namespaces_validation_success"
Expand Down
Loading

0 comments on commit f4d4ba4

Please sign in to comment.