Skip to main content

reth_rpc/
otterscan.rs

1use alloy_consensus::{BlockHeader, Typed2718};
2use alloy_eips::{eip1898::LenientBlockNumberOrTag, BlockId};
3use alloy_network::{ReceiptResponse, TransactionResponse};
4use alloy_primitives::{Address, Bytes, TxHash, B256, U256};
5use alloy_rpc_types_eth::{BlockTransactions, TransactionReceipt};
6use alloy_rpc_types_trace::{
7    otterscan::{
8        BlockDetails, ContractCreator, InternalOperation, OperationType, OtsBlockTransactions,
9        OtsReceipt, OtsTransactionReceipt, TraceEntry, TransactionsWithReceipts,
10    },
11    parity::{Action, CreateAction, CreateOutput, TraceOutput},
12};
13use async_trait::async_trait;
14use jsonrpsee::{core::RpcResult, types::ErrorObjectOwned};
15use reth_primitives_traits::TxTy;
16use reth_rpc_api::{EthApiServer, OtterscanServer};
17use reth_rpc_convert::RpcTxReq;
18use reth_rpc_eth_api::{
19    helpers::{EthTransactions, TraceExt},
20    FullEthApiTypes, RpcBlock, RpcHeader, RpcReceipt, RpcTransaction,
21};
22use reth_rpc_eth_types::{utils::binary_search, EthApiError};
23use reth_rpc_server_types::result::internal_rpc_err;
24use revm::context_interface::result::ExecutionResult;
25use revm_inspectors::{
26    tracing::{types::CallTraceNode, TracingInspectorConfig},
27    transfer::{TransferInspector, TransferKind},
28};
29
30const API_LEVEL: u64 = 8;
31
32/// Otterscan API.
33#[derive(Debug)]
34pub struct OtterscanApi<Eth> {
35    eth: Eth,
36}
37
38impl<Eth> OtterscanApi<Eth> {
39    /// Creates a new instance of `Otterscan`.
40    pub const fn new(eth: Eth) -> Self {
41        Self { eth }
42    }
43}
44
45impl<Eth> OtterscanApi<Eth>
46where
47    Eth: FullEthApiTypes,
48{
49    /// Constructs a `BlockDetails` from a block and its receipts.
50    fn block_details(
51        &self,
52        block: RpcBlock<Eth::NetworkTypes>,
53        receipts: Vec<RpcReceipt<Eth::NetworkTypes>>,
54    ) -> RpcResult<BlockDetails<RpcHeader<Eth::NetworkTypes>>> {
55        // blob fee is burnt, so we don't need to calculate it
56        let total_fees = receipts
57            .iter()
58            .map(|receipt| {
59                (receipt.gas_used() as u128).saturating_mul(receipt.effective_gas_price())
60            })
61            .sum::<u128>();
62
63        Ok(BlockDetails::new(block, Default::default(), U256::from(total_fees)))
64    }
65}
66
67#[async_trait]
68impl<Eth> OtterscanServer<RpcTransaction<Eth::NetworkTypes>, RpcHeader<Eth::NetworkTypes>>
69    for OtterscanApi<Eth>
70where
71    Eth: EthApiServer<
72            RpcTxReq<Eth::NetworkTypes>,
73            RpcTransaction<Eth::NetworkTypes>,
74            RpcBlock<Eth::NetworkTypes>,
75            RpcReceipt<Eth::NetworkTypes>,
76            RpcHeader<Eth::NetworkTypes>,
77            TxTy<Eth::Primitives>,
78        > + EthTransactions
79        + TraceExt
80        + 'static,
81{
82    /// Handler for `ots_getHeaderByNumber` and `erigon_getHeaderByNumber`
83    async fn get_header_by_number(
84        &self,
85        block_number: LenientBlockNumberOrTag,
86    ) -> RpcResult<Option<RpcHeader<Eth::NetworkTypes>>> {
87        self.eth.header_by_number(block_number.into()).await
88    }
89
90    /// Handler for `ots_hasCode`
91    async fn has_code(&self, address: Address, block_id: Option<BlockId>) -> RpcResult<bool> {
92        EthApiServer::get_code(&self.eth, address, block_id).await.map(|code| !code.is_empty())
93    }
94
95    /// Handler for `ots_getApiLevel`
96    async fn get_api_level(&self) -> RpcResult<u64> {
97        Ok(API_LEVEL)
98    }
99
100    /// Handler for `ots_getInternalOperations`
101    async fn get_internal_operations(&self, tx_hash: TxHash) -> RpcResult<Vec<InternalOperation>> {
102        let internal_operations = self
103            .eth
104            .spawn_trace_transaction_in_block_with_inspector(
105                tx_hash,
106                TransferInspector::new(false),
107                |_tx_info, inspector, _, _| Ok(inspector.into_transfers()),
108            )
109            .await
110            .map_err(Into::into)?
111            .map(|transfer_operations| {
112                transfer_operations
113                    .iter()
114                    .map(|op| InternalOperation {
115                        from: op.from,
116                        to: op.to,
117                        value: op.value,
118                        r#type: match op.kind {
119                            TransferKind::Call => OperationType::OpTransfer,
120                            TransferKind::Create => OperationType::OpCreate,
121                            TransferKind::Create2 => OperationType::OpCreate2,
122                            TransferKind::SelfDestruct => OperationType::OpSelfDestruct,
123                        },
124                    })
125                    .collect::<Vec<_>>()
126            })
127            .unwrap_or_default();
128        Ok(internal_operations)
129    }
130
131    /// Handler for `ots_getTransactionError`
132    async fn get_transaction_error(&self, tx_hash: TxHash) -> RpcResult<Option<Bytes>> {
133        let maybe_revert = self
134            .eth
135            .spawn_replay_transaction(tx_hash, |_tx_info, res, _| match res.result {
136                ExecutionResult::Revert { output, .. } => Ok(Some(output)),
137                _ => Ok(None),
138            })
139            .await
140            .map(Option::flatten)
141            .map_err(Into::into)?;
142        Ok(maybe_revert)
143    }
144
145    /// Handler for `ots_traceTransaction`
146    async fn trace_transaction(&self, tx_hash: TxHash) -> RpcResult<Option<Vec<TraceEntry>>> {
147        let traces = self
148            .eth
149            .spawn_trace_transaction_in_block(
150                tx_hash,
151                TracingInspectorConfig::default_parity(),
152                move |_tx_info, inspector, _, _| Ok(inspector.into_traces().into_nodes()),
153            )
154            .await
155            .map_err(Into::into)?
156            .map(|traces| {
157                traces
158                    .into_iter()
159                    .map(|CallTraceNode { trace, .. }| TraceEntry {
160                        r#type: if trace.is_selfdestruct() {
161                            "SELFDESTRUCT".to_string()
162                        } else {
163                            trace.kind.to_string()
164                        },
165                        depth: trace.depth as u32,
166                        from: trace.caller,
167                        to: trace.address,
168                        value: Some(trace.value),
169                        input: trace.data,
170                        output: trace.output,
171                    })
172                    .collect::<Vec<_>>()
173            });
174        Ok(traces)
175    }
176
177    /// Handler for `ots_getBlockDetails`
178    async fn get_block_details(
179        &self,
180        block_number: LenientBlockNumberOrTag,
181    ) -> RpcResult<BlockDetails<RpcHeader<Eth::NetworkTypes>>> {
182        let block_number = block_number.into_inner();
183        let block = self.eth.block_by_number(block_number, true);
184        let block_id = block_number.into();
185        let receipts = self.eth.block_receipts(block_id);
186        let (block, receipts) = futures::try_join!(block, receipts)?;
187        self.block_details(
188            block.ok_or(EthApiError::HeaderNotFound(block_id))?,
189            receipts.ok_or(EthApiError::ReceiptsNotFound(block_id))?,
190        )
191    }
192
193    /// Handler for `ots_getBlockDetailsByHash`
194    async fn get_block_details_by_hash(
195        &self,
196        block_hash: B256,
197    ) -> RpcResult<BlockDetails<RpcHeader<Eth::NetworkTypes>>> {
198        let block = self.eth.block_by_hash(block_hash, true);
199        let block_id = block_hash.into();
200        let receipts = self.eth.block_receipts(block_id);
201        let (block, receipts) = futures::try_join!(block, receipts)?;
202        self.block_details(
203            block.ok_or(EthApiError::HeaderNotFound(block_id))?,
204            receipts.ok_or(EthApiError::ReceiptsNotFound(block_id))?,
205        )
206    }
207
208    /// Handler for `ots_getBlockTransactions`
209    async fn get_block_transactions(
210        &self,
211        block_number: LenientBlockNumberOrTag,
212        page_number: usize,
213        page_size: usize,
214    ) -> RpcResult<
215        OtsBlockTransactions<RpcTransaction<Eth::NetworkTypes>, RpcHeader<Eth::NetworkTypes>>,
216    > {
217        let block_number = block_number.into_inner();
218        // retrieve full block and its receipts
219        let block = self.eth.block_by_number(block_number, true);
220        let block_id = block_number.into();
221        let receipts = self.eth.block_receipts(block_id);
222        let (block, receipts) = futures::try_join!(block, receipts)?;
223
224        let mut block = block.ok_or(EthApiError::HeaderNotFound(block_id))?;
225        let mut receipts = receipts.ok_or(EthApiError::ReceiptsNotFound(block_id))?;
226
227        // check if the number of transactions matches the number of receipts
228        let tx_len = block.transactions.len();
229        if tx_len != receipts.len() {
230            return Err(internal_rpc_err(
231                "the number of transactions does not match the number of receipts",
232            ))
233        }
234
235        // make sure the block is full
236        let BlockTransactions::Full(transactions) = &mut block.transactions else {
237            return Err(internal_rpc_err("block is not full"));
238        };
239
240        let page = block_transaction_page_range(tx_len, page_number, page_size);
241
242        // Crop transactions
243        *transactions = transactions.drain(page.clone()).collect::<Vec<_>>();
244
245        // Crop receipts and transform them into OtsTransactionReceipt
246        let timestamp = Some(block.header.timestamp());
247        let receipts = receipts
248            .drain(page)
249            .zip(transactions.iter().map(Typed2718::ty))
250            .map(|(receipt, tx_ty)| {
251                let inner = OtsReceipt {
252                    status: receipt.status(),
253                    cumulative_gas_used: receipt.cumulative_gas_used(),
254                    logs: None,
255                    logs_bloom: None,
256                    r#type: tx_ty,
257                };
258
259                let receipt = TransactionReceipt {
260                    inner,
261                    transaction_hash: receipt.transaction_hash(),
262                    transaction_index: receipt.transaction_index(),
263                    block_hash: receipt.block_hash(),
264                    block_number: receipt.block_number(),
265                    gas_used: receipt.gas_used(),
266                    effective_gas_price: receipt.effective_gas_price(),
267                    blob_gas_used: receipt.blob_gas_used(),
268                    blob_gas_price: receipt.blob_gas_price(),
269                    from: receipt.from(),
270                    to: receipt.to(),
271                    contract_address: receipt.contract_address(),
272                };
273
274                OtsTransactionReceipt { receipt, timestamp }
275            })
276            .collect();
277
278        // use `transaction_count` to indicate the paginate information
279        let mut block = OtsBlockTransactions { fullblock: block.into(), receipts };
280        block.fullblock.transaction_count = tx_len;
281        Ok(block)
282    }
283
284    /// Handler for `ots_searchTransactionsBefore`
285    async fn search_transactions_before(
286        &self,
287        _address: Address,
288        _block_number: LenientBlockNumberOrTag,
289        _page_size: usize,
290    ) -> RpcResult<TransactionsWithReceipts> {
291        Err(internal_rpc_err("unimplemented"))
292    }
293
294    /// Handler for `ots_searchTransactionsAfter`
295    async fn search_transactions_after(
296        &self,
297        _address: Address,
298        _block_number: LenientBlockNumberOrTag,
299        _page_size: usize,
300    ) -> RpcResult<TransactionsWithReceipts> {
301        Err(internal_rpc_err("unimplemented"))
302    }
303
304    /// Handler for `ots_getTransactionBySenderAndNonce`
305    async fn get_transaction_by_sender_and_nonce(
306        &self,
307        sender: Address,
308        nonce: u64,
309    ) -> RpcResult<Option<TxHash>> {
310        Ok(self
311            .eth
312            .get_transaction_by_sender_and_nonce(sender, nonce, false)
313            .await
314            .map_err(Into::into)?
315            .map(|tx| tx.tx_hash()))
316    }
317
318    /// Handler for `ots_getContractCreator`
319    async fn get_contract_creator(&self, address: Address) -> RpcResult<Option<ContractCreator>> {
320        if !self.has_code(address, None).await? {
321            return Ok(None);
322        }
323
324        let num = binary_search::<_, _, ErrorObjectOwned>(
325            1,
326            self.eth.block_number()?.saturating_to(),
327            |mid| {
328                Box::pin(async move {
329                    Ok(!EthApiServer::get_code(&self.eth, address, Some(mid.into()))
330                        .await?
331                        .is_empty())
332                })
333            },
334        )
335        .await?;
336
337        let traces = self
338            .eth
339            .trace_block_with(
340                num.into(),
341                None,
342                TracingInspectorConfig::default_parity(),
343                |tx_info, mut ctx| {
344                    Ok(ctx
345                        .take_inspector()
346                        .into_parity_builder()
347                        .into_localized_transaction_traces(tx_info))
348                },
349            )
350            .await
351            .map_err(Into::into)?
352            .map(|traces| {
353                traces
354                    .into_iter()
355                    .flatten()
356                    .map(|tx_trace| {
357                        let trace = tx_trace.trace;
358                        Ok(match (trace.action, trace.result, trace.error) {
359                            (
360                                Action::Create(CreateAction { from: creator, .. }),
361                                Some(TraceOutput::Create(CreateOutput {
362                                    address: contract, ..
363                                })),
364                                None,
365                            ) if contract == address => Some(ContractCreator {
366                                hash: tx_trace
367                                    .transaction_hash
368                                    .ok_or(EthApiError::TransactionNotFound)?,
369                                creator,
370                            }),
371                            _ => None,
372                        })
373                    })
374                    .filter_map(Result::transpose)
375                    .collect::<Result<Vec<_>, EthApiError>>()
376            })
377            .transpose()?;
378
379        // A contract maybe created and then destroyed in multiple transactions, here we
380        // return the first found transaction, this behavior is consistent with etherscan's
381        let found = traces.and_then(|traces| traces.first().copied());
382        Ok(found)
383    }
384}
385
386/// Returns the transaction slice for an Otterscan block page.
387///
388/// Otterscan paginates in block order, so page `0` corresponds to the first transactions in the
389/// block instead of the tail.
390fn block_transaction_page_range(
391    tx_len: usize,
392    page_number: usize,
393    page_size: usize,
394) -> std::ops::Range<usize> {
395    let page_start = page_number.saturating_mul(page_size).min(tx_len);
396    let page_end = page_start.saturating_add(page_size).min(tx_len);
397    page_start..page_end
398}
399
400#[cfg(test)]
401mod tests {
402    use super::block_transaction_page_range;
403
404    #[test]
405    fn block_transaction_page_range_returns_first_pages_in_block_order() {
406        assert_eq!(block_transaction_page_range(25, 0, 10), 0..10);
407        assert_eq!(block_transaction_page_range(25, 1, 10), 10..20);
408    }
409
410    #[test]
411    fn block_transaction_page_range_caps_pages_at_the_block_length() {
412        assert_eq!(block_transaction_page_range(25, 2, 10), 20..25);
413        assert_eq!(block_transaction_page_range(25, 3, 10), 25..25);
414    }
415}