alloy-network-primitives 2.4.0

Primitive types for Alloy network abstraction
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
use alloy_primitives::B256;

use crate::TransactionResponse;
use alloc::{vec, vec::Vec};
use alloy_consensus::error::ValueError;
use alloy_eips::Encodable2718;
use core::slice;

/// Representation of the `transactions` field in block JSON-RPC responses.
///
/// [`Full`](Self::Full) corresponds to a block requested with full transactions,
/// [`Hashes`](Self::Hashes) to a block requested with transaction hashes, and
/// [`Uncle`](Self::Uncle) to the omitted transaction field in uncle responses. `Default` is an
/// empty `Hashes` value, not an empty `Full` value. With Serde, the representation is untagged and
/// an empty JSON array deserializes as `Full([])`, so that ambiguous case does not preserve which
/// request form produced it.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(untagged))]
pub enum BlockTransactions<T> {
    /// Full transactions
    Full(Vec<T>),
    /// Only hashes
    Hashes(Vec<B256>),
    /// Special case for uncle response.
    Uncle,
}

impl<T> Default for BlockTransactions<T> {
    fn default() -> Self {
        Self::Hashes(Vec::default())
    }
}

impl<T> BlockTransactions<T> {
    /// Check if the enum variant is used for hashes.
    #[inline]
    pub const fn is_hashes(&self) -> bool {
        matches!(self, Self::Hashes(_))
    }

    /// Fallibly cast to a slice of hashes.
    pub fn as_hashes(&self) -> Option<&[B256]> {
        match self {
            Self::Hashes(hashes) => Some(hashes),
            _ => None,
        }
    }

    /// Returns the first transaction if the transactions are full.
    pub fn first_transaction(&self) -> Option<&T> {
        self.as_transactions().and_then(|txs| txs.first())
    }

    /// Returns true if the enum variant is used for full transactions.
    #[inline]
    pub const fn is_full(&self) -> bool {
        matches!(self, Self::Full(_))
    }

    /// Converts the transaction type by applying a function to each transaction.
    ///
    /// The function is called only for [`Self::Full`]; hash and uncle representations pass through
    /// unchanged.
    pub fn map<U>(self, f: impl FnMut(T) -> U) -> BlockTransactions<U> {
        match self {
            Self::Full(txs) => BlockTransactions::Full(txs.into_iter().map(f).collect()),
            Self::Hashes(hashes) => BlockTransactions::Hashes(hashes),
            Self::Uncle => BlockTransactions::Uncle,
        }
    }

    /// Converts the transaction type by applying a fallible function to each transaction.
    ///
    /// The function is called only for [`Self::Full`]; hash and uncle representations pass through
    /// unchanged.
    pub fn try_map<U, E>(
        self,
        f: impl FnMut(T) -> Result<U, E>,
    ) -> Result<BlockTransactions<U>, E> {
        match self {
            Self::Full(txs) => {
                Ok(BlockTransactions::Full(txs.into_iter().map(f).collect::<Result<_, _>>()?))
            }
            Self::Hashes(hashes) => Ok(BlockTransactions::Hashes(hashes)),
            Self::Uncle => Ok(BlockTransactions::Uncle),
        }
    }

    /// Fallibly cast to a slice of transactions.
    ///
    /// Returns `None` if the enum variant is not `Full`.
    pub fn as_transactions(&self) -> Option<&[T]> {
        match self {
            Self::Full(txs) => Some(txs),
            _ => None,
        }
    }

    /// Calculates a transaction root from the ordered EIP-2718 encodings of full transactions.
    ///
    /// Returns `None` for other representations. This does not compare the result against a block
    /// header.
    pub fn calculate_transactions_root(&self) -> Option<B256>
    where
        T: Encodable2718,
    {
        self.as_transactions().map(alloy_consensus::proofs::calculate_transaction_root)
    }

    /// Returns true if the enum variant is used for an uncle response.
    #[inline]
    pub const fn is_uncle(&self) -> bool {
        matches!(self, Self::Uncle)
    }

