near-api-types 0.8.6

Rust types library to interact with NEAR Protocol via RPC API
Documentation
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
//! Result and execution types from results of RPC calls to the network.

use std::fmt;

use base64::{Engine as _, engine::general_purpose};
use borsh;
use near_openapi_types::{
    CallResult, ExecutionStatusView, FinalExecutionOutcomeView, FinalExecutionStatus,
    TxExecutionError, TxExecutionStatus,
};

use crate::{
    AccountId, CryptoHash, NearGas, NearToken, Signature,
    errors::{DataConversionError, ExecutionError},
    transaction::{SignedTransaction, Transaction},
};

/// Execution related info as a result of performing a successful transaction
/// execution on the network.
///
/// This value can be converted into the returned
/// value of the transaction via [`ExecutionSuccess::json`] or [`ExecutionSuccess::borsh`]
pub type ExecutionSuccess = ExecutionResult<Value>;

/// Execution related info as a result of performing a failed transaction
/// execution on the network. The related error message can be retrieved
/// from this object or can be forwarded.
pub type ExecutionFailure = ExecutionResult<TxExecutionError>;

/// Struct to hold a type we want to return along w/ the execution result view.
///
/// This view has extra info about the execution, such as gas usage and whether
/// the transaction failed to be processed on the chain.
#[non_exhaustive]
#[must_use = "use `into_result()` to handle potential execution errors"]
pub struct Execution<T> {
    pub result: T,
    pub details: ExecutionFinalResult,
}

impl<T> Execution<T> {
    #[track_caller]
    pub fn assert_success(self) -> T {
        #[allow(clippy::unwrap_used)]
        self.into_result().unwrap()
    }

    #[allow(clippy::result_large_err)]
    pub fn into_result(self) -> Result<T, ExecutionFailure> {
        self.details.into_result()?;
        Ok(self.result)
    }

    /// Checks whether the transaction was successful. Returns true if
    /// the transaction has a status of FinalExecutionStatus::Success.
    pub const fn is_success(&self) -> bool {
        self.details.is_success()
    }

    /// Checks whether the transaction has failed. Returns true if
    /// the transaction has a status of FinalExecutionStatus::Failure.
    pub const fn is_failure(&self) -> bool {
        self.details.is_failure()
    }
}

/// The transaction/receipt details of a transaction execution. This object
/// can be used to retrieve data such as logs and gas burnt per transaction
/// or receipt.
#[derive(Clone)]
pub(crate) struct ExecutionDetails {
    pub(crate) transaction_outcome: ExecutionOutcome,
    pub(crate) transaction: SignedTransaction,
    pub(crate) receipts: Vec<ExecutionOutcome>,
}

impl ExecutionDetails {
    /// Returns just the transaction outcome.
    pub const fn outcome(&self) -> &ExecutionOutcome {
        &self.transaction_outcome
    }

    pub const fn transaction(&self) -> &Transaction {
        &self.transaction.transaction
    }

    pub const fn signature(&self) -> &Signature {
        &self.transaction.signature
    }

    /// Grab all outcomes after the execution of the transaction. This includes outcomes
    /// from the transaction and all the receipts it generated.
    pub fn outcomes(&self) -> Vec<&ExecutionOutcome> {
        let mut outcomes = vec![&self.transaction_outcome];
        outcomes.extend(self.receipt_outcomes());
        outcomes
    }

    /// Grab all outcomes after the execution of the transaction. This includes outcomes
    /// only from receipts generated by this transaction.
    pub fn receipt_outcomes(&self) -> &[ExecutionOutcome] {
        &self.receipts
    }

    /// Grab all outcomes that did not succeed the execution of this transaction. This
    /// will also include the failures from receipts as well.
    pub fn failures(&self) -> Vec<&ExecutionOutcome> {
        let mut failures = Vec::new();
        if matches!(
            self.transaction_outcome.status,
            ExecutionStatusView::Failure(_)
        ) {
            failures.push(&self.transaction_outcome);
        }
        failures.extend(self.receipt_failures());
        failures
    }

