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
//! A collection of node-specific RPC methods.
//! Substrate provides the `sc-rpc` crate, which defines the core RPC layer
//! used by Substrate nodes. This file extends those RPC definitions with
//! capabilities that are specific to this project's runtime configuration.

#![warn(missing_docs)]

pub mod tracing;

use std::{sync::Arc, collections::BTreeMap};

use sc_network::NetworkService;
use jsonrpsee::RpcModule;
use sc_transaction_pool::{ChainApi, Pool};
use sc_transaction_pool_api::TransactionPool;
use sc_client_api::{backend::{Backend, StorageProvider}, client::BlockchainEvents, AuxStore};
use sp_api::ProvideRuntimeApi;
use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
use fc_rpc::{ EthBlockDataCacheTask, OverrideHandle, };
use fc_rpc_core::types::{FeeHistoryCache, FeeHistoryCacheLimit};
pub use fc_storage::overrides_handle;
use futures::channel::mpsc;

pub use sc_rpc_api::DenyUnsafe;
use core_primitives::{Block, Hash};
use crate::service::RuntimeApiCollection;

// pub struct TracingConfig {
//     pub tracing_requesters: tracing::RpcRequesters,
//     pub trace_filter_max_count: u32
// }


/// Full client dependencies.
pub struct FullDeps<C, P, A: ChainApi, SO, CIDP> {
    /// The client instance to use.
    pub client: Arc<C>,
    /// Transaction pool instance.
    pub pool: Arc<P>,
    /// Graph pool instance
    pub graph: Arc<Pool<A>>,
    /// Whether to deny unsafe calls
    pub deny_unsafe: DenyUnsafe,
    /// Node Authority Flag
    pub is_authority: bool,
    /// Network Service
    pub network: Arc<NetworkService<Block, Hash>>,
    /// Chain syncing service
    pub sync: Arc<sc_network_sync::SyncingService<Block>>,
    /// Backend.
    pub frontier_backend: Arc<dyn fc_api::Backend<Block> + Send + Sync>,
    /// EthFilterApi pool
    pub filter_pool: Option<fc_rpc_core::types::FilterPool>,
    /// Ethereum data access overrides.
    pub overrides: Arc<OverrideHandle<Block>>,
    /// Fee history cache.
    pub fee_history_cache: FeeHistoryCache,
    /// Maximum fee history cache size.
    pub fee_history_cache_limit: FeeHistoryCacheLimit,
    /// Cache for Ethereum Block Data
    pub block_data_cache: Arc<EthBlockDataCacheTask<Block>>,
	/// Mandated parent hashes for a given block hash.
	pub forced_parent_hashes: Option<BTreeMap<sp_core::H256, sp_core::H256>>,
    /// Something that can create the inherent data providers for pending state
    pub pending_create_inherent_data_providers: CIDP,
    ///
    pub import_justification_tx: mpsc::UnboundedSender<phron_finality::Justification>,
    ///
    pub justification_translator: phron_finality::JustificationTranslator,
    ///
    pub sync_oracle: SO,
    ///
    pub validator_address_cache: Option<phron_finality::ValidatorAddressCache>,
}

pub struct PhronGasAdapter;

impl fc_rpc::EstimateGasAdapter for PhronGasAdapter {
    fn adapt_request(mut request: fc_rpc_core::types::CallRequest) -> fc_rpc_core::types::CallRequest {
        // Redirect any call to batch precompile:
        // force usage of batchAll method for estimation
        use sp_core::H160;
        const BATCH_PRECOMPILE_ADDRESS: H160 = H160(hex_literal::hex!(
			"0000000000000000000000000000000000000808"
		));
        const BATCH_PRECOMPILE_BATCH_ALL_SELECTOR: [u8; 4] = hex_literal::hex!("96e292b8");
        if request.to == Some(BATCH_PRECOMPILE_ADDRESS) {
            if let Some(ref mut data) = request.data {
                if data.0.len() >= 4 {
                    data.0[..4].copy_from_slice(&BATCH_PRECOMPILE_BATCH_ALL_SELECTOR);
                }
            }
        }
        request
    }
}


pub struct DefaultEthConfig<C, BE>(std::marker::PhantomData<( C, BE)>);

impl<C, BE> fc_rpc::EthConfig<Block, C> for DefaultEthConfig<C, BE>
    where
        C: StorageProvider<Block, BE> + Sync + Send + 'static,
        BE: Backend<Block> + 'static,
{
    type EstimateGasAdapter = PhronGasAdapter;
    type RuntimeStorageOverride =
        fc_rpc::frontier_backend_client::SystemAccountId20StorageOverride<Block, C, BE>;
}

