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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{collections::BTreeMap, future::Future, pin::Pin};

use anyhow::Result;
use futures::{FutureExt, Stream, StreamExt, TryStreamExt};
use pbjson_types::Any;
use penumbra_auction::auction::AuctionId;
use tonic::{codegen::Bytes, Streaming};
use tracing::instrument;

use penumbra_app::params::AppParameters;
use penumbra_asset::{
    asset::{self, Id, Metadata},
    ValueView,
};
use penumbra_dex::{
    lp::position::{self, Position},
    TradingPair,
};
use penumbra_fee::GasPrices;
use penumbra_keys::{keys::AddressIndex, Address};
use penumbra_num::Amount;
use penumbra_proto::view::v1::{
    self as pb, view_service_client::ViewServiceClient, BalancesResponse,
    BroadcastTransactionResponse, WitnessRequest,
};
use penumbra_sct::Nullifier;
use penumbra_shielded_pool::{fmd, note};
use penumbra_stake::IdentityKey;
use penumbra_transaction::{
    txhash::TransactionId, AuthorizationData, Transaction, TransactionPlan, WitnessData,
};

use crate::{SpendableNoteRecord, StatusStreamResponse, SwapRecord, TransactionInfo};

pub(crate) type BroadcastStatusStream = Pin<
    Box<dyn Future<Output = Result<Streaming<BroadcastTransactionResponse>, anyhow::Error>> + Send>,
>;

/// The view protocol is used by a view client, who wants to do some
/// transaction-related actions, to request data from a view service, which is
/// responsible for synchronizing and scanning the public chain state with one
/// or more full viewing keys.
///
/// This trait is a wrapper around the proto-generated [`ViewServiceClient`]
/// that serves two goals:
///
/// 1. It can use domain types rather than proto-generated types, avoiding conversions;
/// 2. It's easier to write as a trait bound than the `CustodyProtocolClient`,
///   which requires complex bounds on its inner type to
///   enforce that it is a tower `Service`.
#[allow(clippy::type_complexity)]
pub trait ViewClient {
    /// Query the auction state
    fn auctions(
        &mut self,
        account_filter: Option<AddressIndex>,
        include_inactive: bool,
        query_latest_state: bool,
    ) -> Pin<
        Box<
            dyn Future<
                    Output = Result<
                        Vec<(AuctionId, SpendableNoteRecord, Option<Any>, Vec<Position>)>,
                    >,
                > + Send
                + 'static,
        >,
    >;

    /// Get the current status of chain sync.
    fn status(
        &mut self,
    ) -> Pin<Box<dyn Future<Output = Result<pb::StatusResponse>> + Send + 'static>>;

    /// Stream status updates on chain sync until it completes.
    fn status_stream(
        &mut self,
    ) -> Pin<
        Box<
            dyn Future<
                    Output = Result<
                        Pin<Box<dyn Stream<Item = Result<StatusStreamResponse>> + Send + 'static>>,
                    >,
                > + Send
                + 'static,
        >,
    >;

    /// Get a copy of the app parameters.
    fn app_params(
        &mut self,
    ) -> Pin<Box<dyn Future<Output = Result<AppParameters>> + Send + 'static>>;

    /// Get a copy of the gas prices.
    fn gas_prices(&mut self) -> Pin<Box<dyn Future<Output = Result<GasPrices>> + Send + 'static>>;

    /// Get a copy of the FMD parameters.
    fn fmd_parameters(
        &mut self,
    ) -> Pin<Box<dyn Future<Output = Result<fmd::Parameters>> + Send + 'static>>;

