-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.rs
More file actions
457 lines (388 loc) · 14 KB
/
server.rs
File metadata and controls
457 lines (388 loc) · 14 KB
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use super::*;
use alloy_consensus::Receipt;
use alloy_primitives::{Address, Bytes, B256, U256, U64};
use alloy_rpc_types_eth::{
pubsub::{Params, SubscriptionKind},
state::StateOverride,
Block as EthBlock, BlockId, BlockNumberOrTag, BlockOverrides, FeeHistory, Index, SyncStatus,
Transaction, TransactionRequest, Work,
};
use futures::FutureExt;
use jsonrpsee::{
core::{async_trait, RpcResult},
PendingSubscriptionSink,
};
use sub_client::handle_accepted_subscription;
use traits::{EthApiServer, EthPubSubApiServer};
pub type SubscriptionTaskExecutor = std::sync::Arc<dyn sp_core::traits::SpawnNamed>;
/// A notification when new block is received.
#[allow(dead_code)] // Used in subscription code path
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct BlockNotification {
pub hash: B256,
pub is_new_best: bool,
}
/// The main ETH adapter struct responsible for handling all the ETH RPC methods and converting them to Substrate calls.
pub struct EthAdapter {
/// The Substrate light client
client: SubLightClient,
/// Accounts managed by this ETH adapter
accounts: Vec<Address>,
/// Subscription task executor (used in EthPubSubApiServer implementation)
#[allow(dead_code)]
executor: SubscriptionTaskExecutor,
}
impl EthAdapter {
/// Create a new instance of the ETH adapter
pub fn new(
client: SubLightClient,
accounts: Vec<Address>,
executor: SubscriptionTaskExecutor,
) -> Self {
Self {
client,
accounts,
executor,
}
}
}
/// Implement the ETH API server
#[async_trait]
impl EthApiServer for EthAdapter {
// ########################################################################
// Client
// ########################################################################
/// Returns protocol version encoded as a string (quotes are necessary).
fn protocol_version(&self) -> RpcResult<u64> {
Ok(1)
}
fn syncing(&self) -> RpcResult<SyncStatus> {
let status = self.client.syncing()?;
Ok(status)
}
/// Returns block author.
fn author(&self) -> RpcResult<Address> {
unimplemented!()
}
/// Returns accounts list.
fn accounts(&self) -> RpcResult<Vec<Address>> {
Ok(self.accounts.clone())
}
/// Returns highest block number.
async fn block_number(&self) -> RpcResult<U256> {
let block_number = self.client.block_number().await?;
Ok(U256::from(block_number))
}
/// Returns the chain ID used for transaction signing at the
/// current best block. None is returned if not
/// available.
fn chain_id(&self) -> RpcResult<Option<U64>> {
Ok(Some(U64::from(self.client.chain_id())))
}
// ########################################################################
// Block
// ########################################################################
/// Returns block with given hash.
async fn block_by_hash(&self, hash: B256, _full: bool) -> RpcResult<Option<EthBlock>> {
let block = self.client.get_block_by_hash(hash.0.into()).await?;
Ok(Some(block))
}
/// Returns block with given number.
async fn block_by_number(
&self,
number: BlockNumberOrTag,
_full: bool,
) -> RpcResult<Option<EthBlock>> {
let block = self.client.get_block_by_number(number).await?;
Ok(block)
}
/// Returns the number of transactions in a block with given hash.
async fn block_transaction_count_by_hash(&self, _hash: B256) -> RpcResult<Option<U256>> {
unimplemented!()
}
/// Returns the number of transactions in a block with given block number.
async fn block_transaction_count_by_number(
&self,
_number: BlockNumberOrTag,
) -> RpcResult<Option<U256>> {
unimplemented!()
}
/// Returns the number of uncles in a block with given hash.
fn block_uncles_count_by_hash(&self, _hash: B256) -> RpcResult<U256> {
unimplemented!()
}
/// Returns the number of uncles in a block with given block number.
fn block_uncles_count_by_number(&self, _number: u64) -> RpcResult<U256> {
unimplemented!()
}
/// Returns an uncles at given block and index.
fn uncle_by_block_hash_and_index(
&self,
_hash: B256,
_index: Index,
) -> RpcResult<Option<EthBlock>> {
unimplemented!()
}
/// Returns an uncles at given block and index.
fn uncle_by_block_number_and_index(
&self,
_number: u64,
_index: Index,
) -> RpcResult<Option<EthBlock>> {
unimplemented!()
}
// ########################################################################
// Transaction
// ########################################################################
/// Get transaction by its hash.
async fn transaction_by_hash(&self, _hash: B256) -> RpcResult<Option<Transaction>> {
unimplemented!()
}
/// Returns transaction by given block number and index.
async fn transaction_by_block_hash_and_index(
&self,
_hash: B256,
_index: Index,
) -> RpcResult<Option<Transaction>> {
unimplemented!()
}
/// Returns transaction by given block number and index.
async fn transaction_by_block_number_and_index(
&self,
number: BlockNumberOrTag,
index: Index,
) -> RpcResult<Option<Transaction>> {
let tx = self
.client
.get_transaction_by_block_and_index(number, index)
.await?;
Ok(tx)
}
/// Returns transaction receipt by transaction hash.
async fn transaction_receipt(&self, _hash: B256) -> RpcResult<Option<Receipt>> {
unimplemented!()
}
// ########################################################################
// State
// ########################################################################
/// Returns balance of the given account.
async fn balance(&self, address: Address, _number_or_tag: Option<BlockId>) -> RpcResult<U256> {
let balance = self.client.get_balance(address).await?;
Ok(balance)
}
/// Returns content of the storage at given address.
async fn storage_at(
&self,
address: Address,
key: B256,
_number_or_tag: Option<BlockId>,
) -> RpcResult<Vec<u8>> {
let storage = self.client.get_storage_at(address, key.0.into()).await?;
Ok(storage)
}
/// Returns the number of transactions sent from given address at given time (block number).
async fn transaction_count(
&self,
address: Address,
_number_or_tag: Option<BlockNumberOrTag>,
) -> RpcResult<U256> {
let count = self.client.get_transaction_count(address).await?;
Ok(count)
}
/// Returns the code at given address at given time (block number).
async fn code_at(
&self,
address: Address,
_number_or_tag: Option<BlockNumberOrTag>,
) -> RpcResult<Bytes> {
let code = self.client.get_code(address)?;
Ok(code.into())
}
// ########################################################################
// Execute
// ########################################################################
/// Call contract, returning the output data.
async fn call(
&self,
request: TransactionRequest,
_block_number: Option<BlockId>,
_state_overrides: Option<StateOverride>,
_block_overrides: Option<Box<BlockOverrides>>,
) -> RpcResult<Bytes> {
let res = self.client.call(request).await?;
if let Some(output) = res {
Ok(output.into())
} else {
Ok(Bytes::new())
}
}
/// Estimate gas needed for execution of given contract.
async fn estimate_gas(
&self,
_request: TransactionRequest,
_block_number: Option<BlockId>,
_state_override: Option<StateOverride>,
) -> RpcResult<U256> {
unimplemented!()
}
// ########################################################################
// Fee
// ########################################################################
/// Returns current gas_price.
fn gas_price(&self) -> RpcResult<U256> {
// TODO: fix this
Ok(U256::from(1_000_000))
}
/// Introduced in EIP-1159 for getting information on the appropriate priority fee to use.
async fn fee_history(
&self,
_block_count: U256,
_newest_block: U256,
_reward_percentiles: Option<Vec<f64>>,
) -> RpcResult<FeeHistory> {
unimplemented!()
}
/// Introduced in EIP-1159, a Geth-specific and simplified priority fee oracle.
/// Leverages the already existing fee history cache.
fn max_priority_fee_per_gas(&self) -> RpcResult<U256> {
unimplemented!()
}
// ########################################################################
// Mining
// ########################################################################
/// Returns true if client is actively mining new blocks.
fn is_mining(&self) -> RpcResult<bool> {
Ok(false)
}
/// Returns the number of hashes per second that the node is mining with.
fn hashrate(&self) -> RpcResult<U256> {
Ok(U256::ZERO)
}
/// Returns the hash of the current block, the seedHash, and the boundary condition to be met.
fn work(&self) -> RpcResult<Work> {
Ok(Work::default())
}
/// Used for submitting mining hashrate.
fn submit_hashrate(&self, _hashrate: U256, _id: B256) -> RpcResult<bool> {
Ok(false)
}
/// Used for submitting a proof-of-work solution.
fn submit_work(&self, _nonce: u64, _pow_hash: B256, _mix_digest: B256) -> RpcResult<bool> {
Ok(false)
}
// ########################################################################
// Submit
// ########################################################################
/// Sends transaction; will block waiting for signer to return the
/// transaction hash.
async fn send_transaction(&self, request: TransactionRequest) -> RpcResult<B256> {
use subeth_primitives::{conversions::*, EthereumTransaction};
// Extract transaction details
let to = match request.to {
Some(alloy_primitives::TxKind::Call(addr)) => alloy_address_to_h160(addr),
_ => {
return Err(jsonrpsee::types::ErrorObject::owned(
-32602,
"Missing 'to' address",
None::<()>,
)
.into())
}
};
let nonce = request.nonce.unwrap_or(0);
let value = alloy_u256_to_sp_u256(request.value.unwrap_or_default());
let data = request.input.input.map(|b| b.to_vec()).unwrap_or_default();
let gas_limit = request.gas.unwrap_or(21000);
// Get gas price
let max_fee_per_gas = alloy_u256_to_sp_u256(
alloy_primitives::U256::from(request.max_fee_per_gas.unwrap_or(1_000_000))
);
let max_priority_fee_per_gas =
alloy_u256_to_sp_u256(alloy_primitives::U256::from(request.max_priority_fee_per_gas.unwrap_or(0)));
// Construct EthereumTransaction
// Note: For now, signature fields are dummy values since we're using a signed extrinsic
// The pallet will verify these, but for MVP we can use placeholder values
let eth_tx = EthereumTransaction {
chain_id: self.client.chain_id(),
nonce,
max_priority_fee_per_gas,
max_fee_per_gas,
gas_limit,
to,
value,
data,
access_list: vec![],
v: 0,
r: Default::default(),
s: Default::default(),
};
// Submit to chain
let tx_hash = self
.client
.submit_evm_transaction(eth_tx)
.await
.map_err(|e| {
jsonrpsee::types::ErrorObject::owned(
-32000,
format!("Transaction submission failed: {:?}", e),
None::<()>,
)
})?;
Ok(tx_hash)
}
/// Sends signed transaction, returning its hash.
async fn send_raw_transaction(&self, bytes: Bytes) -> RpcResult<B256> {
use subeth_primitives::EthereumTransaction;
use parity_scale_codec::Decode;
// Decode the raw transaction
let eth_tx = EthereumTransaction::decode(&mut bytes.as_ref()).map_err(|e| {
jsonrpsee::types::ErrorObject::owned(
-32602,
format!("Failed to decode transaction: {:?}", e),
None::<()>,
)
})?;
// Submit to chain
let tx_hash = self
.client
.submit_evm_transaction(eth_tx)
.await
.map_err(|e| {
jsonrpsee::types::ErrorObject::owned(
-32000,
format!("Transaction submission failed: {:?}", e),
None::<()>,
)
})?;
Ok(tx_hash)
}
}
#[async_trait]
impl EthPubSubApiServer for EthAdapter {
async fn subscribe(
&self,
pending: PendingSubscriptionSink,
kind: SubscriptionKind,
params: Option<Params>,
) -> jsonrpsee::core::SubscriptionResult {
// Handle the subscription logic here
println!(
"Subscribed with kind: {:?}, params: {:?}, id: {:?}",
kind, params, pending
);
let sink = pending.accept().await?;
let client = self.client.clone();
let fut = async move {
match kind {
SubscriptionKind::NewHeads => {
let _ = handle_accepted_subscription(client, kind, sink).await;
}
_ => {}
}
}
.boxed();
self.executor
.spawn("sub-eth-subscription", Some("subeth"), fut);
Ok(())
}
}