Skip to content

Commit 90e2061

Browse files
Update Web3HTTPProvider
- Drop methods `sendRequest` from Web3Provider protocol. - Move out network request code from `Web3HTTPProvider`. - Network enum are now inits from UInt instead of Int. Fixed bug of not decoding Data responses.
1 parent fa80d43 commit 90e2061

File tree

5 files changed

+73
-86
lines changed

5 files changed

+73
-86
lines changed

Sources/web3swift/API/APIMethod.swift

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -232,9 +232,21 @@ extension APIRequest {
232232
/// Don't even try to make network request if the `Result` type dosen't equal to supposed by API
233233
// FIXME: Add appropriate error thrown
234234
guard Result.self == call.responseType else { throw Web3Error.unknownError }
235-
236235
let request = setupRequest(for: call, with: provider)
237-
let (data, response) = try await provider.session.data(for: request)
236+
return try await APIRequest.send(uRLRequest: request, with: provider.session)
237+
}
238+
239+
static func setupRequest(for call: APIRequest, with provider: Web3Provider) -> URLRequest {
240+
var urlRequest = URLRequest(url: provider.url, cachePolicy: .reloadIgnoringCacheData)
241+
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
242+
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
243+
urlRequest.httpMethod = call.method.rawValue
244+
urlRequest.httpBody = call.encodedBody
245+
return urlRequest
246+
}
247+
248+
static func send<Result>(uRLRequest: URLRequest, with session: URLSession) async throws -> APIResponse<Result> {
249+
let (data, response) = try await session.data(for: uRLRequest)
238250

239251
// FIXME: Add appropriate error thrown
240252
guard let httpResponse = response as? HTTPURLResponse,
@@ -243,7 +255,7 @@ extension APIRequest {
243255
// FIXME: Add throwing an error from is server fails.
244256
/// This bit of code is purposed to work with literal types that comes in Response in hexString type.
245257
/// Currently it's just any kind of Integers like `(U)Int`, `Big(U)Int`.
246-
if Result.self == UInt.self || Result.self == Int.self || Result.self == BigInt.self || Result.self == BigUInt.self {
258+
if Result.self == Data.self || Result.self == UInt.self || Result.self == Int.self || Result.self == BigInt.self || Result.self == BigUInt.self {
247259
/// This types for sure conformed with `LiteralInitiableFromString`
248260
// FIXME: Make appropriate error
249261
guard let U = Result.self as? LiteralInitiableFromString.Type else { throw Web3Error.unknownError }
@@ -257,15 +269,6 @@ extension APIRequest {
257269
}
258270
return try JSONDecoder().decode(APIResponse<Result>.self, from: data)
259271
}
260-
261-
static func setupRequest(for call: APIRequest, with provider: Web3Provider) -> URLRequest {
262-
var urlRequest = URLRequest(url: provider.url, cachePolicy: .reloadIgnoringCacheData)
263-
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
264-
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
265-
urlRequest.httpMethod = call.method.rawValue
266-
urlRequest.httpBody = call.encodedBody
267-
return urlRequest
268-
}
269272
}
270273

271274
enum REST: String {
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//
2+
// Async+BackwardCapability.swift
3+
//
4+
//
5+
// Created by Yaroslav Yashin on 05.06.2022.
6+
//
7+
8+
import Foundation
9+
10+
@available(iOS, obsoleted: 15.0, message: "Use the built-in API instead")
11+
@available(macOS, obsoleted: 12.0, message: "Use the built-in API instead")
12+
extension URLSession {
13+
func data(fromUrl url: URL) async throws -> (Data, URLResponse) {
14+
try await withCheckedThrowingContinuation { continuation in
15+
let task = self.dataTask(with: url) { data, response, error in
16+
guard let data = data, let response = response else {
17+
let error = error ?? URLError(.badServerResponse)
18+
return continuation.resume(throwing: error)
19+
}
20+
continuation.resume(returning: (data, response))
21+
}
22+
task.resume()
23+
}
24+
}
25+
26+
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
27+
var dataTask: URLSessionDataTask?
28+
29+
return try await withCheckedThrowingContinuation { continuation in
30+
dataTask = self.dataTask(with: request) { data, response, error in
31+
guard let data = data, let response = response else {
32+
let error = error ?? URLError(.badServerResponse)
33+
return continuation.resume(throwing: error)
34+
}
35+
continuation.resume(returning: (data, response))
36+
}
37+
dataTask?.resume()
38+
}
39+
}
40+
}

Sources/web3swift/Utils/EIP/EIP681.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ extension Web3 {
122122
// return nil
123123
case .ensAddress(let ens):
124124
do {
125-
let web = await web3(provider: InfuraProvider(Networks.fromInt(Int(code.chainID ?? 1)) ?? Networks.Mainnet)!)
125+
let web = await web3(provider: InfuraProvider(Networks.fromInt(UInt(code.chainID ?? 1)) ?? Networks.Mainnet)!)
126126
let ensModel = ENS(web3: web)
127127
try await ensModel?.setENSResolver(withDomain: ens)
128128
let address = try await ensModel?.getAddress(forNode: ens)

Sources/web3swift/Web3/Web3+HttpProvider.swift

Lines changed: 16 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,6 @@ import BigInt
1010

1111
/// Providers abstraction for custom providers (websockets, other custom private key managers). At the moment should not be used.
1212
public protocol Web3Provider {
13-
// func sendAsync(_ request: JSONRPCrequest) async throws -> JSONRPCresponse
14-
// func sendAsync(_ requests: JSONRPCrequestBatch) async throws -> JSONRPCresponseBatch
1513
var network: Networks? {get set}
1614
var attachedKeystoreManager: KeystoreManager? {get set}
1715
var url: URL {get}
@@ -28,79 +26,25 @@ public class Web3HttpProvider: Web3Provider {
2826
let urlSession = URLSession(configuration: config)
2927
return urlSession
3028
}()
31-
public init?(_ httpProviderURL: URL, network net: Networks, keystoreManager manager: KeystoreManager? = nil) {
29+
public init?(_ httpProviderURL: URL, network net: Networks?, keystoreManager manager: KeystoreManager? = nil) async {
3230
guard httpProviderURL.scheme == "http" || httpProviderURL.scheme == "https" else { return nil }
3331
url = httpProviderURL
34-
network = net
35-
attachedKeystoreManager = manager
36-
}
37-
38-
// fileprivate static func dataFrom(session: URLSession, request urlRequest: URLRequest) async throws -> Data{
39-
// let (data, _) = try await session.data(for: urlRequest)
40-
// return data
41-
// }
42-
//
43-
// static func post<T: Decodable, U: Encodable>(_ request: U, providerURL: URL, session: URLSession) async throws -> T {
44-
// let requestData = try JSONEncoder().encode(request)
45-
// var urlRequest = URLRequest(url: providerURL, cachePolicy: .reloadIgnoringCacheData)
46-
// urlRequest.httpMethod = "POST"
47-
// urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
48-
// urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
49-
// urlRequest.httpBody = requestData
50-
//
51-
// let data = try await dataFrom(session: session, request: urlRequest)
52-
//
53-
// let parsedResponse = try JSONDecoder().decode(T.self, from: data)
54-
//
55-
// if let response = parsedResponse as? JSONRPCresponse, response.error != nil {
56-
// throw Web3Error.nodeError(desc: "Received an error message from node\n" + String(describing: response.error!))
57-
// }
58-
// return parsedResponse
59-
//
60-
// }
61-
//
62-
// public func sendAsync(_ request: JSONRPCrequest) async throws -> JSONRPCresponse {
63-
// guard request.method != nil else {
64-
// throw Web3Error.nodeError(desc: "RPC method is nill")
65-
// }
66-
//
67-
// return try await Web3HttpProvider.post(request, providerURL: self.url, session: self.session)
68-
// }
69-
70-
// public func sendAsync(_ requests: JSONRPCrequestBatch) async throws -> JSONRPCresponseBatch {
71-
// return try await Web3HttpProvider.post(requests, providerURL: self.url, session: self.session)
72-
// }
73-
}
74-
75-
76-
@available(iOS, obsoleted: 15.0, message: "Use the built-in API instead")
77-
@available(macOS, obsoleted: 12.0, message: "Use the built-in API instead")
78-
extension URLSession {
79-
func data(fromUrl url: URL) async throws -> (Data, URLResponse) {
80-
try await withCheckedThrowingContinuation { continuation in
81-
let task = self.dataTask(with: url) { data, response, error in
82-
guard let data = data, let response = response else {
83-
let error = error ?? URLError(.badServerResponse)
84-
return continuation.resume(throwing: error)
85-
}
86-
continuation.resume(returning: (data, response))
87-
}
88-
task.resume()
89-
}
90-
}
91-
92-
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
93-
var dataTask: URLSessionDataTask?
94-
95-
return try await withCheckedThrowingContinuation { continuation in
96-
dataTask = self.dataTask(with: request) { data, response, error in
97-
guard let data = data, let response = response else {
98-
let error = error ?? URLError(.badServerResponse)
99-
return continuation.resume(throwing: error)
100-
}
101-
continuation.resume(returning: (data, response))
32+
if let net = net {
33+
network = net
34+
} else {
35+
var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData)
36+
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
37+
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
38+
urlRequest.httpMethod = APIRequest.getNetwork.call
39+
urlRequest.httpBody = APIRequest.getNetwork.encodedBody
40+
do {
41+
let response: APIResponse<UInt> = try await APIRequest.send(uRLRequest: urlRequest, with: session)
42+
let network = Networks.fromInt(response.result)
43+
self.network = network
44+
} catch {
45+
return nil
10246
}
103-
dataTask?.resume()
10447
}
48+
attachedKeystoreManager = manager
10549
}
10650
}

Sources/web3swift/Web3/Web3+Protocols.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ public enum Networks {
5858

5959
static let allValues = [Mainnet, Ropsten, Kovan, Rinkeby]
6060

61-
static func fromInt(_ networkID: Int) -> Networks? {
61+
static func fromInt(_ networkID: UInt) -> Networks? {
6262
switch networkID {
6363
case 1:
6464
return Networks.Mainnet

0 commit comments

Comments
 (0)