    /// Queries for notes.
    fn notes(
        &mut self,
        request: pb::NotesRequest,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<SpendableNoteRecord>>> + Send + 'static>>;

    /// Queries for notes for voting.
    fn notes_for_voting(
        &mut self,
        request: pb::NotesForVotingRequest,
    ) -> Pin<
        Box<dyn Future<Output = Result<Vec<(SpendableNoteRecord, IdentityKey)>>> + Send + 'static>,
    >;

    /// Queries for account balance by address
    fn balances(
        &mut self,
        address_index: AddressIndex,
        asset_id: Option<asset::Id>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<(Id, Amount)>>> + Send + 'static>>;

    /// Queries for a specific note by commitment, returning immediately if it is not found.
    fn note_by_commitment(
        &mut self,
        note_commitment: note::StateCommitment,
    ) -> Pin<Box<dyn Future<Output = Result<SpendableNoteRecord>> + Send + 'static>>;

    /// Queries for a specific swap by commitment, returning immediately if it is not found.
    fn swap_by_commitment(
        &mut self,
        swap_commitment: penumbra_tct::StateCommitment,
    ) -> Pin<Box<dyn Future<Output = Result<SwapRecord>> + Send + 'static>>;

    /// Queries for a specific nullifier's status, returning immediately if it is not found.
    fn nullifier_status(
        &mut self,
        nullifier: Nullifier,
    ) -> Pin<Box<dyn Future<Output = Result<bool>> + Send + 'static>>;

    /// Waits for a specific nullifier to be detected, returning immediately if it is already
    /// present, but waiting otherwise.
    fn await_nullifier(
        &mut self,
        nullifier: Nullifier,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;

    /// Queries for a specific note by commitment, waiting until the note is detected if it is not found.
    ///
    /// This is useful for waiting for a note to be detected by the view service.
    fn await_note_by_commitment(
        &mut self,
        note_commitment: note::StateCommitment,
    ) -> Pin<Box<dyn Future<Output = Result<SpendableNoteRecord>> + Send + 'static>>;

    /// Returns authentication paths for the given note commitments.
    ///
    /// This method takes a batch of input commitments, rather than just one, so
    /// that the client can get a consistent set of authentication paths to a
    /// common root.  (Otherwise, if a client made multiple requests, the wallet
    /// service could have advanced the state commitment tree state between queries).
    fn witness(
        &mut self,
        plan: &TransactionPlan,
    ) -> Pin<Box<dyn Future<Output = Result<WitnessData>> + Send + 'static>>;

    /// Returns a transaction built from the provided TransactionPlan and AuthorizationData
    fn witness_and_build(
        &mut self,
        plan: TransactionPlan,
        auth_data: AuthorizationData,
    ) -> Pin<Box<dyn Future<Output = Result<Transaction>> + Send + 'static>>;

    /// Queries for all known assets.
    fn assets(&mut self) -> Pin<Box<dyn Future<Output = Result<asset::Cache>> + Send + 'static>>;

    /// Queries for liquidity positions owned by the full viewing key.
    fn owned_position_ids(
        &mut self,
        position_state: Option<position::State>,
        trading_pair: Option<TradingPair>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<position::Id>>> + Send + 'static>>;

    /// Generates a full perspective for a selected transaction using a full viewing key
    fn transaction_info_by_hash(
        &mut self,
        id: TransactionId,
    ) -> Pin<Box<dyn Future<Output = Result<TransactionInfo>> + Send + 'static>>;

    /// Queries for transactions in a range of block heights
    fn transaction_info(
        &mut self,
        start_height: Option<u64>,
        end_height: Option<u64>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<TransactionInfo>>> + Send + 'static>>;

    fn broadcast_transaction(
        &mut self,
        transaction: Transaction,
        await_detection: bool,
    ) -> BroadcastStatusStream;

    /// Return unspent notes, grouped by address index and then by asset id.
    #[instrument(skip(self))]
    fn unspent_notes_by_address_and_asset(
        &mut self,
    ) -> Pin<
        Box<
            dyn Future<
                    Output = Result<
                        BTreeMap<AddressIndex, BTreeMap<asset::Id, Vec<SpendableNoteRecord>>>,
                    >,
                > + Send
                + 'static,
        >,
    > {
        let notes = self.notes(pb::NotesRequest {
            include_spent: false,
            ..Default::default()
        });
        async move {
            let notes = notes.await?;
            tracing::trace!(?notes);

            let mut notes_by_address_and_asset = BTreeMap::new();

            for note_record in notes {
                notes_by_address_and_asset
                    .entry(note_record.address_index)
                    .or_insert_with(BTreeMap::new)
                    .entry(note_record.note.asset_id())
                    .or_insert_with(Vec::new)
                    .push(note_record);
            }
            tracing::trace!(?notes_by_address_and_asset);

            Ok(notes_by_address_and_asset)
        }
        .boxed()
    }

    /// Return unspent notes, grouped by account ID (combining ephemeral addresses for the account) and then by asset id.
    #[instrument(skip(self))]
    fn unspent_notes_by_account_and_asset(
        &mut self,
    ) -> Pin<
        Box<
            dyn Future<
                    Output = Result<BTreeMap<u32, BTreeMap<asset::Id, Vec<SpendableNoteRecord>>>>,
                > + Send
                + 'static,
        >,
    > {
        let notes = self.notes(pb::NotesRequest {
            include_spent: false,
            ..Default::default()
        });
        async move {
            let notes = notes.await?;
            tracing::trace!(?notes);

            let mut notes_by_account_and_asset = BTreeMap::new();

            for note_record in notes {
                notes_by_account_and_asset
                    .entry(note_record.address_index.account)
                    .or_insert_with(BTreeMap::new)
                    .entry(note_record.note.asset_id())
                    .or_insert_with(Vec::new)
                    .push(note_record);
            }
            tracing::trace!(?notes_by_account_and_asset);

            Ok(notes_by_account_and_asset)
        }
        .boxed()
    }

    /// Return unspent notes, grouped by denom and then by address index.
    #[instrument(skip(self))]
    fn unspent_notes_by_asset_and_address(
        &mut self,
    ) -> Pin<
        Box<
            dyn Future<
                    Output = Result<
                        BTreeMap<asset::Id, BTreeMap<AddressIndex, Vec<SpendableNoteRecord>>>,
                    >,
                > + Send
                + 'static,
        >,
    > {
        let notes = self.notes(pb::NotesRequest {
            include_spent: false,
            ..Default::default()
        });

        async move {
            let notes = notes.await?;
            tracing::trace!(?notes);

            let mut notes_by_asset_and_address = BTreeMap::new();

            for note_record in notes {
                notes_by_asset_and_address
                    .entry(note_record.note.asset_id())
                    .or_insert_with(BTreeMap::new)
                    .entry(note_record.address_index)
                    .or_insert_with(Vec::new)
                    .push(note_record);
            }
            tracing::trace!(?notes_by_asset_and_address);

            Ok(notes_by_asset_and_address)
        }
        .boxed()
    }

    fn address_by_index(
        &mut self,
        address_index: AddressIndex,
    ) -> Pin<Box<dyn Future<Output = Result<Address>> + Send + 'static>>;

    /// Queries for unclaimed Swaps.
    fn unclaimed_swaps(
        &mut self,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<SwapRecord>>> + Send + 'static>>;
}

// We need to tell `async_trait` not to add a `Send` bound to the boxed
// futures it generates, because the underlying `CustodyProtocolClient` isn't `Sync`,
// but its `authorize` method takes `&mut self`. This would normally cause a huge
// amount of problems, because non-`Send` futures don't compose well, but as long
// as we're calling the method within an async block on a local mutable variable,
// it should be fine.
impl<T> ViewClient for ViewServiceClient<T>
where
    T: tonic::client::GrpcService<tonic::body::BoxBody> + Clone + Send + 'static,
    T::ResponseBody: tonic::codegen::Body<Data = Bytes> + Send + 'static,
    T::Error: Into<tonic::codegen::StdError>,
    T::Future: Send + 'static,
    <T::ResponseBody as tonic::codegen::Body>::Error: Into<tonic::codegen::StdError> + Send,
{
    fn status(
        &mut self,
    ) -> Pin<Box<dyn Future<Output = Result<pb::StatusResponse>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            let status = self2.status(tonic::Request::new(pb::StatusRequest {}));
            let status = status.await?.into_inner();
            Ok(status)
        }
        .boxed()
    }

    fn status_stream(
        &mut self,
    ) -> Pin<
        Box<
            dyn Future<
                    Output = Result<
                        Pin<Box<dyn Stream<Item = Result<StatusStreamResponse>> + Send + 'static>>,
                    >,
                > + Send
                + 'static,
        >,
    > {
        let mut self2 = self.clone();
        async move {
            let stream = self2.status_stream(tonic::Request::new(pb::StatusStreamRequest {}));
            let stream = stream.await?.into_inner();

            Ok(stream
                .map_err(|e| anyhow::anyhow!("view service error: {}", e))
                .and_then(|msg| async move { StatusStreamResponse::try_from(msg) })
                .boxed())
        }
        .boxed()
    }

    fn app_params(
        &mut self,
    ) -> Pin<Box<dyn Future<Output = Result<AppParameters>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            // We have to manually invoke the method on the type, because it has the
            // same name as the one we're implementing.
            let rsp = ViewServiceClient::app_parameters(
                &mut self2,
                tonic::Request::new(pb::AppParametersRequest {}),
            );
            rsp.await?.into_inner().try_into()
        }
        .boxed()
    }

    fn gas_prices(&mut self) -> Pin<Box<dyn Future<Output = Result<GasPrices>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            // We have to manually invoke the method on the type, because it has the
            // same name as the one we're implementing.
            let rsp = ViewServiceClient::gas_prices(
                &mut self2,
                tonic::Request::new(pb::GasPricesRequest {}),
            );
            rsp.await?
                .into_inner()
                .gas_prices
                .ok_or_else(|| anyhow::anyhow!("empty GasPricesResponse message"))?
                .try_into()
        }
        .boxed()
    }

