1- use anyhow:: anyhow;
1+ use anyhow:: { anyhow, Context } ;
2+ use graph:: cheap_clone:: CheapClone ;
23use graph:: prelude:: rand:: { self , seq:: IteratorRandom } ;
34use std:: collections:: HashMap ;
45use std:: sync:: Arc ;
@@ -25,22 +26,25 @@ impl EthereumNetworkAdapters {
2526 pub fn cheapest_with (
2627 & self ,
2728 required_capabilities : & NodeCapabilities ,
28- ) -> Result < & Arc < EthereumAdapter > , Error > {
29- let sufficient_adapters : Vec < & EthereumNetworkAdapter > = self
29+ ) -> Result < Arc < EthereumAdapter > , Error > {
30+ let cheapest_sufficient_capability = self
3031 . adapters
3132 . iter ( )
32- . filter ( |adapter| & adapter. capabilities >= required_capabilities)
33- . collect ( ) ;
34- if sufficient_adapters. is_empty ( ) {
35- return Err ( anyhow ! (
36- "A matching Ethereum network with {:?} was not found." ,
37- required_capabilities
38- ) ) ;
39- }
33+ . find ( |adapter| & adapter. capabilities >= required_capabilities)
34+ . map ( |adapter| & adapter. capabilities ) ;
4035
41- // Select from the matching adapters randomly
42- let mut rng = rand:: thread_rng ( ) ;
43- Ok ( & sufficient_adapters. iter ( ) . choose ( & mut rng) . unwrap ( ) . adapter )
36+ // Select randomly from the cheapest adapters that have sufficent capabilities.
37+ self . adapters
38+ . iter ( )
39+ . filter ( |adapter| Some ( & adapter. capabilities ) == cheapest_sufficient_capability)
40+ . choose ( & mut rand:: thread_rng ( ) )
41+ . map ( |adapter| adapter. adapter . cheap_clone ( ) )
42+ . with_context ( || {
43+ anyhow ! (
44+ "A matching Ethereum network with {:?} was not found." ,
45+ required_capabilities
46+ )
47+ } )
4448 }
4549
4650 pub fn cheapest ( & self ) -> Option < Arc < EthereumAdapter > > {
@@ -126,7 +130,7 @@ impl EthereumNetworks {
126130 & self ,
127131 network_name : String ,
128132 requirements : & NodeCapabilities ,
129- ) -> Result < & Arc < EthereumAdapter > , Error > {
133+ ) -> Result < Arc < EthereumAdapter > , Error > {
130134 self . networks
131135 . get ( & network_name)
132136 . ok_or ( anyhow ! ( "network not supported: {}" , & network_name) )
0 commit comments