    /// Returns an iterator over the transactions (if any). This will be empty
    /// if the block is an uncle or if the transaction list contains only
    /// hashes.
    ///
    /// Use [`Self::try_into_transactions`] when those representations should be treated as an
    /// error instead of an empty collection.
    #[doc(alias = "transactions")]
    pub fn txns(&self) -> impl Iterator<Item = &T> {
        self.as_transactions().map(|txs| txs.iter()).unwrap_or_else(|| [].iter())
    }

    /// Returns an iterator over the transactions (if any). This will be empty if the block is not
    /// full.
    ///
    /// Use [`Self::try_into_transactions`] to preserve the distinction between a full empty block
    /// and a non-full representation.
    pub fn into_transactions(self) -> vec::IntoIter<T> {
        match self {
            Self::Full(txs) => txs.into_iter(),
            _ => vec::IntoIter::default(),
        }
    }

    /// Consumes the type and returns the transactions as a vector.
    ///
    /// Hash and uncle representations are collapsed to an empty vector. Use
    /// [`Self::try_into_transactions`] when that distinction matters.
    pub fn into_transactions_vec(self) -> Vec<T> {
        match self {
            Self::Full(txs) => txs,
            _ => vec![],
        }
    }

    /// Attempts to unwrap the [`Self::Full`] variant.
    ///
    /// Returns an error retaining the original representation for hash and uncle variants.
    pub fn try_into_transactions(self) -> Result<Vec<T>, ValueError<Self>> {
        match self {
            Self::Full(txs) => Ok(txs),
            txs @ Self::Hashes(_) => Err(ValueError::new_static(txs, "Unexpected hashes variant")),
            txs @ Self::Uncle => Err(ValueError::new_static(txs, "Unexpected uncle variant")),
        }
    }

    /// Returns an instance of BlockTransactions with the Uncle special case.
    #[inline]
    pub const fn uncle() -> Self {
        Self::Uncle
    }

    /// Returns the number of transactions.
    #[inline]
    pub const fn len(&self) -> usize {
        match self {
            Self::Hashes(h) => h.len(),
            Self::Full(f) => f.len(),
            Self::Uncle => 0,
        }
    }

    /// Whether the block has no transactions.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<T: TransactionResponse> BlockTransactions<T> {
    /// Creates a new [`BlockTransactions::Hashes`] variant from the given iterator of transactions.
    pub fn new_hashes(txs: impl IntoIterator<Item = impl AsRef<T>>) -> Self {
        Self::Hashes(txs.into_iter().map(|tx| tx.as_ref().tx_hash()).collect())
    }

    /// Converts full transactions to same-order hashes.
    ///
    /// Existing hashes are unchanged. [`Self::Uncle`] is normalized to an empty hash list, losing
    /// the omitted-field representation.
    #[inline]
    pub fn convert_to_hashes(&mut self) {
        if !self.is_hashes() {
            *self = Self::Hashes(self.hashes().collect());
        }
    }

    /// Converts `self` into `Hashes` if the given `condition` is true.
    #[inline]
    pub fn convert_to_hashes_if(&mut self, condition: bool) {
        if !condition {
            return;
        }
        self.convert_to_hashes();
    }

    /// Converts full transactions to same-order hashes.
    ///
    /// Existing hashes are unchanged. [`Self::Uncle`] is normalized to an empty hash list, losing
    /// the omitted-field representation.
    #[inline]
    pub fn into_hashes(mut self) -> Self {
        self.convert_to_hashes();
        self
    }

    /// Converts `self` into `Hashes` if the given `condition` is true.
    #[inline]
    pub fn into_hashes_if(self, condition: bool) -> Self {
        if !condition {
            return self;
        }
        self.into_hashes()
    }

