Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Interface] Replace string with WalletConnectURI #475

Merged
merged 4 commits into from
Sep 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Example/DApp/Auth/AuthView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,3 @@ struct CircleButtonStyle: ButtonStyle {
.cornerRadius(8.0)
}
}

6 changes: 3 additions & 3 deletions Example/DApp/Auth/AuthViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ final class AuthViewModel: ObservableObject {
func setupInitialState() async throws {
state = .none
uri = nil
uri = try await Auth.instance.request(.stub())
uri = try await Auth.instance.request(.stub()).absoluteString
}

func copyDidPressed() {
UIPasteboard.general.string = uri
}

func walletDidPressed() {

}

func deeplinkPressed() {
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion Example/DApp/SceneDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
12 changes: 6 additions & 6 deletions Example/DApp/Sign/Connect/ConnectViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import UIKit
import WalletConnectSign

class ConnectViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let uriString: String
let uri: WalletConnectURI
let activePairings: [Pairing] = Sign.instance.getPairings()
let segmentedControl = UISegmentedControl(items: ["Pairings", "New Pairing"])

init(uri: String) {
self.uriString = uri
init(uri: WalletConnectURI) {
self.uri = uri
super.init(nibName: nil, bundle: nil)
}

Expand All @@ -27,7 +27,7 @@ class ConnectViewController: UIViewController, UITableViewDataSource, UITableVie
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.global().async { [unowned self] in
let qrImage = QRCodeGenerator.generateQRCode(from: uriString)
let qrImage = QRCodeGenerator.generateQRCode(from: uri.absoluteString)
DispatchQueue.main.async { [self] in
self.connectView.qrCodeView.image = qrImage
self.connectView.copyButton.isHidden = false
Expand Down Expand Up @@ -56,11 +56,11 @@ class ConnectViewController: UIViewController, UITableViewDataSource, UITableVie
}

@objc func copyURI() {
UIPasteboard.general.string = uriString
UIPasteboard.general.string = uri.absoluteString
}

@objc func connectWithExampleWallet() {
let url = URL(string: "https://walletconnect.com/wc?uri=\(uriString)")!
let url = URL(string: "https://walletconnect.com/wc?uri=\(uri.absoluteString)")!
DispatchQueue.main.async {
UIApplication.shared.open(url, options: [:]) { [weak self] _ in
self?.dismiss(animated: true, completion: nil)
Expand Down
6 changes: 3 additions & 3 deletions Example/DApp/Sign/SelectChain/SelectChainViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class SelectChainViewController: UIViewController, UITableViewDataSource {
let namespaces: [String: ProposalNamespace] = ["eip155": ProposalNamespace(chains: blockchains, methods: methods, events: [], extensions: nil)]
Task {
let uri = try await Sign.instance.connect(requiredNamespaces: namespaces)
showConnectScreen(uriString: uri!)
showConnectScreen(uri: uri!)
}
}

Expand All @@ -48,9 +48,9 @@ class SelectChainViewController: UIViewController, UITableViewDataSource {
UIApplication.shared.open(URL(string: "walletconnectwallet://")!)
}

private func showConnectScreen(uriString: String) {
private func showConnectScreen(uri: WalletConnectURI) {
DispatchQueue.main.async { [unowned self] in
let vc = UINavigationController(rootViewController: ConnectViewController(uri: uriString))
let vc = UINavigationController(rootViewController: ConnectViewController(uri: uri))
present(vc, animated: true, completion: nil)
}
}
Expand Down
2 changes: 1 addition & 1 deletion Example/ExampleApp/SceneDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
vc.onClientConnected = {
Task {
do {
try await Sign.instance.pair(uri: wcUri)
try await Sign.instance.pair(uri: WalletConnectURI(string: wcUri)!)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we add the check: if uri is for Sign API or something like that?

} catch {
print(error)
}
Expand Down
8 changes: 5 additions & 3 deletions Example/ExampleApp/Wallet/WalletViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ final class WalletViewController: UIViewController {
@objc
private func showTextInput() {
let alert = UIAlertController.createInputAlert { [weak self] inputText in
self?.pairClient(uri: inputText)
guard let self = self, let uri = WalletConnectURI(string: inputText) else { return }
self.pairClient(uri: uri)
}
present(alert, animated: true)
}
Expand Down Expand Up @@ -119,7 +120,7 @@ final class WalletViewController: UIViewController {
}

@MainActor
private func pairClient(uri: String) {
private func pairClient(uri: WalletConnectURI) {
print("[WALLET] Pairing to: \(uri)")
Task {
do {
Expand Down Expand Up @@ -201,7 +202,8 @@ extension WalletViewController: UITableViewDataSource, UITableViewDelegate {
extension WalletViewController: ScannerViewControllerDelegate {

func didScan(_ code: String) {
pairClient(uri: code)
guard let uri = WalletConnectURI(string: code) else { return }
pairClient(uri: uri)
}
}

Expand Down
6 changes: 3 additions & 3 deletions Example/IntegrationTests/Auth/AuthTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand All @@ -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()
Expand All @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
MigrationConfigurator(app: app),
ThirdPartyConfigurator(),
ApplicationConfigurator(app: app),
AppearanceConfigurator(),
AppearanceConfigurator()
]
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
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
return view
}

func updateUIView(_ uiView: ScanQRView, context: Context) {

}

func makeCoordinator() -> Coordinator {
return Coordinator(onValue: onValue, onError: onError)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()
}
Expand All @@ -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,
Expand All @@ -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(
Expand All @@ -98,76 +98,76 @@ 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
bluredView.frame = bounds
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
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/Auth/Auth.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class Auth {
account: config.account,
relayClient: Relay.instance)
}()

private static var config: Config?

private init() { }
Expand Down
Loading