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 #337-fix-hardcoded-self-account

# Conflicts:
#	Tests/ChatTests/Mocks/NetworkingInteractorMock.swift
  • Loading branch information
llbartekll committed Jul 14, 2022
2 parents d38c8ba + b7ff9c4 commit be7a7e9
Show file tree
Hide file tree
Showing 16 changed files with 79 additions and 36 deletions.
4 changes: 2 additions & 2 deletions Example/IntegrationTests/Relay/RelayClientEndToEndTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,15 @@ final class RelayClientEndToEndTests: XCTestCase {
expectationB.fulfill()
}
relayA.socketConnectionStatusPublisher.sink { _ in
relayA.publish(topic: randomTopic, payload: payloadA, tag: .unknown, onNetworkAcknowledge: { error in
relayA.publish(topic: randomTopic, payload: payloadA, tag: 0, onNetworkAcknowledge: { error in
XCTAssertNil(error)
})
relayA.subscribe(topic: randomTopic) { error in
XCTAssertNil(error)
}
}.store(in: &publishers)
relayB.socketConnectionStatusPublisher.sink { _ in
relayB.publish(topic: randomTopic, payload: payloadB, tag: .unknown, onNetworkAcknowledge: { error in
relayB.publish(topic: randomTopic, payload: payloadB, tag: 0, onNetworkAcknowledge: { error in
XCTAssertNil(error)
})
relayB.subscribe(topic: randomTopic) { error in
Expand Down
8 changes: 4 additions & 4 deletions Sources/Chat/NetworkingInteractor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ protocol NetworkInteracting {
var responsePublisher: AnyPublisher<ChatResponse, Never> {get}
func subscribe(topic: String) async throws
func request(_ request: JSONRPCRequest<ChatRequestParams>, topic: String, envelopeType: Envelope.EnvelopeType) async throws
func respond(topic: String, response: JsonRpcResult) async throws
func respond(topic: String, response: JsonRpcResult, tag: Int) async throws
}

extension NetworkInteracting {
Expand Down Expand Up @@ -56,12 +56,12 @@ class NetworkingInteractor: NetworkInteracting {
func request(_ request: JSONRPCRequest<ChatRequestParams>, topic: String, envelopeType: Envelope.EnvelopeType) async throws {
try jsonRpcHistory.set(topic: topic, request: request)
let message = try! serializer.serialize(topic: topic, encodable: request, envelopeType: envelopeType)
try await relayClient.publish(topic: topic, payload: message, tag: .chat)
try await relayClient.publish(topic: topic, payload: message, tag: request.params.tag)
}

func respond(topic: String, response: JsonRpcResult) async throws {
func respond(topic: String, response: JsonRpcResult, tag: Int) async throws {
let message = try serializer.serialize(topic: topic, encodable: response.value)
try await relayClient.publish(topic: topic, payload: message, tag: .chat, prompt: false)
try await relayClient.publish(topic: topic, payload: message, tag: tag, prompt: false)
}

func subscribe(topic: String) async throws {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class InvitationHandlingService {

let responseTopic = try getInviteResponseTopic(payload, invite)

try await networkingInteractor.respond(topic: responseTopic, response: response)
try await networkingInteractor.respond(topic: responseTopic, response: response, tag: payload.request.params.responseTag)

let threadAgreementKeys = try kms.performKeyAgreement(selfPublicKey: selfThreadPubKey, peerPublicKey: invite.publicKey)

Expand Down Expand Up @@ -84,7 +84,7 @@ class InvitationHandlingService {
let error = JSONRPCErrorResponse.Error(code: 0, message: "user rejected")
let response = JsonRpcResult.error(JSONRPCErrorResponse(id: payload.request.id, error: error))

try await networkingInteractor.respond(topic: responseTopic, response: response)
try await networkingInteractor.respond(topic: responseTopic, response: response, tag: payload.request.params.responseTag)

invitePayloadStore.delete(forKey: inviteId)
}
Expand Down
16 changes: 16 additions & 0 deletions Sources/Chat/Types/ChatRequestParams.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,22 @@ enum ChatRequestParams: Codable, Equatable {
}
}

extension ChatRequestParams {

var tag: Int {
switch self {
case .invite:
return 2000
case .message:
return 2002
}
}

var responseTag: Int {
return tag + 1
}
}

extension JSONRPCRequest {
init(id: Int64 = JsonRpcID.generate(), params: T) where T == ChatRequestParams {
var method: String!
Expand Down
5 changes: 0 additions & 5 deletions Sources/WalletConnectRelay/PublishTag.swift

This file was deleted.

8 changes: 4 additions & 4 deletions Sources/WalletConnectRelay/RelayClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ public final class RelayClient {
}

/// Completes when networking client sends a request, error if it fails on client side
public func publish(topic: String, payload: String, tag: PublishTag, prompt: Bool = false) async throws {
let params = RelayJSONRPC.PublishParams(topic: topic, message: payload, ttl: defaultTtl, prompt: prompt, tag: tag.rawValue)
public func publish(topic: String, payload: String, tag: Int, prompt: Bool = false) async throws {
let params = RelayJSONRPC.PublishParams(topic: topic, message: payload, ttl: defaultTtl, prompt: prompt, tag: tag)
let request = JSONRPCRequest<RelayJSONRPC.PublishParams>(method: RelayJSONRPC.Method.publish.method, params: params)
logger.debug("Publishing Payload on Topic: \(topic)")
let requestJson = try request.json()
Expand All @@ -108,10 +108,10 @@ public final class RelayClient {
@discardableResult public func publish(
topic: String,
payload: String,
tag: PublishTag,
tag: Int,
prompt: Bool = false,
onNetworkAcknowledge: @escaping ((Error?) -> Void)) -> Int64 {
let params = RelayJSONRPC.PublishParams(topic: topic, message: payload, ttl: defaultTtl, prompt: prompt, tag: tag.rawValue)
let params = RelayJSONRPC.PublishParams(topic: topic, message: payload, ttl: defaultTtl, prompt: prompt, tag: tag)
let request = JSONRPCRequest<RelayJSONRPC.PublishParams>(method: RelayJSONRPC.Method.publish.method, params: params)
let requestJson = try! request.json()
logger.debug("iridium: Publishing Payload on Topic: \(topic)")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ final class ApproveEngine {
let proposeResponse = SessionType.ProposeResponse(relay: relay, responderPublicKey: selfPublicKey.hexRepresentation)
let response = JSONRPCResponse<AnyCodable>(id: payload.wcRequest.id, result: AnyCodable(proposeResponse))

try await networkingInteractor.respond(topic: payload.topic, response: .response(response))
try await networkingInteractor.respond(topic: payload.topic, response: .response(response), tag: payload.wcRequest.responseTag)
try await settle(topic: sessionTopic, proposal: proposal, namespaces: sessionNamespaces)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ final class SessionEngine {
guard sessionStore.hasSession(forTopic: topic) else {
throw Errors.sessionNotFound(topic: topic)
}
try await networkingInteractor.respond(topic: topic, response: response)
try await networkingInteractor.respond(topic: topic, response: response, tag: 1109) // FIXME: Hardcoded tag
}

func emit(topic: String, event: SessionType.EventParams.Event, chainId: Blockchain) async throws {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ protocol NetworkInteracting: AnyObject {
func requestNetworkAck(_ wcMethod: WCMethod, onTopic topic: String, completion: @escaping ((Error?) -> Void))
/// Completes with a peer response
func requestPeerResponse(_ wcMethod: WCMethod, onTopic topic: String, completion: ((Result<JSONRPCResponse<AnyCodable>, JSONRPCErrorResponse>) -> Void)?)
func respond(topic: String, response: JsonRpcResult) async throws
func respond(topic: String, response: JsonRpcResult, tag: Int) async throws
func respondSuccess(payload: WCRequestSubscriptionPayload) async throws
func respondSuccess(for payload: WCRequestSubscriptionPayload)
func respondError(payload: WCRequestSubscriptionPayload, reason: ReasonCode) async throws
Expand Down Expand Up @@ -71,7 +71,7 @@ class NetworkInteractor: NetworkInteracting {
try jsonRpcHistory.set(topic: topic, request: payload, chainId: getChainId(payload))
let message = try serializer.serialize(topic: topic, encodable: payload)
let prompt = shouldPrompt(payload.method)
try await relayClient.publish(topic: topic, payload: message, tag: .sign, prompt: prompt)
try await relayClient.publish(topic: topic, payload: message, tag: payload.tag, prompt: prompt)
}

func requestPeerResponse(_ wcMethod: WCMethod, onTopic topic: String, completion: ((Result<JSONRPCResponse<AnyCodable>, JSONRPCErrorResponse>) -> Void)?) {
Expand All @@ -80,7 +80,7 @@ class NetworkInteractor: NetworkInteracting {
try jsonRpcHistory.set(topic: topic, request: payload, chainId: getChainId(payload))
let message = try serializer.serialize(topic: topic, encodable: payload)
let prompt = shouldPrompt(payload.method)
relayClient.publish(topic: topic, payload: message, tag: .sign, prompt: prompt) { [weak self] error in
relayClient.publish(topic: topic, payload: message, tag: payload.tag, prompt: prompt) { [weak self] error in
guard let self = self else {return}
if let error = error {
self.logger.error(error)
Expand Down Expand Up @@ -116,7 +116,7 @@ class NetworkInteractor: NetworkInteracting {
try jsonRpcHistory.set(topic: topic, request: payload, chainId: getChainId(payload))
let message = try serializer.serialize(topic: topic, encodable: payload)
let prompt = shouldPrompt(payload.method)
relayClient.publish(topic: topic, payload: message, tag: .sign, prompt: prompt) { error in
relayClient.publish(topic: topic, payload: message, tag: payload.tag, prompt: prompt) { error in
completion(error)
}
} catch WalletConnectError.internal(.jsonRpcDuplicateDetected) {
Expand All @@ -126,27 +126,27 @@ class NetworkInteractor: NetworkInteracting {
}
}

func respond(topic: String, response: JsonRpcResult) async throws {
func respond(topic: String, response: JsonRpcResult, tag: Int) async throws {
_ = try jsonRpcHistory.resolve(response: response)

let message = try serializer.serialize(topic: topic, encodable: response.value)
logger.debug("Responding....topic: \(topic)")

do {
try await relayClient.publish(topic: topic, payload: message, tag: .sign, prompt: false)
try await relayClient.publish(topic: topic, payload: message, tag: tag, prompt: false)
} catch WalletConnectError.internal(.jsonRpcDuplicateDetected) {
logger.info("Info: Json Rpc Duplicate Detected")
}
}

func respondSuccess(payload: WCRequestSubscriptionPayload) async throws {
let response = JSONRPCResponse<AnyCodable>(id: payload.wcRequest.id, result: AnyCodable(true))
try await respond(topic: payload.topic, response: JsonRpcResult.response(response))
try await respond(topic: payload.topic, response: JsonRpcResult.response(response), tag: payload.wcRequest.responseTag)
}

func respondError(payload: WCRequestSubscriptionPayload, reason: ReasonCode) async throws {
let response = JSONRPCErrorResponse(id: payload.wcRequest.id, error: JSONRPCErrorResponse.Error(code: reason.code, message: reason.message))
try await respond(topic: payload.topic, response: JsonRpcResult.error(response))
try await respond(topic: payload.topic, response: JsonRpcResult.error(response), tag: payload.wcRequest.responseTag)
}

// TODO: Move to async
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ protocol NetworkRelaying {
var socketConnectionStatusPublisher: AnyPublisher<SocketConnectionStatus, Never> { get }
func connect() throws
func disconnect(closeCode: URLSessionWebSocketTask.CloseCode) throws
func publish(topic: String, payload: String, tag: PublishTag, prompt: Bool) async throws
func publish(topic: String, payload: String, tag: Int, prompt: Bool) async throws
/// - returns: request id
@discardableResult func publish(topic: String, payload: String, tag: PublishTag, prompt: Bool, onNetworkAcknowledge: @escaping ((Error?) -> Void)) -> Int64
@discardableResult func publish(topic: String, payload: String, tag: Int, prompt: Bool, onNetworkAcknowledge: @escaping ((Error?) -> Void)) -> Int64
func subscribe(topic: String, completion: @escaping (Error?) -> Void)
func subscribe(topic: String) async throws
/// - returns: request id
Expand Down
32 changes: 32 additions & 0 deletions Sources/WalletConnectSign/Types/WCRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,35 @@ extension WCRequest {
}
}
}

extension WCRequest {

var tag: Int {
switch method {
case .pairingDelete:
return 1000
case .pairingPing:
return 1002
case .sessionPropose:
return 1100
case .sessionSettle:
return 1102
case .sessionUpdate:
return 1104
case .sessionExtend:
return 1106
case .sessionDelete:
return 1112
case .sessionRequest:
return 1108
case .sessionPing:
return 1114
case .sessionEvent:
return 1110
}
}

var responseTag: Int {
return tag + 1
}
}
3 changes: 1 addition & 2 deletions Tests/ChatTests/Mocks/NetworkingInteractorMock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ class NetworkingInteractorMock: NetworkInteracting {
}
let socketConnectionStatusPublisherSubject = PassthroughSubject<SocketConnectionStatus, Never>()


let responsePublisherSubject = PassthroughSubject<ChatResponse, Never>()
let requestPublisherSubject = PassthroughSubject<RequestSubscriptionPayload, Never>()

Expand All @@ -30,7 +29,7 @@ class NetworkingInteractorMock: NetworkInteracting {

}

func respond(topic: String, response: JsonRpcResult) async throws {
func respond(topic: String, response: JsonRpcResult, tag: Int) async throws {

}

Expand Down
4 changes: 2 additions & 2 deletions Tests/RelayerTests/IridiumRelayTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class IridiumRelayTests: XCTestCase {

func testPublishRequestAcknowledge() {
let acknowledgeExpectation = expectation(description: "completion with no error on iridium request acknowledge after publish")
let requestId = iridiumRelay.publish(topic: "", payload: "{}", tag: .unknown, onNetworkAcknowledge: { error in
let requestId = iridiumRelay.publish(topic: "", payload: "{}", tag: 0, onNetworkAcknowledge: { error in
acknowledgeExpectation.fulfill()
XCTAssertNil(error)
})
Expand Down Expand Up @@ -72,7 +72,7 @@ class IridiumRelayTests: XCTestCase {
}

func testSendOnPublish() {
iridiumRelay.publish(topic: "", payload: "", tag: .unknown, onNetworkAcknowledge: { _ in})
iridiumRelay.publish(topic: "", payload: "", tag: 0, onNetworkAcknowledge: { _ in})
XCTAssertTrue(dispatcher.sent)
}

Expand Down
4 changes: 2 additions & 2 deletions Tests/WalletConnectSignTests/Mocks/MockedRelayClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ class MockedRelayClient: NetworkRelaying {
socketConnectionStatusPublisherSubject.eraseToAnyPublisher()
}

func publish(topic: String, payload: String, tag: PublishTag, prompt: Bool) async throws {
func publish(topic: String, payload: String, tag: Int, prompt: Bool) async throws {
self.prompt = prompt
}

var onMessage: ((String, String) -> Void)?
var error: Error?
var prompt = false
func publish(topic: String, payload: String, tag: PublishTag, prompt: Bool, onNetworkAcknowledge: @escaping ((Error?) -> Void)) -> Int64 {
func publish(topic: String, payload: String, tag: Int, prompt: Bool, onNetworkAcknowledge: @escaping ((Error?) -> Void)) -> Int64 {
self.prompt = prompt
onNetworkAcknowledge(error)
return 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class NetworkingInteractorMock: NetworkInteracting {
completion(error)
}

func respond(topic: String, response: JsonRpcResult) async throws {
func respond(topic: String, response: JsonRpcResult, tag: Int) async throws {
didRespondOnTopic = topic
}

Expand Down
1 change: 1 addition & 0 deletions Tests/WalletConnectSignTests/PairingEngineTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ final class PairingEngineTests: XCTestCase {
XCTAssertEqual(publishTopic, topicA)
}

// Flaky test: asserting `topicB` and `sessionTopic` failed once, couldn't reproduce
@MainActor
func testHandleSessionProposeResponse() async {
let uri = try! await engine.create()
Expand Down

0 comments on commit be7a7e9

Please sign in to comment.