Cross-plaform Json RPC library for Swift with WebSocket support
JsonRPC.swift
Cross-platform JsonRPC client implementation with HTTP and WebSocket support
Getting started
Installation
Package Manager
Add the following dependency to your Package.swift:
.package(url: "https://github.com/tesseract-one/JsonRPC.swift.git", from: "0.1.0")
// you can enable Serializable support for dynamic error parsing (add dependency to your target too)
// .package(url: "https://github.com/tesseract-one/Serializable.swift.git", from: "0.2.0")
Run swift build
and build your app.
CocoaPods
Add the following to your Podfile:
pod 'JsonRPC.swift', '~> 0.1.0'
# you can enable Serializable support for dynamic error parsing
# pod 'JsonRPC.swift/Serializable', '~> 0.1.0'
Then run pod install
Examples
HTTP connection
import Foundation
import JsonRPC
let rpc = JsonRpc(.http(url: URL(string: "https://api.avax-test.network/ext/bc/C/rpc")!), queue: .main)
rpc.call(method: "web3_clientVersion", params: Params(), String.self, String.self) { res in
print(try! res.get())
}
WebSocket connection
import Foundation
import JsonRPC
let rpc = JsonRpc(.ws(url: URL(string: "wss://api.avax-test.network/ext/bc/C/ws")!), queue: .main)
rpc.call(method: "web3_clientVersion", params: Params(), String.self, String.self) { res in
print(try! res.get())
}
Notifications
import Foundation
import JsonRPC
// This will allow dynamic JSON parsing
// https://github.com/tesseract-one/Serializable.swift
import Serializable
// Notification body structure
struct NewHeadsNotification: Decodable {
let subscription: String
let result: SerializableValue
}
class Delegate: ConnectableDelegate, ServerDelegate, ErrorDelegate {
// Connectable Delegate. Will send connection updates
public func state(_ state: ConnectableState) {
print("Connection state: \(state)")
}
// Error delegate. Will send global errors (uknown response id, etc.)
public func error(_ error: ServiceError) {
print("Error: \(error)")
}
public func notification(method: String, params: Parsable) {
let notification = try! params.parse(to: NewHeadsNotification.self).get()!
print("\(method): \(notification)")
}
}
// Create RPC
let rpc = JsonRpc(.ws(url: URL(string: "wss://main-rpc.linkpool.io/ws")!, autoconnect: false), queue: .main)
// Set delegate. Notification and statuses will be forwarded to it
rpc.delegate = Delegate()
// Connect to the server
rpc.connect()
// Call subsribe method.
// You can use Params() for array of Encodable parameters or provide own custom Encodable value.
// You can omit last parameter if you have Serializable dependency. This will set error data to SerializableValue type.
rpc.call(method: "eth_subscribe", params: Params("newHeads"), String.self) { res in
print(try! res.get())
}
Author
License
JsonRPC.swift is available under the Apache 2.0 license. See the LICENSE file for more information.