实现 WalletConnect 1.x.x 协议的 Swift SDK,适用于原生 iOS Dapp 和钱包。
服务器 (钱包端)
Codable客户端 (原生 Dapp 端)
personal_signeth_signeth_signTypedDataeth_sendTransactioneth_signTransactioneth_sendRawTransactionCodable示例代码位于单独的存储库中: https://github.com/WalletConnect/WalletConnectSwift-Example
要开始连接,您需要创建并保留一个 Server 对象,并向其提供一个委托。
let server = Server(delegate: self)
该库为您处理 WalletConnect 特定的会话请求 - wc_sessionRequest 和 wc_sessionUpdate。
要注册重要的会话更新事件,请实现委托方法 shouldStart、didConnect、didDisconnect 和 didFailToConnect。
默认情况下,服务器无法处理任何其他请求 - 您需要提供自己的实现。
您可以通过注册请求处理程序来完成此操作。您可以灵活地为每个请求方法注册一个处理程序,或者注册一个捕获所有请求的处理程序。
server.register(handler: PersonalSignHandler(for: self, server: server, wallet: wallet))
处理程序会按注册顺序被询问,它们是否可以处理每个请求。第一个从 canHandle(request:) 方法返回 true 的处理程序将获得 handle(request:) 调用。所有其他处理程序将被跳过。
在请求处理程序中,在 canHandle 实现中检查传入请求的方法,并在 handle(request:) 实现中处理实际请求。
func canHandle(request: Request) -> Bool {
return request.method == "eth_signTransaction"
}
您可以使用 send 方法通过服务器发回请求的响应。
func handle(request: Request) {
// do you stuff here ...
// error response - rejected by user
server.send(.reject(request))
// or send actual response - assuming the request.id exists, and MyCodableStruct type defined
try server.send(Response(url: request.url, value: MyCodableStruct(value: "Something"), id: request.id!))
}
有关更多详细信息,请参见 ExampleApps/ServerApp
要开始连接,您需要创建并保持一个 Client 对象,并向其提供 DappInfo 和一个委托。
let client = Client(delegate: self, dAppInfo: dAppInfo)
然后,当连接建立、失败或断开连接时,委托将收到回调。
成功连接后,您可以在 Client 上调用各种 API 方法。
try? client.personal_sign(url: session.url, message: "Hi there!", account: session.walletInfo!.accounts[0]) {
[weak self] response in
// handle the response from Wallet here
}
您还可以发送自定义请求。JSON RPC 所需的请求 ID 由库内部生成和处理。
try? client.send(Request(url: url, method: "eth_gasPrice")) { [weak self] response in
// handle the response
}
您可以将收到的响应结果转换为 Decodable 类型。
let nonceString = try response.result(as: String.self)
您还可以检查钱包是否响应了错误
if let error = response.error { // NSError
// handle error
}
有关更多详细信息,请参见 ExampleApps/ClientApp
通过更改日志级别 LogService.level = .info 来过滤要打印的日志类型。
请打开 ExampleApps/ExampleApps.xcodeproj
在您的 Package.swift 中
dependencies: [
.package(url: "https://github.com/WalletConnect/WalletConnectSwift.git", .upToNextMinor(from: "1.2.0"))
]
在您的 Podfile 中
platform :ios, '13.0'
use_frameworks!
target 'MyApp' do
pod 'WalletConnectSwift'
end
在您的 Cartfile 中
github "WalletConnect/WalletConnectSwift"
运行 carthage update 以构建框架,并将 WalletConnectSwift.framework 拖到您的 Xcode 项目中。
我们要感谢 Trust Wallet 团队在实现此库方面的灵感。
MIT 许可证 (参见 LICENSE 文件)。