    /// Returns transaction hashes by value.
    ///
    /// Stored hashes are copied, full transactions use [`TransactionResponse::tx_hash`], and
    /// [`Self::Uncle`] yields an empty iterator.
    #[inline]
    pub fn hashes(&self) -> BlockTransactionHashes<'_, T> {
        BlockTransactionHashes::new(self)
    }

    /// Consumes the type and returns the hashes as a vector.
    ///
    /// Note: if this is an uncle this will return an empty vector.
    pub fn into_hashes_vec(self) -> Vec<B256> {
        match self {
            Self::Hashes(hashes) => hashes,
            this => this.hashes().collect(),
        }
    }
}

impl<T> From<Vec<B256>> for BlockTransactions<T> {
    fn from(hashes: Vec<B256>) -> Self {
        Self::Hashes(hashes)
    }
}

impl<T: TransactionResponse> From<Vec<T>> for BlockTransactions<T> {
    fn from(transactions: Vec<T>) -> Self {
        Self::Full(transactions)
    }
}

/// An iterator over transaction hashes by value.
///
/// See [`BlockTransactions::hashes`].
#[derive(Clone, Debug)]
pub struct BlockTransactionHashes<'a, T>(BlockTransactionHashesInner<'a, T>);

#[derive(Clone, Debug)]
enum BlockTransactionHashesInner<'a, T> {
    Hashes(slice::Iter<'a, B256>),
    Full(slice::Iter<'a, T>),
    Uncle,
}

impl<'a, T> BlockTransactionHashes<'a, T> {
    #[inline]
    fn new(txs: &'a BlockTransactions<T>) -> Self {
        Self(match txs {
            BlockTransactions::Hashes(txs) => BlockTransactionHashesInner::Hashes(txs.iter()),
            BlockTransactions::Full(txs) => BlockTransactionHashesInner::Full(txs.iter()),
            BlockTransactions::Uncle => BlockTransactionHashesInner::Uncle,
        })
    }
}

impl<T: TransactionResponse> Iterator for BlockTransactionHashes<'_, T> {
    type Item = B256;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.0 {
            BlockTransactionHashesInner::Hashes(txs) => txs.next().copied(),
            BlockTransactionHashesInner::Full(txs) => txs.next().map(|tx| tx.tx_hash()),
            BlockTransactionHashesInner::Uncle => None,
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        match &self.0 {
            BlockTransactionHashesInner::Full(txs) => txs.size_hint(),
            BlockTransactionHashesInner::Hashes(txs) => txs.size_hint(),
            BlockTransactionHashesInner::Uncle => (0, Some(0)),
        }
    }
}

impl<T: TransactionResponse> ExactSizeIterator for BlockTransactionHashes<'_, T> {
    #[inline]
    fn len(&self) -> usize {
        match &self.0 {
            BlockTransactionHashesInner::Full(txs) => txs.len(),
            BlockTransactionHashesInner::Hashes(txs) => txs.len(),
            BlockTransactionHashesInner::Uncle => 0,
        }
    }
}

impl<T: TransactionResponse> DoubleEndedIterator for BlockTransactionHashes<'_, T> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        match &mut self.0 {
            BlockTransactionHashesInner::Full(txs) => txs.next_back().map(|tx| tx.tx_hash()),
            BlockTransactionHashesInner::Hashes(txs) => txs.next_back().copied(),
            BlockTransactionHashesInner::Uncle => None,
        }
    }
}

#[cfg(feature = "std")]
impl<T: TransactionResponse> std::iter::FusedIterator for BlockTransactionHashes<'_, T> {}

/// Determines how the `transactions` field of block should be filled.
///
/// This essentially represents the `full:bool` argument in RPC calls that determine whether the
/// response should include full transaction objects or just the hashes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BlockTransactionsKind {
    /// Only include hashes: [BlockTransactions::Hashes]
    #[default]
    Hashes,
    /// Include full transaction objects: [BlockTransactions::Full]
    Full,
}

impl BlockTransactionsKind {
    /// Returns true if this is [`BlockTransactionsKind::Hashes`]
    pub const fn is_hashes(&self) -> bool {
        matches!(self, Self::Hashes)
    }

