-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathprovider.rs
More file actions
192 lines (166 loc) · 6.89 KB
/
Copy pathprovider.rs
File metadata and controls
192 lines (166 loc) · 6.89 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
/// Types related to provider factories.
pub mod factory;
mod response;
use std::sync::Arc;
use edr_napi_core::provider::SyncProvider;
use edr_solidity::compiler::create_models_and_decode_bytecodes;
use napi::{bindgen_prelude::ObjectFinalize, tokio::runtime, Env, JsFunction, JsObject, Status};
use napi_derive::napi;
use parking_lot::RwLock;
pub use self::factory::ProviderFactory;
use self::response::Response;
use crate::{
async_deallocator::AsyncDeallocatorSender, call_override::CallOverrideCallback,
contract_decoder::ContractDecoder,
};
/// A JSON-RPC provider for Ethereum.
#[napi(custom_finalize)]
pub struct Provider {
contract_decoder: Arc<RwLock<edr_solidity::contract_decoder::ContractDecoder>>,
provider: Arc<dyn SyncProvider>,
runtime: runtime::Handle,
dropped_provider_sender: AsyncDeallocatorSender<Arc<dyn SyncProvider>>,
#[cfg(feature = "scenarios")]
scenario_file: Option<napi::tokio::sync::Mutex<napi::tokio::fs::File>>,
}
impl Provider {
/// Constructs a new instance.
pub fn new(
provider: Arc<dyn SyncProvider>,
runtime: runtime::Handle,
contract_decoder: Arc<RwLock<edr_solidity::contract_decoder::ContractDecoder>>,
dropped_provider_sender: AsyncDeallocatorSender<Arc<dyn SyncProvider>>,
#[cfg(feature = "scenarios")] scenario_file: Option<
napi::tokio::sync::Mutex<napi::tokio::fs::File>,
>,
) -> Self {
Self {
contract_decoder,
provider,
runtime,
dropped_provider_sender,
#[cfg(feature = "scenarios")]
scenario_file,
}
}
}
#[napi]
impl Provider {
#[doc = "Adds a compilation result to the instance."]
#[doc = ""]
#[doc = "For internal use only. Support for this method may be removed in the future."]
#[napi(catch_unwind)]
pub async fn add_compilation_result(
&self,
solc_version: String,
compiler_input: serde_json::Value,
compiler_output: serde_json::Value,
) -> napi::Result<()> {
let contract_decoder = self.contract_decoder.clone();
self.runtime
.spawn_blocking(move || {
let compiler_input = serde_json::from_value(compiler_input)
.map_err(|error| napi::Error::from_reason(error.to_string()))?;
let compiler_output = serde_json::from_value(compiler_output)
.map_err(|error| napi::Error::from_reason(error.to_string()))?;
// `addCompilationResult` is called by both HH2 (via the legacy
// `hardhat_addCompilationResult` JSON-RPC method) and HH3
// (internally, for its provider's in-process compile flow).
// Both feed solc artifacts; solx reaches EDR through HH3's
// `BuildInfoConfig` (`runSolidityTests` / `withContracts`).
// The compiler is derived from the bytecode variant — no
// separate tag needs to be threaded in.
let contracts = match create_models_and_decode_bytecodes(
solc_version,
&compiler_input,
&compiler_output,
) {
Ok(contracts) => contracts,
Err(error) => {
return Err(napi::Error::from_reason(format!("Contract decoder failed to be updated. Please report this to help us improve Hardhat.\n{error}")));
}
};
let mut contract_decoder = contract_decoder.write();
for contract in contracts {
contract_decoder.add_contract_metadata(contract);
}
Ok(())
})
.await
.map_err(|error| napi::Error::new(Status::GenericFailure, error.to_string()))?
}
#[doc = "Retrieves the instance's contract decoder."]
#[napi(catch_unwind)]
pub fn contract_decoder(&self) -> ContractDecoder {
ContractDecoder::from(Arc::clone(&self.contract_decoder))
}
#[doc = "Handles a JSON-RPC request and returns a JSON-RPC response."]
#[napi(catch_unwind)]
pub async fn handle_request(&self, request: String) -> napi::Result<Response> {
let provider = self.provider.clone();
#[cfg(feature = "scenarios")]
if let Some(scenario_file) = &self.scenario_file {
crate::scenarios::write_request(scenario_file, &request).await?;
}
self.runtime
.spawn_blocking(move || provider.handle_request(request))
.await
.map_err(|error| napi::Error::new(Status::GenericFailure, error.to_string()))?
.map(Response::from)
}
#[napi(catch_unwind, ts_return_type = "Promise<void>")]
pub fn set_call_override_callback(
&self,
env: Env,
#[napi(
ts_arg_type = "(contract_address: ArrayBuffer, data: ArrayBuffer) => Promise<CallOverrideResult | undefined>"
)]
call_override_callback: JsFunction,
) -> napi::Result<JsObject> {
let (deferred, promise) = env.create_deferred()?;
let call_override_callback =
match CallOverrideCallback::new(&env, call_override_callback, self.runtime.clone()) {
Ok(callback) => callback,
Err(error) => {
deferred.reject(error);
return Ok(promise);
}
};
let call_override_callback =
Arc::new(move |address, data| call_override_callback.call_override(address, data));
let provider = self.provider.clone();
self.runtime.spawn_blocking(move || {
provider.set_call_override_callback(call_override_callback);
deferred.resolve(|_env| Ok(()));
});
Ok(promise)
}
/// Set to `true` to make the traces returned with `eth_call`,
/// `eth_estimateGas`, `eth_sendRawTransaction`, `eth_sendTransaction`,
/// `evm_mine`, `hardhat_mine` include the full stack and memory. Set to
/// `false` to disable this.
#[napi(catch_unwind)]
pub async fn set_verbose_tracing(&self, verbose_tracing: bool) -> napi::Result<()> {
let provider = self.provider.clone();
self.runtime
.spawn_blocking(move || {
provider.set_verbose_tracing(verbose_tracing);
})
.await
.map_err(|error| napi::Error::new(Status::GenericFailure, error.to_string()))
}
}
impl ObjectFinalize for Provider {
fn finalize(self, _env: Env) -> napi::Result<()> {
let Self {
provider,
dropped_provider_sender,
..
} = self;
// Off-loads deallocation to a background thread to avoid blocking the
// JS thread (the provider may be running thread-safe functions on a
// background thread; dropping it here would deadlock).
dropped_provider_sender.deallocate(provider);
Ok(())
}
}