fix: Get correct runtime everywhere

Made an utils function for it to make sure it is used correctly

--- don't change below this line ---
ENG-4260 Took 9 minutes
This commit is contained in:
Diana Carvalho
2025-02-27 11:16:21 +00:00
parent f95c74fbc6
commit 6a6f2d3221
3 changed files with 38 additions and 21 deletions

View File

@@ -21,7 +21,7 @@ use crate::encoding::{
errors::EncodingError, errors::EncodingError,
evm::{ evm::{
approvals::protocol_approvals_manager::get_client, approvals::protocol_approvals_manager::get_client,
utils::{biguint_to_u256, bytes_to_address, encode_input}, utils::{biguint_to_u256, bytes_to_address, encode_input, get_runtime},
}, },
models::Chain, models::Chain,
}; };
@@ -70,15 +70,7 @@ sol! {
impl Permit2 { impl Permit2 {
pub fn new(swapper_pk: String, chain: Chain) -> Result<Self, EncodingError> { pub fn new(swapper_pk: String, chain: Chain) -> Result<Self, EncodingError> {
let (handle, runtime) = match Handle::try_current() { let (handle, runtime) = get_runtime()?;
Ok(h) => (h, None),
Err(_) => {
let rt = Arc::new(Runtime::new().map_err(|_| {
EncodingError::FatalError("Failed to create a new tokio runtime".to_string())
})?);
(rt.handle().clone(), Some(rt))
}
};
let client = block_in_place(|| handle.block_on(get_client()))?; let client = block_in_place(|| handle.block_on(get_client()))?;
let pk = B256::from_str(&swapper_pk).map_err(|_| { let pk = B256::from_str(&swapper_pk).map_err(|_| {
EncodingError::FatalError("Failed to convert swapper private key to B256".to_string()) EncodingError::FatalError("Failed to convert swapper private key to B256".to_string())

View File

@@ -8,21 +8,32 @@ use alloy::{
use alloy_primitives::{Address, Bytes, TxKind, U256}; use alloy_primitives::{Address, Bytes, TxKind, U256};
use alloy_sol_types::SolValue; use alloy_sol_types::SolValue;
use dotenv::dotenv; use dotenv::dotenv;
use tokio::runtime::Runtime; use tokio::{
runtime::{Handle, Runtime},
task::block_in_place,
};
use crate::encoding::{errors::EncodingError, evm::utils::encode_input}; use crate::encoding::{
errors::EncodingError,
evm::utils::{encode_input, get_runtime},
};
/// A manager for checking if an approval is needed for interacting with a certain spender. /// A manager for checking if an approval is needed for interacting with a certain spender.
pub struct ProtocolApprovalsManager { pub struct ProtocolApprovalsManager {
client: Arc<RootProvider<BoxTransport>>, client: Arc<RootProvider<BoxTransport>>,
runtime: Runtime, runtime_handle: Handle,
// Store the runtime to prevent it from being dropped before use.
// This is required since tycho-execution does not have a pre-existing runtime.
// However, if the library is used in a context where a runtime already exists, it is not
// necessary to store it.
#[allow(dead_code)]
runtime: Option<Arc<Runtime>>,
} }
impl ProtocolApprovalsManager { impl ProtocolApprovalsManager {
pub fn new() -> Result<Self, EncodingError> { pub fn new() -> Result<Self, EncodingError> {
let runtime = Runtime::new() let (handle, runtime) = get_runtime()?;
.map_err(|_| EncodingError::FatalError("Failed to create runtime".to_string()))?; let client = block_in_place(|| handle.block_on(get_client()))?;
let client = runtime.block_on(get_client())?; Ok(Self { client, runtime_handle: handle, runtime })
Ok(Self { client, runtime })
} }
/// Checks the current allowance for the given token, owner, and spender, and returns true /// Checks the current allowance for the given token, owner, and spender, and returns true
@@ -41,9 +52,10 @@ impl ProtocolApprovalsManager {
..Default::default() ..Default::default()
}; };
let output = self let output = block_in_place(|| {
.runtime self.runtime_handle
.block_on(async { self.client.call(&tx).await }); .block_on(async { self.client.call(&tx).await })
});
match output { match output {
Ok(response) => { Ok(response) => {
let allowance: U256 = U256::abi_decode(&response, true).map_err(|_| { let allowance: U256 = U256::abi_decode(&response, true).map_err(|_| {

View File

@@ -1,7 +1,8 @@
use std::cmp::max; use std::{cmp::max, sync::Arc};
use alloy_primitives::{aliases::U24, keccak256, Address, FixedBytes, Keccak256, U256, U8}; use alloy_primitives::{aliases::U24, keccak256, Address, FixedBytes, Keccak256, U256, U8};
use num_bigint::BigUint; use num_bigint::BigUint;
use tokio::runtime::{Handle, Runtime};
use tycho_core::Bytes; use tycho_core::Bytes;
use crate::encoding::{ use crate::encoding::{
@@ -120,3 +121,15 @@ pub fn get_static_attribute(swap: &Swap, attribute_name: &str) -> Result<Vec<u8>
})? })?
.to_vec()) .to_vec())
} }
pub fn get_runtime() -> Result<(Handle, Option<Arc<Runtime>>), EncodingError> {
match Handle::try_current() {
Ok(h) => Ok((h, None)),
Err(_) => {
let rt = Arc::new(Runtime::new().map_err(|_| {
EncodingError::FatalError("Failed to create a new tokio runtime".to_string())
})?);
Ok((rt.handle().clone(), Some(rt)))
}
}
}