1use std::{sync::Arc, time::Duration};
6
7use SafeSingleton::SafeSingletonInstance;
8use alloy::{
9 network::EthereumWallet,
10 providers::{
11 CallItemBuilder, Identity, PendingTransaction, Provider, ProviderBuilder, RootProvider,
12 fillers::{
13 BlobGasFiller, CachedNonceManager, ChainIdFiller, FillProvider, GasFiller, JoinFill, NonceFiller,
14 WalletFiller,
15 },
16 },
17 rpc::{
18 client::RpcClient,
19 types::{Block, TransactionRequest},
20 },
21 signers::local::PrivateKeySigner,
22 sol,
23};
24use async_trait::async_trait;
25use hopr_bindings::hoprnodemanagementmodule::HoprNodeManagementModule::{self, HoprNodeManagementModuleInstance};
26use hopr_chain_types::{ContractAddresses, ContractInstances, NetworkRegistryProxy};
27use hopr_crypto_types::{
28 keypairs::{ChainKeypair, Keypair},
29 prelude::Hash,
30};
31use hopr_internal_types::prelude::{EncodedWinProb, WinningProbability};
32use hopr_primitive_types::prelude::*;
33use primitive_types::U256;
34use serde::{Deserialize, Serialize};
35use tracing::debug;
36use url::Url;
37use validator::Validate;
38
39use crate::{
41 HoprRpcOperations, NodeSafeModuleStatus,
42 client::GasOracleFiller,
43 errors::{Result, RpcError},
44 transport::HttpRequestor,
45};
46
47sol!(
49 #![sol(abi)]
50 #![sol(rpc)]
51 contract SafeSingleton {
52 function isModuleEnabled(address module) public view returns (bool);
53 }
54);
55
56pub const DEFAULT_GAS_ORACLE_URL: &str = "https://ggnosis.blockscan.com/gasapi.ashx?apikey=key&method=gasoracle";
58
59#[derive(Clone, Debug, PartialEq, Eq, smart_default::SmartDefault, Serialize, Deserialize, Validate)]
61pub struct RpcOperationsConfig {
62 #[default = 100]
66 pub chain_id: u64,
67 pub contract_addrs: ContractAddresses,
71 pub module_address: Address,
75 pub safe_address: Address,
79 #[default(Duration::from_secs(5))]
83 pub expected_block_time: Duration,
84 #[validate(range(min = 1))]
90 #[default = 2000]
91 pub max_block_range_fetch_size: u64,
92 #[default(Duration::from_secs(7))]
96 pub tx_polling_interval: Duration,
97 #[validate(range(min = 1, max = 100))]
105 #[default = 8]
106 pub finality: u32,
107 #[default(Some(DEFAULT_GAS_ORACLE_URL.parse().unwrap()))]
111 pub gas_oracle_url: Option<Url>,
112}
113
114pub(crate) type HoprProvider<R> = FillProvider<
115 JoinFill<
116 JoinFill<
117 JoinFill<
118 JoinFill<
119 JoinFill<JoinFill<Identity, WalletFiller<EthereumWallet>>, ChainIdFiller>,
120 NonceFiller<CachedNonceManager>,
121 >,
122 GasFiller,
123 >,
124 GasOracleFiller<R>,
125 >,
126 BlobGasFiller,
127 >,
128 RootProvider,
129>;
130
131#[derive(Debug, Clone)]
133pub struct RpcOperations<R: HttpRequestor + 'static + Clone> {
134 pub(crate) provider: Arc<HoprProvider<R>>,
135 pub(crate) cfg: RpcOperationsConfig,
136 contract_instances: Arc<ContractInstances<HoprProvider<R>>>,
137 node_module: HoprNodeManagementModuleInstance<HoprProvider<R>>,
138 node_safe: SafeSingletonInstance<HoprProvider<R>>,
139}
140
141#[cfg_attr(test, mockall::automock)]
142impl<R: HttpRequestor + 'static + Clone> RpcOperations<R> {
143 pub fn new(
144 rpc_client: RpcClient,
145 requestor: R,
146 chain_key: &ChainKeypair,
147 cfg: RpcOperationsConfig,
148 use_dummy_nr: Option<bool>,
149 ) -> Result<Self> {
150 let wallet =
151 PrivateKeySigner::from_slice(chain_key.secret().as_ref()).map_err(|e| RpcError::SignerError(e.into()))?;
152
153 let provider = ProviderBuilder::new()
154 .disable_recommended_fillers()
155 .wallet(wallet)
156 .filler(ChainIdFiller::default())
157 .filler(NonceFiller::new(CachedNonceManager::default()))
158 .filler(GasFiller)
159 .filler(GasOracleFiller::new(requestor.clone(), cfg.gas_oracle_url.clone()))
160 .filler(BlobGasFiller)
161 .connect_client(rpc_client);
162
163 debug!("{:?}", cfg.contract_addrs);
164
165 Ok(Self {
166 contract_instances: Arc::new(ContractInstances::new(
167 &cfg.contract_addrs,
168 provider.clone(),
169 use_dummy_nr.unwrap_or(cfg!(test)),
170 )),
171 node_module: HoprNodeManagementModule::new(cfg.module_address.into(), provider.clone()),
172 node_safe: SafeSingleton::new(cfg.safe_address.into(), provider.clone()),
173 cfg,
174 provider: Arc::new(provider),
175 })
176 }
177
178 pub(crate) async fn get_block_number(&self) -> Result<u64> {
179 Ok(self
180 .provider
181 .get_block_number()
182 .await?
183 .saturating_sub(self.cfg.finality as u64))
184 }
185
186 pub(crate) async fn get_block(&self, block_number: u64) -> Result<Option<Block>> {
187 let sanitized_block_number = block_number.saturating_sub(self.cfg.finality as u64);
188 let result = self.provider.get_block_by_number(sanitized_block_number.into()).await?;
189 Ok(result)
190 }
191
192 pub(crate) async fn get_xdai_balance(&self, address: Address) -> Result<XDaiBalance> {
193 Ok(XDaiBalance::from(U256::from_be_bytes(
194 self.provider.get_balance(address.into()).await?.to_be_bytes::<32>(),
195 )))
196 }
197
198 pub(crate) async fn get_hopr_balance(&self, address: Address) -> Result<HoprBalance> {
199 Ok(HoprBalance::from(U256::from_be_bytes(
200 self.contract_instances
201 .token
202 .balanceOf(address.into())
203 .call()
204 .await?
205 .to_be_bytes::<32>(),
206 )))
207 }
208
209 pub(crate) async fn get_hopr_allowance(&self, owner: Address, spender: Address) -> Result<HoprBalance> {
210 Ok(HoprBalance::from(U256::from_be_bytes(
211 self.contract_instances
212 .token
213 .allowance(owner.into(), spender.into())
214 .call()
215 .await?
216 .to_be_bytes::<32>(),
217 )))
218 }
219}
220
221#[async_trait]
222impl<R: HttpRequestor + 'static + Clone> HoprRpcOperations for RpcOperations<R> {
223 async fn get_timestamp(&self, block_number: u64) -> Result<Option<u64>> {
224 Ok(self.get_block(block_number).await?.map(|b| b.header.timestamp))
225 }
226
227 async fn get_xdai_balance(&self, address: Address) -> Result<XDaiBalance> {
228 self.get_xdai_balance(address).await
229 }
230
231 async fn get_hopr_balance(&self, address: Address) -> Result<HoprBalance> {
232 self.get_hopr_balance(address).await
233 }
234
235 async fn get_hopr_allowance(&self, owner: Address, spender: Address) -> Result<HoprBalance> {
236 self.get_hopr_allowance(owner, spender).await
237 }
238
239 async fn get_minimum_network_winning_probability(&self) -> Result<WinningProbability> {
240 match self.contract_instances.win_prob_oracle.currentWinProb().call().await {
241 Ok(encoded_win_prob) => {
242 let mut encoded: EncodedWinProb = Default::default();
243 encoded.copy_from_slice(&encoded_win_prob.to_be_bytes_vec());
244 Ok(encoded.into())
245 }
246 Err(e) => Err(e.into()),
247 }
248 }
249
250 async fn get_minimum_network_ticket_price(&self) -> Result<HoprBalance> {
251 Ok(self
252 .contract_instances
253 .price_oracle
254 .currentTicketPrice()
255 .call()
256 .await
257 .map(|v| HoprBalance::from(U256::from_be_bytes(v.to_be_bytes::<32>())))?)
258 }
259
260 async fn get_eligibility_status(&self, address: Address) -> Result<bool> {
261 let tx_2 = CallItemBuilder::new(
264 self.contract_instances
265 .network_registry
266 .nodeRegisterdToAccount(address.into()),
267 )
268 .allow_failure(false);
269
270 let tx_3 = CallItemBuilder::new(
272 self.contract_instances
273 .network_registry
274 .isNodeRegisteredAndEligible(address.into()),
275 )
276 .allow_failure(true);
277
278 debug!(address = %self.contract_instances.network_registry_proxy.address(),"building tx_3 for eligibility check");
279 let (stake_threshold, node_registration, quick_check) = match &self.contract_instances.network_registry_proxy {
281 NetworkRegistryProxy::Dummy(c) => {
282 debug!(proxy_address = %c.address(), "Using dummy network registry proxy for eligibility check");
283 let tx_1_dummy = CallItemBuilder::new(c.maxAllowedRegistrations(address.into())).allow_failure(false);
284 let multicall = self
285 .provider
286 .multicall()
287 .add_call(tx_1_dummy)
288 .add_call(tx_2)
289 .add_call(tx_3);
290 let (max_allowed_registration, node_registered_to_account, quick_check) =
291 multicall.aggregate3().await.map_err(RpcError::MulticallError)?;
292 (
293 max_allowed_registration
294 .map_err(|e| RpcError::MulticallFailure(e.idx, e.return_data.to_string()))?,
295 node_registered_to_account
296 .map_err(|e| RpcError::MulticallFailure(e.idx, e.return_data.to_string()))?,
297 quick_check,
298 )
299 }
300 NetworkRegistryProxy::Safe(c) => {
301 debug!(proxy_address = %c.address(), "Using safe network registry proxy for eligibility check");
302 let tx_1_proxy = CallItemBuilder::new(c.stakeThreshold()).allow_failure(false);
303 let multicall = self
304 .provider
305 .multicall()
306 .add_call(tx_1_proxy)
307 .add_call(tx_2)
308 .add_call(tx_3);
309 let (stake_threshold, node_registered_to_account, quick_check) =
310 multicall.aggregate3().await.map_err(RpcError::MulticallError)?;
311 (
312 stake_threshold.map_err(|e| RpcError::MulticallFailure(e.idx, e.return_data.to_string()))?,
313 node_registered_to_account
314 .map_err(|e| RpcError::MulticallFailure(e.idx, e.return_data.to_string()))?,
315 quick_check,
316 )
317 }
318 };
319
320 match &quick_check {
321 Ok(eligibility_quick_check) => return Ok(*eligibility_quick_check),
322 Err(e) => {
323 if e.return_data.starts_with(&[0x4e, 0x48, 0x7b, 0x71])
330 && e.return_data[e.return_data.len() - 1] == 0x12
331 {
332 return Ok(stake_threshold.is_zero() && !node_registration.is_zero());
335 }
336 return Ok(false);
337 }
338 }
339 }
340
341 async fn get_node_management_module_target_info(&self, target: Address) -> Result<Option<U256>> {
342 match self.node_module.tryGetTarget(target.into()).call().await {
343 Ok(returned_result) => Ok(returned_result
344 ._0
345 .then_some(U256::from_big_endian(returned_result._1.to_be_bytes_vec().as_slice()))),
346 Err(e) => Err(e.into()),
347 }
348 }
349
350 async fn get_safe_from_node_safe_registry(&self, node_address: Address) -> Result<Address> {
351 match self
352 .contract_instances
353 .safe_registry
354 .nodeToSafe(node_address.into())
355 .call()
356 .await
357 {
358 Ok(returned_result) => Ok(returned_result.into()),
359 Err(e) => Err(e.into()),
360 }
361 }
362
363 async fn get_module_target_address(&self) -> Result<Address> {
364 match self.node_module.owner().call().await {
365 Ok(returned_result) => Ok(returned_result.into()),
366 Err(e) => Err(e.into()),
367 }
368 }
369
370 async fn get_channel_closure_notice_period(&self) -> Result<Duration> {
371 match self
373 .contract_instances
374 .channels
375 .noticePeriodChannelClosure()
376 .call()
377 .await
378 {
379 Ok(returned_result) => Ok(Duration::from_secs(returned_result.into())),
380 Err(e) => Err(e.into()),
381 }
382 }
383
384 async fn check_node_safe_module_status(&self, node_address: Address) -> Result<NodeSafeModuleStatus> {
386 let tx_1 = CallItemBuilder::new(self.node_module.isNode(node_address.into())).allow_failure(false);
388 let tx_2 =
390 CallItemBuilder::new(self.node_safe.isModuleEnabled(self.cfg.module_address.into())).allow_failure(false);
391 let tx_3 = CallItemBuilder::new(self.node_module.owner()).allow_failure(false);
393 let multicall = self.provider.multicall().add_call(tx_1).add_call(tx_2).add_call(tx_3);
394
395 let (node_in_module_inclusion, module_safe_enabling, safe_of_module_ownership) =
396 multicall.aggregate3_value().await.map_err(RpcError::MulticallError)?;
397 let is_node_included_in_module =
398 node_in_module_inclusion.map_err(|e| RpcError::MulticallFailure(e.idx, e.return_data.to_string()))?;
399 let is_module_enabled_in_safe =
400 module_safe_enabling.map_err(|e| RpcError::MulticallFailure(e.idx, e.return_data.to_string()))?;
401 let is_safe_owner_of_module = self.cfg.safe_address.eq(&safe_of_module_ownership
402 .map_err(|e| RpcError::MulticallFailure(e.idx, e.return_data.to_string()))?
403 .0
404 .0
405 .into());
406
407 Ok(NodeSafeModuleStatus {
408 is_node_included_in_module,
409 is_module_enabled_in_safe,
410 is_safe_owner_of_module,
411 })
412 }
413
414 async fn send_transaction(&self, tx: TransactionRequest) -> Result<PendingTransaction> {
415 let sent_tx = self.provider.send_transaction(tx).await?;
416
417 let pending_tx = sent_tx.register().await.map_err(RpcError::PendingTransactionError)?;
418
419 Ok(pending_tx)
420 }
421
422 async fn send_transaction_with_confirm(&self, tx: TransactionRequest) -> Result<Hash> {
423 let sent_tx = self.provider.send_transaction(tx).await?;
424
425 let receipt = sent_tx.get_receipt().await.map_err(RpcError::PendingTransactionError)?;
426
427 let tx_hash = Hash::from(receipt.transaction_hash.0);
428
429 if receipt.status() {
432 Ok(tx_hash)
433 } else {
434 Err(RpcError::TransactionFailed(tx_hash))
436 }
437 }
438}
439
440#[cfg(test)]
441mod tests {
442 use std::{sync::Arc, time::Duration};
443
444 use alloy::{
445 network::{Ethereum, TransactionBuilder},
446 primitives::{U256, address},
447 providers::Provider,
448 rpc::{client::ClientBuilder, types::TransactionRequest},
449 transports::{http::ReqwestTransport, layers::RetryBackoffLayer},
450 };
451 use hex_literal::hex;
452 use hopr_async_runtime::prelude::sleep;
453 use hopr_chain_types::{ContractAddresses, ContractInstances, NetworkRegistryProxy, utils::create_native_transfer};
454 use hopr_crypto_types::keypairs::{ChainKeypair, Keypair};
455 use hopr_primitive_types::prelude::*;
456 use primitive_types::H160;
457
458 use crate::{
459 HoprRpcOperations, PendingTransaction,
460 client::{AnvilRpcClient, create_rpc_client_to_anvil},
461 errors::Result,
462 rpc::{RpcOperations, RpcOperationsConfig},
463 };
464
465 lazy_static::lazy_static! {
466 static ref RANDY: Address = hex!("762614a5ed652457a2f1cdb8006380530c26ae6a").into();
467 static ref MULTICALL3_DEPLOY_CODE: [u8; 3926] = hex!("f90f538085174876e800830f42408080b90f00608060405234801561001057600080fd5b50610ee0806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e1461025a578063bce38bd714610275578063c3077fa914610288578063ee82ac5e1461029b57600080fd5b80634d2301cc146101ec57806372425d9d1461022157806382ad56cb1461023457806386d516e81461024757600080fd5b80633408e470116100c65780633408e47014610191578063399542e9146101a45780633e64a696146101c657806342cbb15c146101d957600080fd5b80630f28c97d146100f8578063174dea711461011a578063252dba421461013a57806327e86d6e1461015b575b600080fd5b34801561010457600080fd5b50425b6040519081526020015b60405180910390f35b61012d610128366004610a85565b6102ba565b6040516101119190610bbe565b61014d610148366004610a85565b6104ef565b604051610111929190610bd8565b34801561016757600080fd5b50437fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0140610107565b34801561019d57600080fd5b5046610107565b6101b76101b2366004610c60565b610690565b60405161011193929190610cba565b3480156101d257600080fd5b5048610107565b3480156101e557600080fd5b5043610107565b3480156101f857600080fd5b50610107610207366004610ce2565b73ffffffffffffffffffffffffffffffffffffffff163190565b34801561022d57600080fd5b5044610107565b61012d610242366004610a85565b6106ab565b34801561025357600080fd5b5045610107565b34801561026657600080fd5b50604051418152602001610111565b61012d610283366004610c60565b61085a565b6101b7610296366004610a85565b610a1a565b3480156102a757600080fd5b506101076102b6366004610d18565b4090565b60606000828067ffffffffffffffff8111156102d8576102d8610d31565b60405190808252806020026020018201604052801561031e57816020015b6040805180820190915260008152606060208201528152602001906001900390816102f65790505b5092503660005b8281101561047757600085828151811061034157610341610d60565b6020026020010151905087878381811061035d5761035d610d60565b905060200281019061036f9190610d8f565b6040810135958601959093506103886020850185610ce2565b73ffffffffffffffffffffffffffffffffffffffff16816103ac6060870187610dcd565b6040516103ba929190610e32565b60006040518083038185875af1925050503d80600081146103f7576040519150601f19603f3d011682016040523d82523d6000602084013e6103fc565b606091505b50602080850191909152901515808452908501351761046d577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b5050600101610325565b508234146104e6576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601a60248201527f4d756c746963616c6c333a2076616c7565206d69736d6174636800000000000060448201526064015b60405180910390fd5b50505092915050565b436060828067ffffffffffffffff81111561050c5761050c610d31565b60405190808252806020026020018201604052801561053f57816020015b606081526020019060019003908161052a5790505b5091503660005b8281101561068657600087878381811061056257610562610d60565b90506020028101906105749190610e42565b92506105836020840184610ce2565b73ffffffffffffffffffffffffffffffffffffffff166105a66020850185610dcd565b6040516105b4929190610e32565b6000604051808303816000865af19150503d80600081146105f1576040519150601f19603f3d011682016040523d82523d6000602084013e6105f6565b606091505b5086848151811061060957610609610d60565b602090810291909101015290508061067d576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601760248201527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060448201526064016104dd565b50600101610546565b5050509250929050565b43804060606106a086868661085a565b905093509350939050565b6060818067ffffffffffffffff8111156106c7576106c7610d31565b60405190808252806020026020018201604052801561070d57816020015b6040805180820190915260008152606060208201528152602001906001900390816106e55790505b5091503660005b828110156104e657600084828151811061073057610730610d60565b6020026020010151905086868381811061074c5761074c610d60565b905060200281019061075e9190610e76565b925061076d6020840184610ce2565b73ffffffffffffffffffffffffffffffffffffffff166107906040850185610dcd565b60405161079e929190610e32565b6000604051808303816000865af19150503d80600081146107db576040519150601f19603f3d011682016040523d82523d6000602084013e6107e0565b606091505b506020808401919091529015158083529084013517610851577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b50600101610714565b6060818067ffffffffffffffff81111561087657610876610d31565b6040519080825280602002602001820160405280156108bc57816020015b6040805180820190915260008152606060208201528152602001906001900390816108945790505b5091503660005b82811015610a105760008482815181106108df576108df610d60565b602002602001015190508686838181106108fb576108fb610d60565b905060200281019061090d9190610e42565b925061091c6020840184610ce2565b73ffffffffffffffffffffffffffffffffffffffff1661093f6020850185610dcd565b60405161094d929190610e32565b6000604051808303816000865af19150503d806000811461098a576040519150601f19603f3d011682016040523d82523d6000602084013e61098f565b606091505b506020830152151581528715610a07578051610a07576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601760248201527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060448201526064016104dd565b506001016108c3565b5050509392505050565b6000806060610a2b60018686610690565b919790965090945092505050565b60008083601f840112610a4b57600080fd5b50813567ffffffffffffffff811115610a6357600080fd5b6020830191508360208260051b8501011115610a7e57600080fd5b9250929050565b60008060208385031215610a9857600080fd5b823567ffffffffffffffff811115610aaf57600080fd5b610abb85828601610a39565b90969095509350505050565b6000815180845260005b81811015610aed57602081850181015186830182015201610ad1565b81811115610aff576000602083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b600082825180855260208086019550808260051b84010181860160005b84811015610bb1578583037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe001895281518051151584528401516040858501819052610b9d81860183610ac7565b9a86019a9450505090830190600101610b4f565b5090979650505050505050565b602081526000610bd16020830184610b32565b9392505050565b600060408201848352602060408185015281855180845260608601915060608160051b870101935082870160005b82811015610c52577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa0888703018452610c40868351610ac7565b95509284019290840190600101610c06565b509398975050505050505050565b600080600060408486031215610c7557600080fd5b83358015158114610c8557600080fd5b9250602084013567ffffffffffffffff811115610ca157600080fd5b610cad86828701610a39565b9497909650939450505050565b838152826020820152606060408201526000610cd96060830184610b32565b95945050505050565b600060208284031215610cf457600080fd5b813573ffffffffffffffffffffffffffffffffffffffff81168114610bd157600080fd5b600060208284031215610d2a57600080fd5b5035919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600082357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81833603018112610dc357600080fd5b9190910192915050565b60008083357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1843603018112610e0257600080fd5b83018035915067ffffffffffffffff821115610e1d57600080fd5b602001915036819003821315610a7e57600080fd5b8183823760009101908152919050565b600082357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc1833603018112610dc357600080fd5b600082357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa1833603018112610dc357600080fdfea2646970667358221220bb2b5c71a328032f97c676ae39a1ec2148d3e5d6f73d95e9b17910152d61f16264736f6c634300080c00331ca0edce47092c0f398cebf3ffc267f05c8e7076e3b89445e0fe50f6332273d4569ba01b0b9d000e19b24c5869b0fc3b22b0d6fa47cd63316875cbbd577d76e6fde086");
468 static ref MULTICALL3_DEPLOYER_ADDRESS: alloy::primitives::Address = address!("05f32b3cc3888453ff71b01135b34ff8e41263f2");
469 }
470
471 pub const ETH_VALUE_FOR_MULTICALL3_DEPLOYER: u128 = 100_000_000_000_000_000;
472 pub async fn wait_until_tx(pending: PendingTransaction, timeout: Duration) {
475 let tx_hash = *pending.tx_hash();
476 sleep(timeout).await;
477 pending
478 .await
479 .unwrap_or_else(|_| panic!("timeout awaiting tx hash {tx_hash} after {} seconds", timeout.as_secs()));
480 }
481
482 pub async fn deploy_multicall3_to_anvil<P: Provider>(provider: &P) -> Result<()> {
484 let tx = TransactionRequest::default()
486 .with_to(*MULTICALL3_DEPLOYER_ADDRESS)
487 .with_value(U256::from(ETH_VALUE_FOR_MULTICALL3_DEPLOYER));
488
489 provider.send_transaction(tx).await?.watch().await?;
490
491 provider
492 .send_raw_transaction(MULTICALL3_DEPLOY_CODE.as_ref())
493 .await?
494 .watch()
495 .await?;
496 Ok(())
497 }
498
499 #[tokio::test]
500 async fn test_should_estimate_tx() -> anyhow::Result<()> {
501 let _ = env_logger::builder().is_test(true).try_init();
502
503 let expected_block_time = Duration::from_secs(1);
504 let anvil = hopr_chain_types::utils::create_anvil(Some(expected_block_time));
505 let chain_key_0 = ChainKeypair::from_secret(anvil.keys()[0].to_bytes().as_ref())?;
506
507 let mut server = mockito::Server::new_async().await;
508 let gas_oracle_mock = server.mock("GET", "/gas_oracle")
509 .with_status(200)
510 .with_body(r#"{"status":"1","message":"OK","result":{"LastBlock":"38791478","SafeGasPrice":"1.1","ProposeGasPrice":"1.1","FastGasPrice":"1.6","UsdPrice":"0.999985432689946"}}"#)
511 .expect(0)
512 .create_async()
513 .await;
514
515 let cfg = RpcOperationsConfig {
516 chain_id: anvil.chain_id(),
517 tx_polling_interval: Duration::from_millis(10),
518 expected_block_time,
519 finality: 2,
520 gas_oracle_url: Some((server.url() + "/gas_oracle").parse()?),
521 ..RpcOperationsConfig::default()
522 };
523
524 let transport_client = ReqwestTransport::new(anvil.endpoint_url());
525
526 let rpc_client = ClientBuilder::default()
527 .layer(RetryBackoffLayer::new(2, 100, 100))
528 .transport(transport_client.clone(), transport_client.guess_local());
529
530 sleep((1 + cfg.finality) * expected_block_time).await;
532
533 let rpc = RpcOperations::new(rpc_client, transport_client.client().clone(), &chain_key_0, cfg, None)?;
534
535 let fees = rpc.provider.estimate_eip1559_fees().await?;
537
538 assert!(
539 fees.max_priority_fee_per_gas.ge(&0_u128),
540 "estimated_max_priority_fee must be equal or greater than 0, 0.1 gwei"
542 );
543
544 let estimated_gas_price = rpc.provider.get_gas_price().await?;
545 assert!(
546 estimated_gas_price.ge(&100_000_000_u128),
547 "estimated_max_fee must be greater than 0.1 gwei"
548 );
549
550 gas_oracle_mock.assert();
551
552 Ok(())
553 }
554
555 #[tokio::test]
556 async fn test_should_send_tx() -> anyhow::Result<()> {
557 let _ = env_logger::builder().is_test(true).try_init();
558
559 let expected_block_time = Duration::from_secs(1);
560 let anvil = hopr_chain_types::utils::create_anvil(Some(expected_block_time));
561 let chain_key_0 = ChainKeypair::from_secret(anvil.keys()[0].to_bytes().as_ref())?;
562
563 let cfg = RpcOperationsConfig {
564 chain_id: anvil.chain_id(),
565 tx_polling_interval: Duration::from_millis(10),
566 expected_block_time,
567 finality: 2,
568 gas_oracle_url: None,
569 ..RpcOperationsConfig::default()
570 };
571
572 let transport_client = ReqwestTransport::new(anvil.endpoint_url());
573
574 let rpc_client = ClientBuilder::default()
575 .layer(RetryBackoffLayer::new(2, 100, 100))
576 .transport(transport_client.clone(), transport_client.guess_local());
577
578 sleep((1 + cfg.finality) * expected_block_time).await;
580
581 let rpc = RpcOperations::new(rpc_client, transport_client.client().clone(), &chain_key_0, cfg, None)?;
582
583 let balance_1: XDaiBalance = rpc.get_xdai_balance((&chain_key_0).into()).await?;
584 assert!(balance_1.amount().gt(&0.into()), "balance must be greater than 0");
585
586 let tx_1 = create_native_transfer::<Ethereum>(*RANDY, U256::from(1000000_u32));
588 let tx_hash = rpc.send_transaction(tx_1).await?;
589
590 wait_until_tx(tx_hash, Duration::from_secs(8)).await;
591
592 let tx_2 = create_native_transfer::<Ethereum>(*RANDY, U256::from(1000000_u32));
594 let _receipt = rpc.send_transaction_with_confirm(tx_2).await?;
595
596 Ok(())
597 }
598
599 #[tokio::test]
600 async fn test_should_send_consecutive_txs() -> anyhow::Result<()> {
601 let _ = env_logger::builder().is_test(true).try_init();
602
603 let expected_block_time = Duration::from_secs(1);
604 let anvil = hopr_chain_types::utils::create_anvil(Some(expected_block_time));
605 let chain_key_0 = ChainKeypair::from_secret(anvil.keys()[0].to_bytes().as_ref())?;
606
607 let cfg = RpcOperationsConfig {
608 chain_id: anvil.chain_id(),
609 tx_polling_interval: Duration::from_millis(10),
610 expected_block_time,
611 finality: 2,
612 gas_oracle_url: None,
613 ..RpcOperationsConfig::default()
614 };
615
616 let transport_client = ReqwestTransport::new(anvil.endpoint_url());
617
618 let rpc_client = ClientBuilder::default()
619 .layer(RetryBackoffLayer::new(2, 100, 100))
620 .transport(transport_client.clone(), transport_client.guess_local());
621
622 sleep((1 + cfg.finality) * expected_block_time).await;
624
625 let rpc = RpcOperations::new(
626 rpc_client,
627 transport_client.client().clone(),
628 &chain_key_0,
629 cfg.clone(),
630 None,
631 )?;
632
633 let balance_1: XDaiBalance = rpc.get_xdai_balance((&chain_key_0).into()).await?;
634 assert!(balance_1.amount().gt(&0.into()), "balance must be greater than 0");
635
636 let txs_count = 5_u64;
637 let send_amount = 1000000_u64;
638
639 futures::future::join_all((0..txs_count).map(|_| async {
641 rpc.send_transaction(create_native_transfer::<Ethereum>(*RANDY, U256::from(send_amount)))
642 .await
643 .expect("tx should be sent")
644 .await
645 .expect("tx should resolve")
646 }))
647 .await;
648
649 sleep((1 + cfg.finality) * expected_block_time).await;
650
651 let balance_2: XDaiBalance = rpc.get_xdai_balance((&chain_key_0).into()).await?;
652
653 assert!(
654 balance_2.amount() <= balance_1.amount() - txs_count * send_amount,
655 "balance must be less"
656 );
657
658 Ok(())
659 }
660
661 #[tokio::test]
662 async fn test_get_balance_native() -> anyhow::Result<()> {
663 let _ = env_logger::builder().is_test(true).try_init();
664
665 let expected_block_time = Duration::from_secs(1);
666 let anvil = hopr_chain_types::utils::create_anvil(Some(expected_block_time));
667 let chain_key_0 = ChainKeypair::from_secret(anvil.keys()[0].to_bytes().as_ref())?;
668
669 let cfg = RpcOperationsConfig {
670 chain_id: anvil.chain_id(),
671 tx_polling_interval: Duration::from_millis(10),
672 expected_block_time,
673 finality: 2,
674 gas_oracle_url: None,
675 ..RpcOperationsConfig::default()
676 };
677
678 let transport_client = ReqwestTransport::new(anvil.endpoint_url());
679
680 let rpc_client = ClientBuilder::default()
681 .layer(RetryBackoffLayer::new(2, 100, 100))
682 .transport(transport_client.clone(), transport_client.guess_local());
683
684 sleep((1 + cfg.finality) * expected_block_time).await;
686
687 let rpc = RpcOperations::new(rpc_client, transport_client.client().clone(), &chain_key_0, cfg, None)?;
688
689 let balance_1: XDaiBalance = rpc.get_xdai_balance((&chain_key_0).into()).await?;
690 assert!(balance_1.amount().gt(&0.into()), "balance must be greater than 0");
691
692 let tx_hash = rpc
694 .send_transaction(create_native_transfer::<Ethereum>(*RANDY, U256::from(1_u32)))
695 .await?;
696
697 wait_until_tx(tx_hash, Duration::from_secs(8)).await;
698
699 let balance_2: XDaiBalance = rpc.get_xdai_balance((&chain_key_0).into()).await?;
700 assert!(balance_2.lt(&balance_1), "balance must be diminished");
701
702 Ok(())
703 }
704
705 #[tokio::test]
706 async fn test_get_balance_token() -> anyhow::Result<()> {
707 let _ = env_logger::builder().is_test(true).try_init();
708
709 let expected_block_time = Duration::from_secs(1);
710 let anvil = hopr_chain_types::utils::create_anvil(Some(expected_block_time));
711 let chain_key_0 = ChainKeypair::from_secret(anvil.keys()[0].to_bytes().as_ref())?;
712
713 let contract_instances = {
715 let client = create_rpc_client_to_anvil(&anvil, &chain_key_0);
716 ContractInstances::deploy_for_testing(client, &chain_key_0).await?
717 };
718
719 let cfg = RpcOperationsConfig {
720 chain_id: anvil.chain_id(),
721 tx_polling_interval: Duration::from_millis(10),
722 expected_block_time,
723 finality: 2,
724 contract_addrs: ContractAddresses::from(&contract_instances),
725 gas_oracle_url: None,
726 ..RpcOperationsConfig::default()
727 };
728
729 let amount = 1024_u64;
730 let _ = hopr_chain_types::utils::mint_tokens(contract_instances.token, U256::from(amount)).await;
731
732 let transport_client = ReqwestTransport::new(anvil.endpoint_url());
733
734 let rpc_client = ClientBuilder::default()
735 .layer(RetryBackoffLayer::new(2, 100, 100))
736 .transport(transport_client.clone(), transport_client.guess_local());
737
738 sleep((1 + cfg.finality) * expected_block_time).await;
740
741 let rpc = RpcOperations::new(rpc_client, transport_client.client().clone(), &chain_key_0, cfg, None)?;
742
743 let balance: HoprBalance = rpc.get_hopr_balance((&chain_key_0).into()).await?;
744 assert_eq!(amount, balance.amount().as_u64(), "invalid balance");
745
746 Ok(())
747 }
748
749 #[tokio::test]
750 async fn test_check_node_safe_module_status() -> anyhow::Result<()> {
751 let _ = env_logger::builder().is_test(true).try_init();
752
753 let expected_block_time = Duration::from_secs(1);
754 let anvil = hopr_chain_types::utils::create_anvil(Some(expected_block_time));
755 let chain_key_0 = ChainKeypair::from_secret(anvil.keys()[0].to_bytes().as_ref())?;
756
757 let (contract_instances, module, safe) = {
759 let client = create_rpc_client_to_anvil(&anvil, &chain_key_0);
760 let instances = ContractInstances::deploy_for_testing(client.clone(), &chain_key_0).await?;
761
762 deploy_multicall3_to_anvil(&client.clone()).await?;
764
765 let (module, safe) = hopr_chain_types::utils::deploy_one_safe_one_module_and_setup_for_testing::<
766 Arc<AnvilRpcClient>,
767 >(&instances, client.clone(), &chain_key_0)
768 .await?;
769
770 (instances, module, safe)
773 };
774
775 let cfg = RpcOperationsConfig {
776 chain_id: anvil.chain_id(),
777 tx_polling_interval: Duration::from_millis(10),
778 expected_block_time,
779 finality: 2,
780 contract_addrs: ContractAddresses::from(&contract_instances),
781 module_address: module,
782 safe_address: safe,
783 gas_oracle_url: None,
784 ..RpcOperationsConfig::default()
785 };
786
787 let transport_client = ReqwestTransport::new(anvil.endpoint_url());
788
789 let rpc_client = ClientBuilder::default()
790 .layer(RetryBackoffLayer::new(2, 100, 100))
791 .transport(transport_client.clone(), transport_client.guess_local());
792
793 sleep((1 + cfg.finality) * expected_block_time).await;
795
796 let rpc = RpcOperations::new(rpc_client, transport_client.client().clone(), &chain_key_0, cfg, None)?;
797
798 let result_before_including_node = rpc.check_node_safe_module_status((&chain_key_0).into()).await?;
799 assert!(
801 !result_before_including_node.is_node_included_in_module,
802 "node should not be included in a default module"
803 );
804 assert!(
805 result_before_including_node.is_module_enabled_in_safe,
806 "module should be enabled in a default safe"
807 );
808 assert!(
809 result_before_including_node.is_safe_owner_of_module,
810 "safe should not be the owner of a default module"
811 );
812
813 hopr_chain_types::utils::include_node_to_module_by_safe(
815 contract_instances.channels.provider().clone(),
816 safe,
817 module,
818 (&chain_key_0).into(),
819 &chain_key_0,
820 )
821 .await?;
822
823 let result_with_node_included = rpc.check_node_safe_module_status((&chain_key_0).into()).await?;
824 assert!(
826 result_with_node_included.is_node_included_in_module,
827 "node should be included in a default module"
828 );
829 assert!(
830 result_with_node_included.is_module_enabled_in_safe,
831 "module should be enabled in a default safe"
832 );
833 assert!(
834 result_with_node_included.is_safe_owner_of_module,
835 "safe should be the owner of a default module"
836 );
837
838 Ok(())
839 }
840
841 #[tokio::test]
842 async fn test_get_eligibility_status() -> anyhow::Result<()> {
843 let _ = env_logger::builder().is_test(true).try_init();
844
845 let expected_block_time = Duration::from_secs(1);
846 let anvil = hopr_chain_types::utils::create_anvil(Some(expected_block_time));
847 let chain_key_0 = ChainKeypair::from_secret(anvil.keys()[0].to_bytes().as_ref())?;
848 let node_address: H160 = chain_key_0.public().to_address().into();
849
850 let (contract_instances, module, safe) = {
852 let client = create_rpc_client_to_anvil(&anvil, &chain_key_0);
853 let instances = ContractInstances::deploy_for_testing(client.clone(), &chain_key_0).await?;
854
855 deploy_multicall3_to_anvil(&client.clone()).await?;
857
858 let (module, safe) = hopr_chain_types::utils::deploy_one_safe_one_module_and_setup_for_testing::<
859 Arc<AnvilRpcClient>,
860 >(&instances, client.clone(), &chain_key_0)
861 .await?;
862
863 (instances, module, safe)
866 };
867
868 let cfg = RpcOperationsConfig {
869 chain_id: anvil.chain_id(),
870 tx_polling_interval: Duration::from_millis(10),
871 expected_block_time,
872 finality: 2,
873 contract_addrs: ContractAddresses::from(&contract_instances),
874 module_address: module,
875 safe_address: safe,
876 gas_oracle_url: None,
877 ..RpcOperationsConfig::default()
878 };
879
880 let transport_client = ReqwestTransport::new(anvil.endpoint_url());
881
882 let rpc_client = ClientBuilder::default()
883 .layer(RetryBackoffLayer::new(2, 100, 100))
884 .transport(transport_client.clone(), transport_client.guess_local());
885
886 sleep((1 + cfg.finality) * expected_block_time).await;
888
889 let rpc = RpcOperations::new(
890 rpc_client,
891 transport_client.client().clone(),
892 &chain_key_0,
893 cfg.clone(),
894 None,
895 )?;
896
897 let result_before_register_in_the_network_registry = rpc.get_eligibility_status(node_address.into()).await?;
899
900 assert!(
901 !result_before_register_in_the_network_registry,
902 "node should not be eligible"
903 );
904
905 match &rpc.contract_instances.network_registry_proxy {
907 NetworkRegistryProxy::Dummy(e) => {
908 let _ = e.ownerAddAccount(cfg.safe_address.into()).send().await?.watch().await?;
909 }
910 NetworkRegistryProxy::Safe(_) => {}
911 };
912
913 let _ = rpc
914 .contract_instances
915 .network_registry
916 .managerRegister(
917 vec![cfg.safe_address.into()],
918 vec![alloy::primitives::Address::from_slice(node_address.as_ref())],
919 )
920 .send()
921 .await?
922 .watch()
923 .await?;
924
925 let result_after_register_in_the_network_registry = rpc.get_eligibility_status(node_address.into()).await?;
927
928 assert!(result_after_register_in_the_network_registry, "node should be eligible");
929 Ok(())
930 }
931
932 #[tokio::test]
933 async fn test_get_eligibility_status_for_staking_proxy() -> anyhow::Result<()> {
934 let _ = env_logger::builder().is_test(true).try_init();
935
936 let expected_block_time = Duration::from_secs(1);
937 let anvil = hopr_chain_types::utils::create_anvil(Some(expected_block_time));
938 let chain_key_0 = ChainKeypair::from_secret(anvil.keys()[0].to_bytes().as_ref())?;
939 let node_address: H160 = chain_key_0.public().to_address().into();
940
941 let (contract_instances, module, safe) = {
943 let client = create_rpc_client_to_anvil(&anvil, &chain_key_0);
944 let instances =
945 ContractInstances::deploy_for_testing_with_staking_proxy(client.clone(), &chain_key_0).await?;
946
947 deploy_multicall3_to_anvil(&client.clone()).await?;
949
950 let (module, safe) = hopr_chain_types::utils::deploy_one_safe_one_module_and_setup_for_testing::<
951 Arc<AnvilRpcClient>,
952 >(&instances, client.clone(), &chain_key_0)
953 .await?;
954
955 (instances, module, safe)
958 };
959
960 let cfg = RpcOperationsConfig {
961 chain_id: anvil.chain_id(),
962 tx_polling_interval: Duration::from_millis(10),
963 expected_block_time,
964 finality: 2,
965 contract_addrs: ContractAddresses::from(&contract_instances),
966 module_address: module,
967 safe_address: safe,
968 gas_oracle_url: None,
969 ..RpcOperationsConfig::default()
970 };
971
972 let transport_client = ReqwestTransport::new(anvil.endpoint_url());
973
974 let rpc_client = ClientBuilder::default()
975 .layer(RetryBackoffLayer::new(2, 100, 100))
976 .transport(transport_client.clone(), transport_client.guess_local());
977
978 sleep((1 + cfg.finality) * expected_block_time).await;
980
981 let rpc = RpcOperations::new(
982 rpc_client,
983 transport_client.client().clone(),
984 &chain_key_0,
985 cfg.clone(),
986 Some(false),
987 )?;
988
989 let result_before_register_in_the_network_registry = rpc.get_eligibility_status(node_address.into()).await?;
991
992 assert!(
993 !result_before_register_in_the_network_registry,
994 "node should not be eligible"
995 );
996
997 match &rpc.contract_instances.network_registry_proxy {
999 NetworkRegistryProxy::Dummy(p) => {
1000 let _ = p.ownerAddAccount(cfg.safe_address.into()).send().await?.watch().await?;
1001 }
1002 NetworkRegistryProxy::Safe(_) => {}
1003 };
1004
1005 let _ = rpc
1006 .contract_instances
1007 .network_registry
1008 .managerRegister(
1009 vec![cfg.safe_address.into()],
1010 vec![alloy::primitives::Address::from_slice(node_address.as_ref())],
1011 )
1012 .send()
1013 .await?
1014 .watch()
1015 .await?;
1016
1017 let result_after_register_in_the_network_registry = rpc.get_eligibility_status(node_address.into()).await?;
1019
1020 assert!(result_after_register_in_the_network_registry, "node should be eligible");
1021 Ok(())
1022 }
1023}