    /// Just like `failures`, grab only failed receipt outcomes.
    pub fn receipt_failures(&self) -> Vec<&ExecutionOutcome> {
        self.receipts
            .iter()
            .filter(|receipt| matches!(receipt.status, ExecutionStatusView::Failure(_)))
            .collect()
    }

    /// Grab all logs from both the transaction and receipt outcomes.
    pub fn logs(&self) -> Vec<&str> {
        self.outcomes()
            .iter()
            .flat_map(|outcome| &outcome.logs)
            .map(String::as_str)
            .collect()
    }
}

/// The result after evaluating the status of an execution. This can be [`ExecutionSuccess`]
/// for successful executions or a [`ExecutionFailure`] for failed ones.
#[derive(Clone)]
#[non_exhaustive]
pub struct ExecutionResult<T> {
    /// Total gas burnt by the execution
    pub total_gas_burnt: NearGas,

    /// Value returned from an execution. This is a base64 encoded str for a successful
    /// execution or a `TxExecutionError` if a failed one.
    pub(crate) value: T,
    // pub(crate) transaction: ExecutionOutcome,
    // pub(crate) receipts: Vec<ExecutionOutcome>,
    pub(crate) details: ExecutionDetails,
}

impl<T: fmt::Debug> fmt::Debug for ExecutionResult<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ExecutionResult")
            .field("total_gas_burnt", &self.total_gas_burnt)
            .field("transaction", &self.details.transaction)
            .field("receipts", &self.details.receipts)
            .field("value", &self.value)
            .finish()
    }
}

impl fmt::Display for ExecutionResult<TxExecutionError> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ExecutionFailure: {:?}", self.value)
    }
}

// Might be a good idea to consider wrapping this into thiserror as we do for other errors in the project
// Though, to not introduce breaking change we will just mark it as error for now
impl std::error::Error for ExecutionResult<TxExecutionError> {}

/// Execution related info found after performing a transaction. Can be converted
/// into [`ExecutionSuccess`] or [`ExecutionFailure`] through [`into_result`](ExecutionFinalResult::into_result)
#[derive(Clone)]
#[must_use = "use `into_result()` to handle potential execution errors"]
pub struct ExecutionFinalResult {
    /// Total gas burnt by the execution
    pub total_gas_burnt: NearGas,

    pub(crate) status: FinalExecutionStatus,
    pub(crate) details: ExecutionDetails,
}

impl fmt::Debug for ExecutionFinalResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ExecutionFinalResult")
            .field("total_gas_burnt", &self.total_gas_burnt)
            .field("transaction", &self.details.transaction)
            .field("receipts", &self.details.receipts)
            .field("status", &self.status)
            .finish()
    }
}

impl TryFrom<FinalExecutionOutcomeView> for ExecutionFinalResult {
    type Error = DataConversionError;
    fn try_from(view: FinalExecutionOutcomeView) -> Result<Self, Self::Error> {
        let FinalExecutionOutcomeView {
            receipts_outcome,
            status,
            transaction,
            transaction_outcome,
        } = view;

        let total_gas_burnt = transaction_outcome.outcome.gas_burnt.as_gas()
            + receipts_outcome
                .iter()
                .map(|t| t.outcome.gas_burnt.as_gas())
                .sum::<u64>();

        let transaction_outcome = transaction_outcome.into();
        let receipts = receipts_outcome
            .into_iter()
            .map(ExecutionOutcome::from)
            .collect();

        let total_gas_burnt = NearGas::from_gas(total_gas_burnt);
        Ok(Self {
            total_gas_burnt,
            status,
            details: ExecutionDetails {
                transaction_outcome,
                transaction: SignedTransaction::try_from(transaction)?,
                receipts,
            },
        })
    }
}