    /// Returns true if this is [`BlockTransactionsKind::Full`]
    pub const fn is_full(&self) -> bool {
        matches!(self, Self::Full)
    }
}

impl From<bool> for BlockTransactionsKind {
    fn from(is_full: bool) -> Self {
        if is_full {
            Self::Full
        } else {
            Self::Hashes
        }
    }
}

impl From<BlockTransactionsKind> for bool {
    fn from(kind: BlockTransactionsKind) -> Self {
        match kind {
            BlockTransactionsKind::Full => true,
            BlockTransactionsKind::Hashes => false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_full_conversion() {
        let full = true;
        assert_eq!(BlockTransactionsKind::Full, full.into());

        let full = false;
        assert_eq!(BlockTransactionsKind::Hashes, full.into());
    }

    #[test]
    fn test_block_transactions_default() {
        let default: BlockTransactions<()> = BlockTransactions::default();
        assert!(default.is_hashes());
        assert_eq!(default.len(), 0);
    }

    #[test]
    fn test_block_transactions_is_methods() {
        let hashes: BlockTransactions<()> = BlockTransactions::Hashes(vec![B256::ZERO]);
        let full: BlockTransactions<u32> = BlockTransactions::Full(vec![42]);
        let uncle: BlockTransactions<()> = BlockTransactions::Uncle;

        assert!(hashes.is_hashes());
        assert!(!hashes.is_full());
        assert!(!hashes.is_uncle());

        assert!(full.is_full());
        assert!(!full.is_hashes());
        assert!(!full.is_uncle());

        assert!(uncle.is_uncle());
        assert!(!uncle.is_full());
        assert!(!uncle.is_hashes());
    }

    #[test]
    fn test_as_hashes() {
        let hashes = vec![B256::ZERO, B256::repeat_byte(1)];
        let tx_hashes: BlockTransactions<()> = BlockTransactions::Hashes(hashes.clone());

        assert_eq!(tx_hashes.as_hashes(), Some(hashes.as_slice()));
    }

    #[test]
    fn test_as_transactions() {
        let transactions = vec![42, 43];
        let txs = BlockTransactions::Full(transactions.clone());

        assert_eq!(txs.as_transactions(), Some(transactions.as_slice()));
    }

    #[test]
    fn test_block_transactions_len_and_is_empty() {
        let hashes: BlockTransactions<()> = BlockTransactions::Hashes(vec![B256::ZERO]);
        let full = BlockTransactions::Full(vec![42]);
        let uncle: BlockTransactions<()> = BlockTransactions::Uncle;

        assert_eq!(hashes.len(), 1);
        assert_eq!(full.len(), 1);
        assert_eq!(uncle.len(), 0);

        assert!(!hashes.is_empty());
        assert!(!full.is_empty());
        assert!(uncle.is_empty());
    }

    #[test]
    fn test_block_transactions_txns_iterator() {
        let transactions = vec![42, 43];
        let txs = BlockTransactions::Full(transactions);
        let mut iter = txs.txns();

        assert_eq!(iter.next(), Some(&42));
        assert_eq!(iter.next(), Some(&43));
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn test_block_transactions_into_transactions() {
        let transactions = vec![42, 43];
        let txs = BlockTransactions::Full(transactions.clone());
        let collected: Vec<_> = txs.into_transactions().collect();

        assert_eq!(collected, transactions);
    }

    #[test]
    fn test_block_transactions_kind_conversion() {
        let full: BlockTransactionsKind = true.into();
        assert_eq!(full, BlockTransactionsKind::Full);

        let hashes: BlockTransactionsKind = false.into();
        assert_eq!(hashes, BlockTransactionsKind::Hashes);

        let bool_full: bool = BlockTransactionsKind::Full.into();
        assert!(bool_full);

        let bool_hashes: bool = BlockTransactionsKind::Hashes.into();
        assert!(!bool_hashes);
    }
}