-
Notifications
You must be signed in to change notification settings - Fork 9
/
GatewayAPIClient+Live.swift
222 lines (204 loc) · 6.88 KB
/
GatewayAPIClient+Live.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// MARK: - Date + Sendable
extension Date: @unchecked Sendable {}
extension JSONDecoder {
static var `default`: JSONDecoder {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(CodableHelper.dateFormatter)
return decoder
}
}
extension GatewayAPIClient {
public struct EmptyEntityDetailsResponse: Error {}
public typealias SingleEntityDetailsResponse = (ledgerState: GatewayAPI.LedgerState, details: GatewayAPI.StateEntityDetailsResponseItem)
public typealias Value = GatewayAPIClient
public static let liveValue = GatewayAPIClient.live(
jsonEncoder: .init(),
jsonDecoder: .default
)
public static func live(
jsonEncoder: JSONEncoder,
jsonDecoder: JSONDecoder
) -> Self {
@Dependency(\.gatewaysClient) var gatewaysClient
@Dependency(\.httpClient) var httpClient
let getCurrentBaseURL: @Sendable () async -> URL = {
await gatewaysClient.getGatewayAPIEndpointBaseURL()
}
@Sendable
func makeRequest<Response>(
httpBodyData httpBody: Data? = nil,
method: String = "POST",
responseType _: Response.Type,
baseURL: URL,
timeoutInterval: TimeInterval? = nil,
urlFromBase: @Sendable (URL) -> URL
) async throws -> Response where Response: Decodable {
let url = urlFromBase(baseURL)
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method
if let httpBody {
urlRequest.httpBody = httpBody
}
urlRequest.setHttpHeaderFields()
if let timeoutInterval {
urlRequest.timeoutInterval = timeoutInterval
}
let data = try await httpClient.executeRequest(urlRequest)
do {
return try jsonDecoder.decode(Response.self, from: data)
} catch {
throw ResponseDecodingError(receivedData: data, error: error)
}
}
@Sendable
func makeRequest<Response>(
httpBodyData httpBody: Data?,
method: String = "POST",
responseType: Response.Type,
urlFromBase: @escaping @Sendable (URL) -> URL
) async throws -> Response where Response: Decodable {
try await makeRequest(
httpBodyData: httpBody,
method: method,
responseType: responseType,
baseURL: getCurrentBaseURL(),
urlFromBase: urlFromBase
)
}
@Sendable
func makeRequest<Response>(
httpBodyData httpBody: Data?,
method: String = "POST",
urlFromBase: @escaping @Sendable (URL) -> URL
) async throws -> Response where Response: Decodable {
try await makeRequest(
httpBodyData: httpBody,
method: method,
responseType: Response.self,
urlFromBase: urlFromBase
)
}
@Sendable
func post<Response>(
urlFromBase: @escaping @Sendable (URL) -> URL
) async throws -> Response where Response: Decodable {
try await makeRequest(httpBodyData: nil, responseType: Response.self, urlFromBase: urlFromBase)
}
@Sendable
func post<Response>(
request: some Encodable,
dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .deferredToDate,
urlFromBase: @escaping @Sendable (URL) -> URL
) async throws -> Response where Response: Decodable {
jsonEncoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
jsonEncoder.dateEncodingStrategy = dateEncodingStrategy
let httpBody = try jsonEncoder.encode(request)
return try await makeRequest(httpBodyData: httpBody, urlFromBase: urlFromBase)
}
@Sendable
func getEntityDetails(_ addresses: [String], explictMetadata: Set<EntityMetadataKey>, ledgerState: GatewayAPI.LedgerStateSelector?) async throws -> GatewayAPI.StateEntityDetailsResponse {
assert(explictMetadata.count <= EntityMetadataKey.maxAllowedKeys)
return try await post(
request: GatewayAPI.StateEntityDetailsRequest(
atLedgerState: ledgerState,
optIns: .init(
explicitMetadata: explictMetadata.map(\.rawValue)
),
addresses: addresses, aggregationLevel: .vault
)) { @Sendable base in base.appendingPathComponent("state/entity/details") }
}
@Sendable
func getSingleEntityDetails(
_ address: String,
explictMetadata: Set<EntityMetadataKey>
) async throws -> SingleEntityDetailsResponse {
let response = try await getEntityDetails([address], explictMetadata: explictMetadata, ledgerState: nil)
guard let item = response.items.first else {
throw EmptyEntityDetailsResponse()
}
return (response.ledgerState, item)
}
return GatewayAPIClient(
getNetworkName: { baseURL in
let response = try await makeRequest(
responseType: GatewayAPI.GatewayStatusResponse.self,
baseURL: baseURL,
timeoutInterval: nil
) {
$0.appendingPathComponent("status/gateway-status")
}
return NetworkDefinition.Name(response.ledgerState.network)
},
getEpoch: {
let response = try await makeRequest(
responseType: GatewayAPI.TransactionConstructionResponse.self,
baseURL: getCurrentBaseURL(),
timeoutInterval: nil
) {
$0.appendingPathComponent("transaction/construction")
}
return Epoch(response.ledgerState.epoch)
},
getEntityDetails: getEntityDetails,
getEntityMetadata: { address, explicitMetadata in
try await getSingleEntityDetails(address, explictMetadata: explicitMetadata).details.metadata
},
getEntityMetadataPage: { request in
try await post(
request: request
) { $0.appendingPathComponent("state/entity/page/metadata/") }
},
getEntityFungiblesPage: { request in
try await post(
request: request
) { $0.appendingPathComponent("state/entity/page/fungibles/") }
},
getEntityFungibleResourceVaultsPage: { request in
try await post(
request: request
) { $0.appendingPathComponent("state/entity/page/fungible-vaults/") }
},
getEntityNonFungiblesPage: { request in
try await post(
request: request
) { $0.appendingPathComponent("state/entity/page/non-fungibles/") }
},
getEntityNonFungibleResourceVaultsPage: { request in
try await post(
request: request
) { $0.appendingPathComponent("state/entity/page/non-fungible-vaults/") }
},
getEntityNonFungibleIdsPage: { request in
try await post(
request: request
) { $0.appendingPathComponent("state/entity/page/non-fungible-vault/ids") }
},
getNonFungibleData: { request in
try await post(
request: request
) { $0.appendingPathComponent("state/non-fungible/data") }
},
submitTransaction: { transactionSubmitRequest in
try await post(
request: transactionSubmitRequest
) { $0.appendingPathComponent("transaction/submit") }
},
transactionStatus: { transactionStatusRequest in
try await post(
request: transactionStatusRequest
) { $0.appendingPathComponent("transaction/status") }
},
transactionPreview: { transactionPreviewRequest in
try await post(
request: transactionPreviewRequest
) { $0.appendingPathComponent("transaction/preview") }
},
streamTransactions: { streamTransactionsRequest in
try await post(
request: streamTransactionsRequest,
dateEncodingStrategy: .iso8601
) { $0.appendingPathComponent("stream/transactions") }
}
)
}
}