impl ExecutionFinalResult {
    /// Converts this object into a [`Result`] holding either [`ExecutionSuccess`] or [`ExecutionFailure`].
    #[allow(clippy::result_large_err)]
    pub fn into_result(self) -> Result<ExecutionSuccess, ExecutionFailure> {
        match self.status {
            FinalExecutionStatus::SuccessValue(value) => Ok(ExecutionResult {
                total_gas_burnt: self.total_gas_burnt,
                value: Value::from_string(value),
                details: self.details,
            }),
            FinalExecutionStatus::Failure(tx_error) => Err(ExecutionResult {
                total_gas_burnt: self.total_gas_burnt,
                value: tx_error,
                details: self.details,
            }),
            FinalExecutionStatus::NotStarted | FinalExecutionStatus::Started => {
                panic!(
                    "called `into_result()` on a transaction that is still pending \
                     (status: {:?}). Use `is_pending()` to check before calling this method, \
                     or use `Transaction::status_with_options()` with a `wait_until` value \
                     of `ExecutedOptimistic` or higher.",
                    self.status
                )
            }
        }
    }

    /// Returns the contained Ok value, consuming the self value.
    ///
    /// Because this function may panic, its use is generally discouraged. Instead, prefer
    /// to call into [`into_result`](ExecutionFinalResult::into_result) then pattern matching and handle the Err case explicitly.
    #[track_caller]
    pub fn assert_success(self) -> ExecutionSuccess {
        #[allow(clippy::unwrap_used)]
        self.into_result().unwrap()
    }

    #[track_caller]
    pub fn assert_failure(self) -> ExecutionResult<TxExecutionError> {
        #[allow(clippy::unwrap_used)]
        self.into_result().unwrap_err()
    }

    /// Deserialize an instance of type `T` from bytes of JSON text sourced from the
    /// execution result of this call. This conversion can fail if the structure of
    /// the internal state does not meet up with [`serde::de::DeserializeOwned`]'s
    /// requirements.
    pub fn json<T: serde::de::DeserializeOwned>(self) -> Result<T, ExecutionError> {
        if self.is_pending() {
            return Err(ExecutionError::ExecutionPendingOrUnknown);
        }

        let val = self.into_result()?;
        match val.json() {
            Err(err) => {
                // This catches the case: `EOF while parsing a value at line 1 column 0`
                // for a function that doesn't return anything; this is a more descriptive error.
                if matches!(
                    err,
                    ExecutionError::DataConversionError(
                        DataConversionError::JsonDeserializationError(_)
                    )
                ) && val.value.repr.is_empty()
                {
                    return Err(ExecutionError::EofWhileParsingValue);
                }

                Err(err)
            }
            ok => ok,
        }
    }

    /// Deserialize an instance of type `T` from bytes sourced from the execution
    /// result. This conversion can fail if the structure of the internal state does
    /// not meet up with [`borsh::BorshDeserialize`]'s requirements.
    pub fn borsh<T: borsh::BorshDeserialize>(self) -> Result<T, ExecutionError> {
        if self.is_pending() {
            return Err(ExecutionError::ExecutionPendingOrUnknown);
        }

        self.into_result()?.borsh()
    }

    /// Grab the underlying raw bytes returned from calling into a contract's function.
    /// If we want to deserialize these bytes into a rust datatype, use [`ExecutionResult::json`]
    /// or [`ExecutionResult::borsh`] instead.
    pub fn raw_bytes(self) -> Result<Vec<u8>, ExecutionError> {
        if self.is_pending() {
            return Err(ExecutionError::ExecutionPendingOrUnknown);
        }

        self.into_result()?.raw_bytes()
    }

    /// Checks whether the transaction was successful. Returns true if
    /// the transaction has a status of [`FinalExecutionStatus::SuccessValue`].
    pub const fn is_success(&self) -> bool {
        matches!(self.status, FinalExecutionStatus::SuccessValue(_))
    }

    /// Checks whether the transaction has failed. Returns true if
    /// the transaction has a status of [`FinalExecutionStatus::Failure`].
    pub const fn is_failure(&self) -> bool {
        matches!(self.status, FinalExecutionStatus::Failure(_))
    }