/// Instantiate all full RPC extensions.
pub fn create_full<C, P, BE, A, SO, CIDP, EC>(
    deps: FullDeps<C, P, A, SO, CIDP>,
    pubsub_notification_sinks: Arc<
        fc_mapping_sync::EthereumBlockNotificationSinks<
            fc_mapping_sync::EthereumBlockNotification<Block>,
        >,
    >,
    subscription_task_executor: sc_rpc::SubscriptionTaskExecutor,
) -> Result<RpcModule<()>, Box<dyn std::error::Error + Send + Sync>>
    where
        BE: Backend<Block> + 'static,
        BE::State: sc_client_api::backend::StateBackend<sp_runtime::traits::BlakeTwo256>,
        C: BlockchainEvents<Block>
            + ProvideRuntimeApi<Block>
            + StorageProvider<Block, BE>
            + HeaderBackend<Block>
            + HeaderMetadata<Block, Error=BlockChainError>
            + Send + Sync + 'static + AuxStore
            + sc_client_api::UsageProvider<Block>
            + sp_api::CallApiAt<Block>,
        C::Api: RuntimeApiCollection,
        C::Api: sp_consensus_aura::AuraApi<Block, sp_consensus_aura::sr25519::AuthorityId>,
        P: TransactionPool<Block=Block> + 'static + Send + Sync,
        A: ChainApi<Block=Block> + 'static,
        SO: sp_consensus::SyncOracle + Send + Sync + 'static,
        CIDP: sp_inherents::CreateInherentDataProviders<Block, ()> + 'static,
        EC: fc_rpc::EthConfig<Block, C>,
{
    use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
    use crate::phron_node_rpc::{PhronNode, PhronNodeApiServer};
    use substrate_frame_rpc_system::{System, SystemApiServer};
    use fc_rpc::{
        Eth, EthApiServer, Net, NetApiServer, Web3, Web3ApiServer, TxPool, TxPoolApiServer, EthFilter, EthFilterApiServer,
        EthPubSub, EthPubSubApiServer
    };

    let mut module = RpcModule::new(());
    let FullDeps {
        client, pool, graph, deny_unsafe, is_authority,
        network, sync, frontier_backend, filter_pool,
        overrides, fee_history_cache, fee_history_cache_limit, block_data_cache,
        forced_parent_hashes, pending_create_inherent_data_providers,
        import_justification_tx, justification_translator,
        sync_oracle, validator_address_cache,
    } = deps;

    // Nor any signers
    let signers = Vec::new();

    // Limit the number of queryable logs.
    let max_past_logs: u32 = 1024;

    module.merge(System::new(client.clone(), pool.clone(), deny_unsafe).into_rpc())?;
    module.merge(TransactionPayment::new(client.clone()).into_rpc())?;
    module.merge(Net::new(client.clone(), network, true).into_rpc())?;

    module.merge(
        Eth::<Block, C, P, _, BE, A, CIDP, EC>::new(
            client.clone(),
            pool.clone(),
            graph.clone(),
            <Option<fp_rpc::NoTransactionConverter>>::None,
            sync.clone(),
            signers,
            overrides.clone(),
            frontier_backend.clone(),
            is_authority,
            block_data_cache.clone(),
            fee_history_cache,
            fee_history_cache_limit,
            // The Maximum allowed gas limit will be ` block.gas_limit * execute_gas_limit_multiplier` when
            // using eth_call/eth_estimateGas.,
            10,
			forced_parent_hashes,
            pending_create_inherent_data_providers,
            Some(Box::new(fc_rpc::pending::AuraConsensusDataProvider::new(
                client.clone(),
            ))),
        )
            .replace_config::<EC>()
            .into_rpc())?;

    module.merge(
        PhronNode::new(
            import_justification_tx,
            justification_translator,
            client.clone(),
            sync_oracle,
            validator_address_cache
        ).into_rpc()
    )?;

    module.merge(TxPool::new(
        client.clone(),
        graph.clone()
    ).into_rpc())?;

    module.merge(Web3::new(
        client.clone(),
    ).into_rpc())?;

    module.merge(
        EthPubSub::new(
            pool,
            client.clone(),
            sync,
            subscription_task_executor,
            overrides,
            pubsub_notification_sinks,
        ).into_rpc(),
    )?;

    if let Some(filter_pool) = filter_pool {
        module.merge(EthFilter::new(
            client,
            frontier_backend,
            graph,
            filter_pool,
            500_usize,
            max_past_logs,
            block_data_cache,
        ).into_rpc())?;
    }


    // Extend this RPC with a custom API by using the following syntax.
    // `YourRpcStruct` should have a reference to a client, which is needed
    // to call into the runtime.
    // `module.merge(YourRpcTrait::into_rpc(YourRpcStruct::new(ReferenceToClient, ...)))?;`

    Ok(module)
}