Skip to content

Commit 65c5a53

Browse files
Add TxPool and getLog implementation
- Temporary disabled getting Network within Web3HttpProvider init. -
1 parent dddf1f2 commit 65c5a53

File tree

7 files changed

+117
-176
lines changed

7 files changed

+117
-176
lines changed

Sources/web3swift/API/APIMethod.swift

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -117,14 +117,14 @@ extension APIRequest {
117117
case .estimateGas: return BigUInt.self
118118
case .call: return Data.self
119119
// FIXME: Not checked
120-
case .getNetwork: return UInt.self
120+
case .getNetwork: return Int.self
121121
case .personalSign: return Data.self
122+
case .getTxPoolStatus: return TxPoolStatus.self
123+
case .getTxPoolContent: return TxPoolContent.self
122124

123125
// FIXME: Not implemented
124126
case .getLogs: return String.self
125127
case .getStorageAt: return String.self
126-
case .getTxPoolStatus: return String.self
127-
case .getTxPoolContent: return String.self
128128
case .getTxPoolInspect: return String.self
129129
}
130130
}
@@ -138,7 +138,7 @@ extension APIRequest {
138138

139139
var parameters: [RequestParameter] {
140140
switch self {
141-
case .gasPrice, .blockNumber, .getNetwork, .getAccounts:
141+
case .gasPrice, .blockNumber, .getNetwork, .getAccounts, .getTxPoolStatus, .getTxPoolContent, .getTxPoolInspect:
142142
return [RequestParameter]()
143143

144144
case .estimateGas(let transactionParameters, let blockNumber):
@@ -192,15 +192,6 @@ extension APIRequest {
192192

193193
case .unlockAccount(let address, let string, let uInt):
194194
return [RequestParameter.string(address), RequestParameter.string(string), RequestParameter.uint(uInt ?? 0)]
195-
196-
case .getTxPoolStatus:
197-
return [RequestParameter]()
198-
199-
case .getTxPoolContent:
200-
return [RequestParameter]()
201-
202-
case .getTxPoolInspect:
203-
return [RequestParameter]()
204195
}
205196
}
206197

Sources/web3swift/EthereumAPICalls/Promise+Web3+TxPool.swift

Lines changed: 0 additions & 53 deletions
This file was deleted.
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// web3swift
2+
//
3+
// Created by Alex Vlasov.
4+
// Copyright © 2018 Alex Vlasov. All rights reserved.
5+
//
6+
7+
import Foundation
8+
import BigInt
9+
10+
11+
extension web3.TxPool {
12+
// public func txPoolInspect() async throws -> [String: [String: [String: String]]] {
13+
// let request = JSONRPCRequestFabric.prepareRequest(.getTxPoolInspect, parameters: [])
14+
// let response = try await web3.dispatch(request)
15+
//
16+
// guard let value: [String: [String: [String: String]]] = response.getValue() else {
17+
// if response.error != nil {
18+
// throw Web3Error.nodeError(desc: response.error!.message)
19+
// }
20+
// throw Web3Error.nodeError(desc: "Invalid value from Ethereum node")
21+
// }
22+
// return value
23+
//
24+
// }
25+
26+
public func txPoolStatus() async throws -> TxPoolStatus {
27+
let response: APIResponse<TxPoolStatus> = try await APIRequest.sendRequest(with: provider, for: .getTxPoolStatus)
28+
return response.result
29+
}
30+
31+
public func txPoolContent() async throws -> TxPoolContent {
32+
let response: APIResponse<TxPoolContent> = try await APIRequest.sendRequest(with: provider, for: .getTxPoolContent)
33+
return response.result
34+
}
35+
}

Sources/web3swift/Web3/Web3+EventParser.swift

Lines changed: 33 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@ extension web3.web3contract {
2828
*Parses the block for events matching the EventParser settings.*
2929

3030
- parameters:
31-
- blockNumber: Ethereum network block number
31+
- blockNumber: Ethereum network block number
3232

3333
- returns:
34-
- Result object
34+
- Result object
3535

3636
- important: This call is synchronous
3737

@@ -45,10 +45,10 @@ extension web3.web3contract {
4545
*Parses the block for events matching the EventParser settings.*
4646

4747
- parameters:
48-
- block: Native web3swift block object
48+
- block: Native web3swift block object
4949

5050
- returns:
51-
- Result object
51+
- Result object
5252

5353
- important: This call is synchronous
5454

@@ -62,10 +62,10 @@ extension web3.web3contract {
6262
*Parses the transaction for events matching the EventParser settings.*
6363

6464
- parameters:
65-
- hash: Transaction hash
65+
- hash: Transaction hash
6666

6767
- returns:
68-
- Result object
68+
- Result object
6969

7070
- important: This call is synchronous
7171

@@ -79,10 +79,10 @@ extension web3.web3contract {
7979
*Parses the transaction for events matching the EventParser settings.*
8080

8181
- parameters:
82-
- transaction: web3swift native EthereumTransaction object
82+
- transaction: web3swift native EthereumTransaction object
8383

8484
- returns:
85-
- Result object
85+
- Result object
8686

8787
- important: This call is synchronous
8888

@@ -174,65 +174,49 @@ extension web3.web3contract.EventParser {
174174
}
175175

176176
extension web3.web3contract {
177-
178177
/**
179178
*Fetches events by doing a lookup on "indexed" parameters of the event. Smart-contract developer can make some of event values "indexed" for such fast queries.*
180179

181180
- parameters:
182-
- eventName: Event name, should be present in ABI interface of the contract
183-
- filter: EventFilter object setting the block limits for query
184-
- joinWithReceipts: Bool indicating whether TransactionReceipt should be fetched separately for every matched transaction
181+
- eventName: Event name, should be present in ABI interface of the contract
182+
- filter: EventFilter object setting the block limits for query
183+
- joinWithReceipts: Bool indicating whether TransactionReceipt should be fetched separately for every matched transaction
185184

186185
- returns:
187-
- Result object
186+
- Result object
188187

189188
- important: This call is synchronous
190189

191190
*/
192191
public func getIndexedEvents(eventName: String?, filter: EventFilter, joinWithReceipts: Bool = false) async throws -> [EventParserResultProtocol] {
193-
let result = try await self.getIndexedEventsPromise(eventName: eventName, filter: filter, joinWithReceipts: joinWithReceipts)
194-
return result
195-
}
196-
}
197-
198-
extension web3.web3contract {
199-
public func getIndexedEventsPromise(eventName: String?, filter: EventFilter, joinWithReceipts: Bool = false) async throws -> [EventParserResultProtocol] {
200-
201-
let rawContract = self.contract
202-
guard let preEncoding = encodeTopicToGetLogs(contract: rawContract, eventName: eventName, filter: filter) else {
203-
throw Web3Error.processingError(desc: "Failed to encode topic for request")
204-
}
205-
206-
if eventName != nil {
207-
guard let _ = rawContract.events[eventName!] else {
208-
throw Web3Error.processingError(desc: "No such event in a contract")
209-
}
210-
}
211-
let request = JSONRPCRequestFabric.prepareRequest(.getLogs, parameters: [preEncoding])
212-
let response = try await self.web3.dispatch(request)
192+
let rawContract = self.contract
193+
guard let preEncoding = encodeTopicToGetLogs(contract: rawContract, eventName: eventName, filter: filter) else {
194+
throw Web3Error.processingError(desc: "Failed to encode topic for request")
195+
}
213196

214-
guard let allLogs: [EventLog] = response.getValue() else {
215-
if response.error != nil {
216-
throw Web3Error.nodeError(desc: response.error!.message)
217-
}
218-
throw Web3Error.nodeError(desc: "Empty or malformed response")
197+
if eventName != nil {
198+
guard let _ = rawContract.events[eventName!] else {
199+
throw Web3Error.processingError(desc: "No such event in a contract")
219200
}
201+
}
220202

203+
// FIXME: This could not worked at all.
204+
let request: APIRequest = .getLogs(preEncoding)
205+
let response: APIResponse<[EventLog]> = try await APIRequest.sendRequest(with: self.web3.provider, for: request)
221206

222-
let decodedLogs = allLogs.compactMap { (log) -> EventParserResult? in
223-
let (n, d) = self.contract.parseEvent(log)
224-
guard let evName = n, let evData = d else {return nil}
225-
var res = EventParserResult(eventName: evName, transactionReceipt: nil, contractAddress: log.address, decodedResult: evData)
226-
res.eventLog = log
227-
return res
228-
}
207+
let decodedLogs = response.result.compactMap { (log) -> EventParserResult? in
208+
let (n, d) = self.contract.parseEvent(log)
209+
guard let evName = n, let evData = d else {return nil}
210+
var res = EventParserResult(eventName: evName, transactionReceipt: nil, contractAddress: log.address, decodedResult: evData)
211+
res.eventLog = log
212+
return res
213+
}
229214
.filter{ res in res.eventLog != nil || (res.eventName == eventName && eventName != nil)}
230215

231216

232-
if (!joinWithReceipts) {
233-
return decodedLogs as [EventParserResultProtocol]
234-
}
235-
217+
if (!joinWithReceipts) {
218+
return decodedLogs as [EventParserResultProtocol]
219+
}
236220

237221
return await withTaskGroup(of: EventParserResultProtocol.self, returning: [EventParserResultProtocol].self) { group -> [EventParserResultProtocol] in
238222

@@ -252,7 +236,6 @@ extension web3.web3contract {
252236
}
253237

254238
return collected
255-
256239
}
257240
}
258241
}

Sources/web3swift/Web3/Web3+HttpProvider.swift

Lines changed: 37 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ 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
13+
// func sendAsync(_ request: JSONRPCrequest) async throws -> JSONRPCresponse
14+
// func sendAsync(_ requests: JSONRPCrequestBatch) async throws -> JSONRPCresponseBatch
1515
var network: Networks? {get set}
1616
var attachedKeystoreManager: KeystoreManager? {get set}
1717
var url: URL {get}
@@ -28,66 +28,44 @@ public class Web3HttpProvider: Web3Provider {
2828
let urlSession = URLSession(configuration: config)
2929
return urlSession
3030
}()
31-
public init?(_ httpProviderURL: URL, network net: Networks? = nil, keystoreManager manager: KeystoreManager? = nil) async {
32-
do {
33-
guard httpProviderURL.scheme == "http" || httpProviderURL.scheme == "https" else {
34-
return nil
35-
}
36-
url = httpProviderURL
37-
if net == nil {
38-
let request = JSONRPCRequestFabric.prepareRequest(.getNetwork, parameters: [])
39-
let response: JSONRPCresponse = try await Web3HttpProvider.post(request, providerURL: httpProviderURL, session: session)
40-
if response.error != nil {
41-
if response.message != nil {
42-
print(response.message!)
43-
}
44-
return nil
45-
}
46-
guard let result: String = response.getValue(), let intNetworkNumber = Int(result) else {return nil}
47-
network = Networks.fromInt(intNetworkNumber)
48-
if network == nil {
49-
return nil
50-
}
51-
} else {
52-
network = net
53-
}
54-
} catch {
55-
return nil
56-
}
31+
public init?(_ httpProviderURL: URL, network net: Networks, keystoreManager manager: KeystoreManager? = nil) {
32+
guard httpProviderURL.scheme == "http" || httpProviderURL.scheme == "https" else { return nil }
33+
url = httpProviderURL
34+
network = net
5735
attachedKeystoreManager = manager
5836
}
5937

60-
fileprivate static func dataFrom(session: URLSession, request urlRequest: URLRequest) async throws -> Data{
61-
let (data, _) = try await session.data(for: urlRequest)
62-
return data
63-
}
64-
65-
static func post<T: Decodable, U: Encodable>(_ request: U, providerURL: URL, session: URLSession) async throws -> T {
66-
let requestData = try JSONEncoder().encode(request)
67-
var urlRequest = URLRequest(url: providerURL, cachePolicy: .reloadIgnoringCacheData)
68-
urlRequest.httpMethod = "POST"
69-
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
70-
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
71-
urlRequest.httpBody = requestData
72-
73-
let data = try await dataFrom(session: session, request: urlRequest)
74-
75-
let parsedResponse = try JSONDecoder().decode(T.self, from: data)
76-
77-
if let response = parsedResponse as? JSONRPCresponse, response.error != nil {
78-
throw Web3Error.nodeError(desc: "Received an error message from node\n" + String(describing: response.error!))
79-
}
80-
return parsedResponse
81-
82-
}
83-
84-
public func sendAsync(_ request: JSONRPCrequest) async throws -> JSONRPCresponse {
85-
guard request.method != nil else {
86-
throw Web3Error.nodeError(desc: "RPC method is nill")
87-
}
88-
89-
return try await Web3HttpProvider.post(request, providerURL: self.url, session: self.session)
90-
}
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+
// }
9169

9270
// public func sendAsync(_ requests: JSONRPCrequestBatch) async throws -> JSONRPCresponseBatch {
9371
// return try await Web3HttpProvider.post(requests, providerURL: self.url, session: self.session)

0 commit comments

Comments
 (0)