    fn fmd_parameters(
        &mut self,
    ) -> Pin<Box<dyn Future<Output = Result<fmd::Parameters>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            let parameters = ViewServiceClient::fmd_parameters(
                &mut self2,
                tonic::Request::new(pb::FmdParametersRequest {}),
            );
            let parameters = parameters.await?.into_inner().parameters;

            parameters
                .ok_or_else(|| anyhow::anyhow!("empty FmdParametersRequest message"))?
                .try_into()
        }
        .boxed()
    }

    fn notes(
        &mut self,
        request: pb::NotesRequest,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<SpendableNoteRecord>>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            let req = self2.notes(tonic::Request::new(request));
            let pb_notes: Vec<_> = req.await?.into_inner().try_collect().await?;

            pb_notes
                .into_iter()
                .map(|note_rsp| {
                    let note_record = note_rsp
                        .note_record
                        .ok_or_else(|| anyhow::anyhow!("empty NotesResponse message"));

                    match note_record {
                        Ok(note) => note.try_into(),
                        Err(e) => Err(e),
                    }
                })
                .collect()
        }
        .boxed()
    }

    fn notes_for_voting(
        &mut self,
        request: pb::NotesForVotingRequest,
    ) -> Pin<
        Box<dyn Future<Output = Result<Vec<(SpendableNoteRecord, IdentityKey)>>> + Send + 'static>,
    > {
        let mut self2 = self.clone();
        async move {
            let req = self2.notes_for_voting(tonic::Request::new(request));
            let pb_notes: Vec<_> = req.await?.into_inner().try_collect().await?;

            pb_notes
                .into_iter()
                .map(|note_rsp| {
                    let note_record = note_rsp
                        .note_record
                        .ok_or_else(|| anyhow::anyhow!("empty NotesForVotingResponse message"))?
                        .try_into()?;

                    let identity_key = note_rsp
                        .identity_key
                        .ok_or_else(|| anyhow::anyhow!("empty NotesForVotingResponse message"))?
                        .try_into()?;

                    Ok((note_record, identity_key))
                })
                .collect()
        }
        .boxed()
    }

    fn note_by_commitment(
        &mut self,
        note_commitment: note::StateCommitment,
    ) -> Pin<Box<dyn Future<Output = Result<SpendableNoteRecord>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            let note_commitment_response = ViewServiceClient::note_by_commitment(
                &mut self2,
                tonic::Request::new(pb::NoteByCommitmentRequest {
                    note_commitment: Some(note_commitment.into()),
                    await_detection: false,
                }),
            );
            let note_commitment_response = note_commitment_response.await?.into_inner();

            note_commitment_response
                .spendable_note
                .ok_or_else(|| anyhow::anyhow!("empty NoteByCommitmentResponse message"))?
                .try_into()
        }
        .boxed()
    }

    fn balances(
        &mut self,
        address_index: AddressIndex,
        asset_id: Option<asset::Id>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<(Id, Amount)>>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            let req = ViewServiceClient::balances(
                &mut self2,
                tonic::Request::new(pb::BalancesRequest {
                    account_filter: Some(address_index.into()),
                    asset_id_filter: asset_id.map(Into::into),
                }),
            );

            let balances: Vec<BalancesResponse> = req.await?.into_inner().try_collect().await?;

            balances
                .into_iter()
                .map(|rsp| {
                    let pb_value_view = rsp
                        .balance_view
                        .ok_or_else(|| anyhow::anyhow!("empty balance view"))?;

                    let value_view: ValueView = pb_value_view.try_into()?;
                    let id = value_view.asset_id();
                    let amount = value_view.value().amount;
                    Ok((id, amount))
                })
                .collect()
        }
        .boxed()
    }

    fn swap_by_commitment(
        &mut self,
        swap_commitment: penumbra_tct::StateCommitment,
    ) -> Pin<Box<dyn Future<Output = Result<SwapRecord>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            let swap_commitment_response = ViewServiceClient::swap_by_commitment(
                &mut self2,
                tonic::Request::new(pb::SwapByCommitmentRequest {
                    swap_commitment: Some(swap_commitment.into()),
                    await_detection: false,
                }),
            );
            let swap_commitment_response = swap_commitment_response.await?.into_inner();

            swap_commitment_response
                .swap
                .ok_or_else(|| anyhow::anyhow!("empty SwapByCommitmentResponse message"))?
                .try_into()
        }
        .boxed()
    }

    /// Queries for a specific note by commitment, waiting until the note is detected if it is not found.
    ///
    /// This is useful for waiting for a note to be detected by the view service.
    fn await_note_by_commitment(
        &mut self,
        note_commitment: note::StateCommitment,
    ) -> Pin<Box<dyn Future<Output = Result<SpendableNoteRecord>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            let spendable_note = ViewServiceClient::note_by_commitment(
                &mut self2,
                tonic::Request::new(pb::NoteByCommitmentRequest {
                    note_commitment: Some(note_commitment.into()),
                    await_detection: true,
                }),
            );
            let spendable_note = spendable_note.await?.into_inner().spendable_note;

            spendable_note
                .ok_or_else(|| anyhow::anyhow!("empty NoteByCommitmentRequest message"))?
                .try_into()
        }
        .boxed()
    }

    /// Queries for a specific nullifier's status, returning immediately if it is not found.
    fn nullifier_status(
        &mut self,
        nullifier: Nullifier,
    ) -> Pin<Box<dyn Future<Output = Result<bool>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            let rsp = ViewServiceClient::nullifier_status(
                &mut self2,
                tonic::Request::new(pb::NullifierStatusRequest {
                    nullifier: Some(nullifier.into()),
                    await_detection: false,
                }),
            );
            Ok(rsp.await?.into_inner().spent)
        }
        .boxed()
    }

    /// Waits for a specific nullifier to be detected, returning immediately if it is already
    /// present, but waiting otherwise.
    fn await_nullifier(
        &mut self,
        nullifier: Nullifier,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            let rsp = ViewServiceClient::nullifier_status(
                &mut self2,
                tonic::Request::new(pb::NullifierStatusRequest {
                    nullifier: Some(nullifier.into()),
                    await_detection: true,
                }),
            );
            rsp.await?;
            Ok(())
        }
        .boxed()
    }

    fn witness(
        &mut self,
        plan: &TransactionPlan,
    ) -> Pin<Box<dyn Future<Output = Result<WitnessData>> + Send + 'static>> {
        let request = WitnessRequest {
            transaction_plan: Some(plan.clone().into()),
        };

        let mut self2 = self.clone();
        async move {
            let rsp = self2.witness(tonic::Request::new(request));

            let witness_data = rsp
                .await?
                .into_inner()
                .witness_data
                .ok_or_else(|| anyhow::anyhow!("empty WitnessResponse message"))?
                .try_into()?;

            Ok(witness_data)
        }
        .boxed()
    }

    fn assets(&mut self) -> Pin<Box<dyn Future<Output = Result<asset::Cache>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            // We have to manually invoke the method on the type, because it has the
            // same name as the one we're implementing.
            let rsp = ViewServiceClient::assets(
                &mut self2,
                tonic::Request::new(pb::AssetsRequest {
                    ..Default::default()
                }),
            );

            let pb_assets: Vec<_> = rsp.await?.into_inner().try_collect().await?;

            let assets = pb_assets
                .into_iter()
                .map(Metadata::try_from)
                .collect::<anyhow::Result<Vec<Metadata>>>()?;

            Ok(assets.into_iter().collect())
        }
        .boxed()
    }

    fn owned_position_ids(
        &mut self,
        position_state: Option<position::State>,
        trading_pair: Option<TradingPair>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<position::Id>>> + Send + 'static>> {
        // should the return be streamed here? none of the other viewclient responses are, probably fine for now
        // but might be an issue eventually
        let mut self2 = self.clone();
        async move {
            // We have to manually invoke the method on the type, because it has the
            // same name as the one we're implementing.
            let rsp = ViewServiceClient::owned_position_ids(
                &mut self2,
                tonic::Request::new(pb::OwnedPositionIdsRequest {
                    trading_pair: trading_pair.map(TryInto::try_into).transpose()?,
                    position_state: position_state.map(TryInto::try_into).transpose()?,
                }),
            );

            let pb_position_ids: Vec<_> = rsp.await?.into_inner().try_collect().await?;

            let position_ids = pb_position_ids
                .into_iter()
                .map(|p| {
                    position::Id::try_from(p.position_id.ok_or_else(|| {
                        anyhow::anyhow!("empty OwnedPositionsIdsResponse message")
                    })?)
                })
                .collect::<anyhow::Result<Vec<position::Id>>>()?;

            Ok(position_ids)
        }
        .boxed()
    }

    fn transaction_info_by_hash(
        &mut self,
        id: TransactionId,
    ) -> Pin<Box<dyn Future<Output = Result<TransactionInfo>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            let rsp = ViewServiceClient::transaction_info_by_hash(
                &mut self2,
                tonic::Request::new(pb::TransactionInfoByHashRequest {
                    id: Some(id.into()),
                }),
            )
            .await?
            .into_inner()
            .tx_info
            .ok_or_else(|| anyhow::anyhow!("empty TransactionInfoByHashResponse message"))?;

            // Check some assumptions about response structure
            if rsp.height == 0 {
                anyhow::bail!("missing height");
            }

            let tx_info = TransactionInfo {
                height: rsp.height,
                id: rsp
                    .id
                    .ok_or_else(|| anyhow::anyhow!("missing id"))?
                    .try_into()?,
                transaction: rsp
                    .transaction
                    .ok_or_else(|| anyhow::anyhow!("missing transaction"))?
                    .try_into()?,
                perspective: rsp
                    .perspective
                    .ok_or_else(|| anyhow::anyhow!("missing perspective"))?
                    .try_into()?,
                view: rsp
                    .view
                    .ok_or_else(|| anyhow::anyhow!("missing view"))?
                    .try_into()?,
            };

            Ok(tx_info)
        }
        .boxed()
    }

    fn transaction_info(
        &mut self,
        start_height: Option<u64>,
        end_height: Option<u64>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<TransactionInfo>>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            // Unpack optional block heights
            let start_h = if let Some(h) = start_height { h } else { 0 };

            let end_h = if let Some(h) = end_height { h } else { 0 };

            let rsp = self2.transaction_info(tonic::Request::new(pb::TransactionInfoRequest {
                start_height: start_h,
                end_height: end_h,
            }));
            let pb_txs: Vec<_> = rsp.await?.into_inner().try_collect().await?;

            pb_txs
                .into_iter()
                .map(|rsp| {
                    let tx_rsp = rsp
                        .tx_info
                        .ok_or_else(|| anyhow::anyhow!("empty TransactionInfoResponse message"))?;

                    // Confirm height is populated
                    if tx_rsp.height == 0 {
                        anyhow::bail!("missing height");
                    }

                    let tx_info = TransactionInfo {
                        height: tx_rsp.height,
                        transaction: tx_rsp
                            .transaction
                            .ok_or_else(|| {
                                anyhow::anyhow!("empty TransactionInfoResponse message")
                            })?
                            .try_into()?,
                        id: tx_rsp
                            .id
                            .ok_or_else(|| anyhow::anyhow!("missing id"))?
                            .try_into()?,
                        perspective: tx_rsp
                            .perspective
                            .ok_or_else(|| anyhow::anyhow!("missing perspective"))?
                            .try_into()?,
                        view: tx_rsp
                            .view
                            .ok_or_else(|| anyhow::anyhow!("missing view"))?
                            .try_into()?,
                    };

                    Ok(tx_info)
                })
                .collect()
        }
        .boxed()
    }

    fn broadcast_transaction(
        &mut self,
        transaction: Transaction,
        await_detection: bool,
    ) -> BroadcastStatusStream {
        let mut self2 = self.clone();
        async move {
            let rsp = ViewServiceClient::broadcast_transaction(
                &mut self2,
                tonic::Request::new(pb::BroadcastTransactionRequest {
                    transaction: Some(transaction.into()),
                    await_detection,
                }),
            )
            .await?
            .into_inner();

            Ok(rsp)
        }
        .boxed()
    }

    fn address_by_index(
        &mut self,
        address_index: AddressIndex,
    ) -> Pin<Box<dyn Future<Output = Result<Address>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            let address = self2.address_by_index(tonic::Request::new(pb::AddressByIndexRequest {
                address_index: Some(address_index.into()),
            }));
            let address = address
                .await?
                .into_inner()
                .address
                .ok_or_else(|| anyhow::anyhow!("No address available for this address index"))?
                .try_into()?;
            Ok(address)
        }
        .boxed()
    }

    fn witness_and_build(
        &mut self,
        transaction_plan: TransactionPlan,
        authorization_data: AuthorizationData,
    ) -> Pin<Box<dyn Future<Output = Result<Transaction>> + Send + 'static>> {
        let request = pb::WitnessAndBuildRequest {
            transaction_plan: Some(transaction_plan.into()),
            authorization_data: Some(authorization_data.into()),
        };
        let mut self2 = self.clone();
        async move {
            let mut rsp = self2
                .witness_and_build(tonic::Request::new(request))
                .await?
                .into_inner();

            while let Some(rsp) = rsp.try_next().await? {
                match rsp.status {
                    Some(status) => match status {
                        pb::witness_and_build_response::Status::BuildProgress(_) => {
                            // TODO: should update progress here
                        }
                        pb::witness_and_build_response::Status::Complete(c) => {
                            return c.transaction
                                .ok_or_else(|| {
                                    anyhow::anyhow!("WitnessAndBuildResponse complete status message missing transaction")
                                })?
                                .try_into();
                        }
                    },
                    None => {
                        // No status is unexpected behavior
                        return Err(anyhow::anyhow!(
                            "empty WitnessAndBuildResponse message"
                        ));
                    }
                }
            }

            Err(anyhow::anyhow!("should have received complete status or error"))
        }
            .boxed()
    }

    fn unclaimed_swaps(
        &mut self,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<SwapRecord>>> + Send + 'static>> {
        let mut self2 = self.clone();
        async move {
            let swaps_response = ViewServiceClient::unclaimed_swaps(
                &mut self2,
                tonic::Request::new(pb::UnclaimedSwapsRequest {}),
            );
            let pb_swaps: Vec<_> = swaps_response.await?.into_inner().try_collect().await?;

            pb_swaps
                .into_iter()
                .map(|swap_rsp| {
                    let swap_record = swap_rsp
                        .swap
                        .ok_or_else(|| anyhow::anyhow!("empty UnclaimedSwapsResponse message"));

                    match swap_record {
                        Ok(swap) => swap.try_into(),
                        Err(e) => Err(e),
                    }
                })
                .collect()
        }
        .boxed()
    }

    fn auctions(
        &mut self,
        account_filter: Option<AddressIndex>,
        include_inactive: bool,
        query_latest_state: bool,
    ) -> Pin<
        Box<
            dyn Future<
                    Output = Result<
                        Vec<(AuctionId, SpendableNoteRecord, Option<Any>, Vec<Position>)>,
                    >,
                > + Send
                + 'static,
        >,
    > {
        let mut client = self.clone();
        async move {
            let request = tonic::Request::new(pb::AuctionsRequest {
                account_filter: account_filter.map(Into::into),
                include_inactive,
                query_latest_state,
            });

            let auctions: Vec<pb::AuctionsResponse> =
                ViewServiceClient::auctions(&mut client, request)
                    .await?
                    .into_inner()
                    .try_collect()
                    .await?;

            let resp: Vec<(AuctionId, SpendableNoteRecord, Option<Any>, Vec<Position>)> =
                auctions
                    .into_iter()
                    .map(|auction_rsp| {
                        let pb_id = auction_rsp
                            .id
                            .ok_or_else(|| anyhow::anyhow!("missing auction id!!"))?;
                        let auction_id: AuctionId = pb_id.try_into()?;
                        let snr: SpendableNoteRecord = auction_rsp
                            .note_record
                            .ok_or_else(|| anyhow::anyhow!("mission SNR from auction response"))?
                            .try_into()?;

                        let auction = auction_rsp.auction;
                        let lps: Vec<Position> = auction_rsp
                            .positions
                            .into_iter()
                            .map(TryInto::try_into)
                            .collect::<Result<Vec<_>>>()?;

                        Ok::<
                            (AuctionId, SpendableNoteRecord, Option<Any>, Vec<Position>),
                            anyhow::Error,
                        >((auction_id, snr, auction, lps))
                    })
                    .filter_map(|res| res.ok()) // TODO: scrap this later.
                    .collect();

            Ok(resp)
        }
        .boxed()
    }
}