    /// Checks whether the transaction execution is still pending (not started or in progress).
    ///
    /// Returns `true` if the status is [`FinalExecutionStatus::NotStarted`] or
    /// [`FinalExecutionStatus::Started`]. When this returns `true`, calling
    /// [`into_result`](Self::into_result), [`json`](Self::json), [`borsh`](Self::borsh),
    /// or [`raw_bytes`](Self::raw_bytes) will fail.
    pub const fn is_pending(&self) -> bool {
        matches!(
            self.status,
            FinalExecutionStatus::NotStarted | FinalExecutionStatus::Started
        )
    }

    /// Returns just the transaction outcome.
    pub const fn outcome(&self) -> &ExecutionOutcome {
        self.details.outcome()
    }

    /// Returns the transaction that was executed.
    pub const fn transaction(&self) -> &Transaction {
        self.details.transaction()
    }

    /// Grab all outcomes after the execution of the transaction. This includes outcomes
    /// from the transaction and all the receipts it generated.
    pub fn outcomes(&self) -> Vec<&ExecutionOutcome> {
        self.details.outcomes()
    }

    /// Grab all outcomes after the execution of the transaction. This includes outcomes
    /// only from receipts generated by this transaction.
    pub fn receipt_outcomes(&self) -> &[ExecutionOutcome] {
        self.details.receipt_outcomes()
    }

    /// Grab all outcomes that did not succeed the execution of this transaction. This
    /// will also include the failures from receipts as well.
    pub fn failures(&self) -> Vec<&ExecutionOutcome> {
        self.details.failures()
    }

    /// Just like `failures`, grab only failed receipt outcomes.
    pub fn receipt_failures(&self) -> Vec<&ExecutionOutcome> {
        self.details.receipt_failures()
    }

    /// Grab all logs from both the transaction and receipt outcomes.
    pub fn logs(&self) -> Vec<&str> {
        self.details.logs()
    }
}

/// The result of sending a transaction to the network.
///
/// Depending on the [`TxExecutionStatus`] used with `wait_until`, the RPC may return
/// either a full execution result or just a confirmation that the transaction was received.
///
/// - `wait_until(TxExecutionStatus::None)` or `wait_until(TxExecutionStatus::Included)` will
///   return [`TransactionResult::Pending`] since the transaction hasn't been executed yet.
/// - Higher finality levels (`ExecutedOptimistic`, `Final`, etc.) will return
///   [`TransactionResult::Full`] with the full execution outcome.
#[derive(Clone, Debug)]
#[must_use = "use `into_result()` to handle potential execution errors and cases when transaction is pending"]
pub enum TransactionResult {
    /// Transaction was submitted but execution results are not yet available.
    ///
    /// This is returned when `wait_until` is set to `None` or `Included`.
    /// The `status` field indicates how far the transaction has progressed.
    Pending { status: TxExecutionStatus },
    /// Full execution result is available.
    Full(Box<ExecutionFinalResult>),
}

impl TransactionResult {
    /// Returns the full execution result if available, or an error if the transaction is still pending.
    #[allow(clippy::result_large_err)]
    pub fn into_result(self) -> Result<ExecutionSuccess, TransactionResultError> {
        match self {
            Self::Full(result) => result
                .into_result()
                .map_err(|e| TransactionResultError::Failure(Box::new(e))),
            Self::Pending { status } => Err(TransactionResultError::Pending(status)),
        }
    }

    /// Unwraps the full execution result, panicking if the transaction is pending or failed.
    #[track_caller]
    pub fn assert_success(self) -> ExecutionSuccess {
        match self {
            Self::Full(result) => result.assert_success(),
            Self::Pending { status } => panic!(
                "called `assert_success()` on a pending transaction (status: {status:?}). \
                 Use wait_until(TxExecutionStatus::Final) or handle the pending case."
            ),
        }
    }

    /// Returns `true` if the transaction has a full execution result.
    pub const fn is_full(&self) -> bool {
        matches!(self, Self::Full(_))
    }

    /// Returns `true` if the transaction is still pending.
    pub const fn is_pending(&self) -> bool {
        matches!(self, Self::Pending { .. })
    }

    /// Returns the full execution result, if available.
    pub fn into_full(self) -> Option<ExecutionFinalResult> {
        match self {
            Self::Full(result) => Some(*result),
            Self::Pending { .. } => None,
        }
    }

