From 1992c9176a615057786635cff9e78d1aa597b919 Mon Sep 17 00:00:00 2001 From: Matthias Seitz Date: Thu, 30 Jun 2022 18:20:33 +0200 Subject: [PATCH] feat(core): impl Ord for receipt (#1434) --- ethers-core/src/types/transaction/response.rs | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/ethers-core/src/types/transaction/response.rs b/ethers-core/src/types/transaction/response.rs index 90d532de..54fe85b3 100644 --- a/ethers-core/src/types/transaction/response.rs +++ b/ethers-core/src/types/transaction/response.rs @@ -9,6 +9,7 @@ use crate::{ }; use rlp::{Decodable, DecoderError, RlpStream}; use serde::{Deserialize, Serialize}; +use std::cmp::Ordering; /// Details of a signed transaction #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -434,6 +435,28 @@ impl rlp::Encodable for TransactionReceipt { } } +// Compares the transaction receipt against another receipt by checking the blocks first and then +// the transaction index in the block +impl Ord for TransactionReceipt { + fn cmp(&self, other: &Self) -> Ordering { + match (self.block_number, other.block_number) { + (Some(number), Some(other_number)) => match number.cmp(&other_number) { + Ordering::Equal => self.transaction_index.cmp(&other.transaction_index), + ord => ord, + }, + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => self.transaction_index.cmp(&other.transaction_index), + } + } +} + +impl PartialOrd for TransactionReceipt { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + #[cfg(test)] #[cfg(not(feature = "celo"))] mod tests { @@ -886,4 +909,17 @@ mod tests { let receipt = serde_json::to_value(receipt).unwrap(); assert_eq!(v, receipt); } + + #[test] + fn can_sort_receipts() { + let mut a = TransactionReceipt { block_number: Some(0u64.into()), ..Default::default() }; + let b = TransactionReceipt { block_number: Some(1u64.into()), ..Default::default() }; + assert!(a < b); + + a = b.clone(); + assert_eq!(a.cmp(&b), Ordering::Equal); + + a.transaction_index = 1u64.into(); + assert!(a > b); + } }