Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove EVM config, improve presentation for docs #422

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ lock_api = "0.4.12"
log = "0.4.22"
multiaddr = { version = "0.18.1", default-features = false }
nix = { version = "0.29.0", features = ["process", "signal"] }
num-bigint = "0.4.6"
parking_lot = "0.12.3"
proc-macro2 = "1.0"
prometheus = { version = "0.13.4", default-features = false }
Expand Down
5 changes: 3 additions & 2 deletions blueprint-test-utils/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,9 @@ impl BlueprintProcessManager {
}

if let Protocol::Eigenlayer = protocol {
in_memory_keystore.bls_bn254_generate_from_string("1371012690269088913462269866874713266643928125698382731338806296762673180359922".to_string())
let public = in_memory_keystore.bls_bn254_generate_from_string("1371012690269088913462269866874713266643928125698382731338806296762673180359922".to_string())
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
println!("Public key: {:?}", public);
};

let mut arguments = vec![
Expand All @@ -139,7 +140,7 @@ impl BlueprintProcessManager {
format!("--ws-rpc-url={}", Url::parse(ws_endpoint).unwrap()),
format!("--keystore-uri={}", keystore_uri_str.clone()),
format!("--chain={}", SupportedChains::LocalTestnet),
format!("--vvv"),
format!("-vvv"),
format!("--pretty"),
format!("--blueprint-id={}", instance_id),
format!("--service-id={}", instance_id),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ impl AggregatorContext {
pub async fn new(
port_address: String,
task_manager_address: Address,
http_rpc_url: String,
wallet: EthereumWallet,
sdk_config: StdGadgetConfiguration,
) -> Result<Self, std::io::Error> {
Expand All @@ -70,7 +69,7 @@ impl AggregatorContext {
tasks: Arc::new(Mutex::new(HashMap::new())),
tasks_responses: Arc::new(Mutex::new(HashMap::new())),
bls_aggregation_service: None,
http_rpc_url,
http_rpc_url: sdk_config.http_rpc_endpoint.clone(),
wallet,
response_cache: Arc::new(Mutex::new(VecDeque::new())),
sdk_config,
Expand Down
13 changes: 8 additions & 5 deletions blueprints/incredible-squaring-eigenlayer/src/contexts/client.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use alloy_rpc_client::ReqwestClient;
use color_eyre::Result;
use eigensdk::crypto_bls::{OperatorId, Signature};
use gadget_sdk::{config::StdGadgetConfiguration, ctx::KeystoreContext};
use reqwest::Url;
use serde::{Deserialize, Serialize};
use serde_json::json;
Expand All @@ -19,18 +20,20 @@ pub struct SignedTaskResponse {
pub operator_id: OperatorId,
}

/// Client for interacting with the Aggregator RPC
#[derive(Debug, Clone)]
/// Client for interacting with the Aggregator RPC server
#[derive(Debug, Clone, KeystoreContext)]
pub struct AggregatorClient {
client: ReqwestClient,
#[config]
pub std_config: StdGadgetConfiguration,
}

impl AggregatorClient {
/// Creates a new AggregatorClient
pub fn new(aggregator_address: &str) -> Result<Self> {
pub fn new(aggregator_address: &str, std_config: StdGadgetConfiguration) -> Result<Self> {
let url = Url::parse(&format!("http://{}", aggregator_address))?;
let client = ReqwestClient::new_http(url);
Ok(Self { client })
Ok(Self { client, std_config })
}

/// Sends a signed task response to the aggregator
Expand Down Expand Up @@ -78,7 +81,7 @@ mod tests {

#[test]
fn test_new_client() {
let client = AggregatorClient::new("127.0.0.1:8545");
let client = AggregatorClient::new("127.0.0.1:8545", Default::default());
assert!(client.is_ok());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,21 @@
use crate::contexts::client::{AggregatorClient, SignedTaskResponse};
use crate::{noop, IncredibleSquaringTaskManager, INCREDIBLE_SQUARING_TASK_MANAGER_ABI_STRING};
use alloy_primitives::keccak256;
use alloy_primitives::{hex, Bytes, U256};
use alloy_primitives::{Bytes, U256};
use alloy_sol_types::SolType;
use ark_bn254::Fq;
use ark_ff::{BigInteger, PrimeField};
use color_eyre::Result;
use eigensdk::crypto_bls::BlsKeyPair;
use eigensdk::crypto_bls::OperatorId;
use gadget_sdk::ctx::KeystoreContext;
use gadget_sdk::keystore::BackendExt;
use gadget_sdk::runners::eigenlayer::derive_operator_id;
use gadget_sdk::{error, info, job};
use std::{convert::Infallible, ops::Deref, sync::OnceLock};
use IncredibleSquaringTaskManager::TaskResponse;

/// Returns x^2 saturating to [`u64::MAX`] if overflow occurs.
/// Sends a signed task response to the BLS Aggregator.
/// This job is triggered by the `NewTaskCreated` event emitted by the `IncredibleSquaringTaskManager`.
/// The job calculates the square of the number to be squared and sends the signed task response to the BLS Aggregator.
/// The job returns 1 if the task response was sent successfully.
/// The job returns 0 if the task response failed to send or failed to get the BLS key.
#[job(
id = 0,
params(number_to_be_squared, task_created_block, quorum_numbers, quorum_threshold_percentage, task_index),
Expand Down Expand Up @@ -42,17 +45,14 @@ pub async fn xsquare_eigen(
numberSquared: number_to_be_squared.saturating_pow(U256::from(2u32)),
};

let bls_key_pair = BlsKeyPair::new(
"1371012690269088913462269866874713266643928125698382731338806296762673180359922"
.to_string(),
)
.unwrap();

let operator_id = alloy_primitives::FixedBytes(
eigensdk::types::operator::operator_id_from_g1_pub_key(bls_key_pair.public_key()).unwrap(),
);
let operator_id: OperatorId =
hex!("fd329fe7e54f459b9c104064efe0172db113a50b5f394949b4ef80b3c34ca7f5").into();
let bls_key_pair = match ctx.keystore().and_then(|ks| Ok(ks.bls_bn254_key())) {
Ok(kp) => match kp {
Ok(k) => k,
Err(e) => return Ok(0),
},
Err(e) => return Ok(0),
};
let operator_id = derive_operator_id(bls_key_pair.public_key());

// Sign the Hashed Message and send it to the BLS Aggregator
let msg_hash = keccak256(<TaskResponse as SolType>::abi_encode(&task_response));
Expand Down Expand Up @@ -96,11 +96,3 @@ pub fn convert_event_to_inputs(
task_index,
)
}

/// Helper for converting a PrimeField to its U256 representation for Ethereum compatibility
/// (U256 reads data as big endian)
pub fn point_to_u256(point: Fq) -> U256 {
let point = point.into_bigint();
let point_bytes = point.to_bytes_be();
U256::from_be_slice(&point_bytes[..])
}
70 changes: 14 additions & 56 deletions blueprints/incredible-squaring-eigenlayer/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use alloy_network::EthereumWallet;
use alloy_provider::ProviderBuilder;
use alloy_signer_local::PrivateKeySigner;
use color_eyre::Result;
use gadget_sdk::{
events_watcher::evm::DefaultNodeConfig,
events_watcher::evm::get_wallet_provider_http,
info,
runners::{eigenlayer::EigenlayerConfig, BlueprintRunner},
};
Expand All @@ -18,74 +16,34 @@ use incredible_squaring_blueprint_eigenlayer::{

#[gadget_sdk::main(env)]
async fn main() {
// Get the ECDSA key from the private key seed using alloy
let signer: PrivateKeySigner = AGGREGATOR_PRIVATE_KEY
.parse()
.expect("failed to generate wallet ");
let wallet = EthereumWallet::from(signer);
let provider = ProviderBuilder::new()
.with_recommended_fillers()
.wallet(wallet.clone())
.on_http(env.http_rpc_endpoint.parse()?);
info!("Task Manager Address: {:?}", *TASK_MANAGER_ADDRESS);
let provider = get_wallet_provider_http(&env.http_rpc_endpoint, wallet.clone());

let server_address = format!("{}:{}", env.bind_addr, 8081);
let aggregator_client = AggregatorClient::new(&server_address, env.clone())?;
let aggregator_context =
AggregatorContext::new(server_address, *TASK_MANAGER_ADDRESS, wallet, env.clone())
.await
.unwrap();

let contract = IncredibleSquaringTaskManager::IncredibleSquaringTaskManagerInstance::new(
*TASK_MANAGER_ADDRESS,
provider,
);

info!("Protocol: Eigenlayer");
info!(
"Registry Coordinator Address: {:?}",
env.protocol_specific
.eigenlayer()?
.registry_coordinator_address
);
info!(
"Operator State Retriever Address: {:?}",
env.protocol_specific
.eigenlayer()?
.operator_state_retriever_address
);
info!(
"Delegation Manager Address: {:?}",
env.protocol_specific
.eigenlayer()?
.delegation_manager_address
);
info!(
"Strategy Manager Address: {:?}",
env.protocol_specific.eigenlayer()?.strategy_manager_address
);
info!(
"AVS Directory Address: {:?}",
env.protocol_specific.eigenlayer()?.avs_directory_address
);

let server_address = format!("{}:{}", env.bind_addr, 8081);
let aggregator_client = AggregatorClient::new(&server_address)?;
let x_square_eigen = XsquareEigenEventHandler::<DefaultNodeConfig> {
ctx: aggregator_client,
let initialize_task = InitializeBlsTaskEventHandler {
ctx: aggregator_context.clone(),
contract: contract.clone().into(),
};

let aggregator_context = AggregatorContext::new(
server_address,
*TASK_MANAGER_ADDRESS,
env.http_rpc_endpoint.clone(),
wallet,
env.clone(),
)
.await
.unwrap();

let initialize_task = InitializeBlsTaskEventHandler::<DefaultNodeConfig> {
ctx: aggregator_context.clone(),
let x_square_eigen = XsquareEigenEventHandler {
ctx: aggregator_client,
contract: contract.clone().into(),
};

// let (handle, aggregator_shutdown_tx) =
// aggregator_context.start(env.ws_rpc_endpoint.clone());

info!("~~~ Executing the incredible squaring blueprint ~~~");
let eigen_config = EigenlayerConfig {};
BlueprintRunner::new(eigen_config, env)
Expand Down
14 changes: 4 additions & 10 deletions blueprints/incredible-squaring-symbiotic/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use alloy_network::EthereumWallet;
use alloy_provider::ProviderBuilder;
use color_eyre::Result;
use gadget_sdk::events_watcher::evm::DefaultNodeConfig;
use gadget_sdk::events_watcher::evm::get_wallet_provider_http;
use gadget_sdk::runners::symbiotic::SymbioticConfig;
use gadget_sdk::runners::BlueprintRunner;
use gadget_sdk::{info, keystore::BackendExt};
Expand All @@ -20,23 +19,18 @@ lazy_static! {

#[gadget_sdk::main(env)]
async fn main() {
// Get the ECDSA key from the private key seed using alloy
let operator_signer = env.keystore()?.ecdsa_key()?.alloy_key()?;
let wallet = EthereumWallet::new(operator_signer);

let provider = ProviderBuilder::new()
.with_recommended_fillers()
.wallet(wallet.clone())
.on_http(env.http_rpc_endpoint.parse()?);
let provider = get_wallet_provider_http(&env.http_rpc_endpoint, wallet);

let contract = IncredibleSquaringTaskManager::IncredibleSquaringTaskManagerInstance::new(
*TASK_MANAGER_ADDRESS,
provider,
);

let x_square = blueprint::XsquareEventHandler::<DefaultNodeConfig> {
let x_square = blueprint::XsquareEventHandler {
context: blueprint::MyContext {},
contract: contract.clone().into(),
contract: contract.into(),
};

info!("~~~ Executing the incredible squaring blueprint ~~~");
Expand Down
11 changes: 5 additions & 6 deletions macros/blueprint-proc-macro/src/event_listener/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub(crate) fn get_evm_instance_data(
let instance_base = event_handler.instance().unwrap();
let instance_name = format_ident!("{}Instance", instance_base);
let instance_wrapper_name = format_ident!("{}InstanceWrapper", instance_base);
let instance = quote! { #instance_base::#instance_name<T::TH, T::PH, alloy_network::Ethereum> };
let instance = quote! { #instance_base::#instance_name<alloy_transport::BoxTransport, alloy_provider::RootProvider<alloy_transport::BoxTransport>, alloy_network::Ethereum> };

(
instance_base,
Expand Down Expand Up @@ -110,12 +110,11 @@ pub(crate) fn generate_evm_event_handler(

#[automatically_derived]
#[async_trait::async_trait]
impl<T> gadget_sdk::events_watcher::evm::EvmEventHandler<T> for #struct_name <T>
impl gadget_sdk::events_watcher::evm::EvmEventHandler for #struct_name
where
T: Clone + Send + Sync + gadget_sdk::events_watcher::evm::Config +'static,
#instance_wrapper_name <T::TH, T::PH>: std::ops::Deref<Target = alloy_contract::ContractInstance<T::TH, T::PH, alloy_network::Ethereum>>,
#instance_wrapper_name <alloy_transport::BoxTransport, alloy_provider::RootProvider<alloy_transport::BoxTransport>>: std::ops::Deref<Target = alloy_contract::ContractInstance<alloy_transport::BoxTransport, alloy_provider::RootProvider<alloy_transport::BoxTransport>, alloy_network::Ethereum>>,
{
type Contract = #instance_wrapper_name <T::TH, T::PH>;
type Contract = #instance_wrapper_name <alloy_transport::BoxTransport, alloy_provider::RootProvider<alloy_transport::BoxTransport>>;
type Event = #event;
const GENESIS_TX_HASH: alloy_primitives::FixedBytes<32> = alloy_primitives::FixedBytes([0; 32]);

Expand Down Expand Up @@ -162,6 +161,6 @@ pub(crate) fn generate_evm_event_handler(
}
}

impl<T: gadget_sdk::events_watcher::evm::Config> gadget_sdk::event_listener::markers::IsEvm for #struct_name <T> {}
impl gadget_sdk::event_listener::markers::IsEvm for #struct_name {}
}
}
Loading