    /// Returns the pending status, if the transaction is still pending.
    pub fn pending_status(self) -> Option<TxExecutionStatus> {
        match self {
            Self::Pending { status } => Some(status),
            Self::Full(_) => None,
        }
    }

    /// Unwraps the execution failure, panicking if the transaction is pending or succeeded.
    #[track_caller]
    pub fn assert_failure(self) -> ExecutionResult<TxExecutionError> {
        match self {
            Self::Full(result) => result.assert_failure(),
            Self::Pending { status } => panic!(
                "called `assert_failure()` on a pending transaction (status: {status:?}). \
                 Use wait_until(TxExecutionStatus::Final) or handle the pending case."
            ),
        }
    }

    /// Checks whether the transaction has failed. Returns `false` if the transaction
    /// is still pending or succeeded.
    pub const fn is_failure(&self) -> bool {
        match self {
            Self::Full(result) => result.is_failure(),
            Self::Pending { .. } => false,
        }
    }

    /// Checks whether the transaction was successful. Returns `false` if the transaction
    /// is still pending or failed.
    pub const fn is_success(&self) -> bool {
        match self {
            Self::Full(result) => result.is_success(),
            Self::Pending { .. } => false,
        }
    }

    /// Returns the transaction that was executed.
    ///
    /// # Panics
    ///
    /// Panics if the transaction is still pending.
    #[track_caller]
    pub fn transaction(&self) -> &Transaction {
        match self {
            Self::Full(result) => result.transaction(),
            Self::Pending { status } => panic!(
                "called `transaction()` on a pending transaction (status: {status:?}). \
                 Use wait_until(TxExecutionStatus::Final) or handle the pending case."
            ),
        }
    }

    /// Grab all logs from both the transaction and receipt outcomes.
    ///
    /// # Panics
    ///
    /// Panics if the transaction is still pending.
    #[track_caller]
    pub fn logs(&self) -> Vec<&str> {
        match self {
            Self::Full(result) => result.logs(),
            Self::Pending { status } => panic!(
                "called `logs()` on a pending transaction (status: {status:?}). \
                 Use wait_until(TxExecutionStatus::Final) or handle the pending case."
            ),
        }
    }
}

/// Error type for [`TransactionResult::into_result`].
#[derive(Debug)]
pub enum TransactionResultError {
    /// The transaction failed execution.
    Failure(Box<ExecutionFailure>),
    /// The transaction is still pending (was sent with `wait_until` set to `None` or `Included`).
    Pending(TxExecutionStatus),
}

impl fmt::Display for TransactionResultError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Failure(err) => write!(f, "Transaction failed: {err}"),
            Self::Pending(status) => write!(
                f,
                "Transaction is pending (status: {status:?}). \
                 Execution results are not yet available."
            ),
        }
    }
}

impl std::error::Error for TransactionResultError {}

impl ExecutionSuccess {
    /// Deserialize an instance of type `T` from bytes of JSON text sourced from the
    /// execution result of this call. This conversion can fail if the structure of
    /// the internal state does not meet up with [`serde::de::DeserializeOwned`]'s
    /// requirements.
    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, ExecutionError> {
        Ok(self.value.json()?)
    }

    /// Deserialize an instance of type `T` from bytes sourced from the execution
    /// result. This conversion can fail if the structure of the internal state does
    /// not meet up with [`borsh::BorshDeserialize`]'s requirements.
    pub fn borsh<T: borsh::BorshDeserialize>(&self) -> Result<T, ExecutionError> {
        Ok(self.value.borsh()?)
    }

    /// Grab the underlying raw bytes returned from calling into a contract's function.
    /// If we want to deserialize these bytes into a rust datatype, use [`ExecutionResult::json`]
    /// or [`ExecutionResult::borsh`] instead.
    pub fn raw_bytes(&self) -> Result<Vec<u8>, ExecutionError> {
        Ok(self.value.raw_bytes()?)
    }
}

