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
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This file is part of Frontier.
//
// Copyright (c) 2022 Parity Technologies (UK) Ltd.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use ethereum_types::{H160, H256, U256};
use jsonrpsee::core::RpcResult;
use scale_codec::Encode;
// Substrate
use sc_client_api::backend::{Backend, StorageProvider};
use sc_transaction_pool::ChainApi;
use sc_transaction_pool_api::{InPoolTransaction, TransactionPool};
use sp_api::ProvideRuntimeApi;
use sp_block_builder::BlockBuilder as BlockBuilderApi;
use sp_blockchain::HeaderBackend;
use sp_inherents::CreateInherentDataProviders;
use sp_runtime::traits::Block as BlockT;
// Frontier
use fc_rpc_core::types::*;
use fp_rpc::EthereumRuntimeRPCApi;

use crate::{
    eth::{Eth, EthConfig},
    frontier_backend_client, internal_err,
};

impl<B, C, P, CT, BE, A, CIDP, EC> Eth<B, C, P, CT, BE, A, CIDP, EC>
where
    B: BlockT,
    C: ProvideRuntimeApi<B>,
    C::Api: BlockBuilderApi<B> + EthereumRuntimeRPCApi<B>,
    C: HeaderBackend<B> + StorageProvider<B, BE> + 'static,
    BE: Backend<B> + 'static,
    P: TransactionPool<Block = B> + 'static,
    A: ChainApi<Block = B>,
    CIDP: CreateInherentDataProviders<B, ()> + Send + 'static,
    EC: EthConfig<B, C>,
{
    pub async fn balance(&self, address: H160, number: Option<BlockNumber>) -> RpcResult<U256> {
        let number = number.unwrap_or(BlockNumber::Latest);
        if number == BlockNumber::Pending {
            let (hash, api) = self
                .pending_runtime_api()
                .await
                .map_err(|err| internal_err(format!("Create pending runtime api error: {err}")))?;
            Ok(api
                .account_basic(hash, address)
                .map_err(|err| internal_err(format!("Fetch account balances failed: {err}")))?
                .balance)
        } else if let Ok(Some(id)) = frontier_backend_client::native_block_id::<B, C>(
            self.client.as_ref(),
            self.backend.as_ref(),
            Some(number),
        )
        .await
        {
            let substrate_hash = self
                .client
                .expect_block_hash_from_id(&id)
                .map_err(|_| internal_err(format!("Expect block number from id: {id}")))?;

            Ok(self
                .client
                .runtime_api()
                .account_basic(substrate_hash, address)
                .map_err(|err| internal_err(format!("Fetch account balances failed: {:?}", err)))?
                .balance)
        } else {
            Ok(U256::zero())
        }
    }

    pub async fn storage_at(
        &self,
        address: H160,
        index: U256,
        number: Option<BlockNumber>,
    ) -> RpcResult<H256> {
        let number = number.unwrap_or(BlockNumber::Latest);
        if number == BlockNumber::Pending {
            let (hash, api) = self
                .pending_runtime_api()
                .await
                .map_err(|err| internal_err(format!("Create pending runtime api error: {err}")))?;
            Ok(api.storage_at(hash, address, index).unwrap_or_default())
        } else if let Ok(Some(id)) = frontier_backend_client::native_block_id::<B, C>(
            self.client.as_ref(),
            self.backend.as_ref(),
            Some(number),
        )
        .await
        {
            let substrate_hash = self
                .client
                .expect_block_hash_from_id(&id)
                .map_err(|_| internal_err(format!("Expect block number from id: {id}")))?;
            let schema = fc_storage::onchain_storage_schema(self.client.as_ref(), substrate_hash);
            Ok(self
                .overrides
                .schemas
                .get(&schema)
                .unwrap_or(&self.overrides.fallback)
                .storage_at(substrate_hash, address, index)
                .unwrap_or_default())
        } else {
            Ok(H256::default())
        }
    }

    pub async fn transaction_count(
        &self,
        address: H160,
        number: Option<BlockNumber>,
    ) -> RpcResult<U256> {
        if let Some(BlockNumber::Pending) = number {
            let substrate_hash = self.client.info().best_hash;

            let nonce = self
                .client
                .runtime_api()
                .account_basic(substrate_hash, address)
                .map_err(|err| internal_err(format!("Fetch account nonce failed: {err}")))?
                .nonce;

            let mut current_nonce = nonce;
            let mut current_tag = (address, nonce).encode();
            for tx in self.pool.ready() {
                // since transactions in `ready()` need to be ordered by nonce
                // it's fine to continue with current iterator.
                if tx.provides().get(0) == Some(&current_tag) {
                    current_nonce = current_nonce.saturating_add(1.into());
                    current_tag = (address, current_nonce).encode();
                }
            }

            return Ok(current_nonce)
        }

        let id = match frontier_backend_client::native_block_id::<B, C>(
            self.client.as_ref(),
            self.backend.as_ref(),
            number,
        )
        .await?
        {
            Some(id) => id,
            None => return Ok(U256::zero()),
        };

        let substrate_hash = self
            .client
            .expect_block_hash_from_id(&id)
            .map_err(|_| internal_err(format!("Expect block number from id: {id}")))?;

        Ok(self
            .client
            .runtime_api()
            .account_basic(substrate_hash, address)
            .map_err(|err| internal_err(format!("Fetch account nonce failed: {err}")))?
            .nonce)
    }

    pub async fn code_at(&self, address: H160, number: Option<BlockNumber>) -> RpcResult<Bytes> {
        let number = number.unwrap_or(BlockNumber::Latest);
        if number == BlockNumber::Pending {
            let (hash, api) = self
                .pending_runtime_api()
                .await
                .map_err(|err| internal_err(format!("Create pending runtime api error: {err}")))?;
            Ok(api
                .account_code_at(hash, address)
                .unwrap_or_default()
                .into())
        } else if let Ok(Some(id)) = frontier_backend_client::native_block_id::<B, C>(
            self.client.as_ref(),
            self.backend.as_ref(),
            Some(number),
        )
        .await
        {
            let substrate_hash = self
                .client
                .expect_block_hash_from_id(&id)
                .map_err(|_| internal_err(format!("Expect block number from id: {id}")))?;
            let schema = fc_storage::onchain_storage_schema(self.client.as_ref(), substrate_hash);

            Ok(self
                .overrides
                .schemas
                .get(&schema)
                .unwrap_or(&self.overrides.fallback)
                .account_code_at(substrate_hash, address)
                .unwrap_or_default()
                .into())
        } else {
            Ok(Bytes(vec![]))
        }
    }
}