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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use std::error::Error;
use std::future::Future;
use std::pin::Pin;
use http::uri::PathAndQuery;
use http_body::Body;
use otopr::decoding::DecodableMessage;
use otopr::encoding::EncodableMessage;
use tonic::body::BoxBody;
use tonic::client::{Grpc, GrpcService};
use tonic::Request;
use crate::access::*;
use crate::codec::{OtoprCodec, PreEncode};
use crate::entities::{Account, Block, BlockHeader, Collection};
use crate::error::TonicError;
use crate::protobuf::*;
use crate::requests::FlowRequest;
use crate::transaction::{TransactionD, TransactionE};
pub trait GrpcClient<I, O> {
type Error: Into<Box<dyn Error + Send + Sync>>;
fn send<'a>(
&'a mut self,
input: I,
) -> Pin<Box<dyn Future<Output = Result<O, Self::Error>> + 'a>>;
}
impl<'t, T, I, O> GrpcClient<I, O> for &'t mut T
where
T: GrpcClient<I, O>,
{
type Error = T::Error;
fn send<'a>(
&'a mut self,
input: I,
) -> Pin<Box<dyn Future<Output = Result<O, Self::Error>> + 'a>> {
T::send(self, input)
}
}
#[derive(Default, Debug, Clone, Copy)]
pub struct FlowClient<T> {
inner: T,
}
pub type TonicClient<Service> = Grpc<Service>;
pub type TonicFlowClient<Service> = FlowClient<TonicClient<Service>>;
#[cfg(feature = "tonic-transport")]
pub type TonicHyperClient = TonicClient<tonic::transport::Channel>;
#[cfg(feature = "tonic-transport")]
pub type TonicHyperFlowClient = FlowClient<TonicHyperClient>;
pub type GrpcSendResult<'a, Output> =
Pin<Box<dyn Future<Output = Result<Output, TonicError>> + 'a>>;
macro_rules! choose {
((), ($($empty:tt)*), ($($non_empty:tt)*)) => {
$($empty)*
};
(($($tt:tt)+), ($($empty:tt)*), ($($non_empty:tt)*)) => {
$($non_empty)*
};
}
macro_rules! define_requests {
($($(#[$meta:meta])* $vis:vis async fn $fn_name:ident$(<($($ttss:tt)*)>)?($($tt:tt)*) $input:ty $(=> $output:ty)? $(where ($($tts:tt)*))? { $expr:expr })+) => {
$(
choose! {
($($output)?),
(
$(#[$meta])*
$vis fn $fn_name<'grpc, O, $($($ttss)*)?>(&'grpc mut self,$($tt)*) -> Pin<Box<dyn Future<Output = Result<O, Inner::Error>> + 'grpc>>
where
Inner: GrpcClient< $input, O >,
$($($tts)*)?
{
self.send($expr)
}
),
(
$(#[$meta])*
$vis fn $fn_name<'grpc, $($($ttss)*)?>(&'grpc mut self,$($tt)*) -> Pin<Box<dyn Future<Output = Result< $($output)? , Inner::Error>> + 'grpc>>
where
Inner: GrpcClient< $input, $($output)? >,
$($($tts)*)?
{
self.send($expr)
}
)
}
)+
}
}
macro_rules! remapping_requests {
($($(#[$meta:meta])* $vis:vis async fn $fn_name:ident$(<($($ttss:tt)*)>)?($($tt:tt)*)
$input:ty => $output:ty $(where ($($tts:tt)*))? {
$expr:expr;
remap = |$paramName:ident| -> $remappedty:ty $remap:block
})+) => {
$($(#[$meta])*
$vis fn $fn_name<'grpc, $($($ttss)*)?>(&'grpc mut self,$($tt)*) ->
futures_util::future::Map<
Pin<Box<dyn Future<Output = Result< $output, Inner::Error> > + 'grpc>>,
fn(Result< $output, Inner::Error >) -> Result< $remappedty, Inner::Error >,
>
where
Inner: GrpcClient< $input, $output >,
$($($tts)*)?
{
fn remap_ok($paramName: $output) -> $remappedty {
$remap
}
fn remap<E>(res: Result< $output, E >) -> Result< $remappedty, E > {
res.map(remap_ok)
}
use futures_util::FutureExt;
self.send($expr).map(remap::<Inner::Error>)
})+
}
}
impl<Inner> FlowClient<Inner> {
#[inline]
pub const fn new(inner: Inner) -> Self {
Self { inner }
}
#[inline]
pub fn into_inner(self) -> Inner {
self.inner
}
#[inline]
pub fn inner_mut(&mut self) -> &mut Inner {
&mut self.inner
}
#[inline]
pub fn send<'a, T, U>(
&'a mut self,
input: T,
) -> Pin<Box<dyn Future<Output = Result<U, Inner::Error>> + 'a>>
where
Inner: GrpcClient<T, U>,
{
self.inner.send(input)
}
define_requests! {
pub async fn ping() PingRequest => PingResponse {
PingRequest {}
}
pub async fn events_for_height_range<(EventTy)>(ty: EventTy, start_height: u64, end_height: u64) GetEventsForHeightRangeRequest<EventTy> => EventsResponse {
GetEventsForHeightRangeRequest { ty, start_height, end_height }
}
pub async fn events_for_blocks_by_ids<(EventTy, BlockIds)>(ty: EventTy, block_ids: BlockIds) GetEventsForBlockIdsRequest<EventTy, BlockIds> => EventsResponse {
GetEventsForBlockIdsRequest { ty, block_ids }
}
pub async fn execute_script_at_latest_block<(Script, Arguments)>(script: Script, arguments: Arguments) ExecuteScriptAtLatestBlockRequest<Script, Arguments> => ExecuteScriptResponse {
ExecuteScriptAtLatestBlockRequest { script, arguments }
}
pub async fn execute_script_at_block_id<(BlockId, Script, Arguments)>(block_id: BlockId, script: Script, arguments: Arguments) ExecuteScriptAtBlockIdRequest<BlockId, Script, Arguments> => ExecuteScriptResponse {
ExecuteScriptAtBlockIdRequest { block_id, script, arguments }
}
pub async fn execute_script_at_block_height<(Script, Arguments)>(block_height: u64, script: Script, arguments: Arguments) ExecuteScriptAtBlockHeightRequest<Script, Arguments> => ExecuteScriptResponse {
ExecuteScriptAtBlockHeightRequest { block_height, script, arguments }
}
pub async fn send_transaction<(
Script,
Arguments,
ReferenceBlockId,
ProposalKeyAddress,
Payer,
Authorizers,
PayloadSignatures,
EnvelopeSignatures,
)>(transaction: TransactionE<
Script,
Arguments,
ReferenceBlockId,
ProposalKeyAddress,
Payer,
Authorizers,
PayloadSignatures,
EnvelopeSignatures,
>) SendTransactionRequest<
Script,
Arguments,
ReferenceBlockId,
ProposalKeyAddress,
Payer,
Authorizers,
PayloadSignatures,
EnvelopeSignatures,
> => SendTransactionResponse
{
SendTransactionRequest { transaction }
}
pub async fn transaction_result_by_id<(Id)>(id: Id) GetTransactionRequest<Id> => TransactionResultResponse {
GetTransactionRequest { id }
}
}
remapping_requests! {
pub async fn transaction_by_id<(Id)>(id: Id) GetTransactionRequest<Id> => TransactionResponse {
GetTransactionRequest { id };
remap = |txn_response| -> TransactionD {
txn_response.transaction
}
}
pub async fn account_at_latest_block<(Addr)>(address: Addr) GetAccountAtLatestBlockRequest<Addr> => AccountResponse {
GetAccountAtLatestBlockRequest { address };
remap = |acc_response| -> Account {
acc_response.account
}
}
pub async fn account_at_block_height<(Addr)>(address: Addr, block_height: u64) GetAccountAtBlockHeightRequest<Addr> => AccountResponse {
GetAccountAtBlockHeightRequest { address, block_height };
remap = |acc_response| -> Account {
acc_response.account
}
}
pub async fn latest_block_header(seal: Seal) GetLatestBlockHeaderRequest => BlockHeaderResponse {
GetLatestBlockHeaderRequest { seal };
remap = |header_response| -> BlockHeader {
header_response.0
}
}
pub async fn block_header_by_height(height: u64) GetBlockHeaderByHeightRequest => BlockHeaderResponse {
GetBlockHeaderByHeightRequest { height };
remap = |header_response| -> BlockHeader {
header_response.0
}
}
pub async fn block_header_by_id<(Id)>(id: Id) GetBlockHeaderByIdRequest<Id> => BlockHeaderResponse {
GetBlockHeaderByIdRequest { id };
remap = |header_response| -> BlockHeader {
header_response.0
}
}
pub async fn latest_block(seal: Seal) GetLatestBlockRequest => BlockResponse {
GetLatestBlockRequest { seal };
remap = |block_response| -> Block {
block_response.0
}
}
pub async fn block_by_height(height: u64) GetBlockByHeightRequest => BlockResponse {
GetBlockByHeightRequest { height };
remap = |block_response| -> Block {
block_response.0
}
}
pub async fn block_by_id<(Id)>(id: Id) GetBlockByIdRequest<Id> => BlockResponse {
GetBlockByIdRequest { id };
remap = |block_response| -> Block {
block_response.0
}
}
pub async fn collection_by_id<(Id)>(id: Id) GetCollectionByIdRequest<Id> => CollectionResponse {
GetCollectionByIdRequest { id };
remap = |collection_response| -> Collection {
collection_response.collection
}
}
}
}
#[cfg(feature = "tonic-transport")]
impl TonicHyperFlowClient {
pub async fn connect_static(uri: &'static str) -> Result<Self, tonic::transport::Error> {
Self::connect(tonic::transport::Endpoint::from_static(uri)).await
}
pub async fn connect(
endpoint: tonic::transport::Endpoint,
) -> Result<Self, tonic::transport::Error> {
Ok(Self {
inner: Grpc::new(endpoint.connect().await?),
})
}
pub async fn mainnet() -> Result<Self, tonic::transport::Error> {
Self::connect_static("http://access.mainnet.nodes.onflow.org:9000").await
}
pub async fn testnet() -> Result<Self, tonic::transport::Error> {
Self::connect_static("http://access.devnet.nodes.onflow.org:9000").await
}
pub fn connect_static_lazy(uri: &'static str) -> Result<Self, tonic::transport::Error> {
Self::connect_lazy(tonic::transport::Endpoint::from_static(uri))
}
pub fn connect_lazy(
endpoint: tonic::transport::Endpoint,
) -> Result<Self, tonic::transport::Error> {
Ok(Self {
inner: Grpc::new(endpoint.connect_lazy()?),
})
}
pub fn mainnet_lazy() -> Result<Self, tonic::transport::Error> {
Self::connect_static_lazy("http://access.mainnet.nodes.onflow.org:9000")
}
pub fn testnet_lazy() -> Result<Self, tonic::transport::Error> {
Self::connect_static_lazy("http://access.devnet.nodes.onflow.org:9000")
}
}
impl<I, O, Service> GrpcClient<I, O> for Grpc<Service>
where
I: FlowRequest<O> + Send + Sync + EncodableMessage,
O: for<'b> DecodableMessage<'b> + Send + Sync + Default + 'static,
Service: GrpcService<BoxBody> + 'static,
Service::Error: Into<Box<dyn Error + Send + Sync>>,
Service::ResponseBody: Body + Send + Sync + 'static,
<Service::ResponseBody as Body>::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
{
type Error = TonicError;
fn send(&mut self, input: I) -> GrpcSendResult<O> {
let preenc = PreEncode::new(&input);
Box::pin(async move {
self.ready().await.map_err(Into::into)?;
Ok(self
.unary(
Request::new(preenc),
PathAndQuery::from_static(I::PATH),
OtoprCodec::default(),
)
.await?
.into_inner())
})
}
}
impl<Inner, I, O> GrpcClient<I, O> for FlowClient<Inner>
where
Inner: GrpcClient<I, O>,
{
type Error = Inner::Error;
#[inline]
fn send<'a>(
&'a mut self,
input: I,
) -> Pin<Box<dyn Future<Output = Result<O, Self::Error>> + 'a>> {
self.inner.send(input)
}
}