impl<T> ExecutionResult<T> {
    /// Returns just the transaction outcome.
    pub const fn outcome(&self) -> &ExecutionOutcome {
        self.details.outcome()
    }

    /// Returns the transaction that was executed.
    pub const fn transaction(&self) -> &Transaction {
        self.details.transaction()
    }

    pub const fn signature(&self) -> &Signature {
        self.details.signature()
    }

    /// Grab all outcomes after the execution of the transaction. This includes outcomes
    /// from the transaction and all the receipts it generated.
    pub fn outcomes(&self) -> Vec<&ExecutionOutcome> {
        self.details.outcomes()
    }

    /// Grab all outcomes after the execution of the transaction. This includes outcomes
    /// only from receipts generated by this transaction.
    pub fn receipt_outcomes(&self) -> &[ExecutionOutcome] {
        self.details.receipt_outcomes()
    }

    /// Grab all outcomes that did not succeed the execution of this transaction. This
    /// will also include the failures from receipts as well.
    pub fn failures(&self) -> Vec<&ExecutionOutcome> {
        self.details.failures()
    }

    /// Just like `failures`, grab only failed receipt outcomes.
    pub fn receipt_failures(&self) -> Vec<&ExecutionOutcome> {
        self.details.receipt_failures()
    }

    /// Grab all logs from both the transaction and receipt outcomes.
    pub fn logs(&self) -> Vec<&str> {
        self.details.logs()
    }
}

/// The result from a call into a View function. This contains the contents or
/// the results from the view function call itself. The consumer of this object
/// can choose how to deserialize its contents.
#[derive(PartialEq, Eq, Clone, Debug)]
#[non_exhaustive]
pub struct ViewResultDetails {
    /// Our result from our call into a view function.
    pub result: Vec<u8>,
    /// Logs generated from the view function.
    pub logs: Vec<String>,
}

impl ViewResultDetails {
    /// Deserialize an instance of type `T` from bytes of JSON text sourced from the
    /// execution result of this call. This conversion can fail if the structure of
    /// the internal state does not meet up with [`serde::de::DeserializeOwned`]'s
    /// requirements.
    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, DataConversionError> {
        Ok(serde_json::from_slice(&self.result)?)
    }

    /// Deserialize an instance of type `T` from bytes sourced from this view call's
    /// result. This conversion can fail if the structure of the internal state does
    /// not meet up with [`borsh::BorshDeserialize`]'s requirements.
    pub fn borsh<T: borsh::BorshDeserialize>(&self) -> Result<T, DataConversionError> {
        Ok(borsh::BorshDeserialize::try_from_slice(&self.result)?)
    }
}

impl From<CallResult> for ViewResultDetails {
    fn from(result: CallResult) -> Self {
        Self {
            result: result.result,
            logs: result.logs,
        }
    }
}

/// The execution outcome of a transaction. This type contains all data relevant to
/// calling into a function, and getting the results back.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ExecutionOutcome {
    /// The hash of the transaction that generated this outcome.
    pub transaction_hash: CryptoHash,
    /// The hash of the block that generated this outcome.
    pub block_hash: CryptoHash,
    /// Logs from this transaction or receipt.
    pub logs: Vec<String>,
    /// Receipt IDs generated by this transaction or receipt.
    pub receipt_ids: Vec<CryptoHash>,
    /// The amount of the gas burnt by the given transaction or receipt.
    pub gas_burnt: NearGas,
    /// The amount of tokens burnt corresponding to the burnt gas amount.
    /// This value doesn't always equal to the `gas_burnt` multiplied by the gas price, because
    /// the prepaid gas price might be lower than the actual gas price and it creates a deficit.
    pub tokens_burnt: NearToken,
    /// The id of the account on which the execution happens. For transaction this is signer_id,
    /// for receipt this is receiver_id.
    pub executor_id: AccountId,

    /// Execution status. Contains the result in case of successful execution.
    pub(crate) status: ExecutionStatusView,
}

impl ExecutionOutcome {
    /// Checks whether this execution outcome was a success. Returns true if a success value or
    /// receipt id is present.
    pub const fn is_success(&self) -> bool {
        matches!(
            self.status,
            ExecutionStatusView::SuccessValue(_) | ExecutionStatusView::SuccessReceiptId(_)
        )
    }

