fc_rpc/
web3.rs

1// This file is part of Frontier.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19use std::{marker::PhantomData, sync::Arc};
20
21use ethereum_types::H256;
22use jsonrpsee::core::RpcResult;
23// Substrate
24use sp_api::{Core, ProvideRuntimeApi};
25use sp_blockchain::HeaderBackend;
26use sp_core::keccak_256;
27use sp_runtime::traits::Block as BlockT;
28// Frontier
29use fc_rpc_core::{types::Bytes, Web3ApiServer};
30use fp_rpc::EthereumRuntimeRPCApi;
31
32use crate::internal_err;
33
34/// Web3 API implementation.
35pub struct Web3<B, C> {
36	client: Arc<C>,
37	_marker: PhantomData<B>,
38}
39
40impl<B, C> Web3<B, C> {
41	pub fn new(client: Arc<C>) -> Self {
42		Self {
43			client,
44			_marker: PhantomData,
45		}
46	}
47}
48
49impl<B, C> Web3ApiServer for Web3<B, C>
50where
51	B: BlockT,
52	C: ProvideRuntimeApi<B>,
53	C::Api: EthereumRuntimeRPCApi<B>,
54	C: HeaderBackend<B> + 'static,
55{
56	fn client_version(&self) -> RpcResult<String> {
57		let hash = self.client.info().best_hash;
58		let version = self
59			.client
60			.runtime_api()
61			.version(hash)
62			.map_err(|err| internal_err(format!("fetch runtime version failed: {err:?}")))?;
63		Ok(format!(
64			"{spec_name}/v{spec_version}.{impl_version}/{pkg_name}-{pkg_version}",
65			spec_name = version.spec_name,
66			spec_version = version.spec_version,
67			impl_version = version.impl_version,
68			pkg_name = env!("CARGO_PKG_NAME"),
69			pkg_version = env!("CARGO_PKG_VERSION")
70		))
71	}
72
73	fn sha3(&self, input: Bytes) -> RpcResult<H256> {
74		Ok(H256::from(keccak_256(&input.into_vec())))
75	}
76}