    /// Checks whether this execution outcome was a failure. Returns true if it failed with
    /// an error or the execution state was unknown or pending.
    pub const fn is_failure(&self) -> bool {
        matches!(
            self.status,
            ExecutionStatusView::Failure(_) | ExecutionStatusView::Unknown
        )
    }

    /// Converts this [`ExecutionOutcome`] into a Result type to match against whether the
    /// particular outcome has failed or not.
    pub fn into_result(self) -> Result<ValueOrReceiptId, ExecutionError> {
        match self.status {
            ExecutionStatusView::SuccessValue(value) => {
                Ok(ValueOrReceiptId::Value(Value::from_string(value)))
            }
            ExecutionStatusView::SuccessReceiptId(hash) => {
                Ok(ValueOrReceiptId::ReceiptId(hash.into()))
            }
            ExecutionStatusView::Failure(err) => {
                Err(ExecutionError::TransactionExecutionFailed(Box::new(err)))
            }
            ExecutionStatusView::Unknown => Err(ExecutionError::ExecutionPendingOrUnknown),
        }
    }
}

/// Value or ReceiptId from a successful execution.
#[derive(Debug)]
pub enum ValueOrReceiptId {
    /// The final action succeeded and returned some value or an empty vec encoded in base64.
    Value(Value),
    /// The final action of the receipt returned a promise or the signed transaction was converted
    /// to a receipt. Contains the receipt_id of the generated receipt.
    ReceiptId(CryptoHash),
}

/// Value type returned from an [`ExecutionOutcome`] or receipt result. This value
/// can be converted into the underlying Rust datatype, or directly grab the raw
/// bytes associated to the value.
#[derive(Debug, Clone)]
pub struct Value {
    repr: String,
}

impl Value {
    const fn from_string(value: String) -> Self {
        Self { repr: value }
    }

    /// Deserialize an instance of type `T` from bytes of JSON text sourced from the
    /// execution result of this call. This conversion can fail if the structure of
    /// the internal state does not meet up with [`serde::de::DeserializeOwned`]'s
    /// requirements.
    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, DataConversionError> {
        let buf = self.raw_bytes()?;
        Ok(serde_json::from_slice(&buf)?)
    }

    /// Deserialize an instance of type `T` from bytes sourced from the execution
    /// result. This conversion can fail if the structure of the internal state does
    /// not meet up with [`borsh::BorshDeserialize`]'s requirements.
    pub fn borsh<T: borsh::BorshDeserialize>(&self) -> Result<T, DataConversionError> {
        let buf = self.raw_bytes()?;
        Ok(borsh::BorshDeserialize::try_from_slice(&buf)?)
    }

    /// Grab the underlying raw bytes returned from calling into a contract's function.
    /// If we want to deserialize these bytes into a rust datatype, use [`json`]
    /// or [`borsh`] instead.
    ///
    /// [`json`]: Value::json
    /// [`borsh`]: Value::borsh
    pub fn raw_bytes(&self) -> Result<Vec<u8>, DataConversionError> {
        Ok(general_purpose::STANDARD.decode(&self.repr)?)
    }
}

impl From<near_openapi_types::ExecutionOutcomeWithIdView> for ExecutionOutcome {
    fn from(view: near_openapi_types::ExecutionOutcomeWithIdView) -> Self {
        let near_openapi_types::ExecutionOutcomeWithIdView {
            id,
            block_hash,
            outcome,
            proof: _, // TODO: research if we need this
        } = view;

        Self {
            transaction_hash: id.into(),
            block_hash: block_hash.into(),
            logs: outcome.logs,
            receipt_ids: outcome
                .receipt_ids
                .into_iter()
                .map(CryptoHash::from)
                .collect(),
            gas_burnt: outcome.gas_burnt,
            tokens_burnt: outcome.tokens_burnt,
            executor_id: outcome.executor_id,
            status: outcome.status,
        }
    }
}