From dd9fbcafed9d80b9af1458e7cbd243b4b193ec69 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Fri, 2 Aug 2024 13:45:10 -0500 Subject: [PATCH 01/43] Changes from moving repo --- avs/incredible-squaring-avs/Cargo.toml | 1 + avs/incredible-squaring-avs/src/avs/mod.rs | 10 + avs/incredible-squaring-avs/src/operator.rs | 653 ++++++++++++++------ contracts/src/lib.rs | 33 +- 4 files changed, 517 insertions(+), 180 deletions(-) diff --git a/avs/incredible-squaring-avs/Cargo.toml b/avs/incredible-squaring-avs/Cargo.toml index d9a70df..42a944f 100644 --- a/avs/incredible-squaring-avs/Cargo.toml +++ b/avs/incredible-squaring-avs/Cargo.toml @@ -46,6 +46,7 @@ serde_json.workspace = true thiserror.workspace = true tokio.workspace = true env_logger.workspace = true +ethabi = "18.0.0" [dev-dependencies] anvil.workspace = true diff --git a/avs/incredible-squaring-avs/src/avs/mod.rs b/avs/incredible-squaring-avs/src/avs/mod.rs index 41fb548..5ad68ba 100644 --- a/avs/incredible-squaring-avs/src/avs/mod.rs +++ b/avs/incredible-squaring-avs/src/avs/mod.rs @@ -3,6 +3,7 @@ pub mod subscriber; pub mod writer; use alloy_primitives::{Address, Bytes, U256}; +use alloy_provider::Provider; use alloy_rpc_types::{Log, TransactionReceipt}; use alloy_sol_types::sol; @@ -81,16 +82,25 @@ impl IncredibleSquaringContractManager { eth_client_ws: T::PW, signer: T::S, ) -> Result { + log::info!("Building IncredibleSquaringContractManager"); let registry_coordinator = RegistryCoordinator::new(registry_coordinator_addr, eth_client_http.clone()); + + let result = eth_client_http.get_code_at(registry_coordinator_addr).await.unwrap(); + log::info!("Registry Coordinator Code: {:?}", result); + + log::info!("Built RegistryCoordinator"); let service_manager_addr = registry_coordinator.serviceManager().call().await?._0; + log::info!("Found Service Manager: {:?}", service_manager_addr); let service_manager = IncredibleSquaringServiceManager::new(service_manager_addr, eth_client_http.clone()); + log::info!("Built Service Manager"); let task_manager_addr = service_manager .incredibleSquaringTaskManager() .call() .await? ._0; + log::info!("Found Task Manager: {:?}", task_manager_addr); Ok(Self { task_manager_addr, diff --git a/avs/incredible-squaring-avs/src/operator.rs b/avs/incredible-squaring-avs/src/operator.rs index e5dd2af..97c8f38 100644 --- a/avs/incredible-squaring-avs/src/operator.rs +++ b/avs/incredible-squaring-avs/src/operator.rs @@ -59,7 +59,7 @@ pub enum OperatorError { #[error("Cannot get operator id: {0}")] OperatorIdError(String), #[error( - "Operator is not registered. Register using the operator-cli before starting operator." + "Operator is not registered. Register using the operator-cli before starting operator." )] OperatorNotRegistered, #[error("Error in metrics server: {0}")] @@ -209,7 +209,7 @@ impl Operator { &config.bls_private_key_store_path, &bls_key_password, ) - .map_err(OperatorError::from)?; + .map_err(OperatorError::from)?; let _chain_id = eth_client_http .get_chain_id() @@ -224,7 +224,7 @@ impl Operator { &config.ecdsa_private_key_store_path, &ecdsa_key_password, ) - .unwrap(); + .unwrap(); let ecdsa_signing_key = SigningKey::from(&ecdsa_secret_key); // TODO: Ecdsa signing key is not used @@ -247,8 +247,8 @@ impl Operator { eth_client_ws.clone(), signer.clone(), ) - .await - .unwrap(); + .await + .unwrap(); log::info!("About to build AVS Registry Contract Manager"); let avs_registry_contract_manager = AvsRegistryContractManager::build( @@ -261,8 +261,8 @@ impl Operator { eth_client_ws.clone(), signer.clone(), ) - .await - .unwrap(); + .await + .unwrap(); log::info!("About to build aggregator service"); let aggregator_service = Aggregator::build( @@ -270,8 +270,8 @@ impl Operator { operator_info_service, config.server_ip_port_address.clone(), ) - .await - .unwrap(); + .await + .unwrap(); log::info!("About to build aggregator RPC client"); let aggregator_rpc_client = AggregatorRpcClient::new(config.server_ip_port_address.clone()); @@ -284,8 +284,8 @@ impl Operator { eth_client_ws.clone(), signer.clone(), ) - .await - .unwrap(); + .await + .unwrap(); log::info!("About to get operator id and address"); let operator_addr = Address::from_str(&config.operator_address).unwrap(); @@ -357,9 +357,9 @@ impl Operator { .avs_registry_contract_manager .is_operator_registered(self.operator_addr) .await; //?; - // if !operator_is_registered { - // return Err(OperatorError::OperatorNotRegistered); - // } + // if !operator_is_registered { + // return Err(OperatorError::OperatorNotRegistered); + // } log::info!("Operator registration status: {:?}", operator_is_registered); if self.config.enable_node_api { @@ -449,22 +449,33 @@ mod tests { use k256::ecdsa::VerifyingKey; use k256::elliptic_curve::SecretKey; use std::path::Path; - use std::time::Duration; //, Bytes, U256}; + use std::time::Duration; + use std::vec; + //, Bytes, U256}; static BLS_PASSWORD: &str = "BLS_PASSWORD"; static ECDSA_PASSWORD: &str = "ECDSA_PASSWORD"; - - // use alloy::signers::Signer; - // use alloy_provider::network::{TransactionBuilder, TxSigner}; - // use crate::avs; - // use avs::IncredibleSquaringServiceManager; - // use eigen_contracts::*; - // use gadget_common::subxt_signer::bip39::rand_core::OsRng; - // use alloy_rpc_types_eth::BlockId; - // use anvil::spawn; - // use ark_bn254::Fq as F; - // use ark_bn254::{Fr, G1Affine, G2Affine, G2Projective}; - // use url::Url; + static TASK_RESPONSE_WINDOW_BLOCK: u32 = 10; + static TASK_DURATION_BLOCKS: u32 = 0; + // static QUORUM_THRESHOLD_PERCENTAGE: U256 = U256::from(100); + static AGGREGATOR_ADDR: Address = address!("a0Ee7A142d267C1f36714E4a8F75612F20a79720"); + static TASK_GENERATOR_ADDR: Address = address!("a0Ee7A142d267C1f36714E4a8F75612F20a79720"); + + use crate::avs; + use alloy::signers::Signer; + use alloy_provider::network::{TransactionBuilder, TxSigner}; + use alloy_rpc_types_eth::BlockId; + use alloy_sol_types::private::SolTypeValue; + use anvil::spawn; + use ark_bn254::Fq as F; + use ark_bn254::{Fr, G1Affine, G2Affine, G2Projective}; + use avs::IncredibleSquaringServiceManager; + use eigen_contracts::RegistryCoordinator::{OperatorSetParam, StrategyParams}; + use eigen_contracts::*; + use ethabi::ethereum_types::H160; + use ethabi::{encode, Token}; + use gadget_common::subxt_signer::bip39::rand_core::OsRng; + use url::Url; struct ContractAddresses { pub service_manager: Address, @@ -477,7 +488,7 @@ mod tests { // async fn run_anvil_testnet() -> ContractAddresses { // // Initialize the logger - // env_logger::init(); + // let _ = env_logger::try_init(); // // let (api, mut handle) = spawn(anvil::NodeConfig::test().with_port(33125)).await; // api.anvil_auto_impersonate_account(true).await.unwrap(); @@ -511,6 +522,14 @@ mod tests { // // Empty address for initial deployment of all contracts // let empty_address = Address::default(); // + // // let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); + // // let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); + // // let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); + // // let proxy_admin_addr = address!("5FbDB2315678afecb367f032d93F642f64180aa3"); + // // let pauser_registry_addr = address!("e7f1725E7734CE288F8367e1Bb143E90bb3F0512"); + // // let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); + // + // // Deploy Eigenlayer Contracts // let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); // let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); // let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); @@ -525,116 +544,342 @@ mod tests { // let proxy_admin = ProxyAdmin::new(proxy_admin_addr, provider.clone()); // let pauser_registry = PauserRegistry::new(pauser_registry_addr, provider.clone()); // let base_strategy = StrategyBaseTVLLimits::new(base_strategy_addr, provider.clone()); + // // let istrategy_manager = IStrategyManager::deploy(provider.clone()).await.unwrap(); + // // let &strategy_manager_addr = istrategy_manager.address(); + // // + // // let idelegation_manager = IDelegationManager::deploy(provider.clone()).await.unwrap(); + // // let &delegation_manager_addr = idelegation_manager.address(); + // // + // // let iavs_directory = IAVSDirectory::deploy(provider.clone()).await.unwrap(); + // // let &avs_directory_addr = iavs_directory.address(); + // // + // // let proxy_admin = ProxyAdmin::deploy(provider.clone()).await.unwrap(); + // // let &proxy_admin_addr = proxy_admin.address(); + // // + // // let pauser_registry = PauserRegistry::deploy(provider.clone()).await.unwrap(); + // // let &pauser_registry_addr = pauser_registry.address(); + // // + // // let base_strategy = StrategyBaseTVLLimits::deploy(provider.clone(), Default::default()) + // // .await + // // .unwrap(); + // // let &base_strategy_addr = base_strategy.address(); // - // // let erc20_mock = ERC20Mock::new( - // // TransparentUpgradeableProxy::deploy( - // // provider.clone(), - // // base_strategy_addr, - // // proxy_admin_addr, - // // ) - // // ); + // let erc20_mock = ERC20Mock::deploy(provider.clone()).await.unwrap(); + // let &erc20_mock_addr = erc20_mock.address(); // - // // Deploy contracts for Incredible Squaring - // let registry_coordinator = RegistryCoordinator::deploy( + // let ierc20 = IERC20::new(erc20_mock_addr, provider.clone()); + // let &ierc20_addr = ierc20.address(); + // + // let tokens = vec![ + // Token::Uint(1.into()), + // Token::Uint(100.into()), + // Token::Address(H160::from_slice(ierc20_addr.as_slice())), + // Token::Address(H160::from_slice(pauser_registry_addr.as_slice())), + // ]; + // let encoded_data = encode(&tokens); + // let strategy_proxy = TransparentUpgradeableProxy::deploy( // provider.clone(), - // empty_address, - // empty_address, - // empty_address, - // empty_address, + // base_strategy_addr, + // proxy_admin_addr, + // alloy_primitives::Bytes::from(encoded_data), // ) // .await // .unwrap(); - // let registry_coordinator_addr = registry_coordinator.address(); + // let &strategy_proxy_addr = strategy_proxy.address(); + // + // let erc20_mock_strategy = + // StrategyBaseTVLLimits::deploy(provider.clone(), strategy_proxy_addr) + // .await + // .unwrap(); + // let &erc20_mock_strategy_addr = erc20_mock_strategy.address(); // - // let index_registry = IndexRegistry::deploy(provider.clone()).await.unwrap(); - // let index_registry_addr = index_registry.address(); + // let strategies = vec![erc20_mock_strategy_addr]; // - // let bls_apk_registry = BlsApkRegistry::deploy(provider.clone(), empty_address) + // let add_strategies = istrategy_manager + // .addStrategiesToDepositWhitelist(strategies, vec![false]) + // .send() + // .await + // .unwrap() + // .get_receipt() // .await // .unwrap(); - // let bls_apk_registry_addr = bls_apk_registry.address(); + // println!("Add Strategies Receipt: {:?}", add_strategies); + // + // // Deploy Incredible Squaring Contracts + // let number_of_strategies = strategies.len(); + // + // let incredible_squaring_proxy_admin = ProxyAdmin::deploy(provider.clone()).await.unwrap(); + // let &incredible_squaring_proxy_admin_addr = incredible_squaring_proxy_admin.address(); // - // let stake_registry = StakeRegistry::deploy(provider.clone(), empty_address, empty_address) + // let pausers = vec![ + // address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), + // address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), + // ]; + // + // let incredible_squaring_pauser_registry_addr = + // PauserRegistry::deploy_builder(provider.clone()) + // .from(from) + // .send() + // .await + // .unwrap() + // .get_receipt() + // .await + // .unwrap() + // .contract_address + // .unwrap(); + // let incredible_squaring_pauser_registry = + // PauserRegistry::new(incredible_squaring_pauser_registry_addr, provider.clone()); + // let is_pauser = incredible_squaring_pauser_registry + // .isPauser(address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266")) + // .call() // .await // .unwrap(); - // let stake_registry_addr = stake_registry.address(); + // println!("Is Dev Account 0 Pauser: {:?}", is_pauser._0); // - // let slasher = ISlasher::deploy(provider.clone()).await.unwrap(); - // let slasher_addr = slasher.address(); + // let empty_contract = EmptyContract::deploy(provider.clone()).await.unwrap(); + // let &empty_contract_addr = empty_contract.address(); // - // let eigen_pod_manager = EigenPodManager::deploy( + // let incredible_squaring_service_manager = IncredibleSquaringServiceManager::new( + // TransparentUpgradeableProxy::deploy( + // provider.clone(), + // empty_contract_addr, + // incredible_squaring_proxy_admin_addr, + // Bytes::from(""), + // ) + // .await + // .unwrap(), // provider.clone(), - // empty_address, - // empty_address, - // empty_address, - // empty_address, - // empty_address, - // ) - // .await - // .unwrap(); - // let eigen_pod_manager_addr = eigen_pod_manager.address(); + // ); + // let &incredible_squaring_service_manager_addr = + // incredible_squaring_service_manager.address(); + // + // let incredible_squaring_task_manager = IncredibleSquaringTaskManager::new( + // TransparentUpgradeableProxy::deploy( + // provider.clone(), + // empty_contract_addr, + // incredible_squaring_proxy_admin_addr, + // Bytes::from(""), + // ) + // .await + // .unwrap(), + // provider.clone(), + // ); + // let &incredible_squaring_task_manager_addr = incredible_squaring_task_manager.address(); + // + // let registry_coordinator = RegistryCoordinator::new( + // TransparentUpgradeableProxy::deploy( + // provider.clone(), + // empty_contract_addr, + // incredible_squaring_proxy_admin_addr, + // Bytes::from(""), + // ) + // .await + // .unwrap(), + // provider.clone(), + // ); + // let ®istry_coordinator_addr = registry_coordinator.address(); + // + // let bls_apk_registry = BlsApkRegistry::new( + // TransparentUpgradeableProxy::deploy( + // provider.clone(), + // empty_contract_addr, + // incredible_squaring_proxy_admin_addr, + // Bytes::from(""), + // ) + // .await + // .unwrap(), + // provider.clone(), + // ); + // let &bls_apk_registry_addr = bls_apk_registry.address(); + // + // let bls_apk_registry = IBlsApkRegistry::new( + // TransparentUpgradeableProxy::deploy( + // provider.clone(), + // empty_contract_addr, + // incredible_squaring_proxy_admin_addr, + // Bytes::from(""), + // ) + // .await + // .unwrap(), + // provider.clone(), + // ); + // let &bls_apk_registry_addr = bls_apk_registry.address(); + // + // let index_registry = IIndexRegistry::new( + // TransparentUpgradeableProxy::deploy( + // provider.clone(), + // empty_contract_addr, + // incredible_squaring_proxy_admin_addr, + // Bytes::from(""), + // ) + // .await + // .unwrap(), + // provider.clone(), + // ); + // let &index_registry_addr = index_registry.address(); + // + // let stake_registry = IStakeRegistry::new( + // TransparentUpgradeableProxy::deploy( + // provider.clone(), + // empty_contract_addr, + // incredible_squaring_proxy_admin_addr, + // Bytes::from(""), + // ) + // .await + // .unwrap(), + // provider.clone(), + // ); + // let &stake_registry_addr = stake_registry.address(); // - // let delegation_manager = DelegationManager::deploy( + // let operator_state_retriever = OperatorStateRetriever::deploy(provider.clone()) + // .await + // .unwrap(); + // let &operator_state_retriever_addr = operator_state_retriever.address(); + // + // //Now, deploy the implementation contracts using the proxy contracts as inputs + // let stake_registry_implementation = StakeRegistry::deploy( // provider.clone(), - // empty_address, - // empty_address, - // empty_address, + // registry_coordinator_addr, + // delegation_manager_addr, // ) // .await // .unwrap(); - // let delegation_manager_addr = delegation_manager.address(); - // - // let avs_directory = AVSDirectory::deploy(provider.clone(), empty_address.clone()) + // let &stake_registry_implementation_addr = stake_registry_implementation.address(); + // let stake_registry_upgrade = incredible_squaring_proxy_admin + // .upgrade(stake_registry_addr, stake_registry_implementation_addr) + // .send() + // .await + // .unwrap() + // .get_receipt() // .await // .unwrap(); - // let avs_directory_addr = avs_directory.address(); + // log::info!( + // "Stake Registry Upgrade Receipt: {:?}", + // stake_registry_upgrade + // ); // - // let state_retriever = OperatorStateRetriever::deploy(provider.clone()) + // let bls_apk_registry_implementation = + // BlsApkRegistry::deploy(provider.clone(), registry_coordinator_addr) + // .await + // .unwrap(); + // let &bls_apk_registry_implementation_addr = bls_apk_registry_implementation.address(); + // let bls_apk_registry_upgrade = incredible_squaring_proxy_admin + // .upgrade(bls_apk_registry_addr, bls_apk_registry_implementation_addr) + // .send() + // .await + // .unwrap() + // .get_receipt() // .await // .unwrap(); - // let state_retriever_addr = state_retriever.address(); + // log::info!( + // "Bls Apk Registry Upgrade Receipt: {:?}", + // bls_apk_registry_upgrade + // ); // - // let task_manager = - // IncredibleSquaringTaskManager::deploy(provider.clone(), empty_address, 5u32) + // let index_registry_implementation = + // IndexRegistry::deploy(provider.clone(), registry_coordinator_addr) // .await // .unwrap(); - // let task_manager_addr = task_manager.address(); + // let &index_registry_implementation_addr = index_registry_implementation.address(); + // let index_registry_upgrade = incredible_squaring_proxy_admin + // .upgrade(index_registry_addr, index_registry_implementation_addr) + // .send() + // .await + // .unwrap() + // .get_receipt() + // .await + // .unwrap(); + // log::info!( + // "Index Registry Upgrade Receipt: {:?}", + // index_registry_upgrade + // ); // - // let service_manager = IncredibleSquaringServiceManager::deploy( + // let registry_coordinator_implementation = RegistryCoordinator::deploy( // provider.clone(), - // empty_address, - // empty_address, - // empty_address, - // empty_address, + // incredible_squaring_service_manager_addr, + // stake_registry_addr, + // bls_apk_registry_addr, + // index_registry_addr, // ) // .await // .unwrap(); - // let service_manager_addr = service_manager.address(); + // let ®istry_coordinator_implementation_addr = + // registry_coordinator_implementation.address(); + // // let registry_coordinator_upgrade = incredible_squaring_proxy_admin.upgrade( + // // registry_coordinator_addr, + // // registry_coordinator_implementation_addr, + // // ).send().await.unwrap().get_receipt().await.unwrap(); + // // log::info!("Registry Coordinator Upgrade Receipt: {:?}", registry_coordinator_upgrade); + // + // let number_of_quorums = 1; + // // For each quorum we want to set up, we must define QuorumOperatorSetParam, minimumStakeForQuorum, and strategyParams + // let mut quorum_operator_set_params = Vec::::new(); + // for i in 0..number_of_quorums { + // log::info!("Deploying quorum {}", i); + // quorum_operator_set_params.push(OperatorSetParam { + // maxOperatorCount: 10000, + // kickBIPsOfOperatorStake: 15000, + // kickBIPsOfTotalStake: 100, + // }); + // } + // // Set to 0 for each quorum + // let quorums_minimum_stake = Vec::::new(); + // let mut quorums_strategy_params = Vec::>::new(); + // + // for j in 0..number_of_quorums { + // quorums_strategy_params.push(Vec::::new()); + // for k in 0..number_of_strategies { + // quorums_strategy_params[j][k] = StrategyParams { + // strategy: strategies[j], + // multiplier: 1, + // } + // } + // } + // + // let tokens = vec![ + // Token::Address(H160::from_slice(pausers[0].as_slice())), + // Token::Address(H160::from_slice(pausers[0].as_slice())), + // Token::Address(H160::from_slice(pausers[0].as_slice())), + // Token::Address(H160::from_slice(pausers[1].as_slice())), + // Token::Uint(0.into()), + // Token::Array(quorum_operator_set_params), + // Token::Array(quorums_minimum_stake), + // Token::Array(quorums_strategy_params), + // ]; + // let encoded_data = encode(&tokens); + // let registry_coordinator_upgrade = incredible_squaring_proxy_admin + // .upgradeAndCall( + // registry_coordinator_addr, + // registry_coordinator_implementation_addr, + // alloy_primitives::Bytes::from(encoded_data), + // ) + // .send() + // .await + // .unwrap() + // .get_receipt() + // .await + // .unwrap(); + // log::info!( + // "Registry Coordinator Upgrade Receipt: {:?}", + // registry_coordinator_upgrade + // ); // - // let eigen_strategy = EigenStrategy::deploy(provider.clone(), empty_address) + // let incredible_squaring_service_manager_implementation = + // IncredibleSquaringServiceManager::deploy( + // provider.clone(), + // avs_directory_addr, + // registry_coordinator_addr, + // stake_registry_addr, + // incredible_squaring_task_manager_addr, + // ) // .await // .unwrap(); - // let eigen_strategy_addr = eigen_strategy.address(); - // - // api.mine_one().await; - // - // let rc_init = registry_coordinator - // .initialize( - // from, - // from, - // from, - // pauser_registry_addr, - // Default::default(), - // vec![OperatorSetParam { - // maxOperatorCount: 10, - // kickBIPsOfOperatorStake: 5, - // kickBIPsOfTotalStake: 2, - // }], - // vec![10], - // vec![vec![StrategyParams { - // strategy: *eigen_strategy_addr, - // multiplier: 2, - // }]], + // let &incredible_squaring_service_manager_implementation_addr = + // incredible_squaring_service_manager_implementation.address(); + // let incredible_squaring_service_manager_upgrade = incredible_squaring_proxy_admin + // .upgrade( + // incredible_squaring_service_manager_addr, + // incredible_squaring_service_manager_implementation_addr, // ) // .send() // .await @@ -642,82 +887,125 @@ mod tests { // .get_receipt() // .await // .unwrap(); - // println!("Registry Coordinator Initialization Receipt: {:?}", rc_init); + // log::info!( + // "Incredible Squaring Service Manager Upgrade Receipt: {:?}", + // incredible_squaring_service_manager_upgrade + // ); // - // let _block = provider - // .get_block(BlockId::latest(), false.into()) + // let tokens = vec![ + // Token::Address(H160::from_slice(pauser_registry_addr.as_slice())), + // Token::Address(H160::from_slice(pausers[0].as_slice())), + // Token::Address(H160::from_slice(AGGREGATOR_ADDR.as_slice())), + // Token::Address(H160::from_slice(TASK_GENERATOR_ADDR.as_slice())), + // ]; + // let encoded_data = encode(&tokens); + // let incredible_squaring_task_manager_implementation = + // IncredibleSquaringTaskManager::deploy( + // provider.clone(), + // registry_coordinator_addr, + // TASK_RESPONSE_WINDOW_BLOCK, + // ) + // .await + // .unwrap(); + // let &incredible_squaring_task_manager_implementation_addr = + // incredible_squaring_task_manager_implementation.address(); + // let incredible_squaring_task_manager_upgrade = incredible_squaring_proxy_admin + // .upgradeAndCall( + // incredible_squaring_task_manager_addr, + // incredible_squaring_service_manager_implementation_addr, + // alloy_primitives::Bytes::from(encoded_data), + // ) + // .send() // .await // .unwrap() + // .get_receipt() + // .await // .unwrap(); + // log::info!( + // "Incredible Squaring Task Manager Upgrade Receipt: {:?}", + // incredible_squaring_task_manager_upgrade + // ); // - // api.anvil_set_auto_mine(true).await.unwrap(); - // let run_testnet = async move { - // let serv = handle.servers.pop().unwrap(); - // let res = serv.await.unwrap(); - // res.unwrap(); - // }; - // let spawner_task_manager_address = task_manager_addr.clone(); - // // let spawner_provider = provider.clone(); - // let spawner_provider = provider; - // let task_spawner = async move { - // let manager = IncredibleSquaringTaskManager::new( - // spawner_task_manager_address, - // spawner_provider.clone(), - // ); - // loop { - // api.mine_one().await; - // log::info!("About to create new task"); - // tokio::time::sleep(std::time::Duration::from_millis(5000)).await; - // let result = manager - // .createNewTask(U256::from(2), 100u32, Bytes::from("0")) - // .send() - // .await - // .unwrap() - // .watch() - // .await - // .unwrap(); - // api.mine_one().await; - // log::info!("Created new task: {:?}", result); - // // let latest_task = manager.latestTaskNum().call().await.unwrap()._0; - // // log::info!("Latest task: {:?}", latest_task); - // // let task_hash = manager.allTaskHashes(latest_task).call().await.unwrap()._0; - // // log::info!("Task info: {:?}", task_hash); - // } - // }; - // tokio::spawn(run_testnet); - // tokio::spawn(task_spawner); + // log::info!("ERC20MOCK ADDRESS: {:?}", erc20_mock_addr); + // log::info!("ERC20MOCK STRATEGY ADDRESS: {:?}", erc20_mock_strategy_addr); + // log::info!( + // "INCREDIBLE SQUARING TASK MANAGER ADDRESS: {:?}", + // incredible_squaring_task_manager_addr + // ); + // log::info!( + // "INCREDIBLE SQUARING TASK MANAGER IMPLEMENTATION ADDRESS: {:?}", + // incredible_squaring_task_manager_implementation_addr + // ); + // log::info!( + // "INCREDIBLE SQUARING SERVICE MANAGER ADDRESS: {:?}", + // incredible_squaring_service_manager_addr + // ); + // log::info!( + // "INCREDIBLE SQUARING SERVICE MANAGER IMPLEMENTATION ADDRESS: {:?}", + // incredible_squaring_service_manager_implementation_addr + // ); + // log::info!( + // "REGISTRY COORDINATOR ADDRESS: {:?}", + // registry_coordinator_addr + // ); + // log::info!( + // "REGISTRY COORDINATOR IMPLEMENTATION ADDRESS: {:?}", + // registry_coordinator_implementation_addr + // ); + // log::info!( + // "OPERATOR STATE RETRIEVER ADDRESS: {:?}", + // operator_state_retriever_addr + // ); // - // // let ws = ProviderBuilder::new().on_ws(WsConnect::new(handle.ws_endpoint())).await.unwrap(); - // // - // // // Subscribe to new blocks. - // // let sub = ws.subscribe_blocks().await.unwrap(); - // // - // // // Wait and take the next 4 blocks. - // // let mut stream = sub.into_stream(); - // // - // // log::warn!("Awaiting blocks..."); + // // let _block = provider + // // .get_block(BlockId::latest(), false.into()) + // // .await + // // .unwrap() + // // .unwrap(); // // - // // // Take the stream and print the block number upon receiving a new block. - // // let handle = tokio::spawn(async move { - // // log::warn!("About to mine blocks..."); - // // api.mine_one().await; - // // while let Some(block) = stream.next().await { - // // log::warn!( - // // "Latest block number: {}", - // // block.header.number.expect("Failed to get block number") - // // ); + // // api.anvil_set_auto_mine(true).await.unwrap(); + // // let run_testnet = async move { + // // let serv = handle.servers.pop().unwrap(); + // // let res = serv.await.unwrap(); + // // res.unwrap(); + // // }; + // // let spawner_task_manager_address = task_manager_addr.clone(); + // // // let spawner_provider = provider.clone(); + // // let spawner_provider = provider; + // // let task_spawner = async move { + // // let manager = IncredibleSquaringTaskManager::new( + // // spawner_task_manager_address, + // // spawner_provider.clone(), + // // ); + // // loop { // // api.mine_one().await; + // // log::info!("About to create new task"); + // // tokio::time::sleep(std::time::Duration::from_millis(5000)).await; + // // let result = manager + // // .createNewTask(U256::from(2), 100u32, Bytes::from("0")) + // // .send() + // // .await + // // .unwrap() + // // .watch() + // // .await + // // .unwrap(); + // // api.mine_one().await; + // // log::info!("Created new task: {:?}", result); + // // // let latest_task = manager.latestTaskNum().call().await.unwrap()._0; + // // // log::info!("Latest task: {:?}", latest_task); + // // // let task_hash = manager.allTaskHashes(latest_task).call().await.unwrap()._0; + // // // log::info!("Task info: {:?}", task_hash); // // } - // // }); - // // - // // handle.await.unwrap(); + // // }; + // // tokio::spawn(run_testnet); + // // tokio::spawn(task_spawner); // // ContractAddresses { - // service_manager: *service_manager_addr, - // registry_coordinator: *registry_coordinator_addr, - // operator_state_retriever: *state_retriever_addr, - // delegation_manager: *delegation_manager_addr, - // avs_directory: *avs_directory_addr, + // service_manager: incredible_squaring_service_manager_implementation_addr, + // registry_coordinator: registry_coordinator_implementation_addr, + // operator_state_retriever: operator_state_retriever_addr, + // delegation_manager: delegation_manager_addr, + // avs_directory: avs_directory_addr, // operator: from, // } // } @@ -726,16 +1014,16 @@ mod tests { async fn test_anvil() { env_logger::init(); // let contract_addresses = run_anvil_testnet().await; - let chain = eigen_utils::test_utils::local_chain::LocalEvmChain::new_with_chain_state( - 31337, - String::from("eigen-testnet"), - Path::new("../../eigen-utils/saved-anvil-state.json"), - Some(8545u16), - ); - let chain_id = chain.chain_id(); - let chain_name = chain.name(); - println!("chain_id: {:?}", chain_id); - println!("chain_name: {:?}", chain_name); + // let chain = eigen_utils::test_utils::local_chain::LocalEvmChain::new_with_chain_state( + // 31337, + // String::from("eigen-testnet"), + // Path::new("../../eigen-utils/saved-anvil-state.json"), + // Some(8545u16), + // ); + // let chain_id = chain.chain_id(); + // let chain_name = chain.name(); + // println!("chain_id: {:?}", chain_id); + // println!("chain_name: {:?}", chain_name); let contract_addresses = ContractAddresses { service_manager: address!("84eA74d481Ee0A5332c457a4d796187F6Ba67fEB"), @@ -746,6 +1034,15 @@ mod tests { operator: address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), }; + // let contract_addresses = ContractAddresses { + // service_manager: address!("84eA74d481Ee0A5332c457a4d796187F6Ba67fEB"), + // registry_coordinator: address!("9d4454B023096f34B160D6B654540c56A1F81688"), + // operator_state_retriever: address!("95401dc811bb5740090279Ba06cfA8fcF6113778"), + // delegation_manager: address!("B7f8BC63BbcaD18155201308C8f3540b07f84F5e"), + // avs_directory: address!("0DCd1Bf9A1b36cE34237eEaFef220932846BCD82"), + // operator: address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), + // }; + let http_endpoint = "http://127.0.0.1:8545"; let ws_endpoint = "ws://127.0.0.1:8545"; let node_config = NodeConfig { @@ -807,8 +1104,8 @@ mod tests { operator_info_service, signer, ) - .await - .unwrap(); + .await + .unwrap(); operator.start().await.unwrap(); } diff --git a/contracts/src/lib.rs b/contracts/src/lib.rs index e7c490c..2635338 100644 --- a/contracts/src/lib.rs +++ b/contracts/src/lib.rs @@ -8,6 +8,14 @@ sol!( "out/BLSApkRegistry.sol/BLSApkRegistry.json" ); +sol!( + #[allow(missing_docs)] + #[derive(Debug)] + #[sol(rpc)] + IBlsApkRegistry, + "out/IBLSApkRegistry.sol/IBLSApkRegistry.json" +); + sol!( #[allow(missing_docs)] #[sol(rpc)] @@ -22,6 +30,13 @@ sol!( "out/StakeRegistry.sol/StakeRegistry.json" ); +sol!( + #[allow(missing_docs)] + #[sol(rpc)] + IStakeRegistry, + "out/IStakeRegistry.sol/IStakeRegistry.json" +); + sol!( #[allow(missing_docs, clippy::too_many_arguments)] #[sol(rpc)] @@ -88,10 +103,17 @@ sol!( sol!( #[allow(missing_docs)] #[sol(rpc)] - IndexRegistry, + IIndexRegistry, "out/IIndexRegistry.sol/IIndexRegistry.json" ); +sol!( + #[allow(missing_docs)] + #[sol(rpc)] + IndexRegistry, + "lib/eigenlayer-middleware/out/IndexRegistry.sol/IndexRegistry.json" +); + sol!( #[allow(missing_docs)] #[sol(rpc)] @@ -117,7 +139,7 @@ sol!( #[allow(missing_docs)] #[sol(rpc)] EigenStrategy, - "lib/eigenlayer-contracts/out/EigenStrategy.sol/EigenStrategy.json" + "out/EigenStrategy.sol/EigenStrategy.json" ); sol!( @@ -161,3 +183,10 @@ sol!( ERC20Mock, "lib/eigenlayer-contracts/out/ERC20Mock.sol/ERC20Mock.json" ); + +sol!( + #[allow(missing_docs)] + #[sol(rpc)] + EmptyContract, + "lib/eigenlayer-contracts/out/EmptyContract.sol/EmptyContract.json" +); From c43e3731b6d5808ff24119a84995c6129d33cee6 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Fri, 2 Aug 2024 22:02:19 -0500 Subject: [PATCH 02/43] Debugging and some Fixes --- Cargo.lock | 97 ++++++++--------- avs/incredible-squaring-avs/Cargo.toml | 2 +- avs/incredible-squaring-avs/keystore/bls | 2 +- avs/incredible-squaring-avs/keystore/ecdsa | 2 +- avs/incredible-squaring-avs/src/avs/mod.rs | 5 +- avs/incredible-squaring-avs/src/operator.rs | 113 ++++++++++++++++---- contracts/src/lib.rs | 2 +- eigensdk-rs/src/lib.rs | 6 +- utils/src/avs_registry/writer.rs | 20 +++- utils/src/types.rs | 27 +++-- 10 files changed, 181 insertions(+), 95 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a50339f..c0756c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4158,6 +4158,55 @@ dependencies = [ "alloy-sol-types", ] +[[package]] +name = "eigen-gadget" +version = "0.1.0" +dependencies = [ + "alloy", + "alloy-contract", + "alloy-primitives", + "alloy-provider 0.2.1", + "alloy-pubsub", + "alloy-rpc-client 0.2.1", + "alloy-rpc-types", + "alloy-rpc-types-eth 0.2.1", + "alloy-signer 0.2.1", + "alloy-signer-local", + "alloy-sol-types", + "alloy-transport 0.2.1", + "alloy-transport-http 0.2.1", + "alloy-transport-ws", + "anvil", + "ark-bn254", + "ark-ec", + "ark-ff 0.4.2", + "async-trait", + "aws-kms", + "aws-sdk-kms", + "eigen-contracts", + "eigen-utils", + "env_logger 0.11.5", + "ethabi", + "foundry-common", + "futures", + "gadget-common", + "getrandom", + "hex", + "http-body-util", + "hyper 1.4.1", + "k256", + "lazy_static", + "log", + "prometheus", + "rand", + "reqwest 0.12.5", + "serde", + "serde_json", + "thiserror", + "tokio", + "url", +] + [[package]] name = "eigen-utils" version = "0.1.0" @@ -6660,54 +6709,6 @@ dependencies = [ "quote", ] -[[package]] -name = "incredible-squaring-avs" -version = "0.1.0" -dependencies = [ - "alloy", - "alloy-contract", - "alloy-primitives", - "alloy-provider 0.2.1", - "alloy-pubsub", - "alloy-rpc-client 0.2.1", - "alloy-rpc-types", - "alloy-rpc-types-eth 0.2.1", - "alloy-signer 0.2.1", - "alloy-signer-local", - "alloy-sol-types", - "alloy-transport 0.2.1", - "alloy-transport-http 0.2.1", - "alloy-transport-ws", - "anvil", - "ark-bn254", - "ark-ec", - "ark-ff 0.4.2", - "async-trait", - "aws-kms", - "aws-sdk-kms", - "eigen-contracts", - "eigen-utils", - "env_logger 0.11.5", - "foundry-common", - "futures", - "gadget-common", - "getrandom", - "hex", - "http-body-util", - "hyper 1.4.1", - "k256", - "lazy_static", - "log", - "prometheus", - "rand", - "reqwest 0.12.5", - "serde", - "serde_json", - "thiserror", - "tokio", - "url", -] - [[package]] name = "indenter" version = "0.3.3" diff --git a/avs/incredible-squaring-avs/Cargo.toml b/avs/incredible-squaring-avs/Cargo.toml index 42a944f..18d9906 100644 --- a/avs/incredible-squaring-avs/Cargo.toml +++ b/avs/incredible-squaring-avs/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "incredible-squaring-avs" +name = "eigen-gadget" version = "0.1.0" authors.workspace = true edition.workspace = true diff --git a/avs/incredible-squaring-avs/keystore/bls b/avs/incredible-squaring-avs/keystore/bls index a807f65..77e9863 100644 --- a/avs/incredible-squaring-avs/keystore/bls +++ b/avs/incredible-squaring-avs/keystore/bls @@ -1 +1 @@ -{"pub_key":{"x":"0x56246c96821468637fbf1a68d553be0898c8cef2b10ae5bb8dfcab517ccb973","y":"0xa50d400e19adf2f1e2ce2a5a8228f41984060fa831516159365756a4047e5d5"},"crypto":{"encrypted_data":"gkbFM2Zmml9nIlIIsx335H+c2b9y4LIGaLWo4BQXTVUeE7JsPbhw0cKf9n7LOBpA","nonce":"tDOCuKJk5zGvXRZQ","password_hash":"JHNjcnlwdCRsbj0xNyxyPTgscD0xJFZyd2taWmpvTEJFaFZPR3JJRnpXV0EkMGRpcmpuM3ViNEhqRG1YRy8vRnB4SzczYmUxeXpOamV4ZGJ4SjhzQkFhWQ=="}} \ No newline at end of file +{"pub_key":{"x":"0x463de28ab3e1e233712d91d7580444829c8bc03c45508a9688b0397712646ec","y":"0x1f17178fa6a666080eb468ec4b53efbf948605b6cbf0f328aeab10176df2b58b"},"crypto":{"encrypted_data":"stUp9hUW/6XSnXyFuBK/y56HoBN7j3DGt+X1cwXwdYf8AwkKyKmqzFAB/WRuS04o","nonce":"c93GqdKHPO89BnRc","password_hash":"JHNjcnlwdCRsbj0xNyxyPTgscD0xJEV4MWpYblpiRUlBTFc2WXRTNzNHa2ckdUFsaWlYM1Y3ZWo1bEIzaGVzQXpyRFRudEpWZTFBQlBIK3dWUnVPeVNvaw=="}} \ No newline at end of file diff --git a/avs/incredible-squaring-avs/keystore/ecdsa b/avs/incredible-squaring-avs/keystore/ecdsa index efd01cb..5c7b348 100644 --- a/avs/incredible-squaring-avs/keystore/ecdsa +++ b/avs/incredible-squaring-avs/keystore/ecdsa @@ -1 +1 @@ -{"address":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266","crypto":{"Cipher":"aes-128-ctr","CipherText":"f348898932b4b5f819c95cc560a67df8ee3776082fe90cb140f3b2604e722448","CipherParams":{"IV":"2cb190a314af75f3321b97e71b831e32"},"KDF":"scrypt","KDFParams":{"n":17,"r":8,"p":1,"dklen":32,"salt":"48fd308353074bb3c6cc88fd5e13f4d536c71b2b2361645355ededb8da517406"},"MAC":"ee79ee96718af612668e734bac853b1bb217138181a4d2691db921bc7deacc3f"},"id":"6ca45f44-b821-4f91-8edd-28e063eeb96d","version":"3"} \ No newline at end of file +{"address":"0x70997970C51812dc3A010C7d01b50e0d17dc79C8","crypto":{"Cipher":"aes-128-ctr","CipherText":"718edf3a1df8a921f6bf525a57018621543899b0290d7c689f10f22f52822d04","CipherParams":{"IV":"d50e5438eec799d2fcf449996bfaed6a"},"KDF":"scrypt","KDFParams":{"n":17,"r":8,"p":1,"dklen":32,"salt":"df0cd633b589c36daf6afe873f745763b2cb2350687ee6774101f748cb939127"},"MAC":"0b4977229f8765680b350945e978e13b349fc12b615ab426b51105e30c89e9df"},"id":"3738e3aa-e9b8-41d5-bdfa-aac231187845","version":"3"} \ No newline at end of file diff --git a/avs/incredible-squaring-avs/src/avs/mod.rs b/avs/incredible-squaring-avs/src/avs/mod.rs index 5ad68ba..443ec4c 100644 --- a/avs/incredible-squaring-avs/src/avs/mod.rs +++ b/avs/incredible-squaring-avs/src/avs/mod.rs @@ -86,7 +86,10 @@ impl IncredibleSquaringContractManager { let registry_coordinator = RegistryCoordinator::new(registry_coordinator_addr, eth_client_http.clone()); - let result = eth_client_http.get_code_at(registry_coordinator_addr).await.unwrap(); + let result = eth_client_http + .get_code_at(registry_coordinator_addr) + .await + .unwrap(); log::info!("Registry Coordinator Code: {:?}", result); log::info!("Built RegistryCoordinator"); diff --git a/avs/incredible-squaring-avs/src/operator.rs b/avs/incredible-squaring-avs/src/operator.rs index 97c8f38..d3d2f44 100644 --- a/avs/incredible-squaring-avs/src/operator.rs +++ b/avs/incredible-squaring-avs/src/operator.rs @@ -59,7 +59,7 @@ pub enum OperatorError { #[error("Cannot get operator id: {0}")] OperatorIdError(String), #[error( - "Operator is not registered. Register using the operator-cli before starting operator." + "Operator is not registered. Register using the operator-cli before starting operator." )] OperatorNotRegistered, #[error("Error in metrics server: {0}")] @@ -209,7 +209,7 @@ impl Operator { &config.bls_private_key_store_path, &bls_key_password, ) - .map_err(OperatorError::from)?; + .map_err(OperatorError::from)?; let _chain_id = eth_client_http .get_chain_id() @@ -224,7 +224,7 @@ impl Operator { &config.ecdsa_private_key_store_path, &ecdsa_key_password, ) - .unwrap(); + .unwrap(); let ecdsa_signing_key = SigningKey::from(&ecdsa_secret_key); // TODO: Ecdsa signing key is not used @@ -247,8 +247,8 @@ impl Operator { eth_client_ws.clone(), signer.clone(), ) - .await - .unwrap(); + .await + .unwrap(); log::info!("About to build AVS Registry Contract Manager"); let avs_registry_contract_manager = AvsRegistryContractManager::build( @@ -261,8 +261,8 @@ impl Operator { eth_client_ws.clone(), signer.clone(), ) - .await - .unwrap(); + .await + .unwrap(); log::info!("About to build aggregator service"); let aggregator_service = Aggregator::build( @@ -270,8 +270,8 @@ impl Operator { operator_info_service, config.server_ip_port_address.clone(), ) - .await - .unwrap(); + .await + .unwrap(); log::info!("About to build aggregator RPC client"); let aggregator_rpc_client = AggregatorRpcClient::new(config.server_ip_port_address.clone()); @@ -284,8 +284,8 @@ impl Operator { eth_client_ws.clone(), signer.clone(), ) - .await - .unwrap(); + .await + .unwrap(); log::info!("About to get operator id and address"); let operator_addr = Address::from_str(&config.operator_address).unwrap(); @@ -301,6 +301,14 @@ impl Operator { bls_keypair.clone().get_pub_key_g2(), ); + let answer = avs_registry_contract_manager + .is_operator_registered(alloy_primitives::address!( + "70997970C51812dc3A010C7d01b50e0d17dc79C8" + )) + .await + .unwrap(); + log::info!("Is operator registered: {:?}", answer); + let mut salt = [0u8; 32]; rand::thread_rng().fill(&mut salt); let sig_salt = FixedBytes::from_slice(&salt); @@ -313,7 +321,7 @@ impl Operator { // ); let current_block_number = eth_client_http.get_block_number().await.unwrap(); let expiry: U256 = U256::from(current_block_number + 20); - let quorum_nums = Bytes::from(vec![0, 1]); + let quorum_nums = Bytes::from(vec![0]); let register_result = avs_registry_contract_manager .register_operator_in_quorum_with_avs_registry_coordinator( &ecdsa_signing_key, @@ -321,7 +329,8 @@ impl Operator { expiry, &bls_keypair, quorum_nums, - "ws://127.0.0.1:33125".to_string(), + // "ws://127.0.0.1:33125".to_string(), + config.eth_rpc_url.clone(), ) .await; log::info!("Register result: {:?}", register_result); @@ -357,9 +366,9 @@ impl Operator { .avs_registry_contract_manager .is_operator_registered(self.operator_addr) .await; //?; - // if !operator_is_registered { - // return Err(OperatorError::OperatorNotRegistered); - // } + // if !operator_is_registered { + // return Err(OperatorError::OperatorNotRegistered); + // } log::info!("Operator registration status: {:?}", operator_is_registered); if self.config.enable_node_api { @@ -1025,13 +1034,16 @@ mod tests { // println!("chain_id: {:?}", chain_id); // println!("chain_name: {:?}", chain_name); + let account_one = address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"); + let account_two = address!("70997970C51812dc3A010C7d01b50e0d17dc79C8"); + let contract_addresses = ContractAddresses { service_manager: address!("84eA74d481Ee0A5332c457a4d796187F6Ba67fEB"), registry_coordinator: address!("a82fF9aFd8f496c3d6ac40E2a0F282E47488CFc9"), operator_state_retriever: address!("95401dc811bb5740090279Ba06cfA8fcF6113778"), delegation_manager: address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"), avs_directory: address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"), - operator: address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), + operator: account_two, }; // let contract_addresses = ContractAddresses { @@ -1104,12 +1116,66 @@ mod tests { operator_info_service, signer, ) - .await - .unwrap(); + .await + .unwrap(); operator.start().await.unwrap(); } + #[tokio::test] + async fn test_load_issue() { + env_logger::init(); + + let http_endpoint = "http://127.0.0.1:8545"; + let ws_endpoint = "ws://127.0.0.1:8545"; + + let provider = ProviderBuilder::new() + .with_recommended_fillers() + .on_http(http_endpoint.parse().unwrap()) + .root() + .clone() + .boxed(); + + // let ws_provider = ProviderBuilder::new() + // .with_recommended_fillers() + // .on_ws(WsConnect::new(ws_endpoint)) + // .await + // .unwrap() + // .root() + // .clone() + // .boxed(); + + let registry_coordinator_addr = address!("a82fF9aFd8f496c3d6ac40E2a0F282E47488CFc9"); + let registry_coordinator_implementation_addr = + address!("9d4454B023096f34B160D6B654540c56A1F81688"); + + // let registry_coordinator = RegistryCoordinator::new(registry_coordinator_addr, provider.clone()); + let registry_coordinator_code = provider + .get_code_at(registry_coordinator_addr) + .await + .unwrap(); + // println!("Code at Registry Coordinator Address: {:?}", registry_coordinator_code); + let registry_coordinator = + RegistryCoordinator::new(registry_coordinator_addr, provider.clone()); + let response_one = registry_coordinator.owner().call().await.unwrap(); + println!("Owner from RC: {:?}", response_one._0); + + // let registry_coordinator = RegistryCoordinator::new(registry_coordinator_implementation_addr, provider.clone()); + let registry_coordinator_implementation_code = provider + .get_code_at(registry_coordinator_implementation_addr) + .await + .unwrap(); + // println!("Code at Registry Coordinator Implementation Address: {:?}", registry_coordinator_implementation_code); + let registry_coordinator_implementation = + RegistryCoordinator::new(registry_coordinator_implementation_addr, provider.clone()); + let response_two = registry_coordinator_implementation + .owner() + .call() + .await + .unwrap(); + println!("Owner from RC Implementation: {:?}", response_two._0); + } + #[tokio::test] async fn test_start_chain_from_state() { env_logger::init(); @@ -1145,9 +1211,16 @@ mod tests { assert_eq!(bls_pair.pub_key, bls_keys.pub_key); //---------------- ECDSA ---------------- + // First Account + // let hex_key = + // hex::decode("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80") + // .unwrap(); + + // Second Account let hex_key = - hex::decode("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80") + hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d") .unwrap(); + let secret_key = SecretKey::from_slice(&hex_key).unwrap(); let signing_key = SigningKey::from(secret_key.clone()); let public_key = secret_key.public_key(); diff --git a/contracts/src/lib.rs b/contracts/src/lib.rs index 2635338..b60c798 100644 --- a/contracts/src/lib.rs +++ b/contracts/src/lib.rs @@ -139,7 +139,7 @@ sol!( #[allow(missing_docs)] #[sol(rpc)] EigenStrategy, - "out/EigenStrategy.sol/EigenStrategy.json" + "lib/eigenlayer-contracts/out/EigenStrategy.sol/EigenStrategy.json" ); sol!( diff --git a/eigensdk-rs/src/lib.rs b/eigensdk-rs/src/lib.rs index 30ca55d..a66e250 100644 --- a/eigensdk-rs/src/lib.rs +++ b/eigensdk-rs/src/lib.rs @@ -1,5 +1,5 @@ -pub use eigen_utils; -pub use eigen_gadget; pub use eigen_contracts; +pub use eigen_gadget; +pub use eigen_tangle_avs; +pub use eigen_utils; pub use fireblocks_client; -pub use eigen_tangle_avs; \ No newline at end of file diff --git a/utils/src/avs_registry/writer.rs b/utils/src/avs_registry/writer.rs index 65b9ad1..83a1068 100644 --- a/utils/src/avs_registry/writer.rs +++ b/utils/src/avs_registry/writer.rs @@ -1,9 +1,8 @@ #![allow(async_fn_in_trait)] -use alloy_primitives::{address, Address, Bytes, FixedBytes, U256}; +use alloy_primitives::{Address, Bytes, FixedBytes, U256}; use alloy_provider::Provider; use crate::crypto::bls::{G1Point, KeyPair}; -use crate::crypto::bn254::{point_to_u256, u256_to_point}; use crate::crypto::ecdsa::ToAddress; use crate::el_contracts::reader::ElReader; use crate::{types::*, Config}; @@ -11,8 +10,6 @@ use alloy_rpc_types::TransactionReceipt; use alloy_signer::k256::ecdsa; use alloy_signer::Signer; use eigen_contracts::RegistryCoordinator; -use eigen_contracts::RegistryCoordinator::{OperatorSetParam, StrategyParams}; -use eigen_contracts::StakeRegistry::StakeRegistryCalls::strategyParams; use k256::ecdsa::VerifyingKey; use super::{AvsRegistryContractManager, AvsRegistryContractResult}; @@ -127,9 +124,12 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { .await .map_err(AvsError::from)?; + let mut signature = operator_signature.as_bytes(); + signature[64] += 27; + let operator_signature_with_salt_and_expiry = RegistryCoordinator::SignatureWithSaltAndExpiry { - signature: Bytes::copy_from_slice(operator_signature.as_bytes().as_ref()), + signature: Bytes::from(signature), salt: operator_to_avs_registration_sig_salt, expiry: operator_to_avs_registration_sig_expiry, }; @@ -155,6 +155,16 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { operator_signature_with_salt_and_expiry, ); + let quorum_count = registry_coordinator.quorumCount().call().await.unwrap(); + log::info!("Quorum count: {:?}", quorum_count._0); + + let bitmap = registry_coordinator + .getCurrentQuorumBitmap(operator_id_from_key_pair(bls_key_pair)) + .call() + .await + .unwrap(); + log::info!("Bitmap: {:?}", bitmap._0); + let _call = builder.call().await.unwrap(); let tx = builder.send().await?; diff --git a/utils/src/types.rs b/utils/src/types.rs index c45f564..7f7e8b5 100644 --- a/utils/src/types.rs +++ b/utils/src/types.rs @@ -16,9 +16,9 @@ use std::collections::HashMap; use thiserror::Error; -use crate::crypto::bls::G1Point; use crate::crypto::bls::KeyPair; use crate::crypto::bls::Signature; +use crate::crypto::bls::{g1_point_to_ark_point, g1_projective_to_g1_point, G1Point}; use crate::services::bls_aggregation::BlsAggregationError; use crate::utils::*; @@ -96,10 +96,7 @@ pub type StakeAmount = U256; pub type OperatorId = B256; pub fn operator_id_from_g1_pubkey(pubkey: &G1Point) -> OperatorId { - let pubkey: Bn254G1Affine = Bn254G1Affine::new( - Bn254Fq::from(BigInt::new(pubkey.x.into_limbs())), - Bn254Fq::from(BigInt::new(pubkey.y.into_limbs())), - ); + let pubkey = g1_point_to_ark_point(&pubkey); let mut x_bytes: Vec = vec![0; pubkey.x.serialized_size(Compress::Yes)]; pubkey.x.serialize_compressed(&mut x_bytes).unwrap(); @@ -115,20 +112,22 @@ pub fn operator_id_from_contract_g1_pubkey(pubkey: G1Point) -> OperatorId { } pub fn operator_id_from_key_pair(key_pair: &KeyPair) -> OperatorId { - let point = G1Point::new(key_pair.pub_key.x, key_pair.pub_key.y); + let point = g1_projective_to_g1_point(&key_pair.pub_key); operator_id_from_g1_pubkey(&point) } pub fn sign_hashed_to_curve_message(pt: G1Point, key_pair: &KeyPair) -> Signature { - let ark_pt: Bn254G1Affine = Bn254G1Affine::new( - Bn254Fq::from(BigInt::new(pt.x.into_limbs())), - Bn254Fq::from(BigInt::new(pt.y.into_limbs())), - ); + // let ark_pt: Bn254G1Affine = Bn254G1Affine::new( + // Bn254Fq::from(BigInt::new(pt.x.into_limbs())), + // Bn254Fq::from(BigInt::new(pt.y.into_limbs())), + // ); + let ark_pt = g1_point_to_ark_point(&pt); let sig = ark_pt.mul_bigint(&key_pair.priv_key.0); - let sig_point = G1Point { - x: U256::from_limbs(sig.x.0 .0), - y: U256::from_limbs(sig.y.0 .0), - }; + let sig_point = g1_projective_to_g1_point(&sig); + // let sig_point = G1Point { + // x: U256::from_limbs(sig.x.0 .0), + // y: U256::from_limbs(sig.y.0 .0), + // }; Signature { g1_point: sig_point, } From 6987d551acdbd6d0baac13558ba21d1d83f8a5d8 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Mon, 5 Aug 2024 13:52:40 -0500 Subject: [PATCH 03/43] Fixes all contract errors and submodule issue --- Cargo.lock | 1278 ++--------------- avs/incredible-squaring-avs/Cargo.toml | 2 +- .../contracts/lib/eigenlayer-middleware | 2 +- .../contracts/lib/forge-std | 2 +- avs/incredible-squaring-avs/src/avs/mod.rs | 6 +- contracts/lib/eigenlayer-middleware | 2 +- contracts/lib/forge-std | 2 +- contracts/src/lib.rs | 108 +- utils/src/el_contracts/reader.rs | 2 +- utils/src/el_contracts/writer.rs | 4 +- 10 files changed, 185 insertions(+), 1223 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c0756c9..ed511a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1159,20 +1159,6 @@ version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" -[[package]] -name = "aquamarine" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21cc1548309245035eb18aa7f0967da6bc65587005170c56e6ef2788a4cf3f4e" -dependencies = [ - "include_dir", - "itertools 0.10.5", - "proc-macro-error", - "proc-macro2", - "quote", - "syn 2.0.72", -] - [[package]] name = "arbitrary" version = "1.3.2" @@ -1598,17 +1584,6 @@ dependencies = [ "term", ] -[[package]] -name = "async-channel" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" -dependencies = [ - "concurrent-queue", - "event-listener 2.5.3", - "futures-core", -] - [[package]] name = "async-channel" version = "2.3.1" @@ -1692,7 +1667,7 @@ version = "2.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7eda79bbd84e29c2b308d1dc099d7de8dcc7035e48f4bf5dc4a531a44ff5e2a" dependencies = [ - "async-channel 2.3.1", + "async-channel", "async-io", "async-lock", "async-signal", @@ -2592,7 +2567,7 @@ version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703f41c54fc768e63e091340b424302bb1c29ef4aa0c7f10fe849dfb114d29ea" dependencies = [ - "async-channel 2.3.1", + "async-channel", "async-task", "futures-io", "futures-lite", @@ -2803,15 +2778,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" -[[package]] -name = "cfg-expr" -version = "0.15.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" -dependencies = [ - "smallvec", -] - [[package]] name = "cfg-if" version = "1.0.0" @@ -3232,26 +3198,6 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" -[[package]] -name = "const-random" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" -dependencies = [ - "const-random-macro", -] - -[[package]] -name = "const-random-macro" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" -dependencies = [ - "getrandom", - "once_cell", - "tiny-keccak", -] - [[package]] name = "constant_time_eq" version = "0.1.5" @@ -3319,50 +3265,6 @@ dependencies = [ "libc", ] -[[package]] -name = "cranelift-bforest" -version = "0.95.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1277fbfa94bc82c8ec4af2ded3e639d49ca5f7f3c7eeab2c66accd135ece4e70" -dependencies = [ - "cranelift-entity", -] - -[[package]] -name = "cranelift-codegen" -version = "0.95.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6e8c31ad3b2270e9aeec38723888fe1b0ace3bea2b06b3f749ccf46661d3220" -dependencies = [ - "bumpalo", - "cranelift-bforest", - "cranelift-codegen-meta", - "cranelift-codegen-shared", - "cranelift-entity", - "cranelift-isle", - "gimli 0.27.3", - "hashbrown 0.13.2", - "log", - "regalloc2", - "smallvec", - "target-lexicon", -] - -[[package]] -name = "cranelift-codegen-meta" -version = "0.95.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8ac5ac30d62b2d66f12651f6b606dbdfd9c2cfd0908de6b387560a277c5c9da" -dependencies = [ - "cranelift-codegen-shared", -] - -[[package]] -name = "cranelift-codegen-shared" -version = "0.95.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd82b8b376247834b59ed9bdc0ddeb50f517452827d4a11bccf5937b213748b8" - [[package]] name = "cranelift-entity" version = "0.95.1" @@ -3372,51 +3274,6 @@ dependencies = [ "serde", ] -[[package]] -name = "cranelift-frontend" -version = "0.95.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64a25d9d0a0ae3079c463c34115ec59507b4707175454f0eee0891e83e30e82d" -dependencies = [ - "cranelift-codegen", - "log", - "smallvec", - "target-lexicon", -] - -[[package]] -name = "cranelift-isle" -version = "0.95.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80de6a7d0486e4acbd5f9f87ec49912bf4c8fb6aea00087b989685460d4469ba" - -[[package]] -name = "cranelift-native" -version = "0.95.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb6b03e0e03801c4b3fd8ce0758a94750c07a44e7944cc0ffbf0d3f2e7c79b00" -dependencies = [ - "cranelift-codegen", - "libc", - "target-lexicon", -] - -[[package]] -name = "cranelift-wasm" -version = "0.95.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff3220489a3d928ad91e59dd7aeaa8b3de18afb554a6211213673a71c90737ac" -dependencies = [ - "cranelift-codegen", - "cranelift-entity", - "cranelift-frontend", - "itertools 0.10.5", - "log", - "smallvec", - "wasmparser", - "wasmtime-types", -] - [[package]] name = "crc" version = "3.2.1" @@ -3779,17 +3636,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "derive-syn-parse" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e79116f119dd1dba1abf1f3405f03b9b0e79a27a3883864bfebded8a3dc768cd" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "derive-syn-parse" version = "0.2.0" @@ -3901,16 +3747,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "directories-next" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "339ee130d97a610ea5a5872d2bbb130fdf68884ff09d3028b81bec8a1ac23bbc" -dependencies = [ - "cfg-if", - "dirs-sys-next", -] - [[package]] name = "dirs" version = "5.0.1" @@ -3996,14 +3832,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a081e51fb188742f5a7a1164ad752121abcb22874b21e2c3b0dd040c515fdad" dependencies = [ "common-path", - "derive-syn-parse 0.2.0", + "derive-syn-parse", "once_cell", "proc-macro2", "quote", "regex", "syn 2.0.72", "termcolor", - "toml 0.8.19", + "toml", "walkdir", ] @@ -4158,55 +3994,6 @@ dependencies = [ "alloy-sol-types", ] -[[package]] -name = "eigen-gadget" -version = "0.1.0" -dependencies = [ - "alloy", - "alloy-contract", - "alloy-primitives", - "alloy-provider 0.2.1", - "alloy-pubsub", - "alloy-rpc-client 0.2.1", - "alloy-rpc-types", - "alloy-rpc-types-eth 0.2.1", - "alloy-signer 0.2.1", - "alloy-signer-local", - "alloy-sol-types", - "alloy-transport 0.2.1", - "alloy-transport-http 0.2.1", - "alloy-transport-ws", - "anvil", - "ark-bn254", - "ark-ec", - "ark-ff 0.4.2", - "async-trait", - "aws-kms", - "aws-sdk-kms", - "eigen-contracts", - "eigen-utils", - "env_logger 0.11.5", - "ethabi", - "foundry-common", - "futures", - "gadget-common", - "getrandom", - "hex", - "http-body-util", - "hyper 1.4.1", - "k256", - "lazy_static", - "log", - "prometheus", - "rand", - "reqwest 0.12.5", - "serde", - "serde_json", - "thiserror", - "tokio", - "url", -] - [[package]] name = "eigen-utils" version = "0.1.0" @@ -4610,7 +4397,7 @@ dependencies = [ "serde", "serde_json", "syn 2.0.72", - "toml 0.8.19", + "toml", "walkdir", ] @@ -4957,7 +4744,7 @@ dependencies = [ "atomic", "pear", "serde", - "toml 0.8.19", + "toml", "uncased", "version_check", ] @@ -4972,16 +4759,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "file-per-thread-logger" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84f2e425d9790201ba4af4630191feac6dcc98765b118d4d18e91d23c2353866" -dependencies = [ - "env_logger 0.10.2", - "log", -] - [[package]] name = "finito" version = "0.1.0" @@ -5164,7 +4941,7 @@ dependencies = [ "semver 1.0.23", "serde_json", "thiserror", - "toml 0.8.19", + "toml", "tracing 0.1.40", "vergen", "walkdir", @@ -5413,7 +5190,7 @@ dependencies = [ "serde_regex", "solang-parser", "thiserror", - "toml 0.8.19", + "toml", "toml_edit 0.22.20", "tracing 0.1.40", "walkdir", @@ -5683,88 +5460,6 @@ dependencies = [ "serde", ] -[[package]] -name = "frame-support" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "aquamarine", - "array-bytes", - "bitflags 1.3.2", - "docify", - "environmental", - "frame-metadata 16.0.0", - "frame-support-procedural", - "impl-trait-for-tuples", - "k256", - "log", - "macro_magic", - "parity-scale-codec", - "paste", - "scale-info", - "serde", - "serde_json", - "smallvec", - "sp-api", - "sp-arithmetic", - "sp-core", - "sp-crypto-hashing-proc-macro", - "sp-debug-derive 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "sp-genesis-builder", - "sp-inherents", - "sp-io", - "sp-metadata-ir", - "sp-runtime", - "sp-staking", - "sp-state-machine", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "sp-weights", - "static_assertions", - "tt-call", -] - -[[package]] -name = "frame-support-procedural" -version = "23.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "Inflector", - "cfg-expr", - "derive-syn-parse 0.1.5", - "expander", - "frame-support-procedural-tools", - "itertools 0.10.5", - "macro_magic", - "proc-macro-warning", - "proc-macro2", - "quote", - "sp-crypto-hashing 0.0.0", - "syn 2.0.72", -] - -[[package]] -name = "frame-support-procedural-tools" -version = "10.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "frame-support-procedural-tools-derive", - "proc-macro-crate 3.1.0", - "proc-macro2", - "quote", - "syn 2.0.72", -] - -[[package]] -name = "frame-support-procedural-tools-derive" -version = "11.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.72", -] - [[package]] name = "fs-err" version = "2.11.0" @@ -5952,13 +5647,11 @@ dependencies = [ [[package]] name = "gadget-common" version = "0.1.0" -source = "git+https://github.com/webb-tools/gadget#8b88cb4e1fb6ebebcd2be4f4d6822974c3c0061f" +source = "git+https://github.com/webb-tools/gadget#7e47266d904800f1d568f23cb1581256ac727b86" dependencies = [ - "anyhow", "async-trait", "auto_impl", "color-eyre", - "frame-support", "futures", "futures-util", "gadget-core", @@ -5967,21 +5660,15 @@ dependencies = [ "hex", "lazy_static", "libsecp256k1", - "linked-hash-map", "log", "parity-scale-codec", "parking_lot", "prometheus", "protocol-macros", - "round-based 0.1.7", - "round-based 0.2.2", - "sc-client-api", - "scale-info", + "round-based", "serde", - "serde_bytes", "serde_json", "sp-api", - "sp-application-crypto", "sp-core", "sp-io", "sp-runtime", @@ -5989,7 +5676,7 @@ dependencies = [ "sp-tracing 16.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", "sqlx", "substrate-prometheus-endpoint", - "subxt 0.34.0", + "subxt", "subxt-signer", "tangle-subxt", "thiserror", @@ -6001,7 +5688,7 @@ dependencies = [ [[package]] name = "gadget-core" version = "0.0.1" -source = "git+https://github.com/webb-tools/gadget#8b88cb4e1fb6ebebcd2be4f4d6822974c3c0061f" +source = "git+https://github.com/webb-tools/gadget#7e47266d904800f1d568f23cb1581256ac727b86" dependencies = [ "async-trait", "auto_impl", @@ -6021,13 +5708,10 @@ dependencies = [ [[package]] name = "gadget-executor" version = "0.1.0" -source = "git+https://github.com/webb-tools/gadget#8b88cb4e1fb6ebebcd2be4f4d6822974c3c0061f" +source = "git+https://github.com/webb-tools/gadget#7e47266d904800f1d568f23cb1581256ac727b86" dependencies = [ "failure", "futures", - "gadget-common", - "gadget-io", - "itertools 0.13.0", "nix 0.29.0", "serde", "serde_json", @@ -6038,9 +5722,8 @@ dependencies = [ [[package]] name = "gadget-io" version = "0.0.1" -source = "git+https://github.com/webb-tools/gadget#8b88cb4e1fb6ebebcd2be4f4d6822974c3c0061f" +source = "git+https://github.com/webb-tools/gadget#7e47266d904800f1d568f23cb1581256ac727b86" dependencies = [ - "anyhow", "color-eyre", "getrandom", "hex", @@ -6691,22 +6374,52 @@ dependencies = [ ] [[package]] -name = "include_dir" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd" +name = "incredible-squaring-avs" +version = "0.1.0" dependencies = [ - "include_dir_macros", -] - -[[package]] -name = "include_dir_macros" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75" -dependencies = [ - "proc-macro2", - "quote", + "alloy", + "alloy-contract", + "alloy-primitives", + "alloy-provider 0.2.1", + "alloy-pubsub", + "alloy-rpc-client 0.2.1", + "alloy-rpc-types", + "alloy-rpc-types-eth 0.2.1", + "alloy-signer 0.2.1", + "alloy-signer-local", + "alloy-sol-types", + "alloy-transport 0.2.1", + "alloy-transport-http 0.2.1", + "alloy-transport-ws", + "anvil", + "ark-bn254", + "ark-ec", + "ark-ff 0.4.2", + "async-trait", + "aws-kms", + "aws-sdk-kms", + "eigen-contracts", + "eigen-utils", + "env_logger 0.11.5", + "ethabi", + "foundry-common", + "futures", + "gadget-common", + "getrandom", + "hex", + "http-body-util", + "hyper 1.4.1", + "k256", + "lazy_static", + "log", + "prometheus", + "rand", + "reqwest 0.12.5", + "serde", + "serde_json", + "thiserror", + "tokio", + "url", ] [[package]] @@ -6928,18 +6641,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "jsonrpsee" -version = "0.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9579d0ca9fb30da026bac2f0f7d9576ec93489aeb7cd4971dd5b4617d82c79b2" -dependencies = [ - "jsonrpsee-client-transport 0.21.0", - "jsonrpsee-core 0.21.0", - "jsonrpsee-http-client 0.21.0", - "jsonrpsee-types 0.21.0", -] - [[package]] name = "jsonrpsee" version = "0.22.5" @@ -6948,7 +6649,7 @@ checksum = "cfdb12a2381ea5b2e68c3469ec604a007b367778cdb14d09612c8069ebd616ad" dependencies = [ "jsonrpsee-client-transport 0.22.5", "jsonrpsee-core 0.22.5", - "jsonrpsee-http-client 0.22.5", + "jsonrpsee-http-client", "jsonrpsee-types 0.22.5", ] @@ -6963,27 +6664,6 @@ dependencies = [ "jsonrpsee-ws-client", ] -[[package]] -name = "jsonrpsee-client-transport" -version = "0.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9f9ed46590a8d5681975f126e22531698211b926129a40a2db47cbca429220" -dependencies = [ - "futures-util", - "http 0.2.12", - "jsonrpsee-core 0.21.0", - "pin-project", - "rustls-native-certs 0.7.1", - "rustls-pki-types", - "soketto 0.7.1", - "thiserror", - "tokio", - "tokio-rustls 0.25.0", - "tokio-util", - "tracing 0.1.40", - "url", -] - [[package]] name = "jsonrpsee-client-transport" version = "0.22.5" @@ -7028,30 +6708,6 @@ dependencies = [ "url", ] -[[package]] -name = "jsonrpsee-core" -version = "0.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "776d009e2f591b78c038e0d053a796f94575d66ca4e77dd84bfc5e81419e436c" -dependencies = [ - "anyhow", - "async-lock", - "async-trait", - "beef", - "futures-timer", - "futures-util", - "hyper 0.14.30", - "jsonrpsee-types 0.21.0", - "pin-project", - "rustc-hash 1.1.0", - "serde", - "serde_json", - "thiserror", - "tokio", - "tokio-stream", - "tracing 0.1.40", -] - [[package]] name = "jsonrpsee-core" version = "0.22.5" @@ -7097,26 +6753,6 @@ dependencies = [ "tracing 0.1.40", ] -[[package]] -name = "jsonrpsee-http-client" -version = "0.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78b7de9f3219d95985eb77fd03194d7c1b56c19bce1abfcc9d07462574b15572" -dependencies = [ - "async-trait", - "hyper 0.14.30", - "hyper-rustls 0.24.2", - "jsonrpsee-core 0.21.0", - "jsonrpsee-types 0.21.0", - "serde", - "serde_json", - "thiserror", - "tokio", - "tower", - "tracing 0.1.40", - "url", -] - [[package]] name = "jsonrpsee-http-client" version = "0.22.5" @@ -7137,19 +6773,6 @@ dependencies = [ "url", ] -[[package]] -name = "jsonrpsee-types" -version = "0.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3266dfb045c9174b24c77c2dfe0084914bb23a6b2597d70c9dc6018392e1cd1b" -dependencies = [ - "anyhow", - "beef", - "serde", - "serde_json", - "thiserror", -] - [[package]] name = "jsonrpsee-types" version = "0.22.5" @@ -7251,15 +6874,6 @@ dependencies = [ "sha3-asm", ] -[[package]] -name = "kvdb" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7d770dcb02bf6835887c3a979b5107a04ff4bbde97a5f0928d27404a155add9" -dependencies = [ - "smallvec", -] - [[package]] name = "kzg-rs" version = "0.1.0" @@ -7517,12 +7131,6 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "linked-hash-map" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" - [[package]] name = "linux-raw-sys" version = "0.1.4" @@ -7575,54 +7183,6 @@ dependencies = [ "libc", ] -[[package]] -name = "macro_magic" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc33f9f0351468d26fbc53d9ce00a096c8522ecb42f19b50f34f2c422f76d21d" -dependencies = [ - "macro_magic_core", - "macro_magic_macros", - "quote", - "syn 2.0.72", -] - -[[package]] -name = "macro_magic_core" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1687dc887e42f352865a393acae7cf79d98fab6351cde1f58e9e057da89bf150" -dependencies = [ - "const-random", - "derive-syn-parse 0.2.0", - "macro_magic_core_macros", - "proc-macro2", - "quote", - "syn 2.0.72", -] - -[[package]] -name = "macro_magic_core_macros" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b02abfe41815b5bd98dbd4260173db2c116dda171dc0fe7838cb206333b83308" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.72", -] - -[[package]] -name = "macro_magic_macros" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ea28ee64b88876bf45277ed9a5817c1817df061a74f2b988971a12570e5869" -dependencies = [ - "macro_magic_core", - "quote", - "syn 2.0.72", -] - [[package]] name = "matchers" version = "0.0.1" @@ -8844,17 +8404,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "proc-macro-warning" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "834da187cfe638ae8abb0203f0b33e5ccdb02a28e7199f2f47b3e2754f50edca" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.72", -] - [[package]] name = "proc-macro2" version = "1.0.86" @@ -8945,7 +8494,7 @@ dependencies = [ [[package]] name = "protocol-macros" version = "0.1.0" -source = "git+https://github.com/webb-tools/gadget#8b88cb4e1fb6ebebcd2be4f4d6822974c3c0061f" +source = "git+https://github.com/webb-tools/gadget#7e47266d904800f1d568f23cb1581256ac727b86" dependencies = [ "proc-macro2", "quote", @@ -9193,18 +8742,6 @@ dependencies = [ "syn 2.0.72", ] -[[package]] -name = "regalloc2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80535183cae11b149d618fbd3c37e38d7cda589d82d7769e196ca9a9042d7621" -dependencies = [ - "fxhash", - "log", - "slice-group-by", - "smallvec", -] - [[package]] name = "regex" version = "1.10.6" @@ -9532,23 +9069,11 @@ dependencies = [ [[package]] name = "round-based" -version = "0.1.7" -source = "git+https://github.com/webb-tools/round-based-protocol#959126f9f6edce16d4ee95954091b93e33a83140" -dependencies = [ - "async-stream", - "futures", - "log", - "serde", - "thiserror", - "tokio", -] - -[[package]] -name = "round-based" -version = "0.2.2" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3479f80b42725325d77c7336f47548d9ab97662f3f7ab495ded03c9d65f0962" +checksum = "55f473f56ecfa6457a75c0922c4e51ad036d4a1d27b0a697ac3a9b26f74acc3b" dependencies = [ + "displaydoc", "futures-util", "phantom-type", "round-based-derive", @@ -9920,96 +9445,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "sc-allocator" -version = "23.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "log", - "sp-core", - "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "thiserror", -] - -[[package]] -name = "sc-client-api" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "fnv", - "futures", - "log", - "parity-scale-codec", - "parking_lot", - "sc-executor", - "sc-transaction-pool-api", - "sc-utils", - "sp-api", - "sp-blockchain", - "sp-consensus", - "sp-core", - "sp-database", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "sp-runtime", - "sp-state-machine", - "sp-statement-store", - "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "sp-trie", - "substrate-prometheus-endpoint", -] - -[[package]] -name = "sc-executor" -version = "0.32.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "parity-scale-codec", - "parking_lot", - "sc-executor-common", - "sc-executor-wasmtime", - "schnellru", - "sp-api", - "sp-core", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "sp-io", - "sp-panic-handler", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "sp-trie", - "sp-version", - "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "tracing 0.1.40", -] - -[[package]] -name = "sc-executor-common" -version = "0.29.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "sc-allocator", - "sp-maybe-compressed-blob", - "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "thiserror", - "wasm-instrument", -] - -[[package]] -name = "sc-executor-wasmtime" -version = "0.29.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "anyhow", - "cfg-if", - "libc", - "log", - "parking_lot", - "rustix 0.36.17", - "sc-allocator", - "sc-executor-common", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "sp-wasm-interface 20.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "wasmtime", -] - [[package]] name = "sc-keystore" version = "25.0.0" @@ -10024,48 +9459,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "sc-transaction-pool-api" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "async-trait", - "futures", - "log", - "parity-scale-codec", - "serde", - "sp-blockchain", - "sp-core", - "sp-runtime", - "thiserror", -] - -[[package]] -name = "sc-utils" -version = "14.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "async-channel 1.9.0", - "futures", - "futures-timer", - "lazy_static", - "log", - "parking_lot", - "prometheus", - "sp-arithmetic", -] - -[[package]] -name = "scale-bits" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "036575c29af9b6e4866ffb7fa055dbf623fe7a9cc159b33786de6013a6969d89" -dependencies = [ - "parity-scale-codec", - "scale-info", - "serde", -] - [[package]] name = "scale-bits" version = "0.6.0" @@ -10078,21 +9471,6 @@ dependencies = [ "serde", ] -[[package]] -name = "scale-decode" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7caaf753f8ed1ab4752c6afb20174f03598c664724e0e32628e161c21000ff76" -dependencies = [ - "derive_more", - "parity-scale-codec", - "primitive-types", - "scale-bits 0.4.0", - "scale-decode-derive 0.10.0", - "scale-info", - "smallvec", -] - [[package]] name = "scale-decode" version = "0.13.1" @@ -10102,25 +9480,12 @@ dependencies = [ "derive_more", "parity-scale-codec", "primitive-types", - "scale-bits 0.6.0", - "scale-decode-derive 0.13.1", + "scale-bits", + "scale-decode-derive", "scale-type-resolver", "smallvec", ] -[[package]] -name = "scale-decode-derive" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3475108a1b62c7efd1b5c65974f30109a598b2f45f23c9ae030acb9686966db" -dependencies = [ - "darling 0.14.4", - "proc-macro-crate 1.3.1", - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "scale-decode-derive" version = "0.13.1" @@ -10133,21 +9498,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "scale-encode" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d70cb4b29360105483fac1ed567ff95d65224a14dd275b6303ed0a654c78de5" -dependencies = [ - "derive_more", - "parity-scale-codec", - "primitive-types", - "scale-bits 0.4.0", - "scale-encode-derive 0.5.0", - "scale-info", - "smallvec", -] - [[package]] name = "scale-encode" version = "0.7.1" @@ -10157,25 +9507,12 @@ dependencies = [ "derive_more", "parity-scale-codec", "primitive-types", - "scale-bits 0.6.0", - "scale-encode-derive 0.7.1", + "scale-bits", + "scale-encode-derive", "scale-type-resolver", "smallvec", ] -[[package]] -name = "scale-encode-derive" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "995491f110efdc6bea96d6a746140e32bfceb4ea47510750a5467295a4707a25" -dependencies = [ - "darling 0.14.4", - "proc-macro-crate 1.3.1", - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "scale-encode-derive" version = "0.7.1" @@ -10225,19 +9562,6 @@ dependencies = [ "smallvec", ] -[[package]] -name = "scale-typegen" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00860983481ac590ac87972062909bef0d6a658013b592ccc0f2feb272feab11" -dependencies = [ - "proc-macro2", - "quote", - "scale-info", - "syn 2.0.72", - "thiserror", -] - [[package]] name = "scale-typegen" version = "0.8.0" @@ -10251,26 +9575,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "scale-value" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58223c7691bf0bd46b43c9aea6f0472d1067f378d574180232358d7c6e0a8089" -dependencies = [ - "base58", - "blake2", - "derive_more", - "either", - "frame-metadata 15.1.0", - "parity-scale-codec", - "scale-bits 0.4.0", - "scale-decode 0.10.0", - "scale-encode 0.5.0", - "scale-info", - "serde", - "yap", -] - [[package]] name = "scale-value" version = "0.16.1" @@ -10283,9 +9587,9 @@ dependencies = [ "either", "frame-metadata 15.1.0", "parity-scale-codec", - "scale-bits 0.6.0", - "scale-decode 0.13.1", - "scale-encode 0.7.1", + "scale-bits", + "scale-decode", + "scale-encode", "scale-info", "scale-type-resolver", "serde", @@ -10820,12 +10124,6 @@ dependencies = [ "autocfg", ] -[[package]] -name = "slice-group-by" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "826167069c09b99d56f31e9ae5c99049e932a98c9dc2dac47645b08dbbf76ba7" - [[package]] name = "smallvec" version = "1.13.2" @@ -10838,7 +10136,7 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e635339259e51ef85ac7aa29a1cd991b957047507288697a690e80ab97d07cad" dependencies = [ - "async-channel 2.3.1", + "async-channel", "async-executor", "async-fs", "async-io", @@ -10910,7 +10208,7 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5496f2d116b7019a526b1039ec2247dd172b8670633b1a64a614c9ea12c9d8c7" dependencies = [ - "async-channel 2.3.1", + "async-channel", "async-lock", "base64 0.21.7", "blake2-rfc", @@ -11064,47 +10362,14 @@ dependencies = [ "ark-bls12-381-ext", "sp-crypto-ec-utils", ] - -[[package]] -name = "sp-ark-ed-on-bls12-381-bandersnatch" -version = "0.4.2" -source = "git+https://github.com/paritytech/arkworks-substrate#caa2eed74beb885dd07c7db5f916f2281dad818f" -dependencies = [ - "ark-ed-on-bls12-381-bandersnatch-ext", - "sp-crypto-ec-utils", -] - -[[package]] -name = "sp-blockchain" -version = "28.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "futures", - "log", - "parity-scale-codec", - "parking_lot", - "schnellru", - "sp-api", - "sp-consensus", - "sp-database", - "sp-runtime", - "sp-state-machine", - "thiserror", -] - -[[package]] -name = "sp-consensus" -version = "0.32.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "async-trait", - "futures", - "log", - "sp-core", - "sp-inherents", - "sp-runtime", - "sp-state-machine", - "thiserror", + +[[package]] +name = "sp-ark-ed-on-bls12-381-bandersnatch" +version = "0.4.2" +source = "git+https://github.com/paritytech/arkworks-substrate#caa2eed74beb885dd07c7db5f916f2281dad818f" +dependencies = [ + "ark-ed-on-bls12-381-bandersnatch-ext", + "sp-crypto-ec-utils", ] [[package]] @@ -11153,24 +10418,10 @@ dependencies = [ "zeroize", ] -[[package]] -name = "sp-core-hashing" -version = "15.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e0f4990add7b2cefdeca883c0efa99bb4d912cb2196120e1500c0cc099553b0" -dependencies = [ - "blake2b_simd", - "byteorder", - "digest 0.10.7", - "sha2 0.10.8", - "sha3", - "twox-hash", -] - [[package]] name = "sp-crypto-ec-utils" version = "0.10.0" -source = "git+https://github.com/paritytech/polkadot-sdk#ce6938ae92b77b54aa367e6d367a4d490dede7c4" +source = "git+https://github.com/paritytech/polkadot-sdk#035211d707d0a74a2a768fd658160721f09d5b44" dependencies = [ "ark-bls12-377", "ark-bls12-377-ext", @@ -11224,15 +10475,6 @@ dependencies = [ "syn 2.0.72", ] -[[package]] -name = "sp-database" -version = "10.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "kvdb", - "parking_lot", -] - [[package]] name = "sp-debug-derive" version = "14.0.0" @@ -11246,7 +10488,7 @@ dependencies = [ [[package]] name = "sp-debug-derive" version = "14.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#ce6938ae92b77b54aa367e6d367a4d490dede7c4" +source = "git+https://github.com/paritytech/polkadot-sdk#035211d707d0a74a2a768fd658160721f09d5b44" dependencies = [ "proc-macro2", "quote", @@ -11267,38 +10509,13 @@ dependencies = [ [[package]] name = "sp-externalities" version = "0.25.0" -source = "git+https://github.com/paritytech/polkadot-sdk#ce6938ae92b77b54aa367e6d367a4d490dede7c4" +source = "git+https://github.com/paritytech/polkadot-sdk#035211d707d0a74a2a768fd658160721f09d5b44" dependencies = [ "environmental", "parity-scale-codec", "sp-storage 19.0.0 (git+https://github.com/paritytech/polkadot-sdk)", ] -[[package]] -name = "sp-genesis-builder" -version = "0.7.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "serde_json", - "sp-api", - "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", -] - -[[package]] -name = "sp-inherents" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "async-trait", - "impl-trait-for-tuples", - "parity-scale-codec", - "scale-info", - "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "thiserror", -] - [[package]] name = "sp-io" version = "30.0.0" @@ -11336,15 +10553,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "sp-maybe-compressed-blob" -version = "11.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "thiserror", - "zstd 0.12.4", -] - [[package]] name = "sp-metadata-ir" version = "0.6.0" @@ -11411,7 +10619,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface" version = "24.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#ce6938ae92b77b54aa367e6d367a4d490dede7c4" +source = "git+https://github.com/paritytech/polkadot-sdk#035211d707d0a74a2a768fd658160721f09d5b44" dependencies = [ "bytes", "impl-trait-for-tuples", @@ -11443,7 +10651,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface-proc-macro" version = "17.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#ce6938ae92b77b54aa367e6d367a4d490dede7c4" +source = "git+https://github.com/paritytech/polkadot-sdk#035211d707d0a74a2a768fd658160721f09d5b44" dependencies = [ "Inflector", "expander", @@ -11453,20 +10661,6 @@ dependencies = [ "syn 2.0.72", ] -[[package]] -name = "sp-staking" -version = "26.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "impl-trait-for-tuples", - "parity-scale-codec", - "scale-info", - "serde", - "sp-core", - "sp-runtime", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", -] - [[package]] name = "sp-state-machine" version = "0.35.0" @@ -11488,31 +10682,6 @@ dependencies = [ "trie-db", ] -[[package]] -name = "sp-statement-store" -version = "10.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0#851c824dc7a8e7e6db2d0c9fb29d232f2f45198a" -dependencies = [ - "aes-gcm", - "curve25519-dalek 4.1.3", - "ed25519-dalek", - "hkdf", - "parity-scale-codec", - "rand", - "scale-info", - "sha2 0.10.8", - "sp-api", - "sp-application-crypto", - "sp-core", - "sp-crypto-hashing 0.0.0", - "sp-externalities 0.25.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "sp-runtime", - "sp-runtime-interface 24.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "sp-std 14.0.0 (git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.7.0)", - "thiserror", - "x25519-dalek", -] - [[package]] name = "sp-std" version = "14.0.0" @@ -11521,7 +10690,7 @@ source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot [[package]] name = "sp-std" version = "14.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#ce6938ae92b77b54aa367e6d367a4d490dede7c4" +source = "git+https://github.com/paritytech/polkadot-sdk#035211d707d0a74a2a768fd658160721f09d5b44" [[package]] name = "sp-storage" @@ -11539,7 +10708,7 @@ dependencies = [ [[package]] name = "sp-storage" version = "19.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#ce6938ae92b77b54aa367e6d367a4d490dede7c4" +source = "git+https://github.com/paritytech/polkadot-sdk#035211d707d0a74a2a768fd658160721f09d5b44" dependencies = [ "impl-serde", "parity-scale-codec", @@ -11563,7 +10732,7 @@ dependencies = [ [[package]] name = "sp-tracing" version = "16.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#ce6938ae92b77b54aa367e6d367a4d490dede7c4" +source = "git+https://github.com/paritytech/polkadot-sdk#035211d707d0a74a2a768fd658160721f09d5b44" dependencies = [ "parity-scale-codec", "tracing 0.1.40", @@ -11639,7 +10808,7 @@ dependencies = [ [[package]] name = "sp-wasm-interface" version = "20.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk#ce6938ae92b77b54aa367e6d367a4d490dede7c4" +source = "git+https://github.com/paritytech/polkadot-sdk#035211d707d0a74a2a768fd658160721f09d5b44" dependencies = [ "impl-trait-for-tuples", "log", @@ -12074,42 +11243,6 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" -[[package]] -name = "subxt" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3323d5c27898b139d043dc1ee971f602f937b99354ee33ee933bd90e0009fbd" -dependencies = [ - "async-trait", - "base58", - "blake2", - "derivative", - "either", - "frame-metadata 16.0.0", - "futures", - "hex", - "impl-serde", - "instant", - "jsonrpsee 0.21.0", - "parity-scale-codec", - "primitive-types", - "scale-bits 0.4.0", - "scale-decode 0.10.0", - "scale-encode 0.5.0", - "scale-info", - "scale-value 0.13.0", - "serde", - "serde_json", - "sp-core-hashing", - "subxt-lightclient 0.34.0", - "subxt-macro 0.34.0", - "subxt-metadata 0.34.0", - "thiserror", - "tokio-util", - "tracing 0.1.40", - "url", -] - [[package]] name = "subxt" version = "0.37.0" @@ -12128,45 +11261,24 @@ dependencies = [ "parity-scale-codec", "primitive-types", "reconnecting-jsonrpsee-ws-client", - "scale-bits 0.6.0", - "scale-decode 0.13.1", - "scale-encode 0.7.1", + "scale-bits", + "scale-decode", + "scale-encode", "scale-info", - "scale-value 0.16.1", + "scale-value", "serde", "serde_json", "sp-crypto-hashing 0.1.0", "subxt-core", - "subxt-lightclient 0.37.0", - "subxt-macro 0.37.0", - "subxt-metadata 0.37.0", + "subxt-lightclient", + "subxt-macro", + "subxt-metadata", "thiserror", "tokio-util", "tracing 0.1.40", "url", ] -[[package]] -name = "subxt-codegen" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d0e58c3f88651cff26aa52bae0a0a85f806a2e923a20eb438c16474990743ea" -dependencies = [ - "frame-metadata 16.0.0", - "heck 0.4.1", - "hex", - "jsonrpsee 0.21.0", - "parity-scale-codec", - "proc-macro2", - "quote", - "scale-info", - "scale-typegen 0.1.1", - "subxt-metadata 0.34.0", - "syn 2.0.72", - "thiserror", - "tokio", -] - [[package]] name = "subxt-codegen" version = "0.37.0" @@ -12181,8 +11293,8 @@ dependencies = [ "proc-macro2", "quote", "scale-info", - "scale-typegen 0.8.0", - "subxt-metadata 0.37.0", + "scale-typegen", + "subxt-metadata", "syn 2.0.72", "thiserror", "tokio", @@ -12203,32 +11315,15 @@ dependencies = [ "impl-serde", "parity-scale-codec", "primitive-types", - "scale-bits 0.6.0", - "scale-decode 0.13.1", - "scale-encode 0.7.1", + "scale-bits", + "scale-decode", + "scale-encode", "scale-info", - "scale-value 0.16.1", + "scale-value", "serde", "serde_json", "sp-crypto-hashing 0.1.0", - "subxt-metadata 0.37.0", - "tracing 0.1.40", -] - -[[package]] -name = "subxt-lightclient" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecec7066ba7bc0c3608fcd1d0c7d9584390990cd06095b6ae4f114f74c4b8550" -dependencies = [ - "futures", - "futures-util", - "serde", - "serde_json", - "smoldot-light", - "thiserror", - "tokio", - "tokio-stream", + "subxt-metadata", "tracing 0.1.40", ] @@ -12249,21 +11344,6 @@ dependencies = [ "tracing 0.1.40", ] -[[package]] -name = "subxt-macro" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "365251668613323064803427af8c7c7bc366cd8b28e33639640757669dafebd5" -dependencies = [ - "darling 0.20.10", - "parity-scale-codec", - "proc-macro-error", - "quote", - "scale-typegen 0.1.1", - "subxt-codegen 0.34.0", - "syn 2.0.72", -] - [[package]] name = "subxt-macro" version = "0.37.0" @@ -12274,24 +11354,11 @@ dependencies = [ "parity-scale-codec", "proc-macro-error", "quote", - "scale-typegen 0.8.0", - "subxt-codegen 0.37.0", + "scale-typegen", + "subxt-codegen", "syn 2.0.72", ] -[[package]] -name = "subxt-metadata" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c02aca8d39a1f6c55fff3a8fd81557d30a610fedc1cef03f889a81bc0f8f0b52" -dependencies = [ - "frame-metadata 16.0.0", - "parity-scale-codec", - "scale-info", - "sp-core-hashing", - "thiserror", -] - [[package]] name = "subxt-metadata" version = "0.37.0" @@ -12307,11 +11374,12 @@ dependencies = [ [[package]] name = "subxt-signer" -version = "0.34.0" +version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f88a76a5d114bfae2f6f9cc1491c46173ecc3fb2b9e53948eb3c8d43d4b43ab5" +checksum = "f49888ae6ae90fe01b471193528eea5bd4ed52d8eecd2d13f4a2333b87388850" dependencies = [ "bip39", + "cfg-if", "hex", "hmac 0.12.1", "parity-scale-codec", @@ -12320,9 +11388,8 @@ dependencies = [ "schnorrkel", "secrecy", "sha2 0.10.8", - "sp-core-hashing", - "subxt 0.34.0", - "thiserror", + "sp-crypto-hashing 0.1.0", + "subxt-core", "zeroize", ] @@ -12521,11 +11588,12 @@ dependencies = [ [[package]] name = "tangle-subxt" version = "0.1.4" -source = "git+https://github.com/webb-tools/tangle.git?branch=jobs/v2#c6975cc64d71e6b2752affa064aa0ac66ea68c86" +source = "git+https://github.com/webb-tools/tangle.git#cc5105c840cd36eb8e37de2d932bcc201cfc7ea2" dependencies = [ "parity-scale-codec", "scale-info", - "subxt 0.37.0", + "subxt", + "subxt-signer", ] [[package]] @@ -12847,15 +11915,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "toml" -version = "0.5.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" -dependencies = [ - "serde", -] - [[package]] name = "toml" version = "0.8.19" @@ -12973,7 +12032,7 @@ dependencies = [ [[package]] name = "tracing" version = "0.2.0" -source = "git+https://github.com/tokio-rs/tracing#acf92ab944f6fa0c9dee0302a334d4fdf0cfe52a" +source = "git+https://github.com/tokio-rs/tracing#527b4f66a604e7a6baa6aa7536428e3a303ba3c8" dependencies = [ "pin-project-lite", "tracing-attributes 0.2.0", @@ -12994,7 +12053,7 @@ dependencies = [ [[package]] name = "tracing-attributes" version = "0.2.0" -source = "git+https://github.com/tokio-rs/tracing#acf92ab944f6fa0c9dee0302a334d4fdf0cfe52a" +source = "git+https://github.com/tokio-rs/tracing#527b4f66a604e7a6baa6aa7536428e3a303ba3c8" dependencies = [ "proc-macro2", "quote", @@ -13014,7 +12073,7 @@ dependencies = [ [[package]] name = "tracing-core" version = "0.2.0" -source = "git+https://github.com/tokio-rs/tracing#acf92ab944f6fa0c9dee0302a334d4fdf0cfe52a" +source = "git+https://github.com/tokio-rs/tracing#527b4f66a604e7a6baa6aa7536428e3a303ba3c8" dependencies = [ "once_cell", ] @@ -13096,7 +12155,7 @@ dependencies = [ [[package]] name = "tracing-subscriber" version = "0.3.0" -source = "git+https://github.com/tokio-rs/tracing#acf92ab944f6fa0c9dee0302a334d4fdf0cfe52a" +source = "git+https://github.com/tokio-rs/tracing#527b4f66a604e7a6baa6aa7536428e3a303ba3c8" dependencies = [ "tracing-core 0.2.0", ] @@ -13201,12 +12260,6 @@ dependencies = [ "syn 2.0.72", ] -[[package]] -name = "tt-call" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4f195fd851901624eee5a58c4bb2b4f06399148fcd0ed336e6f1cb60a9881df" - [[package]] name = "tungstenite" version = "0.20.1" @@ -13682,15 +12735,6 @@ dependencies = [ "syn 2.0.72", ] -[[package]] -name = "wasm-instrument" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a47ecb37b9734d1085eaa5ae1a81e60801fd8c28d4cabdd8aedb982021918bc" -dependencies = [ - "parity-wasm", -] - [[package]] name = "wasmi" version = "0.31.2" @@ -13757,12 +12801,9 @@ dependencies = [ "once_cell", "paste", "psm", - "rayon", "serde", "target-lexicon", "wasmparser", - "wasmtime-cache", - "wasmtime-cranelift", "wasmtime-environ", "wasmtime-jit", "wasmtime-runtime", @@ -13778,63 +12819,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "wasmtime-cache" -version = "8.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c86437fa68626fe896e5afc69234bb2b5894949083586535f200385adfd71213" -dependencies = [ - "anyhow", - "base64 0.21.7", - "bincode", - "directories-next", - "file-per-thread-logger", - "log", - "rustix 0.36.17", - "serde", - "sha2 0.10.8", - "toml 0.5.11", - "windows-sys 0.45.0", - "zstd 0.11.2+zstd.1.5.2", -] - -[[package]] -name = "wasmtime-cranelift" -version = "8.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1cefde0cce8cb700b1b21b6298a3837dba46521affd7b8c38a9ee2c869eee04" -dependencies = [ - "anyhow", - "cranelift-codegen", - "cranelift-entity", - "cranelift-frontend", - "cranelift-native", - "cranelift-wasm", - "gimli 0.27.3", - "log", - "object 0.30.4", - "target-lexicon", - "thiserror", - "wasmparser", - "wasmtime-cranelift-shared", - "wasmtime-environ", -] - -[[package]] -name = "wasmtime-cranelift-shared" -version = "8.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd041e382ef5aea1b9fc78442394f1a4f6d676ce457e7076ca4cb3f397882f8b" -dependencies = [ - "anyhow", - "cranelift-codegen", - "cranelift-native", - "gimli 0.27.3", - "object 0.30.4", - "target-lexicon", - "wasmtime-environ", -] - [[package]] name = "wasmtime-environ" version = "8.0.1" @@ -13872,7 +12856,6 @@ dependencies = [ "serde", "target-lexicon", "wasmtime-environ", - "wasmtime-jit-debug", "wasmtime-jit-icache-coherence", "wasmtime-runtime", "windows-sys 0.45.0", @@ -13884,9 +12867,7 @@ version = "8.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e0554b84c15a27d76281d06838aed94e13a77d7bf604bbbaf548aa20eb93846" dependencies = [ - "object 0.30.4", "once_cell", - "rustix 0.36.17", ] [[package]] @@ -14428,7 +13409,7 @@ dependencies = [ "pbkdf2 0.11.0", "sha1", "time", - "zstd 0.11.2+zstd.1.5.2", + "zstd", ] [[package]] @@ -14468,16 +13449,7 @@ version = "0.11.2+zstd.1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20cc960326ece64f010d2d2107537f26dc589a6573a316bd5b1dba685fa5fde4" dependencies = [ - "zstd-safe 5.0.2+zstd.1.5.2", -] - -[[package]] -name = "zstd" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a27595e173641171fc74a1232b7b1c7a7cb6e18222c11e9dfb9888fa424c53c" -dependencies = [ - "zstd-safe 6.0.6", + "zstd-safe", ] [[package]] @@ -14490,16 +13462,6 @@ dependencies = [ "zstd-sys", ] -[[package]] -name = "zstd-safe" -version = "6.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee98ffd0b48ee95e6c5168188e44a54550b1564d9d530ee21d5f0eaed1069581" -dependencies = [ - "libc", - "zstd-sys", -] - [[package]] name = "zstd-sys" version = "2.0.13+zstd.1.5.6" diff --git a/avs/incredible-squaring-avs/Cargo.toml b/avs/incredible-squaring-avs/Cargo.toml index 18d9906..42a944f 100644 --- a/avs/incredible-squaring-avs/Cargo.toml +++ b/avs/incredible-squaring-avs/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "eigen-gadget" +name = "incredible-squaring-avs" version = "0.1.0" authors.workspace = true edition.workspace = true diff --git a/avs/incredible-squaring-avs/contracts/lib/eigenlayer-middleware b/avs/incredible-squaring-avs/contracts/lib/eigenlayer-middleware index 7d49b51..3b96caf 160000 --- a/avs/incredible-squaring-avs/contracts/lib/eigenlayer-middleware +++ b/avs/incredible-squaring-avs/contracts/lib/eigenlayer-middleware @@ -1 +1 @@ -Subproject commit 7d49b5181b09198ed275783453aa082bb3766990 +Subproject commit 3b96cafa862902974b8c351a86f761c53453b269 diff --git a/avs/incredible-squaring-avs/contracts/lib/forge-std b/avs/incredible-squaring-avs/contracts/lib/forge-std index 07263d1..6e05729 160000 --- a/avs/incredible-squaring-avs/contracts/lib/forge-std +++ b/avs/incredible-squaring-avs/contracts/lib/forge-std @@ -1 +1 @@ -Subproject commit 07263d193d621c4b2b0ce8b4d54af58f6957d97d +Subproject commit 6e05729b76f1ae0d437e74951aef1ca987788ab3 diff --git a/avs/incredible-squaring-avs/src/avs/mod.rs b/avs/incredible-squaring-avs/src/avs/mod.rs index 443ec4c..367b4d3 100644 --- a/avs/incredible-squaring-avs/src/avs/mod.rs +++ b/avs/incredible-squaring-avs/src/avs/mod.rs @@ -21,7 +21,7 @@ sol!( #[derive(Debug)] #[sol(rpc)] IncredibleSquaringTaskManager, - "contracts/out/IncredibleSquaringTaskManager.sol/IncredibleSquaringTaskManager.json" + "./contracts/out/IncredibleSquaringTaskManager.sol/IncredibleSquaringTaskManager.json" ); sol!( @@ -29,7 +29,7 @@ sol!( #[derive(Debug)] #[sol(rpc)] IncredibleSquaringServiceManager, - "contracts/out/IncredibleSquaringServiceManager.sol/IncredibleSquaringServiceManager.json" + "./contracts/out/IncredibleSquaringServiceManager.sol/IncredibleSquaringServiceManager.json" ); sol!( @@ -37,7 +37,7 @@ sol!( #[derive(Debug)] #[sol(rpc)] Erc20Mock, - "contracts/out/ERC20Mock.sol/ERC20Mock.json" + "./contracts/out/ERC20Mock.sol/ERC20Mock.json" ); #[derive(Debug, Clone)] diff --git a/contracts/lib/eigenlayer-middleware b/contracts/lib/eigenlayer-middleware index 7d49b51..3b96caf 160000 --- a/contracts/lib/eigenlayer-middleware +++ b/contracts/lib/eigenlayer-middleware @@ -1 +1 @@ -Subproject commit 7d49b5181b09198ed275783453aa082bb3766990 +Subproject commit 3b96cafa862902974b8c351a86f761c53453b269 diff --git a/contracts/lib/forge-std b/contracts/lib/forge-std index 07263d1..f73c73d 160000 --- a/contracts/lib/forge-std +++ b/contracts/lib/forge-std @@ -1 +1 @@ -Subproject commit 07263d193d621c4b2b0ce8b4d54af58f6957d97d +Subproject commit f73c73d2018eb6a111f35e4dae7b4f27401e9421 diff --git a/contracts/src/lib.rs b/contracts/src/lib.rs index b60c798..0de23e8 100644 --- a/contracts/src/lib.rs +++ b/contracts/src/lib.rs @@ -2,191 +2,191 @@ use alloy_sol_types::sol; sol!( #[allow(missing_docs)] - #[derive(Debug)] #[sol(rpc)] - BlsApkRegistry, - "out/BLSApkRegistry.sol/BLSApkRegistry.json" + AVSDirectory, + "./out/AVSDirectory.sol/AVSDirectory.json" ); sol!( #[allow(missing_docs)] #[derive(Debug)] #[sol(rpc)] - IBlsApkRegistry, - "out/IBLSApkRegistry.sol/IBLSApkRegistry.json" + BlsApkRegistry, + "./out/BLSApkRegistry.sol/BLSApkRegistry.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - ServiceManagerBase, - "out/ServiceManagerBase.sol/ServiceManagerBase.json" + DelegationManager, + "./out/DelegationManager.sol/DelegationManager.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - StakeRegistry, - "out/StakeRegistry.sol/StakeRegistry.json" + EigenPod, + "./lib/eigenlayer-middleware/out/EigenPod.sol/EigenPod.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - IStakeRegistry, - "out/IStakeRegistry.sol/IStakeRegistry.json" + EigenPodManager, + "./out/EigenPodManager.sol/EigenPodManager.json" ); sol!( - #[allow(missing_docs, clippy::too_many_arguments)] + #[allow(missing_docs)] #[sol(rpc)] - RegistryCoordinator, - "out/RegistryCoordinator.sol/RegistryCoordinator.json" + EigenStrategy, + "./lib/eigenlayer-middleware/lib/eigenlayer-contracts/out//EigenStrategy.sol/EigenStrategy.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - OperatorStateRetriever, - "out/OperatorStateRetriever.sol/OperatorStateRetriever.json" + EmptyContract, + "./lib/eigenlayer-middleware/out/EmptyContract.sol/EmptyContract.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - AVSDirectory, - "out/AVSDirectory.sol/AVSDirectory.json" + ERC20Mock, + "./lib/eigenlayer-middleware/lib/eigenlayer-contracts/out/ERC20Mock.sol/ERC20Mock.json" ); sol!( #[allow(missing_docs)] + #[derive(Debug)] #[sol(rpc)] - IAVSDirectory, - "out/IAVSDirectory.sol/IAVSDirectory.json" + IBlsApkRegistry, + "./out/IBLSApkRegistry.sol/IBLSApkRegistry.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - DelegationManager, - "out/DelegationManager.sol/DelegationManager.json" + IAVSDirectory, + "./out/IAVSDirectory.sol/IAVSDirectory.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] IDelegationManager, - "out/IDelegationManager.sol/IDelegationManager.json" + "./out/IDelegationManager.sol/IDelegationManager.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - ISlasher, - "out/ISlasher.sol/ISlasher.json" + IERC20, + "./out/IERC20.sol/IERC20.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - IStrategy, - "out/IStrategy.sol/IStrategy.json" + IIndexRegistry, + "./out/IIndexRegistry.sol/IIndexRegistry.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - IERC20, - "out/IERC20.sol/IERC20.json" + IndexRegistry, + "./lib/eigenlayer-middleware/out/IndexRegistry.sol/IndexRegistry.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - IIndexRegistry, - "out/IIndexRegistry.sol/IIndexRegistry.json" + IStakeRegistry, + "./out/IStakeRegistry.sol/IStakeRegistry.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - IndexRegistry, - "lib/eigenlayer-middleware/out/IndexRegistry.sol/IndexRegistry.json" + ISlasher, + "./out/ISlasher.sol/ISlasher.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - StrategyManager, - "out/StrategyManager.sol/StrategyManager.json" + IStrategy, + "./out/IStrategy.sol/IStrategy.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] IStrategyManager, - "out/IStrategyManager.sol/IStrategyManager.json" + "./out/IStrategyManager.sol/IStrategyManager.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - EigenPodManager, - "out/EigenPodManager.sol/EigenPodManager.json" + OperatorStateRetriever, + "./out/OperatorStateRetriever.sol/OperatorStateRetriever.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - EigenStrategy, - "lib/eigenlayer-contracts/out/EigenStrategy.sol/EigenStrategy.json" + PauserRegistry, + "./lib/eigenlayer-middleware/out/IPauserRegistry.sol/IPauserRegistry.json" ); sol!( - #[allow(missing_docs)] + #[allow(missing_docs, clippy::too_many_arguments)] #[sol(rpc)] - EigenPod, - "lib/eigenlayer-contracts/out/EigenPod.sol/EigenPod.json" + RegistryCoordinator, + "./out/RegistryCoordinator.sol/RegistryCoordinator.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - PauserRegistry, - "lib/eigenlayer-middleware/out/IPauserRegistry.sol/IPauserRegistry.json" + ProxyAdmin, + "./lib/eigenlayer-middleware/out/ProxyAdmin.sol/ProxyAdmin.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - ProxyAdmin, - "lib/eigenlayer-contracts/out/ProxyAdmin.sol/ProxyAdmin.json" + ServiceManagerBase, + "./out/ServiceManagerBase.sol/ServiceManagerBase.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - TransparentUpgradeableProxy, - "lib/eigenlayer-contracts/out/TransparentUpgradeableProxy.sol/TransparentUpgradeableProxy.json" + StakeRegistry, + "./out/StakeRegistry.sol/StakeRegistry.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] StrategyBaseTVLLimits, - "lib/eigenlayer-contracts/out/StrategyBaseTVLLimits.sol/StrategyBaseTVLLimits.json" + "./lib/eigenlayer-middleware/lib/eigenlayer-contracts/out/StrategyBaseTVLLimits.sol/StrategyBaseTVLLimits.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - ERC20Mock, - "lib/eigenlayer-contracts/out/ERC20Mock.sol/ERC20Mock.json" + StrategyManager, + "./out/StrategyManager.sol/StrategyManager.json" ); sol!( #[allow(missing_docs)] #[sol(rpc)] - EmptyContract, - "lib/eigenlayer-contracts/out/EmptyContract.sol/EmptyContract.json" + TransparentUpgradeableProxy, + "./lib/eigenlayer-middleware/out/TransparentUpgradeableProxy.sol/TransparentUpgradeableProxy.json" ); diff --git a/utils/src/el_contracts/reader.rs b/utils/src/el_contracts/reader.rs index 75234c6..e284465 100644 --- a/utils/src/el_contracts/reader.rs +++ b/utils/src/el_contracts/reader.rs @@ -89,7 +89,7 @@ impl ElReader for ElChainContractManager { .map(|details| details._0)?; Ok(Operator { address: operator.address, - earnings_receiver_address: details.__deprecated_earningsReceiver, + earnings_receiver_address: details.earningsReceiver, staker_opt_out_window_blocks: details.stakerOptOutWindowBlocks, delegation_approver_address: details.delegationApprover, ..operator.clone() diff --git a/utils/src/el_contracts/writer.rs b/utils/src/el_contracts/writer.rs index 5b20ff8..a0be222 100644 --- a/utils/src/el_contracts/writer.rs +++ b/utils/src/el_contracts/writer.rs @@ -38,7 +38,7 @@ impl ElWriter for ElChainContractManager { log::info!("registering operator {} to EigenLayer", operator.address); let op_details = DelegationManager::OperatorDetails { - __deprecated_earningsReceiver: operator.earnings_receiver_address, + earningsReceiver: operator.earnings_receiver_address, stakerOptOutWindowBlocks: operator.staker_opt_out_window_blocks, delegationApprover: operator.delegation_approver_address, }; @@ -70,7 +70,7 @@ impl ElWriter for ElChainContractManager { ); let op_details = DelegationManager::OperatorDetails { - __deprecated_earningsReceiver: operator.earnings_receiver_address, + earningsReceiver: operator.earnings_receiver_address, stakerOptOutWindowBlocks: operator.staker_opt_out_window_blocks, delegationApprover: operator.delegation_approver_address, }; From 6290e6226ef5dde90a7dc685ead6f5e593a8f673 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Mon, 5 Aug 2024 16:08:21 -0500 Subject: [PATCH 04/43] Add simple README --- README.md | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..c9c2192 --- /dev/null +++ b/README.md @@ -0,0 +1,78 @@ +# EigenSDK-RS + +[![Validate PR](https://github.com/webb-tools/gadget/actions/workflows/validate_pr.yml/badge.svg)](https://github.com/webb-tools/gadget/actions/workflows/validate_pr.yml) +[![Rust Version](https://img.shields.io/badge/rust-1.74.0%2B-blue.svg)](https://www.rust-lang.org) +--- + +[//]: # ([![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/Apache-2.0)) + +[//]: # (---) + +Welcome to EigenSDK-RS, the Rust port of Layr-labs' EigenSDK-GO. This SDK is a high-performance, reliable, and efficient library designed to interact with the Eigen Network. It integrates seamlessly with Eigen's ecosystem while leveraging the many advantages of Rust. + +As this SDK is currently under active development, instability should be expected. + +## Table of Contents +- [**Features**](#features) +- [**Getting** Started](#getting-started) +- [**Testing**](#testing) +- [**Documentation**](#documentation) +- [**Contributing**](#contributing) + +[//]: # (- [**License**](#license)) + +## Features + +- **High Performance**: Built with Rust to ensure maximum efficiency and speed. +- **Type Safety**: Leverages Rust's strong type system for robust code. +- **Concurrency**: Utilizes Rust's concurrency model for safe multi-threaded operations. +- **Compatibility**: Full feature parity with the Go implementation, making it easy to port applications from Go to Rust. +- **Comprehensive API**: Complete access to the Eigen network functionalities. + +## Getting Started + +### Installation + +1. Clone the repository: + +```bash +git clone https://github.com/webb-tools/eigensdk-rs/ +cd eigensdk-rs +``` + +2. Build the project: + +```bash +cargo build --release +``` + +### Running an AVS + +[//]: # (#TODO: Commands to run) +```bash + +``` + +## Testing +This repository both contains tests for the included AVSs and provides the tools necessary to test custom AVSs you build with this SDK. + +### Testing on a Local Testnet with Anvil +To run the tests, use the following command: +```bash + +``` + +## Contributing + +To contribute: + +1. Fork the repository. +2. Create a new branch. +3. Make your changes and ensure tests pass. +4. Submit a pull request with a detailed description of your changes. + +[//]: # (## License) + +[//]: # (## Contact) + +[//]: # (If you have any questions or need further information, please contact the developers [here](https://webb.tools/)) From b8cb8d5e826655791ce89b12bf295deb7168c8fc Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Mon, 5 Aug 2024 19:28:48 -0500 Subject: [PATCH 05/43] More registration and signing changes --- .../src/aggregator/mod.rs | 28 ++--- avs/incredible-squaring-avs/src/avs/mod.rs | 13 +-- avs/incredible-squaring-avs/src/operator.rs | 87 ++------------ .../src/TangleValidatorServiceManager.sol | 4 +- avs/tangle-avs/src/lib.rs | 6 +- avs/tangle-avs/src/operator.rs | 76 +----------- utils/src/avs_registry/writer.rs | 108 +++++++++++++++--- utils/src/el_contracts/reader.rs | 1 - utils/src/el_contracts/writer.rs | 3 - 9 files changed, 124 insertions(+), 202 deletions(-) diff --git a/avs/incredible-squaring-avs/src/aggregator/mod.rs b/avs/incredible-squaring-avs/src/aggregator/mod.rs index 3b6f6a2..f0c5814 100644 --- a/avs/incredible-squaring-avs/src/aggregator/mod.rs +++ b/avs/incredible-squaring-avs/src/aggregator/mod.rs @@ -1,5 +1,13 @@ -use std::{collections::HashMap, convert::Infallible, sync::Arc, time::Duration}; - +use crate::{ + avs::{ + writer::IncredibleSquaringWriter, + IncredibleSquaringContractManager, + IncredibleSquaringTaskManager::{self, Task, TaskResponse}, + SetupConfig, SignedTaskResponse, + }, + get_task_response_digest, + operator::OperatorError, +}; use alloy_primitives::U256; use alloy_sol_types::SolType; use eigen_utils::{ @@ -21,23 +29,13 @@ use hyper::{ service::service_fn, Method, Request, Response, StatusCode, }; +use std::{collections::HashMap, convert::Infallible, sync::Arc, time::Duration}; use tokio::{ net::TcpListener, sync::{broadcast, RwLock}, time::interval, }; -use crate::{ - avs::{ - writer::IncredibleSquaringWriter, - IncredibleSquaringContractManager, - IncredibleSquaringTaskManager::{self, Task, TaskResponse}, - SetupConfig, SignedTaskResponse, - }, - get_task_response_digest, - operator::OperatorError, -}; - // Constants pub const TASK_CHALLENGE_WINDOW_BLOCK: u64 = 100; pub const BLOCK_TIME_SECONDS: u64 = 12; @@ -45,8 +43,6 @@ pub const BLOCK_TIME_SECONDS: u64 = 12; pub const QUORUM_THRESHOLD_NUMERATOR: u8 = 100; pub const QUORUM_THRESHOLD_DENOMINATOR: u8 = 100; pub const QUERY_FILTER_FROM_BLOCK: u64 = 1; - -// We only use a single quorum (quorum 0) for incredible squaring pub const QUORUM_NUMBERS: &[QuorumNum] = &[QuorumNum(0)]; #[derive(Clone)] @@ -58,7 +54,6 @@ where server_ip_port_addr: String, incredible_squaring_contract_manager: IncredibleSquaringContractManager, bls_aggregation_service: BlsAggregatorService, - // bls_aggregation_responses: Receiver, tasks: Arc>>, task_responses: Arc>>>, } @@ -100,7 +95,6 @@ where server_ip_port_addr, incredible_squaring_contract_manager, bls_aggregation_service, - // bls_aggregation_responses: rx, tasks: Arc::new(RwLock::new(HashMap::new())), task_responses: Arc::new(RwLock::new(HashMap::new())), }) diff --git a/avs/incredible-squaring-avs/src/avs/mod.rs b/avs/incredible-squaring-avs/src/avs/mod.rs index 367b4d3..c2fae0d 100644 --- a/avs/incredible-squaring-avs/src/avs/mod.rs +++ b/avs/incredible-squaring-avs/src/avs/mod.rs @@ -6,7 +6,6 @@ use alloy_primitives::{Address, Bytes, U256}; use alloy_provider::Provider; use alloy_rpc_types::{Log, TransactionReceipt}; use alloy_sol_types::sol; - use eigen_contracts::RegistryCoordinator; use eigen_utils::{ crypto::bls::{G1Point, Signature}, @@ -82,28 +81,18 @@ impl IncredibleSquaringContractManager { eth_client_ws: T::PW, signer: T::S, ) -> Result { - log::info!("Building IncredibleSquaringContractManager"); let registry_coordinator = RegistryCoordinator::new(registry_coordinator_addr, eth_client_http.clone()); - let result = eth_client_http - .get_code_at(registry_coordinator_addr) - .await - .unwrap(); - log::info!("Registry Coordinator Code: {:?}", result); - - log::info!("Built RegistryCoordinator"); let service_manager_addr = registry_coordinator.serviceManager().call().await?._0; - log::info!("Found Service Manager: {:?}", service_manager_addr); let service_manager = IncredibleSquaringServiceManager::new(service_manager_addr, eth_client_http.clone()); - log::info!("Built Service Manager"); + let task_manager_addr = service_manager .incredibleSquaringTaskManager() .call() .await? ._0; - log::info!("Found Task Manager: {:?}", task_manager_addr); Ok(Self { task_manager_addr, diff --git a/avs/incredible-squaring-avs/src/operator.rs b/avs/incredible-squaring-avs/src/operator.rs index d3d2f44..37bb92c 100644 --- a/avs/incredible-squaring-avs/src/operator.rs +++ b/avs/incredible-squaring-avs/src/operator.rs @@ -186,22 +186,9 @@ impl Operator { signer: T::S, ) -> Result { let _metrics_reg = Registry::new(); - // let avs_and_eigen_metrics = Metrics::new(AVS_NAME, eigen_metrics, &metrics_reg); let node_api = NodeApi::new(AVS_NAME, SEM_VER, &config.node_api_ip_port_address); - // let eth_rpc_client = ProviderBuilder::default() - // .with_recommended_fillers() - // .on_http( - // Url::parse(&config.eth_rpc_url) - // .map_err(|e| OperatorError::HttpEthClientError(e.to_string()))?, - // ); - // let eth_ws_client = ProviderBuilder::default() - // .with_recommended_fillers() - // .on_ws(WsConnect::new(&config.eth_ws_url)) - // .await - // .map_err(|e| AvsError::from(e))?; - log::info!("About to read BLS key"); let bls_key_password = std::env::var("OPERATOR_BLS_KEY_PASSWORD").unwrap_or_else(|_| "".to_string()); @@ -312,13 +299,6 @@ impl Operator { let mut salt = [0u8; 32]; rand::thread_rng().fill(&mut salt); let sig_salt = FixedBytes::from_slice(&salt); - // let expiry = aliases::U256::from( - // SystemTime::now() - // .duration_since(UNIX_EPOCH) - // .unwrap() - // .as_secs() - // + 3600, - // ); let current_block_number = eth_client_http.get_block_number().await.unwrap(); let expiry: U256 = U256::from(current_block_number + 20); let quorum_nums = Bytes::from(vec![0]); @@ -329,7 +309,6 @@ impl Operator { expiry, &bls_keypair, quorum_nums, - // "ws://127.0.0.1:33125".to_string(), config.eth_rpc_url.clone(), ) .await; @@ -1022,7 +1001,11 @@ mod tests { #[tokio::test] async fn test_anvil() { env_logger::init(); + + // // Runs new Anvil Testnet - used for deploying programmatically in rust // let contract_addresses = run_anvil_testnet().await; + + // // Runs saved Anvil Testnet - loads from saved chain state JSON file // let chain = eigen_utils::test_utils::local_chain::LocalEvmChain::new_with_chain_state( // 31337, // String::from("eigen-testnet"), @@ -1046,6 +1029,7 @@ mod tests { operator: account_two, }; + // Implementation version of addresses // let contract_addresses = ContractAddresses { // service_manager: address!("84eA74d481Ee0A5332c457a4d796187F6Ba67fEB"), // registry_coordinator: address!("9d4454B023096f34B160D6B654540c56A1F81688"), @@ -1079,8 +1063,13 @@ mod tests { let operator_info_service = OperatorInfoService {}; + let hex_key = + hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d") + .unwrap(); + let secret_key = SecretKey::from_slice(&hex_key).unwrap(); + let signing_key = SigningKey::from(secret_key.clone()); let signer = EigenGadgetSigner { - signer: PrivateKeySigner::random(), + signer: PrivateKeySigner::from_signing_key(signing_key), }; println!("Creating HTTP Provider..."); @@ -1122,60 +1111,6 @@ mod tests { operator.start().await.unwrap(); } - #[tokio::test] - async fn test_load_issue() { - env_logger::init(); - - let http_endpoint = "http://127.0.0.1:8545"; - let ws_endpoint = "ws://127.0.0.1:8545"; - - let provider = ProviderBuilder::new() - .with_recommended_fillers() - .on_http(http_endpoint.parse().unwrap()) - .root() - .clone() - .boxed(); - - // let ws_provider = ProviderBuilder::new() - // .with_recommended_fillers() - // .on_ws(WsConnect::new(ws_endpoint)) - // .await - // .unwrap() - // .root() - // .clone() - // .boxed(); - - let registry_coordinator_addr = address!("a82fF9aFd8f496c3d6ac40E2a0F282E47488CFc9"); - let registry_coordinator_implementation_addr = - address!("9d4454B023096f34B160D6B654540c56A1F81688"); - - // let registry_coordinator = RegistryCoordinator::new(registry_coordinator_addr, provider.clone()); - let registry_coordinator_code = provider - .get_code_at(registry_coordinator_addr) - .await - .unwrap(); - // println!("Code at Registry Coordinator Address: {:?}", registry_coordinator_code); - let registry_coordinator = - RegistryCoordinator::new(registry_coordinator_addr, provider.clone()); - let response_one = registry_coordinator.owner().call().await.unwrap(); - println!("Owner from RC: {:?}", response_one._0); - - // let registry_coordinator = RegistryCoordinator::new(registry_coordinator_implementation_addr, provider.clone()); - let registry_coordinator_implementation_code = provider - .get_code_at(registry_coordinator_implementation_addr) - .await - .unwrap(); - // println!("Code at Registry Coordinator Implementation Address: {:?}", registry_coordinator_implementation_code); - let registry_coordinator_implementation = - RegistryCoordinator::new(registry_coordinator_implementation_addr, provider.clone()); - let response_two = registry_coordinator_implementation - .owner() - .call() - .await - .unwrap(); - println!("Owner from RC Implementation: {:?}", response_two._0); - } - #[tokio::test] async fn test_start_chain_from_state() { env_logger::init(); diff --git a/avs/tangle-avs/contracts/src/TangleValidatorServiceManager.sol b/avs/tangle-avs/contracts/src/TangleValidatorServiceManager.sol index 3d3f805..5bb637e 100644 --- a/avs/tangle-avs/contracts/src/TangleValidatorServiceManager.sol +++ b/avs/tangle-avs/contracts/src/TangleValidatorServiceManager.sol @@ -1,9 +1,9 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; -import "eigenlayer-contracts/src/contracts/libraries/BytesLib.sol"; +import "./eigenlayer-contracts/src/contracts/libraries/BytesLib.sol"; import "./ITangleValidatorTaskManager.sol"; -import "eigenlayer-middleware/src/ServiceManagerBase.sol"; +import "./eigenlayer-middleware/src/ServiceManagerBase.sol"; /** * @title Primary entrypoint for procuring services from TangleValidator. diff --git a/avs/tangle-avs/src/lib.rs b/avs/tangle-avs/src/lib.rs index b740c42..31daf96 100644 --- a/avs/tangle-avs/src/lib.rs +++ b/avs/tangle-avs/src/lib.rs @@ -7,7 +7,7 @@ sol!( #[derive(Debug)] #[sol(rpc)] TangleValidatorTaskManager, - "contracts/out/TangleValidatorTaskManager.sol/TangleValidatorTaskManager.json" + "./contracts/out/TangleValidatorTaskManager.sol/TangleValidatorTaskManager.json" ); sol!( @@ -15,7 +15,7 @@ sol!( #[derive(Debug)] #[sol(rpc)] TangleValidatorServiceManager, - "contracts/out/TangleValidatorServiceManager.sol/TangleValidatorServiceManager.json" + "./contracts/out/TangleValidatorServiceManager.sol/TangleValidatorServiceManager.json" ); sol!( @@ -23,5 +23,5 @@ sol!( #[derive(Debug)] #[sol(rpc)] ITangleValidatorTaskManager, - "contracts/out/ITangleValidatorTaskManager.sol/ITangleValidatorTaskManager.json" + "./contracts/out/ITangleValidatorTaskManager.sol/ITangleValidatorTaskManager.json" ); diff --git a/avs/tangle-avs/src/operator.rs b/avs/tangle-avs/src/operator.rs index 3858715..0eca072 100644 --- a/avs/tangle-avs/src/operator.rs +++ b/avs/tangle-avs/src/operator.rs @@ -65,18 +65,8 @@ pub enum OperatorError { #[allow(dead_code)] pub struct Operator { config: NodeConfig, - // eth_client: P, - // metrics_reg: Registry, - // metrics: Metrics, node_api: NodeApi, avs_registry_contract_manager: AvsRegistryContractManager, - // tangle_validator_contract_manager: TangleValidatorContractManager, - // avs_writer: AvsWriter, - // avs_reader: AvsReader, - // avs_subscriber: AvsRegistryChainSubscriber, - // eigenlayer_reader: Arc>, - // eigenlayer_writer: Arc, - // bls_keypair: KeyPair, operator_id: [u8; 32], operator_addr: Address, tangle_validator_service_manager_addr: Address, @@ -183,27 +173,10 @@ impl Operator { config: NodeConfig, eth_client_http: T::PH, eth_client_ws: T::PW, - // operator_info_service: I, signer: T::S, ) -> Result { - // let metrics_reg = Registry::new(); - // let avs_and_eigen_metrics = Metrics::new(AVS_NAME, eigen_metrics, &metrics_reg); - let node_api = NodeApi::new(AVS_NAME, SEM_VER, &config.node_api_ip_port_address); - // let eth_rpc_client = ProviderBuilder::default() - // .with_recommended_fillers() - // .on_http( - // Url::parse(&config.eth_rpc_url) - // .map_err(|e| OperatorError::HttpEthClientError(e.to_string()))?, - // ); - // let eth_ws_client = ProviderBuilder::default() - // .with_recommended_fillers() - // .on_ws(WsConnect::new(&config.eth_ws_url)) - // .await - // .map_err(|e| AvsError::from(e))?; - - log::warn!("About to read BLS key"); let bls_key_password = std::env::var("OPERATOR_BLS_KEY_PASSWORD").unwrap_or_else(|_| "".to_string()); let bls_keypair = KeyPair::read_private_key_from_file( @@ -212,12 +185,6 @@ impl Operator { ) .map_err(OperatorError::from)?; - // let chain_id = eth_client_http - // .get_chain_id() - // .await - // .map_err(|e| OperatorError::ChainIdError(e.to_string()))?; - - log::warn!("About to read ECDSA key"); let ecdsa_key_password = std::env::var("OPERATOR_ECDSA_KEY_PASSWORD").unwrap_or_else(|_| "".to_string()); let ecdsa_secret_key = eigen_utils::crypto::ecdsa::read_key( @@ -241,14 +208,6 @@ impl Operator { signer: signer.clone(), }; - // log::info!("Starting Delegation Manager Test"); - // let test_delegation_manager = DelegationManager::new(setup_config.delegate_manager_addr, eth_client_http.clone()); - // let test_addr = test_delegation_manager.address(); - // log::info!("Delegation Manager Test Address: {:?}", test_addr); - // let test = test_delegation_manager.slasher().call().await.map(|a| a._0).unwrap(); - // log::info!("Delegation Manager Test Slash Address: {:?}", test); - - log::info!("About to build AVS Registry Contract Manager"); let avs_registry_contract_manager = AvsRegistryContractManager::build( Address::from_str(&config.tangle_validator_service_manager_address).unwrap(), setup_config.registry_coordinator_addr, @@ -261,40 +220,17 @@ impl Operator { ) .await?; - log::info!("About to get operator address"); let operator_addr = Address::from_str(&config.operator_address) .map_err(|err| OperatorError::OperatorAddressError(err.to_string()))?; - log::info!("About to get operator id"); + let operator_id = avs_registry_contract_manager .get_operator_id(operator_addr) .await?; - log::info!("About to get service manager address"); let tangle_validator_service_manager_addr = Address::from_str(&config.tangle_validator_service_manager_address) .map_err(|err| OperatorError::ServiceManagerAddressError(err.to_string()))?; - // let avs_writer = AvsWriter::build( - // &config.avs_registry_coordinator_address, - // &config.operator_state_retriever_address, - // eth_rpc_client.clone(), - // ) - // .await?; - // - // let avs_reader = AvsReader::build( - // &config.avs_registry_coordinator_address, - // &config.operator_state_retriever_address, - // eth_rpc_client.clone(), - // ) - // .await?; - // - // let avs_subscriber = AvsSubscriber::build( - // &config.avs_registry_coordinator_address, - // &config.operator_state_retriever_address, - // eth_ws_client.clone(), - // ) - // .await?; - // let tangle_validator_contract_manager = TangleValidatorContractManager::build( // setup_config.registry_coordinator_addr, // setup_config.operator_state_retriever_addr, @@ -311,11 +247,6 @@ impl Operator { // ); // } - // let operator_id = sdk_clients - // .avs_registry_chain_reader - // .get_operator_id(&operator.operator_addr)?; - // operator.operator_id = operator_id; - let mut salt = [0u8; 32]; rand::thread_rng().fill(&mut salt); let sig_salt = FixedBytes::from_slice(&salt); @@ -333,10 +264,9 @@ impl Operator { expiry, &bls_keypair, alloy_primitives::Bytes::from(vec![0]), - "33125".to_string(), + "127.0.0.1:8545".to_string(), ) .await; - log::info!("Register result: {:?}", register_result); let operator = Operator { config: config.clone(), @@ -355,8 +285,6 @@ impl Operator { bls_keypair.get_pub_key_g2(), ); - log::info!("Operator Returning"); - Ok(operator) } diff --git a/utils/src/avs_registry/writer.rs b/utils/src/avs_registry/writer.rs index 83a1068..256d2d3 100644 --- a/utils/src/avs_registry/writer.rs +++ b/utils/src/avs_registry/writer.rs @@ -1,20 +1,29 @@ #![allow(async_fn_in_trait)] -use alloy_primitives::{Address, Bytes, FixedBytes, U256}; -use alloy_provider::Provider; - +use super::{AvsRegistryContractManager, AvsRegistryContractResult}; use crate::crypto::bls::{G1Point, KeyPair}; use crate::crypto::ecdsa::ToAddress; use crate::el_contracts::reader::ElReader; use crate::{types::*, Config}; +use alloy_primitives::{Address, Bytes, FixedBytes, U256}; +use alloy_provider::Provider; use alloy_rpc_types::TransactionReceipt; use alloy_signer::k256::ecdsa; -use alloy_signer::Signer; +use alloy_signer::Signer as alloySigner; +use eigen_contracts::IBlsApkRegistry::PubkeyRegistrationParams; use eigen_contracts::RegistryCoordinator; +use eigen_contracts::RegistryCoordinator::SignatureWithSaltAndExpiry; +use k256::ecdsa::signature::Signer; use k256::ecdsa::VerifyingKey; - -use super::{AvsRegistryContractManager, AvsRegistryContractResult}; +use rand::Rng; pub trait AvsRegistryChainWriterTrait { + async fn register_operator( + &self, + operator_ecdsa_private_key: &ecdsa::SigningKey, + bls_key_pair: &KeyPair, + quorum_numbers: Bytes, + socket: String, + ) -> AvsRegistryContractResult; async fn register_operator_in_quorum_with_avs_registry_coordinator( &self, operator_ecdsa_private_key: &ecdsa::SigningKey, @@ -43,6 +52,85 @@ pub trait AvsRegistryChainWriterTrait { } impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { + async fn register_operator( + &self, + operator_ecdsa_private_key: &ecdsa::SigningKey, + bls_key_pair: &KeyPair, + quorum_numbers: Bytes, + socket: String, + ) -> AvsRegistryContractResult { + let operator_addr = operator_ecdsa_private_key.verifying_key().to_bytes(); + let registry_coordinator = + RegistryCoordinator::new(self.registry_coordinator_addr, self.eth_client_http.clone()); + + // params to register bls pubkey with bls apk registry + let g1_hashed_msg_to_sign = registry_coordinator + .pubkeyRegistrationMessageHash(operator_addr) + .call() + .await + .map(|x| x._0) + .map_err(AvsError::from)?; + + let signed_msg = bls_key_pair.sign_hashed_to_curve_message(&g1_hashed_msg_to_sign); + let g1_pubkey_bn254 = bls_key_pair.get_pub_key_g1(); + let g2_pubkey_bn254 = bls_key_pair.get_pub_key_g2(); + + let pubkey_reg_params = PubkeyRegistrationParams { + pubkeyRegistrationSignature: signed_msg, + pubkeyG1: g1_pubkey_bn254, + pubkeyG2: g2_pubkey_bn254, + }; + + // Generate a random salt and 1 hour expiry for the signature + let mut rng = rand::thread_rng(); + let mut operator_to_avs_registration_sig_salt = [0u8; 32]; + rng.fill(&mut operator_to_avs_registration_sig_salt); + + let cur_block_num = self.eth_client_http.get_block_number().await?; + let cur_block = self + .eth_client_http + .get_block_by_number(cur_block_num, false) + .await? + .unwrap(); + let sig_valid_for_seconds = 60 * 60; // 1 hour + let operator_to_avs_registration_sig_expiry = + cur_block.header.timestamp + sig_valid_for_seconds; + + // params to register operator in delegation manager's operator-avs mapping + let msg_to_sign = self + .el_contract_manager + .calculate_operator_avs_registration_digest_hash( + operator_addr, + self.service_manager_addr, + operator_to_avs_registration_sig_salt, + operator_to_avs_registration_sig_expiry, + ) + .await?; + + let operator_signature = operator_ecdsa_private_key.sign(&msg_to_sign); + let mut operator_signature_bytes = operator_signature.as_ref().to_vec(); + operator_signature_bytes[64] += 27; // Convert to Ethereum's 27/28 format + + let operator_signature_with_salt_and_expiry = SignatureWithSaltAndExpiry { + signature: operator_signature_bytes, + salt: operator_to_avs_registration_sig_salt, + expiry: operator_to_avs_registration_sig_expiry.into(), + }; + + let tx = registry_coordinator.registerOperator( + quorum_numbers, + socket, + pubkey_reg_params, + operator_signature_with_salt_and_expiry, + ); + + let receipt = tx.send().await?.get_receipt().await.unwrap(); + log::info!("Registration Receipt: {:?}", receipt); + + Ok(receipt) + } + + /// TODO: This function is considered to be deprecated in original Go implementation async fn register_operator_in_quorum_with_avs_registry_coordinator( &self, operator_ecdsa_private_key: &ecdsa::SigningKey, @@ -54,7 +142,6 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { ) -> AvsRegistryContractResult { let verifying_key = VerifyingKey::from(operator_ecdsa_private_key); let operator_addr = verifying_key.to_address(); - // let operator_addr = alloy_primitives::address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"); log::info!("Operator address: {:?}", operator_addr); let registry_coordinator = @@ -168,11 +255,6 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { let _call = builder.call().await.unwrap(); let tx = builder.send().await?; - // .get_receipt() - // .await?; - - // log::info!("TX: {:?}", tx.inner()); - let watch = tx.watch().await?; log::info!( "Registered operator with the AVS's registry coordinator: {:?}", @@ -186,8 +268,6 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { .unwrap() .unwrap(); - // let receipt = tx.get_receipt().await?; - log::info!("Successfully registered operator with AVS registry coordinator"); Ok(receipt) diff --git a/utils/src/el_contracts/reader.rs b/utils/src/el_contracts/reader.rs index e284465..380a7d6 100644 --- a/utils/src/el_contracts/reader.rs +++ b/utils/src/el_contracts/reader.rs @@ -10,7 +10,6 @@ use eigen_contracts::AVSDirectory; use eigen_contracts::DelegationManager; use eigen_contracts::ISlasher; use eigen_contracts::IStrategy; - use eigen_contracts::IERC20; use super::ElChainContractManager; diff --git a/utils/src/el_contracts/writer.rs b/utils/src/el_contracts/writer.rs index a0be222..9541dac 100644 --- a/utils/src/el_contracts/writer.rs +++ b/utils/src/el_contracts/writer.rs @@ -2,11 +2,8 @@ use crate::types::*; use crate::Config; use alloy_primitives::{Address, U256}; - use alloy_rpc_types::TransactionReceipt; - use async_trait::async_trait; - use eigen_contracts::DelegationManager; use eigen_contracts::StrategyManager; From 0aa835bec10f61c73a620f8d2827b0a01f0a68a8 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Tue, 6 Aug 2024 15:22:23 -0500 Subject: [PATCH 06/43] Registration WIP --- avs/incredible-squaring-avs/src/operator.rs | 72 ++++++++++----------- contracts/src/lib.rs | 7 ++ utils/src/avs_registry/writer.rs | 68 +++++++++++++------ 3 files changed, 93 insertions(+), 54 deletions(-) diff --git a/avs/incredible-squaring-avs/src/operator.rs b/avs/incredible-squaring-avs/src/operator.rs index 37bb92c..d35c8bd 100644 --- a/avs/incredible-squaring-avs/src/operator.rs +++ b/avs/incredible-squaring-avs/src/operator.rs @@ -1,6 +1,6 @@ #![allow(dead_code)] use alloy_contract::private::Ethereum; -use alloy_primitives::{Address, Bytes, ChainId, FixedBytes, Signature, B256, U256}; +use alloy_primitives::{Address, Bytes, ChainId, FixedBytes, Signature, B256, U256, address}; use alloy_provider::{Provider, RootProvider}; use alloy_rpc_types::Log; use alloy_signer_local::PrivateKeySigner; @@ -17,7 +17,7 @@ use eigen_utils::services::operator_info::OperatorInfoServiceTrait; use eigen_utils::types::{AvsError, OperatorInfo}; use eigen_utils::Config; use gadget_common::subxt_signer::bip39::rand; -use k256::ecdsa::SigningKey; +use k256::ecdsa::{SigningKey, VerifyingKey}; use log::error; use prometheus::Registry; use rand::Rng; @@ -25,7 +25,7 @@ use std::future::Future; use std::pin::Pin; use std::str::FromStr; use thiserror::Error; - +use eigen_utils::crypto::ecdsa::ToAddress; use crate::aggregator::Aggregator; use crate::avs::subscriber::IncredibleSquaringSubscriber; use crate::avs::{ @@ -186,6 +186,7 @@ impl Operator { signer: T::S, ) -> Result { let _metrics_reg = Registry::new(); + let operator_address = Address::from_str(&config.operator_address).unwrap(); let node_api = NodeApi::new(AVS_NAME, SEM_VER, &config.node_api_ip_port_address); @@ -213,7 +214,9 @@ impl Operator { ) .unwrap(); let ecdsa_signing_key = SigningKey::from(&ecdsa_secret_key); - // TODO: Ecdsa signing key is not used + let verifying_key = VerifyingKey::from(&ecdsa_signing_key); + let ecdsa_address = verifying_key.to_address(); + assert_eq!(operator_address, ecdsa_address, "Operator Address does not match the address found from the read ECDSA key"); let setup_config = SetupConfig:: { registry_coordinator_addr: Address::from_str(&config.avs_registry_coordinator_addr) @@ -274,47 +277,44 @@ impl Operator { .await .unwrap(); - log::info!("About to get operator id and address"); - let operator_addr = Address::from_str(&config.operator_address).unwrap(); + // let mut salt = [0u8; 32]; + // rand::thread_rng().fill(&mut salt); + // let sig_salt = FixedBytes::from_slice(&salt); + // let current_block_number = eth_client_http.get_block_number().await.unwrap(); + // let expiry: U256 = U256::from(current_block_number + 20); + // let quorum_nums = Bytes::from(vec![0]); + // let register_result = avs_registry_contract_manager + // .register_operator_in_quorum_with_avs_registry_coordinator( + // &ecdsa_signing_key, + // sig_salt, + // expiry, + // &bls_keypair, + // quorum_nums, + // config.eth_rpc_url.clone(), + // ) + // .await; + let quorum_nums = Bytes::from(vec![0]); + let register_result = avs_registry_contract_manager.register_operator(&ecdsa_signing_key, &bls_keypair, quorum_nums, config.eth_rpc_url.clone()).await; + log::info!("Register result: {:?}", register_result); + + let answer = avs_registry_contract_manager + .is_operator_registered(operator_address) + .await + .unwrap(); + log::info!("Is operator registered: {:?}", answer); + let operator_id = avs_registry_contract_manager - .get_operator_id(operator_addr) + .get_operator_id(operator_address) .await?; log::info!( "Operator info: operatorId={}, operatorAddr={}, operatorG1Pubkey={:?}, operatorG2Pubkey={:?}", hex::encode(operator_id), - config.operator_address, + operator_address, bls_keypair.clone().get_pub_key_g1(), bls_keypair.clone().get_pub_key_g2(), ); - let answer = avs_registry_contract_manager - .is_operator_registered(alloy_primitives::address!( - "70997970C51812dc3A010C7d01b50e0d17dc79C8" - )) - .await - .unwrap(); - log::info!("Is operator registered: {:?}", answer); - - let mut salt = [0u8; 32]; - rand::thread_rng().fill(&mut salt); - let sig_salt = FixedBytes::from_slice(&salt); - let current_block_number = eth_client_http.get_block_number().await.unwrap(); - let expiry: U256 = U256::from(current_block_number + 20); - let quorum_nums = Bytes::from(vec![0]); - let register_result = avs_registry_contract_manager - .register_operator_in_quorum_with_avs_registry_coordinator( - &ecdsa_signing_key, - sig_salt, - expiry, - &bls_keypair, - quorum_nums, - config.eth_rpc_url.clone(), - ) - .await; - log::info!("Register result: {:?}", register_result); - - log::info!("About to create operator"); let operator = Operator { config: config.clone(), node_api, @@ -323,7 +323,7 @@ impl Operator { eigenlayer_contract_manager, bls_keypair, operator_id, - operator_addr, + operator_addr: operator_address, aggregator_server_ip_port_addr: config.server_ip_port_address.clone(), aggregator_server: aggregator_service, aggregator_rpc_client, diff --git a/contracts/src/lib.rs b/contracts/src/lib.rs index 0de23e8..bdfc9c6 100644 --- a/contracts/src/lib.rs +++ b/contracts/src/lib.rs @@ -190,3 +190,10 @@ sol!( TransparentUpgradeableProxy, "./lib/eigenlayer-middleware/out/TransparentUpgradeableProxy.sol/TransparentUpgradeableProxy.json" ); + +sol!( + #[allow(missing_docs)] + #[sol(rpc)] + EIP1271SignatureUtils, + "./out/EIP1271SignatureUtils.sol/EIP1271SignatureUtils.json" +); diff --git a/utils/src/avs_registry/writer.rs b/utils/src/avs_registry/writer.rs index 256d2d3..8c66cf8 100644 --- a/utils/src/avs_registry/writer.rs +++ b/utils/src/avs_registry/writer.rs @@ -1,4 +1,6 @@ #![allow(async_fn_in_trait)] + +use std::str::FromStr; use super::{AvsRegistryContractManager, AvsRegistryContractResult}; use crate::crypto::bls::{G1Point, KeyPair}; use crate::crypto::ecdsa::ToAddress; @@ -8,13 +10,14 @@ use alloy_primitives::{Address, Bytes, FixedBytes, U256}; use alloy_provider::Provider; use alloy_rpc_types::TransactionReceipt; use alloy_signer::k256::ecdsa; -use alloy_signer::Signer as alloySigner; +use alloy_signer::{Signer as alloySigner, SignerSync}; use eigen_contracts::IBlsApkRegistry::PubkeyRegistrationParams; -use eigen_contracts::RegistryCoordinator; +use eigen_contracts::{EIP1271SignatureUtils, RegistryCoordinator}; use eigen_contracts::RegistryCoordinator::SignatureWithSaltAndExpiry; use k256::ecdsa::signature::Signer; -use k256::ecdsa::VerifyingKey; +use k256::ecdsa::{SigningKey, VerifyingKey}; use rand::Rng; +use eigen_contracts::EIP1271SignatureUtils::EIP1271SignatureUtilsInstance; pub trait AvsRegistryChainWriterTrait { async fn register_operator( @@ -59,9 +62,9 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { quorum_numbers: Bytes, socket: String, ) -> AvsRegistryContractResult { - let operator_addr = operator_ecdsa_private_key.verifying_key().to_bytes(); - let registry_coordinator = - RegistryCoordinator::new(self.registry_coordinator_addr, self.eth_client_http.clone()); + let operator_addr = operator_ecdsa_private_key.verifying_key().to_address(); + log::info!("Operator address: {:?}", operator_addr); + let registry_coordinator = RegistryCoordinator::new(self.registry_coordinator_addr, self.eth_client_http.clone()); // params to register bls pubkey with bls apk registry let g1_hashed_msg_to_sign = registry_coordinator @@ -71,32 +74,45 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { .map(|x| x._0) .map_err(AvsError::from)?; - let signed_msg = bls_key_pair.sign_hashed_to_curve_message(&g1_hashed_msg_to_sign); + let g1_point = G1Point { + x: g1_hashed_msg_to_sign.X, + y: g1_hashed_msg_to_sign.Y, + }; + + let signed_msg = bls_key_pair.sign_hashed_to_curve_message(&g1_point); let g1_pubkey_bn254 = bls_key_pair.get_pub_key_g1(); let g2_pubkey_bn254 = bls_key_pair.get_pub_key_g2(); - let pubkey_reg_params = PubkeyRegistrationParams { - pubkeyRegistrationSignature: signed_msg, - pubkeyG1: g1_pubkey_bn254, - pubkeyG2: g2_pubkey_bn254, + let pubkey_reg_params = RegistryCoordinator::PubkeyRegistrationParams { + pubkeyRegistrationSignature: RegistryCoordinator::G1Point { + X: signed_msg.g1_point.x, + Y: signed_msg.g1_point.y, + }, + pubkeyG1: RegistryCoordinator::G1Point { + X: g1_pubkey_bn254.x, + Y: g1_pubkey_bn254.y, + }, + pubkeyG2: RegistryCoordinator::G2Point { + X: g2_pubkey_bn254.x, + Y: g2_pubkey_bn254.y, + }, }; // Generate a random salt and 1 hour expiry for the signature let mut rng = rand::thread_rng(); let mut operator_to_avs_registration_sig_salt = [0u8; 32]; rng.fill(&mut operator_to_avs_registration_sig_salt); + let operator_to_avs_registration_sig_salt = FixedBytes::from(operator_to_avs_registration_sig_salt); let cur_block_num = self.eth_client_http.get_block_number().await?; let cur_block = self .eth_client_http - .get_block_by_number(cur_block_num, false) + .get_block_by_number(cur_block_num.into(), false) .await? .unwrap(); let sig_valid_for_seconds = 60 * 60; // 1 hour - let operator_to_avs_registration_sig_expiry = - cur_block.header.timestamp + sig_valid_for_seconds; + let operator_to_avs_registration_sig_expiry = U256::from(cur_block.header.timestamp + sig_valid_for_seconds); - // params to register operator in delegation manager's operator-avs mapping let msg_to_sign = self .el_contract_manager .calculate_operator_avs_registration_digest_hash( @@ -107,9 +123,25 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { ) .await?; - let operator_signature = operator_ecdsa_private_key.sign(&msg_to_sign); - let mut operator_signature_bytes = operator_signature.as_ref().to_vec(); - operator_signature_bytes[64] += 27; // Convert to Ethereum's 27/28 format + // let operator_signature = operator_ecdsa_private_key.sign(&msg_to_sign); + // let mut operator_signature_bytes = operator_signature.as_ref().to_vec(); + + let operator_signature = self.signer.sign_hash(&msg_to_sign).await.map_err(AvsError::from)?; + let operator_signature_bytes = operator_signature.as_bytes(); + log::info!("Operator Hash signature as bytes: {:?}", operator_signature_bytes); + let operator_signature_bytes = Bytes::from(operator_signature_bytes); + log::info!("Operator Hash signature in Alloy Bytes: {:?}", operator_signature_bytes); + + let wallet = alloy_signer_local::PrivateKeySigner::from(operator_ecdsa_private_key.clone()); + let operator_signature = wallet.sign_hash_sync(&msg_to_sign).unwrap(); + let operator_signature_bytes = operator_signature.as_bytes(); + log::info!("Operator Wallet Hash signature as bytes: {:?}", operator_signature_bytes); + let operator_signature_bytes = Bytes::from(operator_signature_bytes); + log::info!("Operator Wallet Hash signature in Alloy Bytes: {:?}", operator_signature_bytes); + + EIP1271SignatureUtils::deploy(self.eth_client_http.clone()).await.unwrap(); + + // operator_signature_bytes[64] += 27; // Convert to Ethereum's 27/28 format let operator_signature_with_salt_and_expiry = SignatureWithSaltAndExpiry { signature: operator_signature_bytes, From b91f2d33d2688d0db37101df4e9f249b89592d8e Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Tue, 6 Aug 2024 19:25:07 -0500 Subject: [PATCH 07/43] Moving back to Rust Contract Deployment --- avs/incredible-squaring-avs/src/operator.rs | 1139 ++++++++++--------- utils/src/avs_registry/writer.rs | 50 +- 2 files changed, 604 insertions(+), 585 deletions(-) diff --git a/avs/incredible-squaring-avs/src/operator.rs b/avs/incredible-squaring-avs/src/operator.rs index d35c8bd..81c625e 100644 --- a/avs/incredible-squaring-avs/src/operator.rs +++ b/avs/incredible-squaring-avs/src/operator.rs @@ -1,6 +1,14 @@ #![allow(dead_code)] +use crate::aggregator::Aggregator; +use crate::avs::subscriber::IncredibleSquaringSubscriber; +use crate::avs::{ + IncredibleSquaringContractManager, IncredibleSquaringTaskManager, SetupConfig, + SignedTaskResponse, +}; +use crate::get_task_response_digest; +use crate::rpc_client::AggregatorRpcClient; use alloy_contract::private::Ethereum; -use alloy_primitives::{Address, Bytes, ChainId, FixedBytes, Signature, B256, U256, address}; +use alloy_primitives::{address, Address, Bytes, ChainId, FixedBytes, Signature, B256, U256}; use alloy_provider::{Provider, RootProvider}; use alloy_rpc_types::Log; use alloy_signer_local::PrivateKeySigner; @@ -11,6 +19,7 @@ use eigen_utils::avs_registry::reader::AvsRegistryChainReaderTrait; use eigen_utils::avs_registry::writer::AvsRegistryChainWriterTrait; use eigen_utils::avs_registry::AvsRegistryContractManager; use eigen_utils::crypto::bls::KeyPair; +use eigen_utils::crypto::ecdsa::ToAddress; use eigen_utils::el_contracts::ElChainContractManager; use eigen_utils::node_api::NodeApi; use eigen_utils::services::operator_info::OperatorInfoServiceTrait; @@ -25,15 +34,6 @@ use std::future::Future; use std::pin::Pin; use std::str::FromStr; use thiserror::Error; -use eigen_utils::crypto::ecdsa::ToAddress; -use crate::aggregator::Aggregator; -use crate::avs::subscriber::IncredibleSquaringSubscriber; -use crate::avs::{ - IncredibleSquaringContractManager, IncredibleSquaringTaskManager, SetupConfig, - SignedTaskResponse, -}; -use crate::get_task_response_digest; -use crate::rpc_client::AggregatorRpcClient; const AVS_NAME: &str = "incredible-squaring"; const SEM_VER: &str = "0.0.1"; @@ -216,7 +216,10 @@ impl Operator { let ecdsa_signing_key = SigningKey::from(&ecdsa_secret_key); let verifying_key = VerifyingKey::from(&ecdsa_signing_key); let ecdsa_address = verifying_key.to_address(); - assert_eq!(operator_address, ecdsa_address, "Operator Address does not match the address found from the read ECDSA key"); + assert_eq!( + operator_address, ecdsa_address, + "Operator Address does not match the address found from the read ECDSA key" + ); let setup_config = SetupConfig:: { registry_coordinator_addr: Address::from_str(&config.avs_registry_coordinator_addr) @@ -277,24 +280,15 @@ impl Operator { .await .unwrap(); - // let mut salt = [0u8; 32]; - // rand::thread_rng().fill(&mut salt); - // let sig_salt = FixedBytes::from_slice(&salt); - // let current_block_number = eth_client_http.get_block_number().await.unwrap(); - // let expiry: U256 = U256::from(current_block_number + 20); - // let quorum_nums = Bytes::from(vec![0]); - // let register_result = avs_registry_contract_manager - // .register_operator_in_quorum_with_avs_registry_coordinator( - // &ecdsa_signing_key, - // sig_salt, - // expiry, - // &bls_keypair, - // quorum_nums, - // config.eth_rpc_url.clone(), - // ) - // .await; let quorum_nums = Bytes::from(vec![0]); - let register_result = avs_registry_contract_manager.register_operator(&ecdsa_signing_key, &bls_keypair, quorum_nums, config.eth_rpc_url.clone()).await; + let register_result = avs_registry_contract_manager + .register_operator( + &ecdsa_signing_key, + &bls_keypair, + quorum_nums, + config.eth_rpc_url.clone(), + ) + .await; log::info!("Register result: {:?}", register_result); let answer = avs_registry_contract_manager @@ -453,6 +447,7 @@ mod tests { use alloy::signers::Signer; use alloy_provider::network::{TransactionBuilder, TxSigner}; use alloy_rpc_types_eth::BlockId; + use alloy_sol_types::abi::Encoder; use alloy_sol_types::private::SolTypeValue; use anvil::spawn; use ark_bn254::Fq as F; @@ -474,536 +469,554 @@ mod tests { pub operator: Address, } - // async fn run_anvil_testnet() -> ContractAddresses { - // // Initialize the logger - // let _ = env_logger::try_init(); - // - // let (api, mut handle) = spawn(anvil::NodeConfig::test().with_port(33125)).await; - // api.anvil_auto_impersonate_account(true).await.unwrap(); - // // let http_provider = handle.http_provider(); - // // let ws_provider = handle.ws_provider(); - // - // let _http_provider = ProviderBuilder::new() - // .on_http(Url::parse(&handle.http_endpoint()).unwrap()) - // .root() - // .clone(); - // // todo: http_provider is unused - // - // // let provider = ProviderBuilder::new().on_ws(WsConnect::new(handle.ws_endpoint())).await.unwrap(); - // - // let provider = ProviderBuilder::new() - // .on_builtin(&handle.ws_endpoint()) - // .await - // .unwrap(); - // - // let accounts = handle.dev_wallets().collect::>(); - // let from = accounts[0].address(); - // let _to = accounts[1].address(); - // - // let _amount = handle - // .genesis_balance() - // .checked_div(U256::from(2u64)) - // .unwrap(); - // - // let _gas_price = provider.get_gas_price().await.unwrap(); - // - // // Empty address for initial deployment of all contracts - // let empty_address = Address::default(); - // - // // let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); - // // let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); - // // let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); - // // let proxy_admin_addr = address!("5FbDB2315678afecb367f032d93F642f64180aa3"); - // // let pauser_registry_addr = address!("e7f1725E7734CE288F8367e1Bb143E90bb3F0512"); - // // let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); - // - // // Deploy Eigenlayer Contracts - // let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); - // let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); - // let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); - // let proxy_admin_addr = address!("5FbDB2315678afecb367f032d93F642f64180aa3"); - // let pauser_registry_addr = address!("e7f1725E7734CE288F8367e1Bb143E90bb3F0512"); - // let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); - // - // let istrategy_manager = IStrategyManager::new(strategy_manager_addr, provider.clone()); - // let idelegation_manager = - // IDelegationManager::new(delegation_manager_addr, provider.clone()); - // let iavs_directory = IAVSDirectory::new(avs_directory_addr, provider.clone()); - // let proxy_admin = ProxyAdmin::new(proxy_admin_addr, provider.clone()); - // let pauser_registry = PauserRegistry::new(pauser_registry_addr, provider.clone()); - // let base_strategy = StrategyBaseTVLLimits::new(base_strategy_addr, provider.clone()); - // // let istrategy_manager = IStrategyManager::deploy(provider.clone()).await.unwrap(); - // // let &strategy_manager_addr = istrategy_manager.address(); - // // - // // let idelegation_manager = IDelegationManager::deploy(provider.clone()).await.unwrap(); - // // let &delegation_manager_addr = idelegation_manager.address(); - // // - // // let iavs_directory = IAVSDirectory::deploy(provider.clone()).await.unwrap(); - // // let &avs_directory_addr = iavs_directory.address(); - // // - // // let proxy_admin = ProxyAdmin::deploy(provider.clone()).await.unwrap(); - // // let &proxy_admin_addr = proxy_admin.address(); - // // - // // let pauser_registry = PauserRegistry::deploy(provider.clone()).await.unwrap(); - // // let &pauser_registry_addr = pauser_registry.address(); - // // - // // let base_strategy = StrategyBaseTVLLimits::deploy(provider.clone(), Default::default()) - // // .await - // // .unwrap(); - // // let &base_strategy_addr = base_strategy.address(); - // - // let erc20_mock = ERC20Mock::deploy(provider.clone()).await.unwrap(); - // let &erc20_mock_addr = erc20_mock.address(); - // - // let ierc20 = IERC20::new(erc20_mock_addr, provider.clone()); - // let &ierc20_addr = ierc20.address(); - // - // let tokens = vec![ - // Token::Uint(1.into()), - // Token::Uint(100.into()), - // Token::Address(H160::from_slice(ierc20_addr.as_slice())), - // Token::Address(H160::from_slice(pauser_registry_addr.as_slice())), - // ]; - // let encoded_data = encode(&tokens); - // let strategy_proxy = TransparentUpgradeableProxy::deploy( - // provider.clone(), - // base_strategy_addr, - // proxy_admin_addr, - // alloy_primitives::Bytes::from(encoded_data), - // ) - // .await - // .unwrap(); - // let &strategy_proxy_addr = strategy_proxy.address(); - // - // let erc20_mock_strategy = - // StrategyBaseTVLLimits::deploy(provider.clone(), strategy_proxy_addr) - // .await - // .unwrap(); - // let &erc20_mock_strategy_addr = erc20_mock_strategy.address(); - // - // let strategies = vec![erc20_mock_strategy_addr]; - // - // let add_strategies = istrategy_manager - // .addStrategiesToDepositWhitelist(strategies, vec![false]) - // .send() - // .await - // .unwrap() - // .get_receipt() - // .await - // .unwrap(); - // println!("Add Strategies Receipt: {:?}", add_strategies); - // - // // Deploy Incredible Squaring Contracts - // let number_of_strategies = strategies.len(); - // - // let incredible_squaring_proxy_admin = ProxyAdmin::deploy(provider.clone()).await.unwrap(); - // let &incredible_squaring_proxy_admin_addr = incredible_squaring_proxy_admin.address(); - // - // let pausers = vec![ - // address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), - // address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), - // ]; - // - // let incredible_squaring_pauser_registry_addr = - // PauserRegistry::deploy_builder(provider.clone()) - // .from(from) - // .send() - // .await - // .unwrap() - // .get_receipt() - // .await - // .unwrap() - // .contract_address - // .unwrap(); - // let incredible_squaring_pauser_registry = - // PauserRegistry::new(incredible_squaring_pauser_registry_addr, provider.clone()); - // let is_pauser = incredible_squaring_pauser_registry - // .isPauser(address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266")) - // .call() - // .await - // .unwrap(); - // println!("Is Dev Account 0 Pauser: {:?}", is_pauser._0); - // - // let empty_contract = EmptyContract::deploy(provider.clone()).await.unwrap(); - // let &empty_contract_addr = empty_contract.address(); - // - // let incredible_squaring_service_manager = IncredibleSquaringServiceManager::new( - // TransparentUpgradeableProxy::deploy( - // provider.clone(), - // empty_contract_addr, - // incredible_squaring_proxy_admin_addr, - // Bytes::from(""), - // ) - // .await - // .unwrap(), - // provider.clone(), - // ); - // let &incredible_squaring_service_manager_addr = - // incredible_squaring_service_manager.address(); - // - // let incredible_squaring_task_manager = IncredibleSquaringTaskManager::new( - // TransparentUpgradeableProxy::deploy( - // provider.clone(), - // empty_contract_addr, - // incredible_squaring_proxy_admin_addr, - // Bytes::from(""), - // ) - // .await - // .unwrap(), - // provider.clone(), - // ); - // let &incredible_squaring_task_manager_addr = incredible_squaring_task_manager.address(); - // - // let registry_coordinator = RegistryCoordinator::new( - // TransparentUpgradeableProxy::deploy( - // provider.clone(), - // empty_contract_addr, - // incredible_squaring_proxy_admin_addr, - // Bytes::from(""), - // ) - // .await - // .unwrap(), - // provider.clone(), - // ); - // let ®istry_coordinator_addr = registry_coordinator.address(); - // - // let bls_apk_registry = BlsApkRegistry::new( - // TransparentUpgradeableProxy::deploy( - // provider.clone(), - // empty_contract_addr, - // incredible_squaring_proxy_admin_addr, - // Bytes::from(""), - // ) - // .await - // .unwrap(), - // provider.clone(), - // ); - // let &bls_apk_registry_addr = bls_apk_registry.address(); - // - // let bls_apk_registry = IBlsApkRegistry::new( - // TransparentUpgradeableProxy::deploy( - // provider.clone(), - // empty_contract_addr, - // incredible_squaring_proxy_admin_addr, - // Bytes::from(""), - // ) - // .await - // .unwrap(), - // provider.clone(), - // ); - // let &bls_apk_registry_addr = bls_apk_registry.address(); - // - // let index_registry = IIndexRegistry::new( - // TransparentUpgradeableProxy::deploy( - // provider.clone(), - // empty_contract_addr, - // incredible_squaring_proxy_admin_addr, - // Bytes::from(""), - // ) - // .await - // .unwrap(), - // provider.clone(), - // ); - // let &index_registry_addr = index_registry.address(); - // - // let stake_registry = IStakeRegistry::new( - // TransparentUpgradeableProxy::deploy( - // provider.clone(), - // empty_contract_addr, - // incredible_squaring_proxy_admin_addr, - // Bytes::from(""), - // ) - // .await - // .unwrap(), - // provider.clone(), - // ); - // let &stake_registry_addr = stake_registry.address(); - // - // let operator_state_retriever = OperatorStateRetriever::deploy(provider.clone()) - // .await - // .unwrap(); - // let &operator_state_retriever_addr = operator_state_retriever.address(); - // - // //Now, deploy the implementation contracts using the proxy contracts as inputs - // let stake_registry_implementation = StakeRegistry::deploy( - // provider.clone(), - // registry_coordinator_addr, - // delegation_manager_addr, - // ) - // .await - // .unwrap(); - // let &stake_registry_implementation_addr = stake_registry_implementation.address(); - // let stake_registry_upgrade = incredible_squaring_proxy_admin - // .upgrade(stake_registry_addr, stake_registry_implementation_addr) - // .send() - // .await - // .unwrap() - // .get_receipt() - // .await - // .unwrap(); - // log::info!( - // "Stake Registry Upgrade Receipt: {:?}", - // stake_registry_upgrade - // ); - // - // let bls_apk_registry_implementation = - // BlsApkRegistry::deploy(provider.clone(), registry_coordinator_addr) - // .await - // .unwrap(); - // let &bls_apk_registry_implementation_addr = bls_apk_registry_implementation.address(); - // let bls_apk_registry_upgrade = incredible_squaring_proxy_admin - // .upgrade(bls_apk_registry_addr, bls_apk_registry_implementation_addr) - // .send() - // .await - // .unwrap() - // .get_receipt() - // .await - // .unwrap(); - // log::info!( - // "Bls Apk Registry Upgrade Receipt: {:?}", - // bls_apk_registry_upgrade - // ); - // - // let index_registry_implementation = - // IndexRegistry::deploy(provider.clone(), registry_coordinator_addr) - // .await - // .unwrap(); - // let &index_registry_implementation_addr = index_registry_implementation.address(); - // let index_registry_upgrade = incredible_squaring_proxy_admin - // .upgrade(index_registry_addr, index_registry_implementation_addr) - // .send() - // .await - // .unwrap() - // .get_receipt() - // .await - // .unwrap(); - // log::info!( - // "Index Registry Upgrade Receipt: {:?}", - // index_registry_upgrade - // ); - // - // let registry_coordinator_implementation = RegistryCoordinator::deploy( - // provider.clone(), - // incredible_squaring_service_manager_addr, - // stake_registry_addr, - // bls_apk_registry_addr, - // index_registry_addr, - // ) - // .await - // .unwrap(); - // let ®istry_coordinator_implementation_addr = - // registry_coordinator_implementation.address(); - // // let registry_coordinator_upgrade = incredible_squaring_proxy_admin.upgrade( - // // registry_coordinator_addr, - // // registry_coordinator_implementation_addr, - // // ).send().await.unwrap().get_receipt().await.unwrap(); - // // log::info!("Registry Coordinator Upgrade Receipt: {:?}", registry_coordinator_upgrade); - // - // let number_of_quorums = 1; - // // For each quorum we want to set up, we must define QuorumOperatorSetParam, minimumStakeForQuorum, and strategyParams - // let mut quorum_operator_set_params = Vec::::new(); - // for i in 0..number_of_quorums { - // log::info!("Deploying quorum {}", i); - // quorum_operator_set_params.push(OperatorSetParam { - // maxOperatorCount: 10000, - // kickBIPsOfOperatorStake: 15000, - // kickBIPsOfTotalStake: 100, - // }); - // } - // // Set to 0 for each quorum - // let quorums_minimum_stake = Vec::::new(); - // let mut quorums_strategy_params = Vec::>::new(); - // - // for j in 0..number_of_quorums { - // quorums_strategy_params.push(Vec::::new()); - // for k in 0..number_of_strategies { - // quorums_strategy_params[j][k] = StrategyParams { - // strategy: strategies[j], - // multiplier: 1, - // } - // } - // } - // - // let tokens = vec![ - // Token::Address(H160::from_slice(pausers[0].as_slice())), - // Token::Address(H160::from_slice(pausers[0].as_slice())), - // Token::Address(H160::from_slice(pausers[0].as_slice())), - // Token::Address(H160::from_slice(pausers[1].as_slice())), - // Token::Uint(0.into()), - // Token::Array(quorum_operator_set_params), - // Token::Array(quorums_minimum_stake), - // Token::Array(quorums_strategy_params), - // ]; - // let encoded_data = encode(&tokens); - // let registry_coordinator_upgrade = incredible_squaring_proxy_admin - // .upgradeAndCall( - // registry_coordinator_addr, - // registry_coordinator_implementation_addr, - // alloy_primitives::Bytes::from(encoded_data), - // ) - // .send() - // .await - // .unwrap() - // .get_receipt() - // .await - // .unwrap(); - // log::info!( - // "Registry Coordinator Upgrade Receipt: {:?}", - // registry_coordinator_upgrade - // ); - // - // let incredible_squaring_service_manager_implementation = - // IncredibleSquaringServiceManager::deploy( - // provider.clone(), - // avs_directory_addr, - // registry_coordinator_addr, - // stake_registry_addr, - // incredible_squaring_task_manager_addr, - // ) - // .await - // .unwrap(); - // let &incredible_squaring_service_manager_implementation_addr = - // incredible_squaring_service_manager_implementation.address(); - // let incredible_squaring_service_manager_upgrade = incredible_squaring_proxy_admin - // .upgrade( - // incredible_squaring_service_manager_addr, - // incredible_squaring_service_manager_implementation_addr, - // ) - // .send() - // .await - // .unwrap() - // .get_receipt() - // .await - // .unwrap(); - // log::info!( - // "Incredible Squaring Service Manager Upgrade Receipt: {:?}", - // incredible_squaring_service_manager_upgrade - // ); - // - // let tokens = vec![ - // Token::Address(H160::from_slice(pauser_registry_addr.as_slice())), - // Token::Address(H160::from_slice(pausers[0].as_slice())), - // Token::Address(H160::from_slice(AGGREGATOR_ADDR.as_slice())), - // Token::Address(H160::from_slice(TASK_GENERATOR_ADDR.as_slice())), - // ]; - // let encoded_data = encode(&tokens); - // let incredible_squaring_task_manager_implementation = - // IncredibleSquaringTaskManager::deploy( - // provider.clone(), - // registry_coordinator_addr, - // TASK_RESPONSE_WINDOW_BLOCK, - // ) - // .await - // .unwrap(); - // let &incredible_squaring_task_manager_implementation_addr = - // incredible_squaring_task_manager_implementation.address(); - // let incredible_squaring_task_manager_upgrade = incredible_squaring_proxy_admin - // .upgradeAndCall( - // incredible_squaring_task_manager_addr, - // incredible_squaring_service_manager_implementation_addr, - // alloy_primitives::Bytes::from(encoded_data), - // ) - // .send() - // .await - // .unwrap() - // .get_receipt() - // .await - // .unwrap(); - // log::info!( - // "Incredible Squaring Task Manager Upgrade Receipt: {:?}", - // incredible_squaring_task_manager_upgrade - // ); - // - // log::info!("ERC20MOCK ADDRESS: {:?}", erc20_mock_addr); - // log::info!("ERC20MOCK STRATEGY ADDRESS: {:?}", erc20_mock_strategy_addr); - // log::info!( - // "INCREDIBLE SQUARING TASK MANAGER ADDRESS: {:?}", - // incredible_squaring_task_manager_addr - // ); - // log::info!( - // "INCREDIBLE SQUARING TASK MANAGER IMPLEMENTATION ADDRESS: {:?}", - // incredible_squaring_task_manager_implementation_addr - // ); - // log::info!( - // "INCREDIBLE SQUARING SERVICE MANAGER ADDRESS: {:?}", - // incredible_squaring_service_manager_addr - // ); - // log::info!( - // "INCREDIBLE SQUARING SERVICE MANAGER IMPLEMENTATION ADDRESS: {:?}", - // incredible_squaring_service_manager_implementation_addr - // ); - // log::info!( - // "REGISTRY COORDINATOR ADDRESS: {:?}", - // registry_coordinator_addr - // ); - // log::info!( - // "REGISTRY COORDINATOR IMPLEMENTATION ADDRESS: {:?}", - // registry_coordinator_implementation_addr - // ); - // log::info!( - // "OPERATOR STATE RETRIEVER ADDRESS: {:?}", - // operator_state_retriever_addr - // ); - // - // // let _block = provider - // // .get_block(BlockId::latest(), false.into()) - // // .await - // // .unwrap() - // // .unwrap(); - // // - // // api.anvil_set_auto_mine(true).await.unwrap(); - // // let run_testnet = async move { - // // let serv = handle.servers.pop().unwrap(); - // // let res = serv.await.unwrap(); - // // res.unwrap(); - // // }; - // // let spawner_task_manager_address = task_manager_addr.clone(); - // // // let spawner_provider = provider.clone(); - // // let spawner_provider = provider; - // // let task_spawner = async move { - // // let manager = IncredibleSquaringTaskManager::new( - // // spawner_task_manager_address, - // // spawner_provider.clone(), - // // ); - // // loop { - // // api.mine_one().await; - // // log::info!("About to create new task"); - // // tokio::time::sleep(std::time::Duration::from_millis(5000)).await; - // // let result = manager - // // .createNewTask(U256::from(2), 100u32, Bytes::from("0")) - // // .send() - // // .await - // // .unwrap() - // // .watch() - // // .await - // // .unwrap(); - // // api.mine_one().await; - // // log::info!("Created new task: {:?}", result); - // // // let latest_task = manager.latestTaskNum().call().await.unwrap()._0; - // // // log::info!("Latest task: {:?}", latest_task); - // // // let task_hash = manager.allTaskHashes(latest_task).call().await.unwrap()._0; - // // // log::info!("Task info: {:?}", task_hash); - // // } - // // }; - // // tokio::spawn(run_testnet); - // // tokio::spawn(task_spawner); - // - // ContractAddresses { - // service_manager: incredible_squaring_service_manager_implementation_addr, - // registry_coordinator: registry_coordinator_implementation_addr, - // operator_state_retriever: operator_state_retriever_addr, - // delegation_manager: delegation_manager_addr, - // avs_directory: avs_directory_addr, - // operator: from, - // } - // } + async fn run_anvil_testnet() -> ContractAddresses { + // Initialize the logger + let _ = env_logger::try_init(); + + let (api, mut handle) = spawn(anvil::NodeConfig::test().with_port(33125)).await; + api.anvil_auto_impersonate_account(true).await.unwrap(); + // let http_provider = handle.http_provider(); + // let ws_provider = handle.ws_provider(); + + let _http_provider = ProviderBuilder::new() + .on_http(Url::parse(&handle.http_endpoint()).unwrap()) + .root() + .clone(); + // todo: http_provider is unused + + // let provider = ProviderBuilder::new().on_ws(WsConnect::new(handle.ws_endpoint())).await.unwrap(); + + let provider = ProviderBuilder::new() + .on_builtin(&handle.ws_endpoint()) + .await + .unwrap(); + + let accounts = handle.dev_wallets().collect::>(); + let from = accounts[0].address(); + let _to = accounts[1].address(); + + let _amount = handle + .genesis_balance() + .checked_div(U256::from(2u64)) + .unwrap(); + + let _gas_price = provider.get_gas_price().await.unwrap(); + + // Empty address for initial deployment of all contracts + let empty_address = Address::default(); + + // let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); + // let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); + // let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); + // let proxy_admin_addr = address!("5FbDB2315678afecb367f032d93F642f64180aa3"); + // let pauser_registry_addr = address!("e7f1725E7734CE288F8367e1Bb143E90bb3F0512"); + // let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); + + // Deploy Eigenlayer Contracts + let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); + let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); + let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); + let proxy_admin_addr = address!("5FbDB2315678afecb367f032d93F642f64180aa3"); + let pauser_registry_addr = address!("e7f1725E7734CE288F8367e1Bb143E90bb3F0512"); + let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); + + let istrategy_manager = IStrategyManager::new(strategy_manager_addr, provider.clone()); + let idelegation_manager = + IDelegationManager::new(delegation_manager_addr, provider.clone()); + let iavs_directory = IAVSDirectory::new(avs_directory_addr, provider.clone()); + let proxy_admin = ProxyAdmin::new(proxy_admin_addr, provider.clone()); + let pauser_registry = PauserRegistry::new(pauser_registry_addr, provider.clone()); + let base_strategy = StrategyBaseTVLLimits::new(base_strategy_addr, provider.clone()); + // let istrategy_manager = IStrategyManager::deploy(provider.clone()).await.unwrap(); + // let &strategy_manager_addr = istrategy_manager.address(); + // + // let idelegation_manager = IDelegationManager::deploy(provider.clone()).await.unwrap(); + // let &delegation_manager_addr = idelegation_manager.address(); + // + // let iavs_directory = IAVSDirectory::deploy(provider.clone()).await.unwrap(); + // let &avs_directory_addr = iavs_directory.address(); + // + // let proxy_admin = ProxyAdmin::deploy(provider.clone()).await.unwrap(); + // let &proxy_admin_addr = proxy_admin.address(); + // + // let pauser_registry = PauserRegistry::deploy(provider.clone()).await.unwrap(); + // let &pauser_registry_addr = pauser_registry.address(); + // + // let base_strategy = StrategyBaseTVLLimits::deploy(provider.clone(), Default::default()) + // .await + // .unwrap(); + // let &base_strategy_addr = base_strategy.address(); + + let erc20_mock = ERC20Mock::deploy(provider.clone()).await.unwrap(); + let &erc20_mock_addr = erc20_mock.address(); + + let ierc20 = IERC20::new(erc20_mock_addr, provider.clone()); + let &ierc20_addr = ierc20.address(); + + let tokens = vec![ + Token::Uint(1.into()), + Token::Uint(100.into()), + Token::Address(H160::from_slice(ierc20_addr.as_slice())), + Token::Address(H160::from_slice(pauser_registry_addr.as_slice())), + ]; + let encoded_data = encode(&tokens); + let strategy_proxy = TransparentUpgradeableProxy::deploy( + provider.clone(), + base_strategy_addr, + proxy_admin_addr, + alloy_primitives::Bytes::from(encoded_data), + ) + .await + .unwrap(); + let &strategy_proxy_addr = strategy_proxy.address(); + + let erc20_mock_strategy = + StrategyBaseTVLLimits::deploy(provider.clone(), strategy_proxy_addr) + .await + .unwrap(); + let &erc20_mock_strategy_addr = erc20_mock_strategy.address(); + + let strategies = vec![erc20_mock_strategy_addr]; + + let add_strategies = istrategy_manager + .addStrategiesToDepositWhitelist(strategies, vec![false]) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + println!("Add Strategies Receipt: {:?}", add_strategies); + + // Deploy Incredible Squaring Contracts + let number_of_strategies = strategies.len(); + + let incredible_squaring_proxy_admin = ProxyAdmin::deploy(provider.clone()).await.unwrap(); + let &incredible_squaring_proxy_admin_addr = incredible_squaring_proxy_admin.address(); + + let pausers = vec![ + address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), + address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), + ]; + + let incredible_squaring_pauser_registry_addr = + PauserRegistry::deploy_builder(provider.clone()) + .from(from) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap() + .contract_address + .unwrap(); + let incredible_squaring_pauser_registry = + PauserRegistry::new(incredible_squaring_pauser_registry_addr, provider.clone()); + let is_pauser = incredible_squaring_pauser_registry + .isPauser(address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266")) + .call() + .await + .unwrap(); + println!("Is Dev Account 0 Pauser: {:?}", is_pauser._0); + + let empty_contract = EmptyContract::deploy(provider.clone()).await.unwrap(); + let &empty_contract_addr = empty_contract.address(); + + let incredible_squaring_service_manager = IncredibleSquaringServiceManager::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let &incredible_squaring_service_manager_addr = + incredible_squaring_service_manager.address(); + + let incredible_squaring_task_manager = IncredibleSquaringTaskManager::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let &incredible_squaring_task_manager_addr = incredible_squaring_task_manager.address(); + + let registry_coordinator = RegistryCoordinator::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let ®istry_coordinator_addr = registry_coordinator.address(); + + let bls_apk_registry = BlsApkRegistry::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let &bls_apk_registry_addr = bls_apk_registry.address(); + + let bls_apk_registry = IBlsApkRegistry::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let &bls_apk_registry_addr = bls_apk_registry.address(); + + let index_registry = IIndexRegistry::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let &index_registry_addr = index_registry.address(); + + let stake_registry = IStakeRegistry::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let &stake_registry_addr = stake_registry.address(); + + let operator_state_retriever = OperatorStateRetriever::deploy(provider.clone()) + .await + .unwrap(); + let &operator_state_retriever_addr = operator_state_retriever.address(); + + //Now, deploy the implementation contracts using the proxy contracts as inputs + let stake_registry_implementation = StakeRegistry::deploy( + provider.clone(), + registry_coordinator_addr, + delegation_manager_addr, + ) + .await + .unwrap(); + let &stake_registry_implementation_addr = stake_registry_implementation.address(); + let stake_registry_upgrade = incredible_squaring_proxy_admin + .upgrade(stake_registry_addr, stake_registry_implementation_addr) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + log::info!( + "Stake Registry Upgrade Receipt: {:?}", + stake_registry_upgrade + ); + + let bls_apk_registry_implementation = + BlsApkRegistry::deploy(provider.clone(), registry_coordinator_addr) + .await + .unwrap(); + let &bls_apk_registry_implementation_addr = bls_apk_registry_implementation.address(); + let bls_apk_registry_upgrade = incredible_squaring_proxy_admin + .upgrade(bls_apk_registry_addr, bls_apk_registry_implementation_addr) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + log::info!( + "Bls Apk Registry Upgrade Receipt: {:?}", + bls_apk_registry_upgrade + ); + + let index_registry_implementation = + IndexRegistry::deploy(provider.clone(), registry_coordinator_addr) + .await + .unwrap(); + let &index_registry_implementation_addr = index_registry_implementation.address(); + let index_registry_upgrade = incredible_squaring_proxy_admin + .upgrade(index_registry_addr, index_registry_implementation_addr) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + log::info!( + "Index Registry Upgrade Receipt: {:?}", + index_registry_upgrade + ); + + let registry_coordinator_implementation = RegistryCoordinator::deploy( + provider.clone(), + incredible_squaring_service_manager_addr, + stake_registry_addr, + bls_apk_registry_addr, + index_registry_addr, + ) + .await + .unwrap(); + let ®istry_coordinator_implementation_addr = + registry_coordinator_implementation.address(); + + let number_of_quorums = 1; + // For each quorum we want to set up, we must define QuorumOperatorSetParam, minimumStakeForQuorum, and strategyParams + let mut quorum_operator_set_params = Vec::::new(); + for i in 0..number_of_quorums { + log::info!("Deploying quorum {}", i); + quorum_operator_set_params.push(OperatorSetParam { + maxOperatorCount: 10000, + kickBIPsOfOperatorStake: 15000, + kickBIPsOfTotalStake: 100, + }); + } + // Set to 0 for each quorum + let quorums_minimum_stake = Vec::::new(); + let mut quorums_strategy_params = Vec::>::new(); + + for j in 0..number_of_quorums { + quorums_strategy_params.push(Vec::::new()); + for k in 0..number_of_strategies { + quorums_strategy_params[j][k] = StrategyParams { + strategy: strategies[j], + multiplier: 1, + } + } + } + + // TODO: These tokens need to be changed for the params types, as they are custom types + let tokens = vec![ + Token::Address(H160::from_slice(pausers[0].as_slice())), + Token::Address(H160::from_slice(pausers[0].as_slice())), + Token::Address(H160::from_slice(pausers[0].as_slice())), + Token::Address(H160::from_slice(pausers[1].as_slice())), + Token::Uint(0.into()), + Token::Array(quorum_operator_set_params), + Token::Array( + quorums_minimum_stake + .iter() + .map(|i| Token::Uint(i)) + .collect(), + ), + Token::Array(quorums_strategy_params), + ]; + // let encoder = Encoder::new(); + // alloy_sol_types::abi::encode_params(alloy_sol_types::abi::TokenSeq::encode_sequence()) + // quorum_operator_set_params.abi_encode_params(); + let encoded_data = encode(&tokens); + let registry_coordinator_upgrade = incredible_squaring_proxy_admin + .upgradeAndCall( + registry_coordinator_addr, + registry_coordinator_implementation_addr, + alloy_primitives::Bytes::from(encoded_data), + ) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + log::info!( + "Registry Coordinator Upgrade Receipt: {:?}", + registry_coordinator_upgrade + ); + + let incredible_squaring_service_manager_implementation = + IncredibleSquaringServiceManager::deploy( + provider.clone(), + avs_directory_addr, + registry_coordinator_addr, + stake_registry_addr, + incredible_squaring_task_manager_addr, + ) + .await + .unwrap(); + let &incredible_squaring_service_manager_implementation_addr = + incredible_squaring_service_manager_implementation.address(); + let incredible_squaring_service_manager_upgrade = incredible_squaring_proxy_admin + .upgrade( + incredible_squaring_service_manager_addr, + incredible_squaring_service_manager_implementation_addr, + ) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + log::info!( + "Incredible Squaring Service Manager Upgrade Receipt: {:?}", + incredible_squaring_service_manager_upgrade + ); + + let tokens = vec![ + Token::Address(H160::from_slice(pauser_registry_addr.as_slice())), + Token::Address(H160::from_slice(pausers[0].as_slice())), + Token::Address(H160::from_slice(AGGREGATOR_ADDR.as_slice())), + Token::Address(H160::from_slice(TASK_GENERATOR_ADDR.as_slice())), + ]; + let encoded_data = encode(&tokens); + let incredible_squaring_task_manager_implementation = + IncredibleSquaringTaskManager::deploy( + provider.clone(), + registry_coordinator_addr, + TASK_RESPONSE_WINDOW_BLOCK, + ) + .await + .unwrap(); + let &incredible_squaring_task_manager_implementation_addr = + incredible_squaring_task_manager_implementation.address(); + let incredible_squaring_task_manager_upgrade = incredible_squaring_proxy_admin + .upgradeAndCall( + incredible_squaring_task_manager_addr, + incredible_squaring_service_manager_implementation_addr, + alloy_primitives::Bytes::from(encoded_data), + ) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + log::info!( + "Incredible Squaring Task Manager Upgrade Receipt: {:?}", + incredible_squaring_task_manager_upgrade + ); + + log::info!("ERC20MOCK ADDRESS: {:?}", erc20_mock_addr); + log::info!("ERC20MOCK STRATEGY ADDRESS: {:?}", erc20_mock_strategy_addr); + log::info!( + "INCREDIBLE SQUARING TASK MANAGER ADDRESS: {:?}", + incredible_squaring_task_manager_addr + ); + log::info!( + "INCREDIBLE SQUARING TASK MANAGER IMPLEMENTATION ADDRESS: {:?}", + incredible_squaring_task_manager_implementation_addr + ); + log::info!( + "INCREDIBLE SQUARING SERVICE MANAGER ADDRESS: {:?}", + incredible_squaring_service_manager_addr + ); + log::info!( + "INCREDIBLE SQUARING SERVICE MANAGER IMPLEMENTATION ADDRESS: {:?}", + incredible_squaring_service_manager_implementation_addr + ); + log::info!( + "REGISTRY COORDINATOR ADDRESS: {:?}", + registry_coordinator_addr + ); + log::info!( + "REGISTRY COORDINATOR IMPLEMENTATION ADDRESS: {:?}", + registry_coordinator_implementation_addr + ); + log::info!( + "OPERATOR STATE RETRIEVER ADDRESS: {:?}", + operator_state_retriever_addr + ); + + // let _block = provider + // .get_block(BlockId::latest(), false.into()) + // .await + // .unwrap() + // .unwrap(); + // + // api.anvil_set_auto_mine(true).await.unwrap(); + // let run_testnet = async move { + // let serv = handle.servers.pop().unwrap(); + // let res = serv.await.unwrap(); + // res.unwrap(); + // }; + // let spawner_task_manager_address = task_manager_addr.clone(); + // // let spawner_provider = provider.clone(); + // let spawner_provider = provider; + // let task_spawner = async move { + // let manager = IncredibleSquaringTaskManager::new( + // spawner_task_manager_address, + // spawner_provider.clone(), + // ); + // loop { + // api.mine_one().await; + // log::info!("About to create new task"); + // tokio::time::sleep(std::time::Duration::from_millis(5000)).await; + // let result = manager + // .createNewTask(U256::from(2), 100u32, Bytes::from("0")) + // .send() + // .await + // .unwrap() + // .watch() + // .await + // .unwrap(); + // api.mine_one().await; + // log::info!("Created new task: {:?}", result); + // // let latest_task = manager.latestTaskNum().call().await.unwrap()._0; + // // log::info!("Latest task: {:?}", latest_task); + // // let task_hash = manager.allTaskHashes(latest_task).call().await.unwrap()._0; + // // log::info!("Task info: {:?}", task_hash); + // } + // }; + // tokio::spawn(run_testnet); + // tokio::spawn(task_spawner); + + ContractAddresses { + service_manager: incredible_squaring_service_manager_implementation_addr, + registry_coordinator: registry_coordinator_implementation_addr, + operator_state_retriever: operator_state_retriever_addr, + delegation_manager: delegation_manager_addr, + avs_directory: avs_directory_addr, + operator: from, + } + } #[tokio::test] async fn test_anvil() { env_logger::init(); - // // Runs new Anvil Testnet - used for deploying programmatically in rust - // let contract_addresses = run_anvil_testnet().await; + // Runs new Anvil Testnet - used for deploying programmatically in rust + let contract_addresses = run_anvil_testnet().await; // // Runs saved Anvil Testnet - loads from saved chain state JSON file // let chain = eigen_utils::test_utils::local_chain::LocalEvmChain::new_with_chain_state( @@ -1017,17 +1030,17 @@ mod tests { // println!("chain_id: {:?}", chain_id); // println!("chain_name: {:?}", chain_name); - let account_one = address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"); - let account_two = address!("70997970C51812dc3A010C7d01b50e0d17dc79C8"); + // let account_one = address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"); + // let account_two = address!("70997970C51812dc3A010C7d01b50e0d17dc79C8"); - let contract_addresses = ContractAddresses { - service_manager: address!("84eA74d481Ee0A5332c457a4d796187F6Ba67fEB"), - registry_coordinator: address!("a82fF9aFd8f496c3d6ac40E2a0F282E47488CFc9"), - operator_state_retriever: address!("95401dc811bb5740090279Ba06cfA8fcF6113778"), - delegation_manager: address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"), - avs_directory: address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"), - operator: account_two, - }; + // let contract_addresses = ContractAddresses { + // service_manager: address!("84eA74d481Ee0A5332c457a4d796187F6Ba67fEB"), + // registry_coordinator: address!("a82fF9aFd8f496c3d6ac40E2a0F282E47488CFc9"), + // operator_state_retriever: address!("95401dc811bb5740090279Ba06cfA8fcF6113778"), + // delegation_manager: address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"), + // avs_directory: address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"), + // operator: account_two, + // }; // Implementation version of addresses // let contract_addresses = ContractAddresses { diff --git a/utils/src/avs_registry/writer.rs b/utils/src/avs_registry/writer.rs index 8c66cf8..394740e 100644 --- a/utils/src/avs_registry/writer.rs +++ b/utils/src/avs_registry/writer.rs @@ -1,6 +1,5 @@ #![allow(async_fn_in_trait)] -use std::str::FromStr; use super::{AvsRegistryContractManager, AvsRegistryContractResult}; use crate::crypto::bls::{G1Point, KeyPair}; use crate::crypto::ecdsa::ToAddress; @@ -11,13 +10,14 @@ use alloy_provider::Provider; use alloy_rpc_types::TransactionReceipt; use alloy_signer::k256::ecdsa; use alloy_signer::{Signer as alloySigner, SignerSync}; +use eigen_contracts::EIP1271SignatureUtils::EIP1271SignatureUtilsInstance; use eigen_contracts::IBlsApkRegistry::PubkeyRegistrationParams; -use eigen_contracts::{EIP1271SignatureUtils, RegistryCoordinator}; use eigen_contracts::RegistryCoordinator::SignatureWithSaltAndExpiry; +use eigen_contracts::{EIP1271SignatureUtils, RegistryCoordinator}; use k256::ecdsa::signature::Signer; use k256::ecdsa::{SigningKey, VerifyingKey}; use rand::Rng; -use eigen_contracts::EIP1271SignatureUtils::EIP1271SignatureUtilsInstance; +use std::str::FromStr; pub trait AvsRegistryChainWriterTrait { async fn register_operator( @@ -64,7 +64,8 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { ) -> AvsRegistryContractResult { let operator_addr = operator_ecdsa_private_key.verifying_key().to_address(); log::info!("Operator address: {:?}", operator_addr); - let registry_coordinator = RegistryCoordinator::new(self.registry_coordinator_addr, self.eth_client_http.clone()); + let registry_coordinator = + RegistryCoordinator::new(self.registry_coordinator_addr, self.eth_client_http.clone()); // params to register bls pubkey with bls apk registry let g1_hashed_msg_to_sign = registry_coordinator @@ -102,7 +103,8 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { let mut rng = rand::thread_rng(); let mut operator_to_avs_registration_sig_salt = [0u8; 32]; rng.fill(&mut operator_to_avs_registration_sig_salt); - let operator_to_avs_registration_sig_salt = FixedBytes::from(operator_to_avs_registration_sig_salt); + let operator_to_avs_registration_sig_salt = + FixedBytes::from(operator_to_avs_registration_sig_salt); let cur_block_num = self.eth_client_http.get_block_number().await?; let cur_block = self @@ -111,7 +113,8 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { .await? .unwrap(); let sig_valid_for_seconds = 60 * 60; // 1 hour - let operator_to_avs_registration_sig_expiry = U256::from(cur_block.header.timestamp + sig_valid_for_seconds); + let operator_to_avs_registration_sig_expiry = + U256::from(cur_block.header.timestamp + sig_valid_for_seconds); let msg_to_sign = self .el_contract_manager @@ -123,25 +126,28 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { ) .await?; - // let operator_signature = operator_ecdsa_private_key.sign(&msg_to_sign); - // let mut operator_signature_bytes = operator_signature.as_ref().to_vec(); - - let operator_signature = self.signer.sign_hash(&msg_to_sign).await.map_err(AvsError::from)?; - let operator_signature_bytes = operator_signature.as_bytes(); - log::info!("Operator Hash signature as bytes: {:?}", operator_signature_bytes); - let operator_signature_bytes = Bytes::from(operator_signature_bytes); - log::info!("Operator Hash signature in Alloy Bytes: {:?}", operator_signature_bytes); - - let wallet = alloy_signer_local::PrivateKeySigner::from(operator_ecdsa_private_key.clone()); - let operator_signature = wallet.sign_hash_sync(&msg_to_sign).unwrap(); + let operator_signature = self + .signer + .sign_hash(&msg_to_sign) + .await + .map_err(AvsError::from)?; let operator_signature_bytes = operator_signature.as_bytes(); - log::info!("Operator Wallet Hash signature as bytes: {:?}", operator_signature_bytes); + log::info!( + "Operator Hash signature as bytes: {:?}", + operator_signature_bytes + ); let operator_signature_bytes = Bytes::from(operator_signature_bytes); - log::info!("Operator Wallet Hash signature in Alloy Bytes: {:?}", operator_signature_bytes); - - EIP1271SignatureUtils::deploy(self.eth_client_http.clone()).await.unwrap(); + log::info!( + "Operator Hash signature in Alloy Bytes: {:?}", + operator_signature_bytes + ); - // operator_signature_bytes[64] += 27; // Convert to Ethereum's 27/28 format + // let wallet = alloy_signer_local::PrivateKeySigner::from(operator_ecdsa_private_key.clone()); + // let operator_signature = wallet.sign_hash_sync(&msg_to_sign).unwrap(); + // let operator_signature_bytes = operator_signature.as_bytes(); + // log::info!("Operator Wallet Hash signature as bytes: {:?}", operator_signature_bytes); + // let operator_signature_bytes = Bytes::from(operator_signature_bytes); + // log::info!("Operator Wallet Hash signature in Alloy Bytes: {:?}", operator_signature_bytes); let operator_signature_with_salt_and_expiry = SignatureWithSaltAndExpiry { signature: operator_signature_bytes, From a8355dfdd595acb4cbf97c050c247b2298b3d3e6 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 7 Aug 2024 19:57:27 -0500 Subject: [PATCH 08/43] Contracts Deployment WIP --- .github/workflows/validate_pr.yml | 92 ++++++++++ Cargo.lock | 10 + Cargo.toml | 1 + README.md | 72 ++++++-- avs/incredible-squaring-avs/Cargo.toml | 1 + avs/incredible-squaring-avs/src/operator.rs | 192 ++++++++++++-------- eigensdk-rs/Cargo.toml | 2 + eigensdk-rs/src/lib.rs | 4 +- utils/Cargo.toml | 1 + utils/src/test_utils/abi.rs | 21 +++ utils/src/test_utils/mod.rs | 1 + 11 files changed, 304 insertions(+), 93 deletions(-) create mode 100644 .github/workflows/validate_pr.yml create mode 100644 utils/src/test_utils/abi.rs diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml new file mode 100644 index 0000000..cb49f5f --- /dev/null +++ b/.github/workflows/validate_pr.yml @@ -0,0 +1,92 @@ +name: Validate PR + +on: + pull_request: + branches: [main] + push: + branches: [main] + +concurrency: + group: rust-validation-${{ github.head_ref }} + cancel-in-progress: true + +env: + RUST_BACKTRACE: full + RUST_LOG: "info" + CARGO_TERM_COLOR: always + +jobs: + formatting: + name: Rustfmt + runs-on: ubuntu-latest + steps: + - name: Checkout Code + uses: actions/checkout@v2 + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + components: rustfmt + + - name: Check Formatting + run: cargo fmt -- --check + + linting: + timeout-minutes: 120 + name: cargo clippy + runs-on: macos-latest + strategy: + matrix: + package: [ + eigensdk-rs + ] + steps: + - name: checkout code + uses: actions/checkout@v2 + + - name: install rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + + - uses: swatinem/rust-cache@v2 + with: + cache-on-failure: "true" + + - name: Run Clippy + run: cargo clippy --package ${{ matrix.package }} --tests -- -D warnings + + testing: + timeout-minutes: 90 + name: cargo test + if: false # temporarily disabled + runs-on: macos-14 + strategy: + matrix: + package: [ + eigensdk-rs, + ] + steps: + - name: checkout code + uses: actions/checkout@v2 + + - name: install rust + uses: dtolnay/rust-toolchain@nightly + with: + toolchain: stable + + - uses: swatinem/rust-cache@v2 + with: + cache-on-failure: "true" + + - name: Set Relevant M1 env vars + run: | + export LIBRARY_PATH=$LIBRARY_PATH:/opt/homebrew/lib + export INCLUDE_PATH=$INCLUDE_PATH:/opt/homebrew/include + + - name: install cargo-nextest + run: cargo install cargo-nextest --locked + + - name: tests + run: cargo nextest run --release --nocapture --package ${{ matrix.package }} \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index ed511a0..8733085 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -127,6 +127,12 @@ dependencies = [ "alloy-transport-http 0.1.4", ] +[[package]] +name = "alloy-abi" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95d80fbdae433a4c98109023eada56d864e49750d131824bad158f59d79a95d2" + [[package]] name = "alloy-chains" version = "0.1.24" @@ -4000,6 +4006,7 @@ version = "0.1.0" dependencies = [ "aes", "aes-gcm", + "alloy-abi", "alloy-consensus 0.2.1", "alloy-contract", "alloy-eips 0.2.1", @@ -4063,6 +4070,8 @@ dependencies = [ "eigen-contracts", "eigen-utils", "fireblocks-client", + "incredible-squaring-avs", + "tangle-avs", ] [[package]] @@ -6378,6 +6387,7 @@ name = "incredible-squaring-avs" version = "0.1.0" dependencies = [ "alloy", + "alloy-abi", "alloy-contract", "alloy-primitives", "alloy-provider 0.2.1", diff --git a/Cargo.toml b/Cargo.toml index 408756d..6af90d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -133,6 +133,7 @@ http-body-util = "0.1.1" anvil = { git = "https://github.com/foundry-rs/foundry.git" } foundry-common = { git = "https://github.com/foundry-rs/foundry.git" } +alloy-abi = "0.1.0" alloy-chains = "0.1.23" alloy-primitives = "0.7.7" alloy-dyn-abi = "0.7.7" diff --git a/README.md b/README.md index c9c2192..c80034e 100644 --- a/README.md +++ b/README.md @@ -8,60 +8,93 @@ [//]: # (---) -Welcome to EigenSDK-RS, the Rust port of Layr-labs' EigenSDK-GO. This SDK is a high-performance, reliable, and efficient library designed to interact with the Eigen Network. It integrates seamlessly with Eigen's ecosystem while leveraging the many advantages of Rust. +EigenSDK-RS is a Rust implementation of Layr-Lab's eigensdk-go. Additionally, it incorporates features for interacting with Tangle and utilizing Gadgets, offering a comprehensive solution for building applications with both Eigenlayer and Tangle. This SDK is a high-performance, reliable, and efficient library that integrates seamlessly with Eigen's ecosystem while leveraging the many advantages of Rust. -As this SDK is currently under active development, instability should be expected. +It should be noted that this SDK is still being actively developed. +--- ## Table of Contents - [**Features**](#features) - [**Getting** Started](#getting-started) + - [**Installation**](#installation) + - [**Running an AVS**](#running-an-avs) - [**Testing**](#testing) + - [**Running the Included Tests**](#running-the-included-tests) + - [**Testing Custom Implementations**](#testing-custom-implementations) - [**Documentation**](#documentation) - [**Contributing**](#contributing) [//]: # (- [**License**](#license)) +--- ## Features -- **High Performance**: Built with Rust to ensure maximum efficiency and speed. -- **Type Safety**: Leverages Rust's strong type system for robust code. -- **Concurrency**: Utilizes Rust's concurrency model for safe multi-threaded operations. -- **Compatibility**: Full feature parity with the Go implementation, making it easy to port applications from Go to Rust. -- **Comprehensive API**: Complete access to the Eigen network functionalities. +- **Full Eigenlayer Integration**: Provides all the robust functionalities of eigensdk-go, now with the performance benefits of Rust. +- **Seamless Tangle Interoperability**: Easily integrates Tangle into Eigenlayer AVSs, allowing a Tangle Validator to live in an AVS. +- **Unlimited Customization**: Equipped with all the tools needed to build custom AVSs, including those that leverage our advanced Gadget capabilities. +- **High Performance**: Developed with Rust to deliver superior efficiency and speed, ensuring your applications run optimally. +- **Enhanced Type Safety**: Takes advantage of Rust's strong type system to create more reliable and maintainable code. +- **Advanced Concurrency**: Utilizes Rust's concurrency model to enable safe and efficient multi-threaded operations. +- **Go Implementation Compatibility**: Achieves full feature parity with the Go version, facilitating straightforward porting of applications from Go to Rust. +- **Comprehensive API Access**: Provides complete access to all Eigen network functionalities, empowering developers to fully exploit the platform's potential. +--- ## Getting Started ### Installation -1. Clone the repository: +Clone the repository: ```bash git clone https://github.com/webb-tools/eigensdk-rs/ cd eigensdk-rs ``` -2. Build the project: +Build the project: ```bash cargo build --release ``` -### Running an AVS - -[//]: # (#TODO: Commands to run) -```bash - +To use EigenSDK-RS in your own Rust project, just add the following dependency to your `Cargo.toml`: +```toml +[dependencies] +eigensdk-rs = { git = "https://github.com/webb-tools/eigensdk-rs" } ``` +### Running an AVS +To programmatically start an AVS operator: + +1. Create a new operator, supplying the necessary inputs (dependent upon the AVS you are running). The following is a general example that a real implementation would closely follow: +```rust +let operator = Operator::new_from_config( + config, + http_provider, + ws_provider, + operator_info_service, + signer, + ) + .await?; +``` +2. With the operator, simply run the start function: +```rust +operator.start().await?; +``` +--- ## Testing This repository both contains tests for the included AVSs and provides the tools necessary to test custom AVSs you build with this SDK. -### Testing on a Local Testnet with Anvil -To run the tests, use the following command: +### Running the included tests +To run the tests, use the following command inside the root directory of the AVS you would like to test: ```bash - +RUST_LOG=info cargo test test_anvil ``` +This test starts a local Anvil testnet, deploys all the required contracts to it, and then starts an operator. +### Testing custom implementations +We include testing utilities that make it easy to run tests for custom implementations. These tools are currently in development. + +--- ## Contributing To contribute: @@ -73,6 +106,7 @@ To contribute: [//]: # (## License) -[//]: # (## Contact) +--- +## Contact -[//]: # (If you have any questions or need further information, please contact the developers [here](https://webb.tools/)) +If you have any questions or need further information, please contact the developers [here](https://webb.tools/) diff --git a/avs/incredible-squaring-avs/Cargo.toml b/avs/incredible-squaring-avs/Cargo.toml index 42a944f..42955f6 100644 --- a/avs/incredible-squaring-avs/Cargo.toml +++ b/avs/incredible-squaring-avs/Cargo.toml @@ -10,6 +10,7 @@ repository.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +alloy-abi.workspace = true alloy-contract.workspace = true alloy-primitives.workspace = true alloy-provider.workspace = true diff --git a/avs/incredible-squaring-avs/src/operator.rs b/avs/incredible-squaring-avs/src/operator.rs index 81c625e..0d12598 100644 --- a/avs/incredible-squaring-avs/src/operator.rs +++ b/avs/incredible-squaring-avs/src/operator.rs @@ -423,7 +423,7 @@ impl Operator { #[cfg(test)] mod tests { use super::*; - use alloy_primitives::{address, Address}; + use alloy_primitives::{address, Address, Uint}; use alloy_provider::Provider; use alloy_provider::ProviderBuilder; use alloy_signer_local::PrivateKeySigner; @@ -445,6 +445,7 @@ mod tests { use crate::avs; use alloy::signers::Signer; + use alloy_primitives::Keccak256; use alloy_provider::network::{TransactionBuilder, TxSigner}; use alloy_rpc_types_eth::BlockId; use alloy_sol_types::abi::Encoder; @@ -455,8 +456,12 @@ mod tests { use avs::IncredibleSquaringServiceManager; use eigen_contracts::RegistryCoordinator::{OperatorSetParam, StrategyParams}; use eigen_contracts::*; - use ethabi::ethereum_types::H160; - use ethabi::{encode, Token}; + // use ethabi::ethereum_types::H160; + // use ethabi::{encode, Token}; + use alloy_sol_types::abi::{self, token::*}; + use alloy_sol_types::Word; + use eigen_utils::encode_params; + use eigen_utils::test_utils::abi::encode_with_selector; use gadget_common::subxt_signer::bip39::rand_core::OsRng; use url::Url; @@ -513,39 +518,40 @@ mod tests { // let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); // Deploy Eigenlayer Contracts - let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); - let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); - let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); - let proxy_admin_addr = address!("5FbDB2315678afecb367f032d93F642f64180aa3"); - let pauser_registry_addr = address!("e7f1725E7734CE288F8367e1Bb143E90bb3F0512"); - let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); - - let istrategy_manager = IStrategyManager::new(strategy_manager_addr, provider.clone()); - let idelegation_manager = - IDelegationManager::new(delegation_manager_addr, provider.clone()); - let iavs_directory = IAVSDirectory::new(avs_directory_addr, provider.clone()); - let proxy_admin = ProxyAdmin::new(proxy_admin_addr, provider.clone()); - let pauser_registry = PauserRegistry::new(pauser_registry_addr, provider.clone()); - let base_strategy = StrategyBaseTVLLimits::new(base_strategy_addr, provider.clone()); - // let istrategy_manager = IStrategyManager::deploy(provider.clone()).await.unwrap(); - // let &strategy_manager_addr = istrategy_manager.address(); - // - // let idelegation_manager = IDelegationManager::deploy(provider.clone()).await.unwrap(); - // let &delegation_manager_addr = idelegation_manager.address(); - // - // let iavs_directory = IAVSDirectory::deploy(provider.clone()).await.unwrap(); - // let &avs_directory_addr = iavs_directory.address(); - // - // let proxy_admin = ProxyAdmin::deploy(provider.clone()).await.unwrap(); - // let &proxy_admin_addr = proxy_admin.address(); - // - // let pauser_registry = PauserRegistry::deploy(provider.clone()).await.unwrap(); - // let &pauser_registry_addr = pauser_registry.address(); - // - // let base_strategy = StrategyBaseTVLLimits::deploy(provider.clone(), Default::default()) - // .await - // .unwrap(); - // let &base_strategy_addr = base_strategy.address(); + // let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); + // let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); + // let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); + // let proxy_admin_addr = address!("5FbDB2315678afecb367f032d93F642f64180aa3"); + // let pauser_registry_addr = address!("e7f1725E7734CE288F8367e1Bb143E90bb3F0512"); + // let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); + + // let istrategy_manager = IStrategyManager::new(strategy_manager_addr, provider.clone()); + // let idelegation_manager = + // IDelegationManager::new(delegation_manager_addr, provider.clone()); + // let iavs_directory = IAVSDirectory::new(avs_directory_addr, provider.clone()); + // let proxy_admin = ProxyAdmin::new(proxy_admin_addr, provider.clone()); + // let pauser_registry = PauserRegistry::new(pauser_registry_addr, provider.clone()); + // let base_strategy = StrategyBaseTVLLimits::new(base_strategy_addr, provider.clone()); + + let istrategy_manager = IStrategyManager::deploy(provider.clone()).await.unwrap(); + let &strategy_manager_addr = istrategy_manager.address(); + + let idelegation_manager = IDelegationManager::deploy(provider.clone()).await.unwrap(); + let &delegation_manager_addr = idelegation_manager.address(); + + let iavs_directory = IAVSDirectory::deploy(provider.clone()).await.unwrap(); + let &avs_directory_addr = iavs_directory.address(); + + let proxy_admin = ProxyAdmin::deploy(provider.clone()).await.unwrap(); + let &proxy_admin_addr = proxy_admin.address(); + + let pauser_registry = PauserRegistry::deploy(provider.clone()).await.unwrap(); + let &pauser_registry_addr = pauser_registry.address(); + + let base_strategy = StrategyBaseTVLLimits::deploy(provider.clone(), Default::default()) + .await + .unwrap(); + let &base_strategy_addr = base_strategy.address(); let erc20_mock = ERC20Mock::deploy(provider.clone()).await.unwrap(); let &erc20_mock_addr = erc20_mock.address(); @@ -553,18 +559,55 @@ mod tests { let ierc20 = IERC20::new(erc20_mock_addr, provider.clone()); let &ierc20_addr = ierc20.address(); - let tokens = vec![ - Token::Uint(1.into()), - Token::Uint(100.into()), - Token::Address(H160::from_slice(ierc20_addr.as_slice())), - Token::Address(H160::from_slice(pauser_registry_addr.as_slice())), - ]; - let encoded_data = encode(&tokens); + // Function with signature initialize(uint256,uint256,address,address) and selector 0x019e2729. + let function_signature = "initialize(uint256,uint256,address,address)"; + // let params = vec![ + // 1.tokenize(), + // 100.tokenize(), + // ierc20_addr.tokenize(), + // pauser_registry_addr.tokenize(), + // // WordToken(Word::from(1)), + // // WordToken(Word::from(100)), + // // WordToken(Word::from(ierc20_addr.as_slice())), + // // WordToken(Word::from(pauser_registry_addr.as_slice())), + // ]; + // let encoded_data = encode_with_selector(function_signature, params); + // let encoded_data = encode_params!(function_signature, 1, 100, ierc20_addr, pauser_registry_addr); + + let mut hasher = Keccak256::new(); + hasher.update(function_signature); + let function_selector = &hasher.finalize()[..4]; + let hex_selector = hex::encode(function_selector); + log::info!("Function selector as hex: {:?}", hex_selector); + let mut data = Vec::from(function_selector); + // let encoded_param = SolValue::abi_encode(&1); + // data.extend_from_slice(&encoded_param); + // let encoded_param = SolValue::abi_encode(&100); + // data.extend_from_slice(&encoded_param); + // let encoded_param = SolValue::abi_encode(&ierc20_addr); + // data.extend_from_slice(&encoded_param); + // let encoded_param = SolValue::abi_encode(&pauser_registry_addr); + // data.extend_from_slice(&encoded_param); + let token = 1.tokenize(); + let encoded_param = abi::encode(&token); + data.extend(&encoded_param); + let token = 100.tokenize(); + let encoded_param = abi::encode(&token); + data.extend(&encoded_param); + let token = ierc20_addr.tokenize(); + let encoded_param = abi::encode(&token); + data.extend(&encoded_param); + let token = pauser_registry_addr.tokenize(); + let encoded_param = abi::encode(&token); + data.extend(&encoded_param); + + let encoded_data = alloy_primitives::Bytes::from(data); + let strategy_proxy = TransparentUpgradeableProxy::deploy( provider.clone(), base_strategy_addr, proxy_admin_addr, - alloy_primitives::Bytes::from(encoded_data), + encoded_data, ) .await .unwrap(); @@ -579,7 +622,7 @@ mod tests { let strategies = vec![erc20_mock_strategy_addr]; let add_strategies = istrategy_manager - .addStrategiesToDepositWhitelist(strategies, vec![false]) + .addStrategiesToDepositWhitelist(strategies.clone(), vec![false]) .send() .await .unwrap() @@ -828,26 +871,20 @@ mod tests { } } - // TODO: These tokens need to be changed for the params types, as they are custom types - let tokens = vec![ - Token::Address(H160::from_slice(pausers[0].as_slice())), - Token::Address(H160::from_slice(pausers[0].as_slice())), - Token::Address(H160::from_slice(pausers[0].as_slice())), - Token::Address(H160::from_slice(pausers[1].as_slice())), - Token::Uint(0.into()), - Token::Array(quorum_operator_set_params), - Token::Array( - quorums_minimum_stake - .iter() - .map(|i| Token::Uint(i)) - .collect(), - ), - Token::Array(quorums_strategy_params), - ]; - // let encoder = Encoder::new(); - // alloy_sol_types::abi::encode_params(alloy_sol_types::abi::TokenSeq::encode_sequence()) - // quorum_operator_set_params.abi_encode_params(); - let encoded_data = encode(&tokens); + // Function with signature initialize(address,address,address,address,uint256,(uint32,uint16,uint16)[],uint96[],(address,uint96)[][]) and selector 0xdd8283f3. + let function_signature = "initialize(address,address,address,address,uint256,(uint32,uint16,uint16)[],uint96[],(address,uint96)[][])"; + + let encoded_data = encode_params!( + function_signature, + pausers[0], + pausers[0], + pausers[0], + pausers[1], + 0, + quorum_operator_set_params, + quorums_minimum_stake, + quorums_strategy_params + ); let registry_coordinator_upgrade = incredible_squaring_proxy_admin .upgradeAndCall( registry_coordinator_addr, @@ -893,13 +930,24 @@ mod tests { incredible_squaring_service_manager_upgrade ); - let tokens = vec![ - Token::Address(H160::from_slice(pauser_registry_addr.as_slice())), - Token::Address(H160::from_slice(pausers[0].as_slice())), - Token::Address(H160::from_slice(AGGREGATOR_ADDR.as_slice())), - Token::Address(H160::from_slice(TASK_GENERATOR_ADDR.as_slice())), - ]; - let encoded_data = encode(&tokens); + // Function with signature initialize(address,address,address,address) and selector 0xf8c8765e. + let function_signature = "initialize(address,address,address,address)"; + // let params = vec![ + // pauser_registry_addr.tokenize(), + // pausers[0].tokenize(), + // AGGREGATOR_ADDR.tokenize(), + // TASK_GENERATOR_ADDR.tokenize(), + // ]; + // let encoded_data = + // eigen_utils::test_utils::abi::encode_with_selector(function_signature, params); + + let encoded_data = encode_params!( + function_signature, + pauser_registry_addr, + pausers[0], + AGGREGATOR_ADDR, + TASK_GENERATOR_ADDR + ); let incredible_squaring_task_manager_implementation = IncredibleSquaringTaskManager::deploy( provider.clone(), diff --git a/eigensdk-rs/Cargo.toml b/eigensdk-rs/Cargo.toml index ebe0732..c070b9c 100644 --- a/eigensdk-rs/Cargo.toml +++ b/eigensdk-rs/Cargo.toml @@ -6,5 +6,7 @@ edition = "2021" [dependencies] eigen-contracts = { workspace = true } eigen-utils = { workspace = true } +tangle-avs = { workspace = true } +incredible-squaring-avs = { workspace = true } fireblocks-client = { workspace = true } aws-kms = { workspace = true } \ No newline at end of file diff --git a/eigensdk-rs/src/lib.rs b/eigensdk-rs/src/lib.rs index a66e250..cada2f5 100644 --- a/eigensdk-rs/src/lib.rs +++ b/eigensdk-rs/src/lib.rs @@ -1,5 +1,5 @@ pub use eigen_contracts; -pub use eigen_gadget; -pub use eigen_tangle_avs; +pub use tangle_avs; +pub use incredible_squaring_avs; pub use eigen_utils; pub use fireblocks_client; diff --git a/utils/Cargo.toml b/utils/Cargo.toml index 769c867..7083f06 100644 --- a/utils/Cargo.toml +++ b/utils/Cargo.toml @@ -31,6 +31,7 @@ tokio.workspace = true hex.workspace = true futures.workspace = true log.workspace = true +alloy-abi.workspace = true alloy-contract.workspace = true alloy-consensus.workspace = true alloy-eips.workspace = true diff --git a/utils/src/test_utils/abi.rs b/utils/src/test_utils/abi.rs new file mode 100644 index 0000000..c4968e8 --- /dev/null +++ b/utils/src/test_utils/abi.rs @@ -0,0 +1,21 @@ +use alloy_sol_types::abi; +use alloy_sol_types::abi::Token; +use sha3::{Digest, Keccak256}; + +/// Macro that acts as the Rust equivalent of Solidity's `abi.encodeWithSelector`. Returns [alloy_primitives::Bytes] +#[macro_export] +macro_rules! encode_params { + ($function_signature:expr, $($param:expr),*) => {{ + let mut hasher = Keccak256::new(); + hasher.update($function_signature); + let function_selector = &hasher.finalize()[..4]; + let mut data = Vec::from(function_selector); + + $( + let p = $param.tokenize(); + data.extend_from_slice(abi::encode(&p).as_slice()); + )* + + alloy_primitives::Bytes::from(data) + }}; +} \ No newline at end of file diff --git a/utils/src/test_utils/mod.rs b/utils/src/test_utils/mod.rs index c8b1160..c044437 100644 --- a/utils/src/test_utils/mod.rs +++ b/utils/src/test_utils/mod.rs @@ -1,3 +1,4 @@ pub mod anvil; pub mod local_chain; mod random_port; +pub mod abi; From 7c1640330c8878c4d4c34b2ee6bea01bd380c18f Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Thu, 8 Aug 2024 18:24:31 -0500 Subject: [PATCH 09/43] Testing utilities WIP and reorganization --- Cargo.lock | 69 +- Cargo.toml | 5 +- avs/incredible-squaring-avs/src/operator.rs | 817 ------------------ eigensdk-rs/src/lib.rs | 4 +- test-utils/Cargo.toml | 64 ++ .../src/anvil}/abi.rs | 2 +- .../src/anvil}/anvil.rs | 0 .../src/anvil}/local_chain.rs | 42 - .../src/anvil}/mod.rs | 3 +- .../src/anvil}/random_port.rs | 0 .../src/anvil/testnet/incredible_squaring.rs | 733 ++++++++++++++++ test-utils/src/anvil/testnet/mod.rs | 1 + test-utils/src/incredible_squaring.rs | 199 +++++ test-utils/src/lib.rs | 2 + utils/src/lib.rs | 1 - 15 files changed, 1075 insertions(+), 867 deletions(-) create mode 100644 test-utils/Cargo.toml rename {utils/src/test_utils => test-utils/src/anvil}/abi.rs (99%) rename {utils/src/test_utils => test-utils/src/anvil}/anvil.rs (100%) rename {utils/src/test_utils => test-utils/src/anvil}/local_chain.rs (72%) rename {utils/src/test_utils => test-utils/src/anvil}/mod.rs (79%) rename {utils/src/test_utils => test-utils/src/anvil}/random_port.rs (100%) create mode 100644 test-utils/src/anvil/testnet/incredible_squaring.rs create mode 100644 test-utils/src/anvil/testnet/mod.rs create mode 100644 test-utils/src/incredible_squaring.rs create mode 100644 test-utils/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 8733085..91b0c24 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -127,6 +127,23 @@ dependencies = [ "alloy-transport-http 0.1.4", ] +[[package]] +name = "alloy" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f4a4aaae80afd4be443a6aecd92a6b255dcdd000f97996928efb33d8a71e100" +dependencies = [ + "alloy-consensus 0.2.1", + "alloy-core", + "alloy-eips 0.2.1", + "alloy-genesis 0.2.1", + "alloy-provider 0.2.1", + "alloy-rpc-client 0.2.1", + "alloy-serde 0.2.1", + "alloy-signer 0.2.1", + "alloy-transport-http 0.2.1", +] + [[package]] name = "alloy-abi" version = "0.1.0" @@ -6386,7 +6403,7 @@ dependencies = [ name = "incredible-squaring-avs" version = "0.1.0" dependencies = [ - "alloy", + "alloy 0.1.4", "alloy-abi", "alloy-contract", "alloy-primitives", @@ -11554,7 +11571,7 @@ dependencies = [ name = "tangle-avs" version = "0.1.0" dependencies = [ - "alloy", + "alloy 0.1.4", "alloy-consensus 0.2.1", "alloy-contract", "alloy-network 0.2.1", @@ -11660,6 +11677,54 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "test-utils" +version = "0.1.0" +dependencies = [ + "alloy 0.2.1", + "alloy-abi", + "alloy-contract", + "alloy-primitives", + "alloy-provider 0.2.1", + "alloy-pubsub", + "alloy-rpc-client 0.2.1", + "alloy-rpc-types", + "alloy-rpc-types-eth 0.2.1", + "alloy-signer 0.2.1", + "alloy-signer-local", + "alloy-sol-types", + "alloy-transport 0.2.1", + "alloy-transport-http 0.2.1", + "alloy-transport-ws", + "anvil", + "ark-bn254", + "async-trait", + "aws-kms", + "aws-sdk-kms", + "eigen-contracts", + "eigen-utils", + "env_logger 0.11.5", + "ethabi", + "foundry-common", + "futures", + "gadget-common", + "hex", + "http-body-util", + "hyper 1.4.1", + "incredible-squaring-avs", + "k256", + "log", + "prometheus", + "rand", + "reqwest 0.12.5", + "serde", + "serde_json", + "sha3", + "thiserror", + "tokio", + "url", +] + [[package]] name = "textwrap" version = "0.11.0" diff --git a/Cargo.toml b/Cargo.toml index 6af90d7..44e8361 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,9 +5,10 @@ members = [ "avs/tangle-avs", "aws", "contracts", - "utils", "eigensdk-rs", "fireblocks-client", + "test-utils", + "utils", ] [workspace.package] @@ -23,6 +24,7 @@ aws-kms = { path = "./aws" } eigen-contracts = { path = "./contracts" } eigen-utils = { path = "./utils" } fireblocks-client = { path = "./fireblocks-client" } +test-utils = { path = "./test-utils" } # AVS examples incredible-squaring-avs = { path = "./avs/incredible-squaring-avs" } @@ -133,6 +135,7 @@ http-body-util = "0.1.1" anvil = { git = "https://github.com/foundry-rs/foundry.git" } foundry-common = { git = "https://github.com/foundry-rs/foundry.git" } +alloy = "0.2.1" alloy-abi = "0.1.0" alloy-chains = "0.1.23" alloy-primitives = "0.7.7" diff --git a/avs/incredible-squaring-avs/src/operator.rs b/avs/incredible-squaring-avs/src/operator.rs index 0d12598..2a9b84d 100644 --- a/avs/incredible-squaring-avs/src/operator.rs +++ b/avs/incredible-squaring-avs/src/operator.rs @@ -419,820 +419,3 @@ impl Operator { Ok(signed_task_response) } } - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, Address, Uint}; - use alloy_provider::Provider; - use alloy_provider::ProviderBuilder; - use alloy_signer_local::PrivateKeySigner; - use alloy_transport_ws::WsConnect; - use k256::ecdsa::VerifyingKey; - use k256::elliptic_curve::SecretKey; - use std::path::Path; - use std::time::Duration; - use std::vec; - //, Bytes, U256}; - - static BLS_PASSWORD: &str = "BLS_PASSWORD"; - static ECDSA_PASSWORD: &str = "ECDSA_PASSWORD"; - static TASK_RESPONSE_WINDOW_BLOCK: u32 = 10; - static TASK_DURATION_BLOCKS: u32 = 0; - // static QUORUM_THRESHOLD_PERCENTAGE: U256 = U256::from(100); - static AGGREGATOR_ADDR: Address = address!("a0Ee7A142d267C1f36714E4a8F75612F20a79720"); - static TASK_GENERATOR_ADDR: Address = address!("a0Ee7A142d267C1f36714E4a8F75612F20a79720"); - - use crate::avs; - use alloy::signers::Signer; - use alloy_primitives::Keccak256; - use alloy_provider::network::{TransactionBuilder, TxSigner}; - use alloy_rpc_types_eth::BlockId; - use alloy_sol_types::abi::Encoder; - use alloy_sol_types::private::SolTypeValue; - use anvil::spawn; - use ark_bn254::Fq as F; - use ark_bn254::{Fr, G1Affine, G2Affine, G2Projective}; - use avs::IncredibleSquaringServiceManager; - use eigen_contracts::RegistryCoordinator::{OperatorSetParam, StrategyParams}; - use eigen_contracts::*; - // use ethabi::ethereum_types::H160; - // use ethabi::{encode, Token}; - use alloy_sol_types::abi::{self, token::*}; - use alloy_sol_types::Word; - use eigen_utils::encode_params; - use eigen_utils::test_utils::abi::encode_with_selector; - use gadget_common::subxt_signer::bip39::rand_core::OsRng; - use url::Url; - - struct ContractAddresses { - pub service_manager: Address, - pub registry_coordinator: Address, - pub operator_state_retriever: Address, - pub delegation_manager: Address, - pub avs_directory: Address, - pub operator: Address, - } - - async fn run_anvil_testnet() -> ContractAddresses { - // Initialize the logger - let _ = env_logger::try_init(); - - let (api, mut handle) = spawn(anvil::NodeConfig::test().with_port(33125)).await; - api.anvil_auto_impersonate_account(true).await.unwrap(); - // let http_provider = handle.http_provider(); - // let ws_provider = handle.ws_provider(); - - let _http_provider = ProviderBuilder::new() - .on_http(Url::parse(&handle.http_endpoint()).unwrap()) - .root() - .clone(); - // todo: http_provider is unused - - // let provider = ProviderBuilder::new().on_ws(WsConnect::new(handle.ws_endpoint())).await.unwrap(); - - let provider = ProviderBuilder::new() - .on_builtin(&handle.ws_endpoint()) - .await - .unwrap(); - - let accounts = handle.dev_wallets().collect::>(); - let from = accounts[0].address(); - let _to = accounts[1].address(); - - let _amount = handle - .genesis_balance() - .checked_div(U256::from(2u64)) - .unwrap(); - - let _gas_price = provider.get_gas_price().await.unwrap(); - - // Empty address for initial deployment of all contracts - let empty_address = Address::default(); - - // let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); - // let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); - // let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); - // let proxy_admin_addr = address!("5FbDB2315678afecb367f032d93F642f64180aa3"); - // let pauser_registry_addr = address!("e7f1725E7734CE288F8367e1Bb143E90bb3F0512"); - // let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); - - // Deploy Eigenlayer Contracts - // let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); - // let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); - // let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); - // let proxy_admin_addr = address!("5FbDB2315678afecb367f032d93F642f64180aa3"); - // let pauser_registry_addr = address!("e7f1725E7734CE288F8367e1Bb143E90bb3F0512"); - // let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); - - // let istrategy_manager = IStrategyManager::new(strategy_manager_addr, provider.clone()); - // let idelegation_manager = - // IDelegationManager::new(delegation_manager_addr, provider.clone()); - // let iavs_directory = IAVSDirectory::new(avs_directory_addr, provider.clone()); - // let proxy_admin = ProxyAdmin::new(proxy_admin_addr, provider.clone()); - // let pauser_registry = PauserRegistry::new(pauser_registry_addr, provider.clone()); - // let base_strategy = StrategyBaseTVLLimits::new(base_strategy_addr, provider.clone()); - - let istrategy_manager = IStrategyManager::deploy(provider.clone()).await.unwrap(); - let &strategy_manager_addr = istrategy_manager.address(); - - let idelegation_manager = IDelegationManager::deploy(provider.clone()).await.unwrap(); - let &delegation_manager_addr = idelegation_manager.address(); - - let iavs_directory = IAVSDirectory::deploy(provider.clone()).await.unwrap(); - let &avs_directory_addr = iavs_directory.address(); - - let proxy_admin = ProxyAdmin::deploy(provider.clone()).await.unwrap(); - let &proxy_admin_addr = proxy_admin.address(); - - let pauser_registry = PauserRegistry::deploy(provider.clone()).await.unwrap(); - let &pauser_registry_addr = pauser_registry.address(); - - let base_strategy = StrategyBaseTVLLimits::deploy(provider.clone(), Default::default()) - .await - .unwrap(); - let &base_strategy_addr = base_strategy.address(); - - let erc20_mock = ERC20Mock::deploy(provider.clone()).await.unwrap(); - let &erc20_mock_addr = erc20_mock.address(); - - let ierc20 = IERC20::new(erc20_mock_addr, provider.clone()); - let &ierc20_addr = ierc20.address(); - - // Function with signature initialize(uint256,uint256,address,address) and selector 0x019e2729. - let function_signature = "initialize(uint256,uint256,address,address)"; - // let params = vec![ - // 1.tokenize(), - // 100.tokenize(), - // ierc20_addr.tokenize(), - // pauser_registry_addr.tokenize(), - // // WordToken(Word::from(1)), - // // WordToken(Word::from(100)), - // // WordToken(Word::from(ierc20_addr.as_slice())), - // // WordToken(Word::from(pauser_registry_addr.as_slice())), - // ]; - // let encoded_data = encode_with_selector(function_signature, params); - // let encoded_data = encode_params!(function_signature, 1, 100, ierc20_addr, pauser_registry_addr); - - let mut hasher = Keccak256::new(); - hasher.update(function_signature); - let function_selector = &hasher.finalize()[..4]; - let hex_selector = hex::encode(function_selector); - log::info!("Function selector as hex: {:?}", hex_selector); - let mut data = Vec::from(function_selector); - // let encoded_param = SolValue::abi_encode(&1); - // data.extend_from_slice(&encoded_param); - // let encoded_param = SolValue::abi_encode(&100); - // data.extend_from_slice(&encoded_param); - // let encoded_param = SolValue::abi_encode(&ierc20_addr); - // data.extend_from_slice(&encoded_param); - // let encoded_param = SolValue::abi_encode(&pauser_registry_addr); - // data.extend_from_slice(&encoded_param); - let token = 1.tokenize(); - let encoded_param = abi::encode(&token); - data.extend(&encoded_param); - let token = 100.tokenize(); - let encoded_param = abi::encode(&token); - data.extend(&encoded_param); - let token = ierc20_addr.tokenize(); - let encoded_param = abi::encode(&token); - data.extend(&encoded_param); - let token = pauser_registry_addr.tokenize(); - let encoded_param = abi::encode(&token); - data.extend(&encoded_param); - - let encoded_data = alloy_primitives::Bytes::from(data); - - let strategy_proxy = TransparentUpgradeableProxy::deploy( - provider.clone(), - base_strategy_addr, - proxy_admin_addr, - encoded_data, - ) - .await - .unwrap(); - let &strategy_proxy_addr = strategy_proxy.address(); - - let erc20_mock_strategy = - StrategyBaseTVLLimits::deploy(provider.clone(), strategy_proxy_addr) - .await - .unwrap(); - let &erc20_mock_strategy_addr = erc20_mock_strategy.address(); - - let strategies = vec![erc20_mock_strategy_addr]; - - let add_strategies = istrategy_manager - .addStrategiesToDepositWhitelist(strategies.clone(), vec![false]) - .send() - .await - .unwrap() - .get_receipt() - .await - .unwrap(); - println!("Add Strategies Receipt: {:?}", add_strategies); - - // Deploy Incredible Squaring Contracts - let number_of_strategies = strategies.len(); - - let incredible_squaring_proxy_admin = ProxyAdmin::deploy(provider.clone()).await.unwrap(); - let &incredible_squaring_proxy_admin_addr = incredible_squaring_proxy_admin.address(); - - let pausers = vec![ - address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), - address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), - ]; - - let incredible_squaring_pauser_registry_addr = - PauserRegistry::deploy_builder(provider.clone()) - .from(from) - .send() - .await - .unwrap() - .get_receipt() - .await - .unwrap() - .contract_address - .unwrap(); - let incredible_squaring_pauser_registry = - PauserRegistry::new(incredible_squaring_pauser_registry_addr, provider.clone()); - let is_pauser = incredible_squaring_pauser_registry - .isPauser(address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266")) - .call() - .await - .unwrap(); - println!("Is Dev Account 0 Pauser: {:?}", is_pauser._0); - - let empty_contract = EmptyContract::deploy(provider.clone()).await.unwrap(); - let &empty_contract_addr = empty_contract.address(); - - let incredible_squaring_service_manager = IncredibleSquaringServiceManager::new( - TransparentUpgradeableProxy::deploy( - provider.clone(), - empty_contract_addr, - incredible_squaring_proxy_admin_addr, - Bytes::from(""), - ) - .await - .unwrap() - .address() - .clone(), - provider.clone(), - ); - let &incredible_squaring_service_manager_addr = - incredible_squaring_service_manager.address(); - - let incredible_squaring_task_manager = IncredibleSquaringTaskManager::new( - TransparentUpgradeableProxy::deploy( - provider.clone(), - empty_contract_addr, - incredible_squaring_proxy_admin_addr, - Bytes::from(""), - ) - .await - .unwrap() - .address() - .clone(), - provider.clone(), - ); - let &incredible_squaring_task_manager_addr = incredible_squaring_task_manager.address(); - - let registry_coordinator = RegistryCoordinator::new( - TransparentUpgradeableProxy::deploy( - provider.clone(), - empty_contract_addr, - incredible_squaring_proxy_admin_addr, - Bytes::from(""), - ) - .await - .unwrap() - .address() - .clone(), - provider.clone(), - ); - let ®istry_coordinator_addr = registry_coordinator.address(); - - let bls_apk_registry = BlsApkRegistry::new( - TransparentUpgradeableProxy::deploy( - provider.clone(), - empty_contract_addr, - incredible_squaring_proxy_admin_addr, - Bytes::from(""), - ) - .await - .unwrap() - .address() - .clone(), - provider.clone(), - ); - let &bls_apk_registry_addr = bls_apk_registry.address(); - - let bls_apk_registry = IBlsApkRegistry::new( - TransparentUpgradeableProxy::deploy( - provider.clone(), - empty_contract_addr, - incredible_squaring_proxy_admin_addr, - Bytes::from(""), - ) - .await - .unwrap() - .address() - .clone(), - provider.clone(), - ); - let &bls_apk_registry_addr = bls_apk_registry.address(); - - let index_registry = IIndexRegistry::new( - TransparentUpgradeableProxy::deploy( - provider.clone(), - empty_contract_addr, - incredible_squaring_proxy_admin_addr, - Bytes::from(""), - ) - .await - .unwrap() - .address() - .clone(), - provider.clone(), - ); - let &index_registry_addr = index_registry.address(); - - let stake_registry = IStakeRegistry::new( - TransparentUpgradeableProxy::deploy( - provider.clone(), - empty_contract_addr, - incredible_squaring_proxy_admin_addr, - Bytes::from(""), - ) - .await - .unwrap() - .address() - .clone(), - provider.clone(), - ); - let &stake_registry_addr = stake_registry.address(); - - let operator_state_retriever = OperatorStateRetriever::deploy(provider.clone()) - .await - .unwrap(); - let &operator_state_retriever_addr = operator_state_retriever.address(); - - //Now, deploy the implementation contracts using the proxy contracts as inputs - let stake_registry_implementation = StakeRegistry::deploy( - provider.clone(), - registry_coordinator_addr, - delegation_manager_addr, - ) - .await - .unwrap(); - let &stake_registry_implementation_addr = stake_registry_implementation.address(); - let stake_registry_upgrade = incredible_squaring_proxy_admin - .upgrade(stake_registry_addr, stake_registry_implementation_addr) - .send() - .await - .unwrap() - .get_receipt() - .await - .unwrap(); - log::info!( - "Stake Registry Upgrade Receipt: {:?}", - stake_registry_upgrade - ); - - let bls_apk_registry_implementation = - BlsApkRegistry::deploy(provider.clone(), registry_coordinator_addr) - .await - .unwrap(); - let &bls_apk_registry_implementation_addr = bls_apk_registry_implementation.address(); - let bls_apk_registry_upgrade = incredible_squaring_proxy_admin - .upgrade(bls_apk_registry_addr, bls_apk_registry_implementation_addr) - .send() - .await - .unwrap() - .get_receipt() - .await - .unwrap(); - log::info!( - "Bls Apk Registry Upgrade Receipt: {:?}", - bls_apk_registry_upgrade - ); - - let index_registry_implementation = - IndexRegistry::deploy(provider.clone(), registry_coordinator_addr) - .await - .unwrap(); - let &index_registry_implementation_addr = index_registry_implementation.address(); - let index_registry_upgrade = incredible_squaring_proxy_admin - .upgrade(index_registry_addr, index_registry_implementation_addr) - .send() - .await - .unwrap() - .get_receipt() - .await - .unwrap(); - log::info!( - "Index Registry Upgrade Receipt: {:?}", - index_registry_upgrade - ); - - let registry_coordinator_implementation = RegistryCoordinator::deploy( - provider.clone(), - incredible_squaring_service_manager_addr, - stake_registry_addr, - bls_apk_registry_addr, - index_registry_addr, - ) - .await - .unwrap(); - let ®istry_coordinator_implementation_addr = - registry_coordinator_implementation.address(); - - let number_of_quorums = 1; - // For each quorum we want to set up, we must define QuorumOperatorSetParam, minimumStakeForQuorum, and strategyParams - let mut quorum_operator_set_params = Vec::::new(); - for i in 0..number_of_quorums { - log::info!("Deploying quorum {}", i); - quorum_operator_set_params.push(OperatorSetParam { - maxOperatorCount: 10000, - kickBIPsOfOperatorStake: 15000, - kickBIPsOfTotalStake: 100, - }); - } - // Set to 0 for each quorum - let quorums_minimum_stake = Vec::::new(); - let mut quorums_strategy_params = Vec::>::new(); - - for j in 0..number_of_quorums { - quorums_strategy_params.push(Vec::::new()); - for k in 0..number_of_strategies { - quorums_strategy_params[j][k] = StrategyParams { - strategy: strategies[j], - multiplier: 1, - } - } - } - - // Function with signature initialize(address,address,address,address,uint256,(uint32,uint16,uint16)[],uint96[],(address,uint96)[][]) and selector 0xdd8283f3. - let function_signature = "initialize(address,address,address,address,uint256,(uint32,uint16,uint16)[],uint96[],(address,uint96)[][])"; - - let encoded_data = encode_params!( - function_signature, - pausers[0], - pausers[0], - pausers[0], - pausers[1], - 0, - quorum_operator_set_params, - quorums_minimum_stake, - quorums_strategy_params - ); - let registry_coordinator_upgrade = incredible_squaring_proxy_admin - .upgradeAndCall( - registry_coordinator_addr, - registry_coordinator_implementation_addr, - alloy_primitives::Bytes::from(encoded_data), - ) - .send() - .await - .unwrap() - .get_receipt() - .await - .unwrap(); - log::info!( - "Registry Coordinator Upgrade Receipt: {:?}", - registry_coordinator_upgrade - ); - - let incredible_squaring_service_manager_implementation = - IncredibleSquaringServiceManager::deploy( - provider.clone(), - avs_directory_addr, - registry_coordinator_addr, - stake_registry_addr, - incredible_squaring_task_manager_addr, - ) - .await - .unwrap(); - let &incredible_squaring_service_manager_implementation_addr = - incredible_squaring_service_manager_implementation.address(); - let incredible_squaring_service_manager_upgrade = incredible_squaring_proxy_admin - .upgrade( - incredible_squaring_service_manager_addr, - incredible_squaring_service_manager_implementation_addr, - ) - .send() - .await - .unwrap() - .get_receipt() - .await - .unwrap(); - log::info!( - "Incredible Squaring Service Manager Upgrade Receipt: {:?}", - incredible_squaring_service_manager_upgrade - ); - - // Function with signature initialize(address,address,address,address) and selector 0xf8c8765e. - let function_signature = "initialize(address,address,address,address)"; - // let params = vec![ - // pauser_registry_addr.tokenize(), - // pausers[0].tokenize(), - // AGGREGATOR_ADDR.tokenize(), - // TASK_GENERATOR_ADDR.tokenize(), - // ]; - // let encoded_data = - // eigen_utils::test_utils::abi::encode_with_selector(function_signature, params); - - let encoded_data = encode_params!( - function_signature, - pauser_registry_addr, - pausers[0], - AGGREGATOR_ADDR, - TASK_GENERATOR_ADDR - ); - let incredible_squaring_task_manager_implementation = - IncredibleSquaringTaskManager::deploy( - provider.clone(), - registry_coordinator_addr, - TASK_RESPONSE_WINDOW_BLOCK, - ) - .await - .unwrap(); - let &incredible_squaring_task_manager_implementation_addr = - incredible_squaring_task_manager_implementation.address(); - let incredible_squaring_task_manager_upgrade = incredible_squaring_proxy_admin - .upgradeAndCall( - incredible_squaring_task_manager_addr, - incredible_squaring_service_manager_implementation_addr, - alloy_primitives::Bytes::from(encoded_data), - ) - .send() - .await - .unwrap() - .get_receipt() - .await - .unwrap(); - log::info!( - "Incredible Squaring Task Manager Upgrade Receipt: {:?}", - incredible_squaring_task_manager_upgrade - ); - - log::info!("ERC20MOCK ADDRESS: {:?}", erc20_mock_addr); - log::info!("ERC20MOCK STRATEGY ADDRESS: {:?}", erc20_mock_strategy_addr); - log::info!( - "INCREDIBLE SQUARING TASK MANAGER ADDRESS: {:?}", - incredible_squaring_task_manager_addr - ); - log::info!( - "INCREDIBLE SQUARING TASK MANAGER IMPLEMENTATION ADDRESS: {:?}", - incredible_squaring_task_manager_implementation_addr - ); - log::info!( - "INCREDIBLE SQUARING SERVICE MANAGER ADDRESS: {:?}", - incredible_squaring_service_manager_addr - ); - log::info!( - "INCREDIBLE SQUARING SERVICE MANAGER IMPLEMENTATION ADDRESS: {:?}", - incredible_squaring_service_manager_implementation_addr - ); - log::info!( - "REGISTRY COORDINATOR ADDRESS: {:?}", - registry_coordinator_addr - ); - log::info!( - "REGISTRY COORDINATOR IMPLEMENTATION ADDRESS: {:?}", - registry_coordinator_implementation_addr - ); - log::info!( - "OPERATOR STATE RETRIEVER ADDRESS: {:?}", - operator_state_retriever_addr - ); - - // let _block = provider - // .get_block(BlockId::latest(), false.into()) - // .await - // .unwrap() - // .unwrap(); - // - // api.anvil_set_auto_mine(true).await.unwrap(); - // let run_testnet = async move { - // let serv = handle.servers.pop().unwrap(); - // let res = serv.await.unwrap(); - // res.unwrap(); - // }; - // let spawner_task_manager_address = task_manager_addr.clone(); - // // let spawner_provider = provider.clone(); - // let spawner_provider = provider; - // let task_spawner = async move { - // let manager = IncredibleSquaringTaskManager::new( - // spawner_task_manager_address, - // spawner_provider.clone(), - // ); - // loop { - // api.mine_one().await; - // log::info!("About to create new task"); - // tokio::time::sleep(std::time::Duration::from_millis(5000)).await; - // let result = manager - // .createNewTask(U256::from(2), 100u32, Bytes::from("0")) - // .send() - // .await - // .unwrap() - // .watch() - // .await - // .unwrap(); - // api.mine_one().await; - // log::info!("Created new task: {:?}", result); - // // let latest_task = manager.latestTaskNum().call().await.unwrap()._0; - // // log::info!("Latest task: {:?}", latest_task); - // // let task_hash = manager.allTaskHashes(latest_task).call().await.unwrap()._0; - // // log::info!("Task info: {:?}", task_hash); - // } - // }; - // tokio::spawn(run_testnet); - // tokio::spawn(task_spawner); - - ContractAddresses { - service_manager: incredible_squaring_service_manager_implementation_addr, - registry_coordinator: registry_coordinator_implementation_addr, - operator_state_retriever: operator_state_retriever_addr, - delegation_manager: delegation_manager_addr, - avs_directory: avs_directory_addr, - operator: from, - } - } - - #[tokio::test] - async fn test_anvil() { - env_logger::init(); - - // Runs new Anvil Testnet - used for deploying programmatically in rust - let contract_addresses = run_anvil_testnet().await; - - // // Runs saved Anvil Testnet - loads from saved chain state JSON file - // let chain = eigen_utils::test_utils::local_chain::LocalEvmChain::new_with_chain_state( - // 31337, - // String::from("eigen-testnet"), - // Path::new("../../eigen-utils/saved-anvil-state.json"), - // Some(8545u16), - // ); - // let chain_id = chain.chain_id(); - // let chain_name = chain.name(); - // println!("chain_id: {:?}", chain_id); - // println!("chain_name: {:?}", chain_name); - - // let account_one = address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"); - // let account_two = address!("70997970C51812dc3A010C7d01b50e0d17dc79C8"); - - // let contract_addresses = ContractAddresses { - // service_manager: address!("84eA74d481Ee0A5332c457a4d796187F6Ba67fEB"), - // registry_coordinator: address!("a82fF9aFd8f496c3d6ac40E2a0F282E47488CFc9"), - // operator_state_retriever: address!("95401dc811bb5740090279Ba06cfA8fcF6113778"), - // delegation_manager: address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"), - // avs_directory: address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"), - // operator: account_two, - // }; - - // Implementation version of addresses - // let contract_addresses = ContractAddresses { - // service_manager: address!("84eA74d481Ee0A5332c457a4d796187F6Ba67fEB"), - // registry_coordinator: address!("9d4454B023096f34B160D6B654540c56A1F81688"), - // operator_state_retriever: address!("95401dc811bb5740090279Ba06cfA8fcF6113778"), - // delegation_manager: address!("B7f8BC63BbcaD18155201308C8f3540b07f84F5e"), - // avs_directory: address!("0DCd1Bf9A1b36cE34237eEaFef220932846BCD82"), - // operator: address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), - // }; - - let http_endpoint = "http://127.0.0.1:8545"; - let ws_endpoint = "ws://127.0.0.1:8545"; - let node_config = NodeConfig { - node_api_ip_port_address: "127.0.0.1:9808".to_string(), - eth_rpc_url: http_endpoint.to_string(), - eth_ws_url: ws_endpoint.to_string(), - bls_private_key_store_path: "./keystore/bls".to_string(), - ecdsa_private_key_store_path: "./keystore/ecdsa".to_string(), - incredible_squaring_service_manager_addr: contract_addresses - .service_manager - .to_string(), - avs_registry_coordinator_addr: contract_addresses.registry_coordinator.to_string(), - operator_state_retriever_addr: contract_addresses.operator_state_retriever.to_string(), - eigen_metrics_ip_port_address: "127.0.0.1:9100".to_string(), - delegation_manager_addr: contract_addresses.delegation_manager.to_string(), - avs_directory_addr: contract_addresses.avs_directory.to_string(), - operator_address: contract_addresses.operator.to_string(), - enable_metrics: false, - enable_node_api: false, - server_ip_port_address: "".to_string(), - }; - - let operator_info_service = OperatorInfoService {}; - - let hex_key = - hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d") - .unwrap(); - let secret_key = SecretKey::from_slice(&hex_key).unwrap(); - let signing_key = SigningKey::from(secret_key.clone()); - let signer = EigenGadgetSigner { - signer: PrivateKeySigner::from_signing_key(signing_key), - }; - - println!("Creating HTTP Provider..."); - - let http_provider = ProviderBuilder::new() - .with_recommended_fillers() - .on_http(http_endpoint.parse().unwrap()) - .root() - .clone() - .boxed(); - - println!("Creating WS Provider..."); - - let ws_provider = ProviderBuilder::new() - .with_recommended_fillers() - .on_ws(WsConnect::new(ws_endpoint)) - .await - .unwrap() - .root() - .clone() - .boxed(); - - println!("Now setting up Operator!"); - - let operator = Operator::::new_from_config( - node_config.clone(), - EigenGadgetProvider { - provider: http_provider, - }, - EigenGadgetProvider { - provider: ws_provider, - }, - operator_info_service, - signer, - ) - .await - .unwrap(); - - operator.start().await.unwrap(); - } - - #[tokio::test] - async fn test_start_chain_from_state() { - env_logger::init(); - - let chain = eigen_utils::test_utils::local_chain::LocalEvmChain::new_with_chain_state( - 31337, - String::from("eigen-testnet"), - Path::new("../../eigen-utils/eigen-gadget-anvil-state.json"), - Some(8545u16), - ); - let chain_id = chain.chain_id(); - let chain_name = chain.name(); - println!("chain_id: {:?}", chain_id); - println!("chain_name: {:?}", chain_name); - let addresses = chain.addresses(); - println!("addresses: {:?}", addresses); - tokio::time::sleep(Duration::from_secs(5)).await; - println!("Now shutting down..."); - chain.shutdown(); - } - - #[tokio::test] - async fn test_generate_keys() { - env_logger::init(); - - // ---------------- BLS ---------------- - let bls_pair = KeyPair::gen_random().unwrap(); - bls_pair - .save_to_file("./keystore/bls", BLS_PASSWORD) - .unwrap(); - let bls_keys = KeyPair::read_private_key_from_file("./keystore/bls", BLS_PASSWORD).unwrap(); - assert_eq!(bls_pair.priv_key, bls_keys.priv_key); - assert_eq!(bls_pair.pub_key, bls_keys.pub_key); - - //---------------- ECDSA ---------------- - // First Account - // let hex_key = - // hex::decode("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80") - // .unwrap(); - - // Second Account - let hex_key = - hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d") - .unwrap(); - - let secret_key = SecretKey::from_slice(&hex_key).unwrap(); - let signing_key = SigningKey::from(secret_key.clone()); - let public_key = secret_key.public_key(); - let verifying_key = VerifyingKey::from(public_key); - eigen_utils::crypto::ecdsa::write_key("./keystore/ecdsa", &secret_key, ECDSA_PASSWORD) - .unwrap(); - - let read_ecdsa_secret_key = - eigen_utils::crypto::ecdsa::read_key("./keystore/ecdsa", ECDSA_PASSWORD).unwrap(); - let read_ecdsa_public_key = read_ecdsa_secret_key.public_key(); - let read_ecdsa_signing_key = SigningKey::from(&read_ecdsa_secret_key); - let read_ecdsa_verifying_key = VerifyingKey::from(&read_ecdsa_signing_key); - - assert_eq!(secret_key, read_ecdsa_secret_key); - assert_eq!(public_key, read_ecdsa_public_key); - assert_eq!(signing_key, read_ecdsa_signing_key); - assert_eq!(verifying_key, read_ecdsa_verifying_key); - } -} diff --git a/eigensdk-rs/src/lib.rs b/eigensdk-rs/src/lib.rs index cada2f5..e39ffa8 100644 --- a/eigensdk-rs/src/lib.rs +++ b/eigensdk-rs/src/lib.rs @@ -1,5 +1,5 @@ pub use eigen_contracts; -pub use tangle_avs; -pub use incredible_squaring_avs; pub use eigen_utils; pub use fireblocks_client; +pub use incredible_squaring_avs; +pub use tangle_avs; diff --git a/test-utils/Cargo.toml b/test-utils/Cargo.toml new file mode 100644 index 0000000..44466d0 --- /dev/null +++ b/test-utils/Cargo.toml @@ -0,0 +1,64 @@ +[package] +name = "test-utils" +version = "0.1.0" +edition.workspace = true +authors.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true + +[dependencies] +alloy-abi.workspace = true +alloy-contract.workspace = true +alloy-primitives.workspace = true +alloy-provider.workspace = true +alloy-pubsub.workspace = true +alloy-rpc-client.workspace = true +alloy-rpc-types.workspace = true +alloy-sol-types.workspace = true +alloy-signer.workspace = true +alloy-signer-local = { workspace = true, features = ["keystore"] } +alloy-transport-http.workspace = true +alloy-transport-ws.workspace = true +alloy-transport.workspace = true +async-trait.workspace = true +aws-sdk-kms.workspace = true + +eigen-contracts.workspace = true +eigen-utils.workspace = true +incredible-squaring-avs.workspace = true +#tangle-avs.workspace = true +aws-kms.workspace = true +gadget-common = { workspace = true, default-features = false, features = ["default"] } +# gadget-common = { workspace = true, features = ["tangle-testnet"] } + +foundry-common.workspace = true +futures.workspace = true +http-body-util.workspace = true +hyper = { workspace = true, features = ["full"] } +k256 = { workspace = true, features = ["expose-field"] } +prometheus.workspace = true +rand.workspace = true +reqwest.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +tokio.workspace = true +ethabi = "18.0.0" +anvil.workspace = true + +#tokio = { workspace = true, features = ["full"] } +alloy = { workspace = true, features = ["serde", "signers"] } +alloy-rpc-types-eth.workspace = true +#alloy-primitives = { workspace = true, features = ["rand"] } +#alloy-signer-local.workspace = true +log.workspace = true +env_logger.workspace = true +#getrandom.workspace = true +hex.workspace = true +#lazy_static.workspace = true +url.workspace = true +#ark-ec.workspace = true +#ark-ff.workspace = true +ark-bn254.workspace = true +sha3 = "0.10.8" \ No newline at end of file diff --git a/utils/src/test_utils/abi.rs b/test-utils/src/anvil/abi.rs similarity index 99% rename from utils/src/test_utils/abi.rs rename to test-utils/src/anvil/abi.rs index c4968e8..00f6541 100644 --- a/utils/src/test_utils/abi.rs +++ b/test-utils/src/anvil/abi.rs @@ -18,4 +18,4 @@ macro_rules! encode_params { alloy_primitives::Bytes::from(data) }}; -} \ No newline at end of file +} diff --git a/utils/src/test_utils/anvil.rs b/test-utils/src/anvil/anvil.rs similarity index 100% rename from utils/src/test_utils/anvil.rs rename to test-utils/src/anvil/anvil.rs diff --git a/utils/src/test_utils/local_chain.rs b/test-utils/src/anvil/local_chain.rs similarity index 72% rename from utils/src/test_utils/local_chain.rs rename to test-utils/src/anvil/local_chain.rs index e6fcbd6..d7c1526 100644 --- a/utils/src/test_utils/local_chain.rs +++ b/test-utils/src/anvil/local_chain.rs @@ -59,16 +59,6 @@ impl LocalEvmChain { self.chain_id } - // /// Returns typed EVM chain id - // pub fn typed_chain_id(&self) -> u64 { - // TypedChainId::Evm(self.chain_id).chain_id() - // } - - // pub fn contracts(&self) -> Vec { - // self.anvil_node_handle - // vec![] - // } - pub fn name(&self) -> &str { &self.name } @@ -127,35 +117,3 @@ impl LocalEvmChain { anvil.spawn() } } - -// #[cfg(test)] -// mod tests { -// use std::io::Error; -// use webb::evm::ethers::types::U256; -// -// use super::*; -// -// #[tokio::test] -// async fn should_load_old_state() -> Result<(), Error> { -// let state = tempfile::Builder::new() -// .prefix("evm-test-utils") -// .tempdir()?; -// assert!(state.path().is_dir()); -// -// let chain = -// LocalEvmChain::new_with_chain_state(5001, String::from("Hermes"), state.path(), None); -// let token = chain -// .deploy_token(String::from("Test"), String::from("TST")) -// .await?; -// let name = token.name().call().await?; -// assert_eq!(name, "Test"); -// chain.shutdown(); -// let chain = -// LocalEvmChain::new_with_chain_state(5001, String::from("Hermes"), state.path(), None); -// let token = ERC20PresetMinterPauserContract::new(token.address(), chain.client()); -// let name = token.name().call().await?; -// assert_eq!(name, "Test"); -// chain.shutdown(); -// Ok(()) -// } -// } diff --git a/utils/src/test_utils/mod.rs b/test-utils/src/anvil/mod.rs similarity index 79% rename from utils/src/test_utils/mod.rs rename to test-utils/src/anvil/mod.rs index c044437..040dc1b 100644 --- a/utils/src/test_utils/mod.rs +++ b/test-utils/src/anvil/mod.rs @@ -1,4 +1,5 @@ +pub mod abi; pub mod anvil; pub mod local_chain; mod random_port; -pub mod abi; +pub mod testnet; diff --git a/utils/src/test_utils/random_port.rs b/test-utils/src/anvil/random_port.rs similarity index 100% rename from utils/src/test_utils/random_port.rs rename to test-utils/src/anvil/random_port.rs diff --git a/test-utils/src/anvil/testnet/incredible_squaring.rs b/test-utils/src/anvil/testnet/incredible_squaring.rs new file mode 100644 index 0000000..decb549 --- /dev/null +++ b/test-utils/src/anvil/testnet/incredible_squaring.rs @@ -0,0 +1,733 @@ +use crate::encode_params; +use alloy::signers::Signer; +use alloy_primitives::{address, bytes::Bytes, Address, Keccak256, Uint, U256}; +use alloy_provider::network::{TransactionBuilder, TxSigner}; +use alloy_provider::{Provider, ProviderBuilder}; +use alloy_rpc_types_eth::BlockId; +use alloy_signer_local::PrivateKeySigner; +use alloy_sol_types::{ + abi::Encoder, + abi::{self, token::*}, + private::SolTypeValue, + SolValue, Word, +}; +use alloy_transport_ws::WsConnect; +use anvil::spawn; +use ark_bn254::{Fq as F, Fr, G1Affine, G2Affine, G2Projective}; +use eigen_contracts::{ + RegistryCoordinator::{OperatorSetParam, StrategyParams}, + *, +}; +use gadget_common::subxt_signer::bip39::rand_core::OsRng; +use incredible_squaring_avs::avs::{ + IncredibleSquaringServiceManager, IncredibleSquaringTaskManager, +}; +use k256::{ecdsa::VerifyingKey, elliptic_curve::SecretKey}; +use std::{path::Path, time::Duration}; +use url::Url; + +pub static BLS_PASSWORD: &str = "BLS_PASSWORD"; +pub static ECDSA_PASSWORD: &str = "ECDSA_PASSWORD"; +pub static TASK_RESPONSE_WINDOW_BLOCK: u32 = 10; +pub static TASK_DURATION_BLOCKS: u32 = 0; +// static QUORUM_THRESHOLD_PERCENTAGE: U256 = U256::from(100); +pub static AGGREGATOR_ADDR: Address = address!("a0Ee7A142d267C1f36714E4a8F75612F20a79720"); +pub static TASK_GENERATOR_ADDR: Address = address!("a0Ee7A142d267C1f36714E4a8F75612F20a79720"); + +pub struct ContractAddresses { + pub service_manager: Address, + pub registry_coordinator: Address, + pub operator_state_retriever: Address, + pub delegation_manager: Address, + pub avs_directory: Address, + pub operator: Address, +} +pub async fn run_anvil_testnet() -> ContractAddresses { + // Initialize the logger + let _ = env_logger::try_init(); + + let (api, mut handle) = spawn(anvil::NodeConfig::test().with_port(8545)).await; + api.anvil_auto_impersonate_account(true).await.unwrap(); + + let _http_provider = ProviderBuilder::new() + .on_http(Url::parse(&handle.http_endpoint()).unwrap()) + .root() + .clone(); + // todo: http_provider is unused + + let provider = ProviderBuilder::new() + .on_builtin(&handle.ws_endpoint()) + .await + .unwrap(); + + let accounts = handle.dev_wallets().collect::>(); + let from = accounts[0].address(); + let _to = accounts[1].address(); + + let dev_account = accounts[0].address(); + + let _amount = handle + .genesis_balance() + .checked_div(U256::from(2u64)) + .unwrap(); + + let _gas_price = provider.get_gas_price().await.unwrap(); + + // Empty address for initial deployment of all contracts + let empty_address = Address::default(); + + // let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); + // let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); + // let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); + // let proxy_admin_addr = address!("5FbDB2315678afecb367f032d93F642f64180aa3"); + // let pauser_registry_addr = address!("e7f1725E7734CE288F8367e1Bb143E90bb3F0512"); + // let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); + + // Deploy Eigenlayer Contracts + // let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); + // let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); + // let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); + // let proxy_admin_addr = address!("5FbDB2315678afecb367f032d93F642f64180aa3"); + // let pauser_registry_addr = address!("e7f1725E7734CE288F8367e1Bb143E90bb3F0512"); + // let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); + + // let istrategy_manager = IStrategyManager::new(strategy_manager_addr, provider.clone()); + // let idelegation_manager = + // IDelegationManager::new(delegation_manager_addr, provider.clone()); + // let iavs_directory = IAVSDirectory::new(avs_directory_addr, provider.clone()); + // let proxy_admin = ProxyAdmin::new(proxy_admin_addr, provider.clone()); + // let pauser_registry = PauserRegistry::new(pauser_registry_addr, provider.clone()); + // let base_strategy = StrategyBaseTVLLimits::new(base_strategy_addr, provider.clone()); + + let istrategy_manager = IStrategyManager::deploy(provider.clone()).await.unwrap(); + let &strategy_manager_addr = istrategy_manager.address(); + + let idelegation_manager = IDelegationManager::deploy(provider.clone()).await.unwrap(); + let &delegation_manager_addr = idelegation_manager.address(); + + let iavs_directory = IAVSDirectory::deploy(provider.clone()).await.unwrap(); + let &avs_directory_addr = iavs_directory.address(); + + let proxy_admin = ProxyAdmin::deploy_builder(provider.clone()) + .from(dev_account) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap() + .contract_address + .unwrap(); + let proxy_admin_addr = proxy_admin; + // let &proxy_admin_addr = proxy_admin.address(); + + let pauser_registry = PauserRegistry::deploy(provider.clone()).await.unwrap(); + let &pauser_registry_addr = pauser_registry.address(); + + let base_strategy = StrategyBaseTVLLimits::deploy(provider.clone(), Default::default()) + .await + .unwrap(); + let &base_strategy_addr = base_strategy.address(); + + let erc20_mock = ERC20Mock::deploy(provider.clone()).await.unwrap(); + let &erc20_mock_addr = erc20_mock.address(); + + let ierc20 = IERC20::new(erc20_mock_addr, provider.clone()); + let &ierc20_addr = ierc20.address(); + + // Function with signature initialize(uint256,uint256,address,address) and selector 0x019e2729. + let function_signature = "initialize(uint256,uint256,address,address)"; + // let params = vec![ + // 1.tokenize(), + // 100.tokenize(), + // ierc20_addr.tokenize(), + // pauser_registry_addr.tokenize(), + // // WordToken(Word::from(1)), + // // WordToken(Word::from(100)), + // // WordToken(Word::from(ierc20_addr.as_slice())), + // // WordToken(Word::from(pauser_registry_addr.as_slice())), + // ]; + // let encoded_data = encode_with_selector(function_signature, params); + // let encoded_data = encode_params!(function_signature, 1, 100, ierc20_addr, pauser_registry_addr); + + let mut hasher = Keccak256::new(); + hasher.update(function_signature); + let function_selector = &hasher.finalize()[..4]; + let hex_selector = hex::encode(function_selector); + log::info!("Function selector as hex: {:?}", hex_selector); + let mut data = Vec::from(function_selector); + // let encoded_param = SolValue::abi_encode(&1); + // data.extend_from_slice(&encoded_param); + // let encoded_param = SolValue::abi_encode(&100); + // data.extend_from_slice(&encoded_param); + // let encoded_param = SolValue::abi_encode(&ierc20_addr); + // data.extend_from_slice(&encoded_param); + // let encoded_param = SolValue::abi_encode(&pauser_registry_addr); + // data.extend_from_slice(&encoded_param); + let token = 1.tokenize(); + let encoded_param = abi::encode(&token); + data.extend(&encoded_param); + let token = 100.tokenize(); + let encoded_param = abi::encode(&token); + data.extend(&encoded_param); + let token = ierc20_addr.tokenize(); + let encoded_param = abi::encode(&token); + data.extend(&encoded_param); + let token = pauser_registry_addr.tokenize(); + let encoded_param = abi::encode(&token); + data.extend(&encoded_param); + + let encoded_data = alloy_primitives::Bytes::from(data); + + let strategy_proxy = TransparentUpgradeableProxy::deploy( + provider.clone(), + base_strategy_addr, + proxy_admin_addr, + encoded_data, + ) + .await + .unwrap(); + let &strategy_proxy_addr = strategy_proxy.address(); + + let erc20_mock_strategy = StrategyBaseTVLLimits::deploy(provider.clone(), strategy_proxy_addr) + .await + .unwrap(); + let &erc20_mock_strategy_addr = erc20_mock_strategy.address(); + + let strategies = vec![erc20_mock_strategy_addr]; + + let add_strategies = istrategy_manager + .addStrategiesToDepositWhitelist(strategies.clone(), vec![false]) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + println!("Add Strategies Receipt: {:?}", add_strategies); + + // Deploy Incredible Squaring Contracts + let number_of_strategies = strategies.len(); + println!("Number of Strategies: {:?}", number_of_strategies); + + // let incredible_squaring_proxy_admin = ProxyAdmin::deploy(provider.clone()).await.unwrap(); + // let &incredible_squaring_proxy_admin_addr = incredible_squaring_proxy_admin.address(); + let incredible_squaring_proxy_admin = ProxyAdmin::deploy_builder(provider.clone()) + .from(dev_account) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap() + .contract_address + .unwrap(); + let incredible_squaring_proxy_admin_addr = incredible_squaring_proxy_admin; + let incredible_squaring_proxy_admin = + ProxyAdmin::new(incredible_squaring_proxy_admin_addr, provider.clone()); + let owner = incredible_squaring_proxy_admin + .owner() + .call() + .await + .unwrap() + ._0; + println!("Owner: {:?}", owner); + + let pausers = vec![dev_account, dev_account]; + + // let incredible_squaring_pauser_registry_addr = + // PauserRegistry::deploy_builder(provider.clone()) + // .from(dev_account) + // .send() + // .await + // .unwrap() + // .get_receipt() + // .await + // .unwrap() + // .contract_address + // .unwrap(); + // println!("Pauser Registry Address: {:?}", incredible_squaring_pauser_registry_addr); + // let incredible_squaring_pauser_registry = + // PauserRegistry::new(incredible_squaring_pauser_registry_addr, provider.clone()); + // incredible_squaring_pauser_registry.address(); + // println!("Pauser Registry: {:?}", incredible_squaring_pauser_registry); + + let incredible_squaring_pauser_registry = + PauserRegistry::deploy(provider.clone()).await.unwrap(); + let &incredible_squaring_pauser_registry_addr = incredible_squaring_pauser_registry.address(); + println!( + "Pauser Registry Address: {:?}", + incredible_squaring_pauser_registry_addr + ); + + // let unpauser = incredible_squaring_pauser_registry.unpauser().from(dev_account).call().await.unwrap()._0; + // println!("Unpauser: {:?}", unpauser); + // + // let is_pauser = incredible_squaring_pauser_registry + // .isPauser(dev_account) + // .from(dev_account) + // .call() + // .await + // .unwrap(); + // println!("Is Dev Account 0 Pauser: {:?}", is_pauser._0); + + let empty_contract = EmptyContract::deploy(provider.clone()).await.unwrap(); + let &empty_contract_addr = empty_contract.address(); + + let incredible_squaring_service_manager = IncredibleSquaringServiceManager::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let &incredible_squaring_service_manager_addr = incredible_squaring_service_manager.address(); + + let incredible_squaring_task_manager = IncredibleSquaringTaskManager::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let &incredible_squaring_task_manager_addr = incredible_squaring_task_manager.address(); + + let registry_coordinator = RegistryCoordinator::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let ®istry_coordinator_addr = registry_coordinator.address(); + + let bls_apk_registry = BlsApkRegistry::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let &bls_apk_registry_addr = bls_apk_registry.address(); + + let bls_apk_registry = IBlsApkRegistry::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let &bls_apk_registry_addr = bls_apk_registry.address(); + + let index_registry = IIndexRegistry::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let &index_registry_addr = index_registry.address(); + + let stake_registry = IStakeRegistry::new( + TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address() + .clone(), + provider.clone(), + ); + let &stake_registry_addr = stake_registry.address(); + + let operator_state_retriever = OperatorStateRetriever::deploy(provider.clone()) + .await + .unwrap(); + let &operator_state_retriever_addr = operator_state_retriever.address(); + + //Now, deploy the implementation contracts using the proxy contracts as inputs + let stake_registry_implementation = StakeRegistry::deploy( + provider.clone(), + registry_coordinator_addr, + delegation_manager_addr, + ) + .await + .unwrap(); + let &stake_registry_implementation_addr = stake_registry_implementation.address(); + let stake_registry_upgrade = incredible_squaring_proxy_admin + .upgrade(stake_registry_addr, stake_registry_implementation_addr) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + log::info!( + "Stake Registry Upgrade Receipt: {:?}", + stake_registry_upgrade + ); + + let bls_apk_registry_implementation = + BlsApkRegistry::deploy(provider.clone(), registry_coordinator_addr) + .await + .unwrap(); + let &bls_apk_registry_implementation_addr = bls_apk_registry_implementation.address(); + let bls_apk_registry_upgrade = incredible_squaring_proxy_admin + .upgrade(bls_apk_registry_addr, bls_apk_registry_implementation_addr) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + log::info!( + "Bls Apk Registry Upgrade Receipt: {:?}", + bls_apk_registry_upgrade + ); + + let index_registry_implementation = + IndexRegistry::deploy(provider.clone(), registry_coordinator_addr) + .await + .unwrap(); + let &index_registry_implementation_addr = index_registry_implementation.address(); + let index_registry_upgrade = incredible_squaring_proxy_admin + .upgrade(index_registry_addr, index_registry_implementation_addr) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + log::info!( + "Index Registry Upgrade Receipt: {:?}", + index_registry_upgrade + ); + + let registry_coordinator_implementation = RegistryCoordinator::deploy( + provider.clone(), + incredible_squaring_service_manager_addr, + stake_registry_addr, + bls_apk_registry_addr, + index_registry_addr, + ) + .await + .unwrap(); + let ®istry_coordinator_implementation_addr = registry_coordinator_implementation.address(); + + let number_of_quorums = 1; + // For each quorum we want to set up, we must define QuorumOperatorSetParam, minimumStakeForQuorum, and strategyParams + let mut quorum_operator_set_params = Vec::::new(); + for i in 0..number_of_quorums { + log::info!("Deploying quorum {}", i); + quorum_operator_set_params.push(OperatorSetParam { + maxOperatorCount: 10000, + kickBIPsOfOperatorStake: 15000, + kickBIPsOfTotalStake: 100, + }); + } + // Set to 0 for each quorum + let mut quorums_minimum_stake = Vec::::new(); + let mut quorums_strategy_params = Vec::>::new(); + for j in 0..number_of_quorums { + quorums_strategy_params.push(Vec::::new()); + quorums_minimum_stake.push(0); + for k in 0..number_of_strategies { + quorums_strategy_params[j].push(StrategyParams { + strategy: strategies[j], + multiplier: 1, + }); + } + } + + // Function with signature initialize(address,address,address,address,uint256,(uint32,uint16,uint16)[],uint96[],(address,uint96)[][]) and selector 0xdd8283f3. + let function_signature = "initialize(address,address,address,address,uint256,(uint32,uint16,uint16)[],uint96[],(address,uint96)[][])"; + + let single_test = 0.tokenize(); + println!("Word Tokenize: {:?}", single_test); + let vec_test = quorum_operator_set_params.tokenize(); + println!("Vec Tokenize: {:?}", vec_test); + + let encoded_word = abi::encode(&single_test); + + let encoded_vec = abi::encode(&vec_test); + + println!( + "Quorums Strategy Params: Strategy: {:?} Multiplier: {:?}", + quorums_strategy_params[0][0].strategy, quorums_strategy_params[0][0].multiplier + ); + println!("Quorum Operator Set Params: Max Operators: {:?}, Kick BIPs of Operator Stake: {:?}, Kick BIPs of Total Stake: {:?}", quorum_operator_set_params[0].maxOperatorCount, quorum_operator_set_params[0].kickBIPsOfOperatorStake, quorum_operator_set_params[0].kickBIPsOfTotalStake); + println!("Quorums Minimum Stake: {:?}", quorums_minimum_stake); + + // let mut hasher = Keccak256::new(); + // hasher.update(function_signature); + // let function_selector = &hasher.finalize()[..4]; + // let mut data = Vec::from(function_selector); + // data.extend_from_slice(&abi::encode(&pausers[0].tokenize())); + // data.extend_from_slice(&abi::encode(&pausers[0].tokenize())); + // data.extend_from_slice(&abi::encode(&pausers[0].tokenize())); + // data.extend_from_slice(&abi::encode(&pausers[1].tokenize())); + // data.extend_from_slice(&abi::encode(&0.tokenize())); + // data.extend_from_slice(&abi::encode(&quorum_operator_set_params.tokenize())); + // data.extend_from_slice(&abi::encode(&quorums_minimum_stake.tokenize())); + // data.extend_from_slice(&abi::encode(&quorums_strategy_params.tokenize())); + // let encoded_data = alloy_primitives::Bytes::from(data); + + let encoded_data = encode_params!( + function_signature, + pausers[0], + pausers[0], + pausers[0], + pausers[1], + 0, + quorum_operator_set_params, + quorums_minimum_stake, + quorums_strategy_params + ); + // let registry_coordinator_upgrade = incredible_squaring_proxy_admin + // .upgradeAndCall( + // registry_coordinator_addr, + // registry_coordinator_implementation_addr, + // encoded_data, + // ) + // // .from(dev_account) + // .send() + // .await + // .unwrap() + // .get_receipt() + // .await + // .unwrap(); + // log::info!( + // "Registry Coordinator Upgrade Receipt: {:?}", + // registry_coordinator_upgrade + // ); + + let registry_coordinator_upgrade = incredible_squaring_proxy_admin + .upgrade( + registry_coordinator_addr, + registry_coordinator_implementation_addr, + ) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(registry_coordinator_upgrade.status()); + + let incredible_squaring_service_manager_implementation = + IncredibleSquaringServiceManager::deploy( + provider.clone(), + avs_directory_addr, + registry_coordinator_addr, + stake_registry_addr, + incredible_squaring_task_manager_addr, + ) + .await + .unwrap(); + let &incredible_squaring_service_manager_implementation_addr = + incredible_squaring_service_manager_implementation.address(); + let incredible_squaring_service_manager_upgrade = incredible_squaring_proxy_admin + .upgrade( + incredible_squaring_service_manager_addr, + incredible_squaring_service_manager_implementation_addr, + ) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + log::info!( + "Incredible Squaring Service Manager Upgrade Receipt: {:?}", + incredible_squaring_service_manager_upgrade + ); + + // Function with signature initialize(address,address,address,address) and selector 0xf8c8765e. + let function_signature = "initialize(address,address,address,address)"; + // let params = vec![ + // pauser_registry_addr.tokenize(), + // pausers[0].tokenize(), + // AGGREGATOR_ADDR.tokenize(), + // TASK_GENERATOR_ADDR.tokenize(), + // ]; + // let encoded_data = + // eigen_utils::test_utils::abi::encode_with_selector(function_signature, params); + + let encoded_data = encode_params!( + function_signature, + pauser_registry_addr, + pausers[0], + AGGREGATOR_ADDR, + TASK_GENERATOR_ADDR + ); + + println!( + "Registry Coordinator Address: {:?}", + registry_coordinator_addr + ); + // let incredible_squaring_task_manager_implementation = + // IncredibleSquaringTaskManager::deploy( + // provider.clone(), + // registry_coordinator_addr, + // // TASK_RESPONSE_WINDOW_BLOCK, + // 100u32, + // ) + // .await + // .unwrap(); + let incredible_squaring_task_manager_implementation_addr = + IncredibleSquaringTaskManager::deploy_builder( + provider.clone(), + registry_coordinator_addr, + TASK_RESPONSE_WINDOW_BLOCK, + ) + .from(dev_account) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap() + .contract_address + .unwrap(); + + // let &incredible_squaring_task_manager_implementation_addr = + // incredible_squaring_task_manager_implementation.address(); + let incredible_squaring_task_manager_upgrade = incredible_squaring_proxy_admin + .upgradeAndCall( + incredible_squaring_task_manager_addr, + incredible_squaring_service_manager_implementation_addr, + alloy_primitives::Bytes::from(encoded_data), + ) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + log::info!( + "Incredible Squaring Task Manager Upgrade Receipt: {:?}", + incredible_squaring_task_manager_upgrade + ); + + log::info!("ERC20MOCK ADDRESS: {:?}", erc20_mock_addr); + log::info!("ERC20MOCK STRATEGY ADDRESS: {:?}", erc20_mock_strategy_addr); + log::info!( + "INCREDIBLE SQUARING TASK MANAGER ADDRESS: {:?}", + incredible_squaring_task_manager_addr + ); + log::info!( + "INCREDIBLE SQUARING TASK MANAGER IMPLEMENTATION ADDRESS: {:?}", + incredible_squaring_task_manager_implementation_addr + ); + log::info!( + "INCREDIBLE SQUARING SERVICE MANAGER ADDRESS: {:?}", + incredible_squaring_service_manager_addr + ); + log::info!( + "INCREDIBLE SQUARING SERVICE MANAGER IMPLEMENTATION ADDRESS: {:?}", + incredible_squaring_service_manager_implementation_addr + ); + log::info!( + "REGISTRY COORDINATOR ADDRESS: {:?}", + registry_coordinator_addr + ); + log::info!( + "REGISTRY COORDINATOR IMPLEMENTATION ADDRESS: {:?}", + registry_coordinator_implementation_addr + ); + log::info!( + "OPERATOR STATE RETRIEVER ADDRESS: {:?}", + operator_state_retriever_addr + ); + + // let _block = provider + // .get_block(BlockId::latest(), false.into()) + // .await + // .unwrap() + // .unwrap(); + // + // api.anvil_set_auto_mine(true).await.unwrap(); + // let run_testnet = async move { + // let serv = handle.servers.pop().unwrap(); + // let res = serv.await.unwrap(); + // res.unwrap(); + // }; + // let spawner_task_manager_address = task_manager_addr.clone(); + // // let spawner_provider = provider.clone(); + // let spawner_provider = provider; + // let task_spawner = async move { + // let manager = IncredibleSquaringTaskManager::new( + // spawner_task_manager_address, + // spawner_provider.clone(), + // ); + // loop { + // api.mine_one().await; + // log::info!("About to create new task"); + // tokio::time::sleep(std::time::Duration::from_millis(5000)).await; + // let result = manager + // .createNewTask(U256::from(2), 100u32, Bytes::from("0")) + // .send() + // .await + // .unwrap() + // .watch() + // .await + // .unwrap(); + // api.mine_one().await; + // log::info!("Created new task: {:?}", result); + // // let latest_task = manager.latestTaskNum().call().await.unwrap()._0; + // // log::info!("Latest task: {:?}", latest_task); + // // let task_hash = manager.allTaskHashes(latest_task).call().await.unwrap()._0; + // // log::info!("Task info: {:?}", task_hash); + // } + // }; + // tokio::spawn(run_testnet); + // tokio::spawn(task_spawner); + + ContractAddresses { + service_manager: incredible_squaring_service_manager_implementation_addr, + registry_coordinator: registry_coordinator_implementation_addr, + operator_state_retriever: operator_state_retriever_addr, + delegation_manager: delegation_manager_addr, + avs_directory: avs_directory_addr, + operator: from, + } +} diff --git a/test-utils/src/anvil/testnet/mod.rs b/test-utils/src/anvil/testnet/mod.rs new file mode 100644 index 0000000..284a9a8 --- /dev/null +++ b/test-utils/src/anvil/testnet/mod.rs @@ -0,0 +1 @@ +pub mod incredible_squaring; diff --git a/test-utils/src/incredible_squaring.rs b/test-utils/src/incredible_squaring.rs new file mode 100644 index 0000000..2486b5e --- /dev/null +++ b/test-utils/src/incredible_squaring.rs @@ -0,0 +1,199 @@ +use crate::anvil::testnet::incredible_squaring::*; +use alloy_provider::Provider; +use alloy_provider::ProviderBuilder; +use alloy_signer_local::PrivateKeySigner; +use alloy_transport_ws::WsConnect; +use incredible_squaring_avs::operator::*; +use k256::ecdsa::SigningKey; +use k256::elliptic_curve::SecretKey; + +async fn run_full_incredible_squaring_test() { + let _ = env_logger::try_init(); + + // Runs new Anvil Testnet - used for deploying programmatically in rust + let contract_addresses = run_anvil_testnet().await; + + // // Runs saved Anvil Testnet - loads from saved chain state JSON file + // let chain = eigen_utils::test_utils::local_chain::LocalEvmChain::new_with_chain_state( + // 31337, + // String::from("eigen-testnet"), + // Path::new("../../eigen-utils/saved-anvil-state.json"), + // Some(8545u16), + // ); + // let chain_id = chain.chain_id(); + // let chain_name = chain.name(); + // println!("chain_id: {:?}", chain_id); + // println!("chain_name: {:?}", chain_name); + + // let account_one = address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"); + // let account_two = address!("70997970C51812dc3A010C7d01b50e0d17dc79C8"); + + // let contract_addresses = ContractAddresses { + // service_manager: address!("84eA74d481Ee0A5332c457a4d796187F6Ba67fEB"), + // registry_coordinator: address!("a82fF9aFd8f496c3d6ac40E2a0F282E47488CFc9"), + // operator_state_retriever: address!("95401dc811bb5740090279Ba06cfA8fcF6113778"), + // delegation_manager: address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"), + // avs_directory: address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"), + // operator: account_two, + // }; + + // Implementation version of addresses + // let contract_addresses = ContractAddresses { + // service_manager: address!("84eA74d481Ee0A5332c457a4d796187F6Ba67fEB"), + // registry_coordinator: address!("9d4454B023096f34B160D6B654540c56A1F81688"), + // operator_state_retriever: address!("95401dc811bb5740090279Ba06cfA8fcF6113778"), + // delegation_manager: address!("B7f8BC63BbcaD18155201308C8f3540b07f84F5e"), + // avs_directory: address!("0DCd1Bf9A1b36cE34237eEaFef220932846BCD82"), + // operator: address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), + // }; + + let http_endpoint = "http://127.0.0.1:8545"; + let ws_endpoint = "ws://127.0.0.1:8545"; + let node_config = NodeConfig { + node_api_ip_port_address: "127.0.0.1:9808".to_string(), + eth_rpc_url: http_endpoint.to_string(), + eth_ws_url: ws_endpoint.to_string(), + bls_private_key_store_path: "./keystore/bls".to_string(), + ecdsa_private_key_store_path: "./keystore/ecdsa".to_string(), + incredible_squaring_service_manager_addr: contract_addresses.service_manager.to_string(), + avs_registry_coordinator_addr: contract_addresses.registry_coordinator.to_string(), + operator_state_retriever_addr: contract_addresses.operator_state_retriever.to_string(), + eigen_metrics_ip_port_address: "127.0.0.1:9100".to_string(), + delegation_manager_addr: contract_addresses.delegation_manager.to_string(), + avs_directory_addr: contract_addresses.avs_directory.to_string(), + operator_address: contract_addresses.operator.to_string(), + enable_metrics: false, + enable_node_api: false, + server_ip_port_address: "".to_string(), + }; + + let operator_info_service = OperatorInfoService {}; + + let hex_key = + hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d").unwrap(); + let secret_key = SecretKey::from_slice(&hex_key).unwrap(); + let signing_key = SigningKey::from(secret_key.clone()); + let signer = EigenGadgetSigner { + signer: PrivateKeySigner::from_signing_key(signing_key), + }; + + println!("Creating HTTP Provider..."); + + let http_provider = ProviderBuilder::new() + .with_recommended_fillers() + .on_http(http_endpoint.parse().unwrap()) + .root() + .clone() + .boxed(); + + println!("Creating WS Provider..."); + + let ws_provider = ProviderBuilder::new() + .with_recommended_fillers() + .on_ws(WsConnect::new(ws_endpoint)) + .await + .unwrap() + .root() + .clone() + .boxed(); + + println!("Now setting up Operator!"); + + let operator = Operator::::new_from_config( + node_config.clone(), + EigenGadgetProvider { + provider: http_provider, + }, + EigenGadgetProvider { + provider: ws_provider, + }, + operator_info_service, + signer, + ) + .await + .unwrap(); + + operator.start().await.unwrap(); +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy::signers::Signer; + use alloy_provider::network::TransactionBuilder; + use eigen_utils::crypto::bls::KeyPair; + use k256::ecdsa::VerifyingKey; + use k256::elliptic_curve::SecretKey; + use std::path::Path; + use std::time::Duration; + + #[tokio::test] + async fn test_anvil() { + env_logger::init(); + run_full_incredible_squaring_test().await; + } + + #[tokio::test] + async fn test_start_chain_from_state() { + env_logger::init(); + + let chain = crate::anvil::local_chain::LocalEvmChain::new_with_chain_state( + 31337, + String::from("eigen-testnet"), + Path::new("../../eigen-utils/eigen-gadget-anvil-state.json"), + Some(8545u16), + ); + let chain_id = chain.chain_id(); + let chain_name = chain.name(); + println!("chain_id: {:?}", chain_id); + println!("chain_name: {:?}", chain_name); + let addresses = chain.addresses(); + println!("addresses: {:?}", addresses); + tokio::time::sleep(Duration::from_secs(5)).await; + println!("Now shutting down..."); + chain.shutdown(); + } + + #[tokio::test] + async fn test_generate_keys() { + env_logger::init(); + + // ---------------- BLS ---------------- + let bls_pair = KeyPair::gen_random().unwrap(); + bls_pair + .save_to_file("./keystore/bls", BLS_PASSWORD) + .unwrap(); + let bls_keys = KeyPair::read_private_key_from_file("./keystore/bls", BLS_PASSWORD).unwrap(); + assert_eq!(bls_pair.priv_key, bls_keys.priv_key); + assert_eq!(bls_pair.pub_key, bls_keys.pub_key); + + //---------------- ECDSA ---------------- + // First Account + // let hex_key = + // hex::decode("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80") + // .unwrap(); + + // Second Account + let hex_key = + hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d") + .unwrap(); + + let secret_key = SecretKey::from_slice(&hex_key).unwrap(); + let signing_key = SigningKey::from(secret_key.clone()); + let public_key = secret_key.public_key(); + let verifying_key = VerifyingKey::from(public_key); + eigen_utils::crypto::ecdsa::write_key("./keystore/ecdsa", &secret_key, ECDSA_PASSWORD) + .unwrap(); + + let read_ecdsa_secret_key = + eigen_utils::crypto::ecdsa::read_key("./keystore/ecdsa", ECDSA_PASSWORD).unwrap(); + let read_ecdsa_public_key = read_ecdsa_secret_key.public_key(); + let read_ecdsa_signing_key = SigningKey::from(&read_ecdsa_secret_key); + let read_ecdsa_verifying_key = VerifyingKey::from(&read_ecdsa_signing_key); + + assert_eq!(secret_key, read_ecdsa_secret_key); + assert_eq!(public_key, read_ecdsa_public_key); + assert_eq!(signing_key, read_ecdsa_signing_key); + assert_eq!(verifying_key, read_ecdsa_verifying_key); + } +} diff --git a/test-utils/src/lib.rs b/test-utils/src/lib.rs new file mode 100644 index 0000000..2cdfd09 --- /dev/null +++ b/test-utils/src/lib.rs @@ -0,0 +1,2 @@ +pub mod anvil; +pub mod incredible_squaring; diff --git a/utils/src/lib.rs b/utils/src/lib.rs index 9d84c05..cf3708b 100644 --- a/utils/src/lib.rs +++ b/utils/src/lib.rs @@ -9,7 +9,6 @@ pub mod crypto; pub mod el_contracts; pub mod node_api; pub mod services; -pub mod test_utils; pub mod types; pub mod utils; // pub mod curve_utils; From a55799d6edd2a4ba6f36522bbdd4283d55dfca77 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Fri, 9 Aug 2024 19:17:42 -0500 Subject: [PATCH 10/43] Debugging Contracts and some cleanup --- Cargo.lock | 2 + Cargo.toml | 1 + avs/incredible-squaring-avs/src/avs/mod.rs | 1 - avs/incredible-squaring-avs/src/operator.rs | 4 +- avs/tangle-avs/src/operator.rs | 2 +- contracts/src/lib.rs | 7 ++ test-utils/Cargo.toml | 4 +- test-utils/keystore/bls | 1 + test-utils/keystore/ecdsa | 1 + test-utils/src/anvil/anvil.rs | 55 +---------- test-utils/src/anvil/local_chain.rs | 6 +- .../src/anvil/testnet/incredible_squaring.rs | 98 +++++++++++++++---- test-utils/src/incredible_squaring.rs | 20 ++-- utils/src/avs_registry/writer.rs | 23 +++-- utils/src/crypto/bls.rs | 3 +- utils/src/el_contracts/reader.rs | 2 +- utils/src/el_contracts/writer.rs | 4 +- utils/src/types.rs | 5 +- 18 files changed, 133 insertions(+), 106 deletions(-) create mode 100644 test-utils/keystore/bls create mode 100644 test-utils/keystore/ecdsa diff --git a/Cargo.lock b/Cargo.lock index 91b0c24..4026692 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11705,6 +11705,7 @@ dependencies = [ "eigen-utils", "env_logger 0.11.5", "ethabi", + "ethers", "foundry-common", "futures", "gadget-common", @@ -11714,6 +11715,7 @@ dependencies = [ "incredible-squaring-avs", "k256", "log", + "nix 0.28.0", "prometheus", "rand", "reqwest 0.12.5", diff --git a/Cargo.toml b/Cargo.toml index 44e8361..94e1661 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -132,6 +132,7 @@ picky-asn1-der = "0.5.0" hyper = "1.3.1" pin-project-lite = "0.2.14" http-body-util = "0.1.1" +ethers = "2.0.14" anvil = { git = "https://github.com/foundry-rs/foundry.git" } foundry-common = { git = "https://github.com/foundry-rs/foundry.git" } diff --git a/avs/incredible-squaring-avs/src/avs/mod.rs b/avs/incredible-squaring-avs/src/avs/mod.rs index c2fae0d..375471e 100644 --- a/avs/incredible-squaring-avs/src/avs/mod.rs +++ b/avs/incredible-squaring-avs/src/avs/mod.rs @@ -3,7 +3,6 @@ pub mod subscriber; pub mod writer; use alloy_primitives::{Address, Bytes, U256}; -use alloy_provider::Provider; use alloy_rpc_types::{Log, TransactionReceipt}; use alloy_sol_types::sol; use eigen_contracts::RegistryCoordinator; diff --git a/avs/incredible-squaring-avs/src/operator.rs b/avs/incredible-squaring-avs/src/operator.rs index 2a9b84d..ea371b4 100644 --- a/avs/incredible-squaring-avs/src/operator.rs +++ b/avs/incredible-squaring-avs/src/operator.rs @@ -8,7 +8,7 @@ use crate::avs::{ use crate::get_task_response_digest; use crate::rpc_client::AggregatorRpcClient; use alloy_contract::private::Ethereum; -use alloy_primitives::{address, Address, Bytes, ChainId, FixedBytes, Signature, B256, U256}; +use alloy_primitives::{Address, Bytes, ChainId, FixedBytes, Signature, B256, U256}; use alloy_provider::{Provider, RootProvider}; use alloy_rpc_types::Log; use alloy_signer_local::PrivateKeySigner; @@ -25,11 +25,9 @@ use eigen_utils::node_api::NodeApi; use eigen_utils::services::operator_info::OperatorInfoServiceTrait; use eigen_utils::types::{AvsError, OperatorInfo}; use eigen_utils::Config; -use gadget_common::subxt_signer::bip39::rand; use k256::ecdsa::{SigningKey, VerifyingKey}; use log::error; use prometheus::Registry; -use rand::Rng; use std::future::Future; use std::pin::Pin; use std::str::FromStr; diff --git a/avs/tangle-avs/src/operator.rs b/avs/tangle-avs/src/operator.rs index 0eca072..5e12dd7 100644 --- a/avs/tangle-avs/src/operator.rs +++ b/avs/tangle-avs/src/operator.rs @@ -257,7 +257,7 @@ impl Operator { .as_secs() + 3600, ); - let register_result = avs_registry_contract_manager + let _register_result = avs_registry_contract_manager .register_operator_in_quorum_with_avs_registry_coordinator( &ecdsa_signing_key, sig_salt, diff --git a/contracts/src/lib.rs b/contracts/src/lib.rs index bdfc9c6..ab6955e 100644 --- a/contracts/src/lib.rs +++ b/contracts/src/lib.rs @@ -149,6 +149,13 @@ sol!( "./out/RegistryCoordinator.sol/RegistryCoordinator.json" ); +sol!( + #[allow(missing_docs, clippy::too_many_arguments)] + #[sol(rpc)] + IRegistryCoordinator, + "./out/IRegistryCoordinator.sol/IRegistryCoordinator.json" +); + sol!( #[allow(missing_docs)] #[sol(rpc)] diff --git a/test-utils/Cargo.toml b/test-utils/Cargo.toml index 44466d0..100ae58 100644 --- a/test-utils/Cargo.toml +++ b/test-utils/Cargo.toml @@ -46,6 +46,7 @@ thiserror.workspace = true tokio.workspace = true ethabi = "18.0.0" anvil.workspace = true +ethers.workspace = true #tokio = { workspace = true, features = ["full"] } alloy = { workspace = true, features = ["serde", "signers"] } @@ -61,4 +62,5 @@ url.workspace = true #ark-ec.workspace = true #ark-ff.workspace = true ark-bn254.workspace = true -sha3 = "0.10.8" \ No newline at end of file +sha3 = "0.10.8" +nix = "0.28.0" \ No newline at end of file diff --git a/test-utils/keystore/bls b/test-utils/keystore/bls new file mode 100644 index 0000000..4ac13e9 --- /dev/null +++ b/test-utils/keystore/bls @@ -0,0 +1 @@ +{"pub_key":{"x":"0x13b15d57e069eee24b23c82947dc6cd57a7c87e965c5dc325ca1e770dd52ad01","y":"0x5d262729c016f000f161c8edef2b55061520c6786042ef93fa61cea057e5b8f"},"crypto":{"encrypted_data":"7FQ+MQN6ZIQaTK20rdiVunAGtZE3SP5fWkKn54spoled8Z4c0+xd06/Hq43Kp3YI","nonce":"qVgmzWcYA4GtWKzP","password_hash":"JHNjcnlwdCRsbj0xNyxyPTgscD0xJHdCdWtNcU5NMmZkenMxaGxwczRVOXckZVRLQUtnbHhHK2lVZlBBakZ5K0tkMXYxNDRveUl6NUUzS2hmT3kzNUNCTQ=="}} \ No newline at end of file diff --git a/test-utils/keystore/ecdsa b/test-utils/keystore/ecdsa new file mode 100644 index 0000000..c0eea57 --- /dev/null +++ b/test-utils/keystore/ecdsa @@ -0,0 +1 @@ +{"address":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266","crypto":{"Cipher":"aes-128-ctr","CipherText":"664c7c0cfe1fd5c56d8724fb2b6dab05b9586055d782a498dadce199b58dbfce","CipherParams":{"IV":"be94caa22073e77a88139e12552516d8"},"KDF":"scrypt","KDFParams":{"n":17,"r":8,"p":1,"dklen":32,"salt":"e79a8ed192e4ed4c06c7d436280a16465ee8fa6b0d4379c0776d37911c050b0c"},"MAC":"6877ae9c653c0e938ee8012eeee3371f03c3584564223a5c7113552e452ae4c3"},"id":"0e1a54e2-b697-4c66-9b04-a4e3dc733f12","version":"3"} \ No newline at end of file diff --git a/test-utils/src/anvil/anvil.rs b/test-utils/src/anvil/anvil.rs index be43d73..c1a0b46 100644 --- a/test-utils/src/anvil/anvil.rs +++ b/test-utils/src/anvil/anvil.rs @@ -1,26 +1,13 @@ -use crate::test_utils; use ethers::core::k256::{ ecdsa::SigningKey, elliptic_curve::generic_array::GenericArray, SecretKey, }; -use ethers::{ - types::{Address, Chain}, - utils::secret_key_to_address, -}; +use ethers::{types::Address, utils::secret_key_to_address}; use std::{ io::{BufRead, BufReader}, path::PathBuf, process::{Child, Command}, time::{Duration, Instant}, }; -// use webb::evm::ethers::core::k256::{ -// ecdsa::SigningKey, elliptic_curve::generic_array::GenericArray, -// SecretKey as K256SecretKey, -// }; - -// use webb::evm::ethers::{ -// types::{Address, Chain}, -// utils::secret_key_to_address, -// }; /// How long we will wait for anvil to indicate that it is ready. const ANVIL_STARTUP_TIMEOUT_MILLIS: u64 = 10_000; @@ -94,22 +81,6 @@ impl Drop for AnvilInstance { /// # Panics /// /// If `spawn` is called without `anvil` being available in the user's $PATH -/// -/// # Example -/// -/// ```no_run -/// use eigen_utils::test_utils::anvil::Anvil; -/// -/// let port = 8545u16; -/// let url = format!("http://localhost:{}", port).to_string(); -/// -/// let anvil = Anvil::new() -/// .port(port) -/// .mnemonic("abstract vacuum mammal awkward pudding scene penalty purchase dinner depart evoke puzzle") -/// .spawn(); -/// -/// drop(anvil); // this will kill the instance -/// ``` #[derive(Debug, Clone, Default)] #[must_use = "This Builder struct does nothing unless it is `spawn`ed"] pub struct Anvil { @@ -127,33 +98,11 @@ pub struct Anvil { impl Anvil { /// Creates an empty Anvil builder. /// The default port is 8545. The mnemonic is chosen randomly. - /// - /// # Example - /// - /// ```no_run - /// # use eigen_utils::test_utils::anvil::Anvil; - /// fn a() { - /// let anvil = Anvil::default().spawn(); - /// - /// println!("Anvil running at `{}`", anvil.endpoint()); - /// } - /// ``` pub fn new() -> Self { Self::default() } /// Creates an Anvil builder which will execute `anvil` at the given path. - /// - /// # Example - /// - /// ```no_run - /// # use eigen_utils::test_utils::anvil::Anvil; - /// fn a() { - /// let anvil = Anvil::at("~/.foundry/bin/anvil").spawn(); - /// - /// println!("Anvil running at `{}`", anvil.endpoint()); - /// } - /// ``` pub fn at(path: impl Into) -> Self { Self::new().path(path) } @@ -253,7 +202,7 @@ impl Anvil { let port = if let Some(port) = self.port { port } else { - test_utils::random_port::random_port() + crate::anvil::random_port::random_port() }; cmd.arg("-p").arg(port.to_string()); diff --git a/test-utils/src/anvil/local_chain.rs b/test-utils/src/anvil/local_chain.rs index d7c1526..c861c8e 100644 --- a/test-utils/src/anvil/local_chain.rs +++ b/test-utils/src/anvil/local_chain.rs @@ -1,5 +1,5 @@ -use crate::test_utils; -use crate::test_utils::anvil::{Anvil, AnvilInstance}; +use crate::anvil::anvil::{Anvil, AnvilInstance}; +use crate::anvil::random_port; use ethers::signers::Signer; use std::sync::Arc; @@ -97,7 +97,7 @@ impl LocalEvmChain { let port = if port.is_some() { port.unwrap() } else { - test_utils::random_port::random_port() + random_port::random_port() }; let mut anvil = Anvil::new() .port(port) diff --git a/test-utils/src/anvil/testnet/incredible_squaring.rs b/test-utils/src/anvil/testnet/incredible_squaring.rs index decb549..4b5e3ac 100644 --- a/test-utils/src/anvil/testnet/incredible_squaring.rs +++ b/test-utils/src/anvil/testnet/incredible_squaring.rs @@ -1,6 +1,6 @@ use crate::encode_params; use alloy::signers::Signer; -use alloy_primitives::{address, bytes::Bytes, Address, Keccak256, Uint, U256}; +use alloy_primitives::{address, Address, Bytes, Keccak256, Uint, U256}; use alloy_provider::network::{TransactionBuilder, TxSigner}; use alloy_provider::{Provider, ProviderBuilder}; use alloy_rpc_types_eth::BlockId; @@ -46,7 +46,14 @@ pub async fn run_anvil_testnet() -> ContractAddresses { // Initialize the logger let _ = env_logger::try_init(); - let (api, mut handle) = spawn(anvil::NodeConfig::test().with_port(8545)).await; + let (api, mut handle) = spawn( + anvil::NodeConfig::test() + .with_port(8545) + .with_print_logs(true) + .disable_block_gas_limit(true) + .with_steps_tracing(true), + ) + .await; api.anvil_auto_impersonate_account(true).await.unwrap(); let _http_provider = ProviderBuilder::new() @@ -319,20 +326,20 @@ pub async fn run_anvil_testnet() -> ContractAddresses { ); let ®istry_coordinator_addr = registry_coordinator.address(); - let bls_apk_registry = BlsApkRegistry::new( - TransparentUpgradeableProxy::deploy( - provider.clone(), - empty_contract_addr, - incredible_squaring_proxy_admin_addr, - Bytes::from(""), - ) - .await - .unwrap() - .address() - .clone(), - provider.clone(), - ); - let &bls_apk_registry_addr = bls_apk_registry.address(); + // let bls_apk_registry = BlsApkRegistry::new( + // TransparentUpgradeableProxy::deploy( + // provider.clone(), + // empty_contract_addr, + // incredible_squaring_proxy_admin_addr, + // Bytes::from(""), + // ) + // .await + // .unwrap() + // .address() + // .clone(), + // provider.clone(), + // ); + // let &bls_apk_registry_addr = bls_apk_registry.address(); let bls_apk_registry = IBlsApkRegistry::new( TransparentUpgradeableProxy::deploy( @@ -553,6 +560,28 @@ pub async fn run_anvil_testnet() -> ContractAddresses { .unwrap(); assert!(registry_coordinator_upgrade.status()); + let registry_coordinator_initialization = registry_coordinator + .initialize( + pausers[0], + pausers[0], + pausers[0], + pausers[1], + U256::from(0), + quorum_operator_set_params, + quorums_minimum_stake, + quorums_strategy_params, + ) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + log::info!( + "Registry Coordinator Initialization Receipt: {:?}", + registry_coordinator_initialization + ); + let incredible_squaring_service_manager_implementation = IncredibleSquaringServiceManager::deploy( provider.clone(), @@ -619,7 +648,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { registry_coordinator_addr, TASK_RESPONSE_WINDOW_BLOCK, ) - .from(dev_account) + // .from(dev_account) .send() .await .unwrap() @@ -634,7 +663,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { let incredible_squaring_task_manager_upgrade = incredible_squaring_proxy_admin .upgradeAndCall( incredible_squaring_task_manager_addr, - incredible_squaring_service_manager_implementation_addr, + incredible_squaring_task_manager_implementation_addr, alloy_primitives::Bytes::from(encoded_data), ) .send() @@ -648,6 +677,34 @@ pub async fn run_anvil_testnet() -> ContractAddresses { incredible_squaring_task_manager_upgrade ); + let eigen_pod_manager = EigenPodManager::deploy( + provider.clone(), + empty_contract_addr, + empty_contract_addr, + strategy_manager_addr, + from, + delegation_manager_addr, + ) + .await + .unwrap(); + let &eigen_pod_manager_addr = eigen_pod_manager.address(); + + let slasher_addr = dev_account; + let delegation_manager = DelegationManager::deploy( + provider.clone(), + strategy_manager_addr, + slasher_addr, + eigen_pod_manager_addr, + ) + .await + .unwrap(); + let &delegation_manager_addr = delegation_manager.address(); + + let avs_directory = AVSDirectory::deploy(provider.clone(), delegation_manager_addr) + .await + .unwrap(); + let &avs_directory_addr = avs_directory.address(); + log::info!("ERC20MOCK ADDRESS: {:?}", erc20_mock_addr); log::info!("ERC20MOCK STRATEGY ADDRESS: {:?}", erc20_mock_strategy_addr); log::info!( @@ -678,6 +735,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { "OPERATOR STATE RETRIEVER ADDRESS: {:?}", operator_state_retriever_addr ); + log::info!("DELEGATION MANAGER ADDRESS: {:?}", delegation_manager_addr); // let _block = provider // .get_block(BlockId::latest(), false.into()) @@ -723,8 +781,8 @@ pub async fn run_anvil_testnet() -> ContractAddresses { // tokio::spawn(task_spawner); ContractAddresses { - service_manager: incredible_squaring_service_manager_implementation_addr, - registry_coordinator: registry_coordinator_implementation_addr, + service_manager: incredible_squaring_service_manager_addr, + registry_coordinator: registry_coordinator_addr, operator_state_retriever: operator_state_retriever_addr, delegation_manager: delegation_manager_addr, avs_directory: avs_directory_addr, diff --git a/test-utils/src/incredible_squaring.rs b/test-utils/src/incredible_squaring.rs index 2486b5e..baace1a 100644 --- a/test-utils/src/incredible_squaring.rs +++ b/test-utils/src/incredible_squaring.rs @@ -124,11 +124,17 @@ mod tests { use eigen_utils::crypto::bls::KeyPair; use k256::ecdsa::VerifyingKey; use k256::elliptic_curve::SecretKey; + use std::env; use std::path::Path; use std::time::Duration; #[tokio::test] - async fn test_anvil() { + async fn test_full_incredible_squaring() { + if env::var("RUST_LOG").is_err() { + env::set_var("RUST_LOG", "info"); + } + env::set_var("BLS_PASSWORD", "BLS_PASSWORD"); + env::set_var("ECDSA_PASSWORD", "ECDSA_PASSWORD"); env_logger::init(); run_full_incredible_squaring_test().await; } @@ -169,15 +175,15 @@ mod tests { //---------------- ECDSA ---------------- // First Account - // let hex_key = - // hex::decode("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80") - // .unwrap(); - - // Second Account let hex_key = - hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d") + hex::decode("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80") .unwrap(); + // Second Account + // let hex_key = + // hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d") + // .unwrap(); + let secret_key = SecretKey::from_slice(&hex_key).unwrap(); let signing_key = SigningKey::from(secret_key.clone()); let public_key = secret_key.public_key(); diff --git a/utils/src/avs_registry/writer.rs b/utils/src/avs_registry/writer.rs index 394740e..97e87fb 100644 --- a/utils/src/avs_registry/writer.rs +++ b/utils/src/avs_registry/writer.rs @@ -9,15 +9,11 @@ use alloy_primitives::{Address, Bytes, FixedBytes, U256}; use alloy_provider::Provider; use alloy_rpc_types::TransactionReceipt; use alloy_signer::k256::ecdsa; -use alloy_signer::{Signer as alloySigner, SignerSync}; -use eigen_contracts::EIP1271SignatureUtils::EIP1271SignatureUtilsInstance; -use eigen_contracts::IBlsApkRegistry::PubkeyRegistrationParams; +use alloy_signer::Signer as alloySigner; +use eigen_contracts::RegistryCoordinator; use eigen_contracts::RegistryCoordinator::SignatureWithSaltAndExpiry; -use eigen_contracts::{EIP1271SignatureUtils, RegistryCoordinator}; -use k256::ecdsa::signature::Signer; -use k256::ecdsa::{SigningKey, VerifyingKey}; +use k256::ecdsa::VerifyingKey; use rand::Rng; -use std::str::FromStr; pub trait AvsRegistryChainWriterTrait { async fn register_operator( @@ -152,9 +148,19 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { let operator_signature_with_salt_and_expiry = SignatureWithSaltAndExpiry { signature: operator_signature_bytes, salt: operator_to_avs_registration_sig_salt, - expiry: operator_to_avs_registration_sig_expiry.into(), + expiry: operator_to_avs_registration_sig_expiry, }; + let quorum_count = registry_coordinator.quorumCount().call().await.unwrap()._0; + log::info!("Quorum count: {:?}", quorum_count); + + let rc_code = self + .eth_client_http + .get_code_at(self.registry_coordinator_addr) + .await + .unwrap(); + log::info!(" Deployed Registry Coordinator Bytecode: {:?}", rc_code); + let tx = registry_coordinator.registerOperator( quorum_numbers, socket, @@ -163,7 +169,6 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { ); let receipt = tx.send().await?.get_receipt().await.unwrap(); - log::info!("Registration Receipt: {:?}", receipt); Ok(receipt) } diff --git a/utils/src/crypto/bls.rs b/utils/src/crypto/bls.rs index c0025c7..153c5da 100644 --- a/utils/src/crypto/bls.rs +++ b/utils/src/crypto/bls.rs @@ -253,8 +253,7 @@ pub fn g1_point_to_g1_projective(pt: &G1Point) -> G1Projective { /// Converts a [G1Projective] to a [G1Point]. pub fn g1_projective_to_g1_point(pt: &G1Projective) -> G1Point { let affine = pt.into_affine(); - let g1_point = ark_point_to_g1_point(&affine); - g1_point + ark_point_to_g1_point(&affine) } /// Converts a [G1Affine] to a [G1Point]. diff --git a/utils/src/el_contracts/reader.rs b/utils/src/el_contracts/reader.rs index 380a7d6..5dc6add 100644 --- a/utils/src/el_contracts/reader.rs +++ b/utils/src/el_contracts/reader.rs @@ -88,7 +88,7 @@ impl ElReader for ElChainContractManager { .map(|details| details._0)?; Ok(Operator { address: operator.address, - earnings_receiver_address: details.earningsReceiver, + earnings_receiver_address: details.__deprecated_earningsReceiver, staker_opt_out_window_blocks: details.stakerOptOutWindowBlocks, delegation_approver_address: details.delegationApprover, ..operator.clone() diff --git a/utils/src/el_contracts/writer.rs b/utils/src/el_contracts/writer.rs index 9541dac..d86f4a9 100644 --- a/utils/src/el_contracts/writer.rs +++ b/utils/src/el_contracts/writer.rs @@ -35,7 +35,7 @@ impl ElWriter for ElChainContractManager { log::info!("registering operator {} to EigenLayer", operator.address); let op_details = DelegationManager::OperatorDetails { - earningsReceiver: operator.earnings_receiver_address, + __deprecated_earningsReceiver: operator.earnings_receiver_address, stakerOptOutWindowBlocks: operator.staker_opt_out_window_blocks, delegationApprover: operator.delegation_approver_address, }; @@ -67,7 +67,7 @@ impl ElWriter for ElChainContractManager { ); let op_details = DelegationManager::OperatorDetails { - earningsReceiver: operator.earnings_receiver_address, + __deprecated_earningsReceiver: operator.earnings_receiver_address, stakerOptOutWindowBlocks: operator.staker_opt_out_window_blocks, delegationApprover: operator.delegation_approver_address, }; diff --git a/utils/src/types.rs b/utils/src/types.rs index 7f7e8b5..af7884b 100644 --- a/utils/src/types.rs +++ b/utils/src/types.rs @@ -4,10 +4,9 @@ use alloy_primitives::{keccak256, Address, B256, U256}; use alloy_transport::RpcError; use alloy_transport::TransportErrorKind; -use ark_bn254::{Fq as Bn254Fq, G1Affine as Bn254G1Affine, G2Affine as Bn254G2Affine}; +use ark_bn254::{G1Affine as Bn254G1Affine, G2Affine as Bn254G2Affine}; use ark_ec::AffineRepr; -use ark_ff::BigInt; use ark_serialize::CanonicalDeserialize; use ark_serialize::CanonicalSerialize; use ark_serialize::Compress; @@ -96,7 +95,7 @@ pub type StakeAmount = U256; pub type OperatorId = B256; pub fn operator_id_from_g1_pubkey(pubkey: &G1Point) -> OperatorId { - let pubkey = g1_point_to_ark_point(&pubkey); + let pubkey = g1_point_to_ark_point(pubkey); let mut x_bytes: Vec = vec![0; pubkey.x.serialized_size(Compress::Yes)]; pubkey.x.serialize_compressed(&mut x_bytes).unwrap(); From 9e24c700545af1ad4d09460ddc666d6c14d1d474 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Mon, 12 Aug 2024 19:02:42 -0500 Subject: [PATCH 11/43] Build Scripts and register debugging --- avs/incredible-squaring-avs/build.rs | 35 ++++++++++++++++++++++++++++ avs/tangle-avs/build.rs | 35 ++++++++++++++++++++++++++++ test-utils/scripts/env_setup.sh | 18 ++++++++++++++ test-utils/scripts/rebuild.sh | 25 ++++++++++++++++++++ test-utils/src/anvil/abi.rs | 15 ++++++++++++ utils/src/avs_registry/writer.rs | 23 ++++++++++-------- utils/src/crypto/bls.rs | 6 +++++ 7 files changed, 147 insertions(+), 10 deletions(-) create mode 100644 avs/incredible-squaring-avs/build.rs create mode 100644 avs/tangle-avs/build.rs create mode 100644 test-utils/scripts/env_setup.sh create mode 100644 test-utils/scripts/rebuild.sh diff --git a/avs/incredible-squaring-avs/build.rs b/avs/incredible-squaring-avs/build.rs new file mode 100644 index 0000000..b5ce6f8 --- /dev/null +++ b/avs/incredible-squaring-avs/build.rs @@ -0,0 +1,35 @@ +use std::env; +use std::path::Path; +use std::process::Command; + +fn main() { + // List of directories containing Solidity contracts + let contract_dirs = vec![ + "contracts", + "contracts/lib/eigenlayer-middleware", + "avs/incredible-squaring-avs/contracts", + ]; + + // Get the project root directory + let root = env::var("CARGO_MANIFEST_DIR").unwrap(); + + for dir in contract_dirs { + let full_path = Path::new(&root).join(dir); + + if full_path.exists() { + println!("cargo:rerun-if-changed={}", full_path.display()); + + let status = Command::new("forge") + .current_dir(&full_path) + .arg("build") + .status() + .expect("Failed to execute Forge build"); + + if !status.success() { + panic!("Forge build failed for directory: {}", full_path.display()); + } + } else { + println!("Directory not found: {}", full_path.display()); + } + } +} diff --git a/avs/tangle-avs/build.rs b/avs/tangle-avs/build.rs new file mode 100644 index 0000000..5ec1a9a --- /dev/null +++ b/avs/tangle-avs/build.rs @@ -0,0 +1,35 @@ +use std::env; +use std::path::Path; +use std::process::Command; + +fn main() { + // List of directories containing Solidity contracts + let contract_dirs = vec![ + "contracts", + "contracts/lib/eigenlayer-middleware", + // "avs/tangle-avs/contracts", + ]; + + // Get the project root directory + let root = env::var("CARGO_MANIFEST_DIR").unwrap(); + + for dir in contract_dirs { + let full_path = Path::new(&root).join(dir); + + if full_path.exists() { + println!("cargo:rerun-if-changed={}", full_path.display()); + + let status = Command::new("forge") + .current_dir(&full_path) + .arg("build") + .status() + .expect("Failed to execute Forge build"); + + if !status.success() { + panic!("Forge build failed for directory: {}", full_path.display()); + } + } else { + println!("Directory not found: {}", full_path.display()); + } + } +} diff --git a/test-utils/scripts/env_setup.sh b/test-utils/scripts/env_setup.sh new file mode 100644 index 0000000..769cee6 --- /dev/null +++ b/test-utils/scripts/env_setup.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +# Check if the script is being sourced +(return 0 2>/dev/null) && sourced=1 || sourced=0 + +if [ $sourced -eq 0 ]; then + echo "Error: This script needs to be sourced. Run it as:" + echo " source $0" + echo " or" + echo " . $0" + exit 1 +fi + +#Export the environment variables +export OPERATOR_ECDSA_KEY_PASSWORD="ECDSA_PASSWORD" +export OPERATOR_BLS_KEY_PASSWORD="BLS_PASSWORD" + +echo "Environment variables have been set." \ No newline at end of file diff --git a/test-utils/scripts/rebuild.sh b/test-utils/scripts/rebuild.sh new file mode 100644 index 0000000..36116e0 --- /dev/null +++ b/test-utils/scripts/rebuild.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +# Define the directories +DIR1="./../contracts/lib/eigenlayer-middleware" +DIR2="./../contracts" + +# Function to run forge commands in a directory +run_forge_commands() { + local dir=$1 + echo "Running forge commands in $dir" + cd "$dir" || exit + forge clean + forge build + cd - || exit +} + +# Run forge commands in both directories +run_forge_commands "$DIR1" +run_forge_commands "$DIR2" + +# Run cargo test in the starting directory +#echo "Running cargo test in the current directory" +#cargo test + +echo "Rebuilt all Smart Contracts!" \ No newline at end of file diff --git a/test-utils/src/anvil/abi.rs b/test-utils/src/anvil/abi.rs index 00f6541..68d0010 100644 --- a/test-utils/src/anvil/abi.rs +++ b/test-utils/src/anvil/abi.rs @@ -19,3 +19,18 @@ macro_rules! encode_params { alloy_primitives::Bytes::from(data) }}; } + +/// Macro that acts as the Rust equivalent of Solidity's `abi.encode`. Returns [alloy_primitives::Bytes] +#[macro_export] +macro_rules! abi_encode { + ($($param:expr),*) => {{ + let mut data = Vec::::new(); + + $( + let p = $param.tokenize(); + data.extend_from_slice(abi::encode(&p).as_slice()); + )* + + alloy_primitives::Bytes::from(data) + }}; +} diff --git a/utils/src/avs_registry/writer.rs b/utils/src/avs_registry/writer.rs index 97e87fb..853b01f 100644 --- a/utils/src/avs_registry/writer.rs +++ b/utils/src/avs_registry/writer.rs @@ -58,6 +58,7 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { quorum_numbers: Bytes, socket: String, ) -> AvsRegistryContractResult { + log::info!("Signing Key: {:?}", operator_ecdsa_private_key); let operator_addr = operator_ecdsa_private_key.verifying_key().to_address(); log::info!("Operator address: {:?}", operator_addr); let registry_coordinator = @@ -71,11 +72,23 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { .map(|x| x._0) .map_err(AvsError::from)?; + log::info!( + "G1 HASHED MESSAGE TO SIGN: X: {:?}, Y: {:?}", + g1_hashed_msg_to_sign.X, + g1_hashed_msg_to_sign.Y + ); + let g1_point = G1Point { x: g1_hashed_msg_to_sign.X, y: g1_hashed_msg_to_sign.Y, }; + log::info!( + "G1 POINT MESSAGE TO SIGN: X: {:?}, Y: {:?}", + g1_point.x, + g1_point.y + ); + let signed_msg = bls_key_pair.sign_hashed_to_curve_message(&g1_point); let g1_pubkey_bn254 = bls_key_pair.get_pub_key_g1(); let g2_pubkey_bn254 = bls_key_pair.get_pub_key_g2(); @@ -151,16 +164,6 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { expiry: operator_to_avs_registration_sig_expiry, }; - let quorum_count = registry_coordinator.quorumCount().call().await.unwrap()._0; - log::info!("Quorum count: {:?}", quorum_count); - - let rc_code = self - .eth_client_http - .get_code_at(self.registry_coordinator_addr) - .await - .unwrap(); - log::info!(" Deployed Registry Coordinator Bytecode: {:?}", rc_code); - let tx = registry_coordinator.registerOperator( quorum_numbers, socket, diff --git a/utils/src/crypto/bls.rs b/utils/src/crypto/bls.rs index 153c5da..8ebef8c 100644 --- a/utils/src/crypto/bls.rs +++ b/utils/src/crypto/bls.rs @@ -119,6 +119,12 @@ impl G1Point { *self = ark_point_to_g1_point(&pt); } + pub fn mul_bigint(&mut self, bigint: U256) { + let affine = g1_point_to_ark_point(self); + let pt = affine.mul_bigint(bigint.as_limbs()).into_affine(); + *self = ark_point_to_g1_point(&pt); + } + pub fn from_ark_g1(ark_g1: &G1Affine) -> Self { ark_point_to_g1_point(ark_g1) } From d244cf6a82dd9226641f5dd398385f9d5cb974b5 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Tue, 13 Aug 2024 11:52:58 -0500 Subject: [PATCH 12/43] Small build script fix --- avs/incredible-squaring-avs/build.rs | 6 +++--- avs/tangle-avs/build.rs | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/avs/incredible-squaring-avs/build.rs b/avs/incredible-squaring-avs/build.rs index b5ce6f8..d4e1a19 100644 --- a/avs/incredible-squaring-avs/build.rs +++ b/avs/incredible-squaring-avs/build.rs @@ -5,16 +5,16 @@ use std::process::Command; fn main() { // List of directories containing Solidity contracts let contract_dirs = vec![ + "../../contracts", + "../../contracts/lib/eigenlayer-middleware", "contracts", - "contracts/lib/eigenlayer-middleware", - "avs/incredible-squaring-avs/contracts", ]; // Get the project root directory let root = env::var("CARGO_MANIFEST_DIR").unwrap(); for dir in contract_dirs { - let full_path = Path::new(&root).join(dir); + let full_path = Path::new(&root).join(dir).canonicalize().unwrap(); if full_path.exists() { println!("cargo:rerun-if-changed={}", full_path.display()); diff --git a/avs/tangle-avs/build.rs b/avs/tangle-avs/build.rs index 5ec1a9a..d4e1a19 100644 --- a/avs/tangle-avs/build.rs +++ b/avs/tangle-avs/build.rs @@ -5,16 +5,16 @@ use std::process::Command; fn main() { // List of directories containing Solidity contracts let contract_dirs = vec![ + "../../contracts", + "../../contracts/lib/eigenlayer-middleware", "contracts", - "contracts/lib/eigenlayer-middleware", - // "avs/tangle-avs/contracts", ]; // Get the project root directory let root = env::var("CARGO_MANIFEST_DIR").unwrap(); for dir in contract_dirs { - let full_path = Path::new(&root).join(dir); + let full_path = Path::new(&root).join(dir).canonicalize().unwrap(); if full_path.exists() { println!("cargo:rerun-if-changed={}", full_path.display()); From c71a1eaef774c556b12e9e450fd7c71314992eef Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Tue, 13 Aug 2024 19:33:04 -0500 Subject: [PATCH 13/43] Debugging, Testing, and Cleanup --- avs/incredible-squaring-avs/build.rs | 2 +- avs/tangle-avs/build.rs | 2 +- .../src/TangleValidatorServiceManager.sol | 7 +- test-utils/Cargo.toml | 8 ++ test-utils/keystore/bls | 2 +- test-utils/keystore/ecdsa | 2 +- test-utils/scripts/avs_rebuild_contracts.sh | 25 +++++++ .../{rebuild.sh => rebuild_contracts.sh} | 0 test-utils/src/anvil/abi.rs | 4 - .../src/anvil/testnet/incredible_squaring.rs | 73 ++----------------- test-utils/src/incredible_squaring.rs | 12 ++- utils/src/avs_registry/writer.rs | 49 ++++++++++--- utils/src/crypto/bls.rs | 14 ++-- utils/src/crypto/bn254.rs | 63 ++-------------- utils/src/crypto/pairing_products.rs | 16 ++-- 15 files changed, 118 insertions(+), 161 deletions(-) create mode 100644 test-utils/scripts/avs_rebuild_contracts.sh rename test-utils/scripts/{rebuild.sh => rebuild_contracts.sh} (100%) diff --git a/avs/incredible-squaring-avs/build.rs b/avs/incredible-squaring-avs/build.rs index d4e1a19..6ad9d8b 100644 --- a/avs/incredible-squaring-avs/build.rs +++ b/avs/incredible-squaring-avs/build.rs @@ -19,7 +19,7 @@ fn main() { if full_path.exists() { println!("cargo:rerun-if-changed={}", full_path.display()); - let status = Command::new("forge") + let status = Command::new("/home/tjemmmic/.foundry/bin/forge") .current_dir(&full_path) .arg("build") .status() diff --git a/avs/tangle-avs/build.rs b/avs/tangle-avs/build.rs index d4e1a19..6ad9d8b 100644 --- a/avs/tangle-avs/build.rs +++ b/avs/tangle-avs/build.rs @@ -19,7 +19,7 @@ fn main() { if full_path.exists() { println!("cargo:rerun-if-changed={}", full_path.display()); - let status = Command::new("forge") + let status = Command::new("/home/tjemmmic/.foundry/bin/forge") .current_dir(&full_path) .arg("build") .status() diff --git a/avs/tangle-avs/contracts/src/TangleValidatorServiceManager.sol b/avs/tangle-avs/contracts/src/TangleValidatorServiceManager.sol index 5bb637e..0939c45 100644 --- a/avs/tangle-avs/contracts/src/TangleValidatorServiceManager.sol +++ b/avs/tangle-avs/contracts/src/TangleValidatorServiceManager.sol @@ -1,9 +1,9 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; -import "./eigenlayer-contracts/src/contracts/libraries/BytesLib.sol"; -import "./ITangleValidatorTaskManager.sol"; -import "./eigenlayer-middleware/src/ServiceManagerBase.sol"; +import "eigenlayer-middleware/lib/eigenlayer-contracts/src/contracts/libraries/BytesLib.sol"; +import "src/ITangleValidatorTaskManager.sol"; +import "eigenlayer-middleware/src/ServiceManagerBase.sol"; /** * @title Primary entrypoint for procuring services from TangleValidator. @@ -32,7 +32,6 @@ contract TangleValidatorServiceManager is ServiceManagerBase { ) ServiceManagerBase( _avsDirectory, - IRewardsCoordinator(address(0)), // inc-sq doesn't need to deal with payments _registryCoordinator, _stakeRegistry ) diff --git a/test-utils/Cargo.toml b/test-utils/Cargo.toml index 100ae58..ab3eda5 100644 --- a/test-utils/Cargo.toml +++ b/test-utils/Cargo.toml @@ -7,6 +7,14 @@ license.workspace = true homepage.workspace = true repository.workspace = true +#[lib] +#name = "test_utils" +#path = "src/lib.rs" +# +#[[bin]] +#name = "incredible_squaring" +#path = "src/incredible_squaring.rs" + [dependencies] alloy-abi.workspace = true alloy-contract.workspace = true diff --git a/test-utils/keystore/bls b/test-utils/keystore/bls index 4ac13e9..efe69c8 100644 --- a/test-utils/keystore/bls +++ b/test-utils/keystore/bls @@ -1 +1 @@ -{"pub_key":{"x":"0x13b15d57e069eee24b23c82947dc6cd57a7c87e965c5dc325ca1e770dd52ad01","y":"0x5d262729c016f000f161c8edef2b55061520c6786042ef93fa61cea057e5b8f"},"crypto":{"encrypted_data":"7FQ+MQN6ZIQaTK20rdiVunAGtZE3SP5fWkKn54spoled8Z4c0+xd06/Hq43Kp3YI","nonce":"qVgmzWcYA4GtWKzP","password_hash":"JHNjcnlwdCRsbj0xNyxyPTgscD0xJHdCdWtNcU5NMmZkenMxaGxwczRVOXckZVRLQUtnbHhHK2lVZlBBakZ5K0tkMXYxNDRveUl6NUUzS2hmT3kzNUNCTQ=="}} \ No newline at end of file +{"pub_key":{"x":"0x2ed159b38ebb1317b82c3a816202ff8b39788b7996164384f7b79eb06ccdb330","y":"0x7a559aedbd3b933c7dd94234b805419be6a22065e646d23b4b1fe8e92fcd823"},"crypto":{"encrypted_data":"MiC+DCC00z+Lg4J9HGfzZqOPnghgiqJiXQ2982hWSnBoLwdvR4+U+YzG7SIXXWh/","nonce":"q+YU8mhCLsll8KDk","password_hash":"JHNjcnlwdCRsbj0xNyxyPTgscD0xJHk5bUR4NGFxM0hmYXU4Ti94U3BiOWckZGhJYWpid1JwN3ZidmQvMDR1VTlITDc3cVNNNkd4YWpYcWZLSWVGb0ZxRQ=="}} \ No newline at end of file diff --git a/test-utils/keystore/ecdsa b/test-utils/keystore/ecdsa index c0eea57..a6ae8b0 100644 --- a/test-utils/keystore/ecdsa +++ b/test-utils/keystore/ecdsa @@ -1 +1 @@ -{"address":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266","crypto":{"Cipher":"aes-128-ctr","CipherText":"664c7c0cfe1fd5c56d8724fb2b6dab05b9586055d782a498dadce199b58dbfce","CipherParams":{"IV":"be94caa22073e77a88139e12552516d8"},"KDF":"scrypt","KDFParams":{"n":17,"r":8,"p":1,"dklen":32,"salt":"e79a8ed192e4ed4c06c7d436280a16465ee8fa6b0d4379c0776d37911c050b0c"},"MAC":"6877ae9c653c0e938ee8012eeee3371f03c3584564223a5c7113552e452ae4c3"},"id":"0e1a54e2-b697-4c66-9b04-a4e3dc733f12","version":"3"} \ No newline at end of file +{"address":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266","crypto":{"Cipher":"aes-128-ctr","CipherText":"1113254d033cc52729222bd5742459a4d054a449aff3def44ae3018fb8dc7748","CipherParams":{"IV":"7e85c58ecd9e5ecb8fc36fdaac3aab96"},"KDF":"scrypt","KDFParams":{"n":17,"r":8,"p":1,"dklen":32,"salt":"f480c3532ddbd9f2c23be95ad94072d3df15284c556d3ba6b0b6fa286ece18e0"},"MAC":"d55830a172e2ac50764a4426c96fe1f9e68ded4470cd234bc0b44a7eea981643"},"id":"99d8665f-eb45-49d0-936d-c69965cb5835","version":"3"} \ No newline at end of file diff --git a/test-utils/scripts/avs_rebuild_contracts.sh b/test-utils/scripts/avs_rebuild_contracts.sh new file mode 100644 index 0000000..30160fb --- /dev/null +++ b/test-utils/scripts/avs_rebuild_contracts.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +# Define the directories +DIR1="./../avs/incredible-squaring-avs/contracts" +DIR2="./../avs/tangle-avs/contract" + +# Function to run forge commands in a directory +run_forge_commands() { + local dir=$1 + echo "Running forge commands in $dir" + cd "$dir" || exit + forge clean + forge build + cd - || exit +} + +# Run forge commands in both directories +run_forge_commands "$DIR1" +run_forge_commands "$DIR2" + +# Run cargo test in the starting directory +#echo "Running cargo test in the current directory" +#cargo test + +echo "Rebuilt all AVS Smart Contracts!" \ No newline at end of file diff --git a/test-utils/scripts/rebuild.sh b/test-utils/scripts/rebuild_contracts.sh similarity index 100% rename from test-utils/scripts/rebuild.sh rename to test-utils/scripts/rebuild_contracts.sh diff --git a/test-utils/src/anvil/abi.rs b/test-utils/src/anvil/abi.rs index 68d0010..8ccb69f 100644 --- a/test-utils/src/anvil/abi.rs +++ b/test-utils/src/anvil/abi.rs @@ -1,7 +1,3 @@ -use alloy_sol_types::abi; -use alloy_sol_types::abi::Token; -use sha3::{Digest, Keccak256}; - /// Macro that acts as the Rust equivalent of Solidity's `abi.encodeWithSelector`. Returns [alloy_primitives::Bytes] #[macro_export] macro_rules! encode_params { diff --git a/test-utils/src/anvil/testnet/incredible_squaring.rs b/test-utils/src/anvil/testnet/incredible_squaring.rs index 4b5e3ac..f7e5b41 100644 --- a/test-utils/src/anvil/testnet/incredible_squaring.rs +++ b/test-utils/src/anvil/testnet/incredible_squaring.rs @@ -1,29 +1,15 @@ use crate::encode_params; -use alloy::signers::Signer; -use alloy_primitives::{address, Address, Bytes, Keccak256, Uint, U256}; -use alloy_provider::network::{TransactionBuilder, TxSigner}; +use alloy_primitives::{address, Address, Bytes, Keccak256, U256}; use alloy_provider::{Provider, ProviderBuilder}; -use alloy_rpc_types_eth::BlockId; -use alloy_signer_local::PrivateKeySigner; -use alloy_sol_types::{ - abi::Encoder, - abi::{self, token::*}, - private::SolTypeValue, - SolValue, Word, -}; -use alloy_transport_ws::WsConnect; +use alloy_sol_types::{abi, SolValue}; use anvil::spawn; -use ark_bn254::{Fq as F, Fr, G1Affine, G2Affine, G2Projective}; use eigen_contracts::{ RegistryCoordinator::{OperatorSetParam, StrategyParams}, *, }; -use gadget_common::subxt_signer::bip39::rand_core::OsRng; use incredible_squaring_avs::avs::{ IncredibleSquaringServiceManager, IncredibleSquaringTaskManager, }; -use k256::{ecdsa::VerifyingKey, elliptic_curve::SecretKey}; -use std::{path::Path, time::Duration}; use url::Url; pub static BLS_PASSWORD: &str = "BLS_PASSWORD"; @@ -46,7 +32,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { // Initialize the logger let _ = env_logger::try_init(); - let (api, mut handle) = spawn( + let (api, handle) = spawn( anvil::NodeConfig::test() .with_port(8545) .with_print_logs(true) @@ -81,7 +67,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { let _gas_price = provider.get_gas_price().await.unwrap(); // Empty address for initial deployment of all contracts - let empty_address = Address::default(); + let _empty_address = Address::default(); // let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); // let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); @@ -477,7 +463,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { for j in 0..number_of_quorums { quorums_strategy_params.push(Vec::::new()); quorums_minimum_stake.push(0); - for k in 0..number_of_strategies { + for _k in 0..number_of_strategies { quorums_strategy_params[j].push(StrategyParams { strategy: strategies[j], multiplier: 1, @@ -488,37 +474,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { // Function with signature initialize(address,address,address,address,uint256,(uint32,uint16,uint16)[],uint96[],(address,uint96)[][]) and selector 0xdd8283f3. let function_signature = "initialize(address,address,address,address,uint256,(uint32,uint16,uint16)[],uint96[],(address,uint96)[][])"; - let single_test = 0.tokenize(); - println!("Word Tokenize: {:?}", single_test); - let vec_test = quorum_operator_set_params.tokenize(); - println!("Vec Tokenize: {:?}", vec_test); - - let encoded_word = abi::encode(&single_test); - - let encoded_vec = abi::encode(&vec_test); - - println!( - "Quorums Strategy Params: Strategy: {:?} Multiplier: {:?}", - quorums_strategy_params[0][0].strategy, quorums_strategy_params[0][0].multiplier - ); - println!("Quorum Operator Set Params: Max Operators: {:?}, Kick BIPs of Operator Stake: {:?}, Kick BIPs of Total Stake: {:?}", quorum_operator_set_params[0].maxOperatorCount, quorum_operator_set_params[0].kickBIPsOfOperatorStake, quorum_operator_set_params[0].kickBIPsOfTotalStake); - println!("Quorums Minimum Stake: {:?}", quorums_minimum_stake); - - // let mut hasher = Keccak256::new(); - // hasher.update(function_signature); - // let function_selector = &hasher.finalize()[..4]; - // let mut data = Vec::from(function_selector); - // data.extend_from_slice(&abi::encode(&pausers[0].tokenize())); - // data.extend_from_slice(&abi::encode(&pausers[0].tokenize())); - // data.extend_from_slice(&abi::encode(&pausers[0].tokenize())); - // data.extend_from_slice(&abi::encode(&pausers[1].tokenize())); - // data.extend_from_slice(&abi::encode(&0.tokenize())); - // data.extend_from_slice(&abi::encode(&quorum_operator_set_params.tokenize())); - // data.extend_from_slice(&abi::encode(&quorums_minimum_stake.tokenize())); - // data.extend_from_slice(&abi::encode(&quorums_strategy_params.tokenize())); - // let encoded_data = alloy_primitives::Bytes::from(data); - - let encoded_data = encode_params!( + let _encoded_data = encode_params!( function_signature, pausers[0], pausers[0], @@ -529,23 +485,6 @@ pub async fn run_anvil_testnet() -> ContractAddresses { quorums_minimum_stake, quorums_strategy_params ); - // let registry_coordinator_upgrade = incredible_squaring_proxy_admin - // .upgradeAndCall( - // registry_coordinator_addr, - // registry_coordinator_implementation_addr, - // encoded_data, - // ) - // // .from(dev_account) - // .send() - // .await - // .unwrap() - // .get_receipt() - // .await - // .unwrap(); - // log::info!( - // "Registry Coordinator Upgrade Receipt: {:?}", - // registry_coordinator_upgrade - // ); let registry_coordinator_upgrade = incredible_squaring_proxy_admin .upgrade( diff --git a/test-utils/src/incredible_squaring.rs b/test-utils/src/incredible_squaring.rs index baace1a..2d48eaa 100644 --- a/test-utils/src/incredible_squaring.rs +++ b/test-utils/src/incredible_squaring.rs @@ -1,3 +1,4 @@ +#[allow(dead_code)] use crate::anvil::testnet::incredible_squaring::*; use alloy_provider::Provider; use alloy_provider::ProviderBuilder; @@ -7,6 +8,15 @@ use incredible_squaring_avs::operator::*; use k256::ecdsa::SigningKey; use k256::elliptic_curve::SecretKey; +#[tokio::main] +async fn main() { + let _ = env_logger::try_init(); + run_full_incredible_squaring_test().await; +} + +/// THIS FUNCTION IS FOR TESTING ONLY +/// +/// Runs the Incredible Squaring Testnet and then creates an Operator that connects and registers. async fn run_full_incredible_squaring_test() { let _ = env_logger::try_init(); @@ -70,7 +80,7 @@ async fn run_full_incredible_squaring_test() { let operator_info_service = OperatorInfoService {}; let hex_key = - hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d").unwrap(); + hex::decode("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80").unwrap(); let secret_key = SecretKey::from_slice(&hex_key).unwrap(); let signing_key = SigningKey::from(secret_key.clone()); let signer = EigenGadgetSigner { diff --git a/utils/src/avs_registry/writer.rs b/utils/src/avs_registry/writer.rs index 853b01f..5db547b 100644 --- a/utils/src/avs_registry/writer.rs +++ b/utils/src/avs_registry/writer.rs @@ -1,7 +1,8 @@ #![allow(async_fn_in_trait)] use super::{AvsRegistryContractManager, AvsRegistryContractResult}; -use crate::crypto::bls::{G1Point, KeyPair}; +use crate::crypto::bls::{g1_point_to_ark_point, g1_point_to_g1_projective, G1Point, KeyPair}; +use crate::crypto::bn254::get_g2_generator; use crate::crypto::ecdsa::ToAddress; use crate::el_contracts::reader::ElReader; use crate::{types::*, Config}; @@ -10,6 +11,8 @@ use alloy_provider::Provider; use alloy_rpc_types::TransactionReceipt; use alloy_signer::k256::ecdsa; use alloy_signer::Signer as alloySigner; +use ark_ec::pairing::Pairing; +use ark_ec::CurveGroup; use eigen_contracts::RegistryCoordinator; use eigen_contracts::RegistryCoordinator::SignatureWithSaltAndExpiry; use k256::ecdsa::VerifyingKey; @@ -58,7 +61,6 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { quorum_numbers: Bytes, socket: String, ) -> AvsRegistryContractResult { - log::info!("Signing Key: {:?}", operator_ecdsa_private_key); let operator_addr = operator_ecdsa_private_key.verifying_key().to_address(); log::info!("Operator address: {:?}", operator_addr); let registry_coordinator = @@ -89,14 +91,21 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { g1_point.y ); - let signed_msg = bls_key_pair.sign_hashed_to_curve_message(&g1_point); + let signed_msg = bls_key_pair + .sign_hashed_to_curve_message(&g1_point) + .g1_point; let g1_pubkey_bn254 = bls_key_pair.get_pub_key_g1(); let g2_pubkey_bn254 = bls_key_pair.get_pub_key_g2(); + log::info!( + "SIGNED MESSAGE G1POINT: X: {:?}, Y: {:?}", + signed_msg.x, + signed_msg.y + ); let pubkey_reg_params = RegistryCoordinator::PubkeyRegistrationParams { pubkeyRegistrationSignature: RegistryCoordinator::G1Point { - X: signed_msg.g1_point.x, - Y: signed_msg.g1_point.y, + X: signed_msg.x, + Y: signed_msg.y, }, pubkeyG1: RegistryCoordinator::G1Point { X: g1_pubkey_bn254.x, @@ -107,6 +116,22 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { Y: g2_pubkey_bn254.y, }, }; + log::info!( + "REGISTRY COORDINATOR G1POINT: X: {:?}, Y: {:?}", + pubkey_reg_params.pubkeyRegistrationSignature.X, + pubkey_reg_params.pubkeyRegistrationSignature.Y + ); + + let signature = g1_point_to_g1_projective(&signed_msg); + // PAIRING TEST + let e1 = ark_bn254::Bn254::pairing(signature.into_affine(), get_g2_generator().unwrap()); + + let e2 = ark_bn254::Bn254::pairing( + g1_point_to_ark_point(&g1_point), + bls_key_pair.get_pub_key_g2().to_ark_g2(), + ); + + assert_eq!(e1, e2); // Generate a random salt and 1 hour expiry for the signature let mut rng = rand::thread_rng(); @@ -164,12 +189,14 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { expiry: operator_to_avs_registration_sig_expiry, }; - let tx = registry_coordinator.registerOperator( - quorum_numbers, - socket, - pubkey_reg_params, - operator_signature_with_salt_and_expiry, - ); + let tx = registry_coordinator + .registerOperator( + quorum_numbers, + socket, + pubkey_reg_params, + operator_signature_with_salt_and_expiry, + ) + .from(operator_addr); let receipt = tx.send().await?.get_receipt().await.unwrap(); diff --git a/utils/src/crypto/bls.rs b/utils/src/crypto/bls.rs index 8ebef8c..7d5a2cd 100644 --- a/utils/src/crypto/bls.rs +++ b/utils/src/crypto/bls.rs @@ -1,3 +1,6 @@ +use super::bn254::{ + get_g2_generator, map_to_curve, mul_by_generator_g1, point_to_u256, u256_to_point, +}; use crate::types::AvsError; use alloy_primitives::U256; use ark_bn254::Fq as F; @@ -22,8 +25,6 @@ use std::fs; use std::ops::Neg; use std::path::Path; -use super::bn254::{map_to_curve, mul_by_generator_g1, point_to_u256, u256_to_point}; - #[derive(Clone, Debug, Serialize, Deserialize)] struct EncryptedBLSKeyJSONV3 { pub pub_key: G1Point, @@ -356,11 +357,10 @@ impl Signature { let p_projective = [g1_point_to_ark_point(&p[0]), g1_point_to_ark_point(&p[1])]; let q_projective = [g2_point_to_ark_point(&q[0]), g2_point_to_ark_point(&q[1])]; - // // If Pairing Left and Right are equal, then the signature is valid as well - // let g2_gen = g2_point_to_ark_point(&G2Point::generator()); - // let pairing_left = Bn254::pairing(self.g1_point.to_ark_g1(), g2_gen); - // let pairing_right = Bn254::pairing(msg_affine, g2_point_to_ark_point(&pubkey.clone())); - // println!("Pairing Comparison: {:?}", pairing_left == pairing_right); + // If Pairing Left and Right are equal, then the signature is valid as well + let e1 = Bn254::pairing(self.g1_point.to_ark_g1(), get_g2_generator().unwrap()); + let e2 = Bn254::pairing(msg_affine, g2_point_to_ark_point(&pubkey.clone())); + log::info!("Are e1 and e2 pairings equal? {:?}", e1 == e2); let pairing_result = Bn254::multi_pairing(p_projective, q_projective); Ok(pairing_result.0.is_one()) diff --git a/utils/src/crypto/bn254.rs b/utils/src/crypto/bn254.rs index 8ff7866..d1af2b5 100644 --- a/utils/src/crypto/bn254.rs +++ b/utils/src/crypto/bn254.rs @@ -1,12 +1,12 @@ use crate::types::AvsError; use alloy_primitives::U256; -use ark_bn254::{Fq2, Fr, G1Affine, G1Projective, G2Affine, G2Projective}; +use ark_bn254::{Fr, G1Affine, G1Projective, G2Affine, G2Projective}; use ark_ff::{BigInteger, BigInteger256}; use ark_ff::{Field, One, PrimeField}; use std::ops::Mul; -use std::str::FromStr; use ark_bn254::Fq as F; +use ark_ec::AffineRepr; pub fn map_to_curve(digest: &[u8; 32]) -> G1Projective { let one = F::one(); @@ -68,62 +68,15 @@ pub fn biginteger256_to_u256(bi: BigInteger256) -> U256 { } pub fn get_g1_generator() -> Result { - let x_result = F::from_str("1"); - - let y_result = F::from_str("2"); - - match x_result { - Ok(x) => match y_result { - Ok(y) => Ok(G1Affine::new(x, y)), - Err(_) => Err(AvsError::KeyError( - "Invalid G1 Generator Y Result".to_string(), - )), - }, - Err(_) => Err(AvsError::KeyError( - "Invalid G1 Generator X Result".to_string(), - )), - } + // let g1_affine = G1Affine::new(G1_GENERATOR_X, G1_GENERATOR_Y); + let g1_affine = G1Affine::generator(); + Ok(g1_affine) } pub fn get_g2_generator() -> Result { - let x_0_result = F::from_str( - "10857046999023057135944570762232829481370756359578518086990519993285655852781", - ); - - let x_1result = F::from_str( - "11559732032986387107991004021392285783925812861821192530917403151452391805634", - ); - - match x_0_result { - Ok(x_0) => { - match x_1result { - Ok(x_1) => { - let x = Fq2::new(x_0, x_1); - - let y_0_result = F::from_str("8495653923123431417604973247489272438418190587263600148770280649306958101930"); - - match y_0_result { - Ok(y_0) => { - let y_1_result = F::from_str("4082367875863433681332203403145435568316851327593401208105741076214120093531"); - - match y_1_result { - Ok(y_1) => { - let y = Fq2::new(y_0, y_1); - Ok(G2Affine::new(x, y)) - } - Err(_) => { - Err(AvsError::KeyError("Invalid G2 Generator Y1".to_string())) - } - } - } - Err(_) => Err(AvsError::KeyError("Invalid G2 Generator Y0".to_string())), - } - } - Err(_) => Err(AvsError::KeyError("Invalid G2 Generator X1".to_string())), - } - } - Err(_) => Err(AvsError::KeyError("Invalid G2 Generator X0".to_string())), - } + // let g2_affine = G2Affine::new(G2_GENERATOR_X, G2_GENERATOR_Y); + let g2_affine = G2Affine::generator(); + Ok(g2_affine) } pub fn mul_by_generator_g1(pvt_key: Fr) -> Result { diff --git a/utils/src/crypto/pairing_products.rs b/utils/src/crypto/pairing_products.rs index f495f0a..2c52934 100644 --- a/utils/src/crypto/pairing_products.rs +++ b/utils/src/crypto/pairing_products.rs @@ -10,8 +10,8 @@ use std::{ marker::PhantomData, }; -#[cfg(feature = "parallel")] -use rayon::prelude::*; +// #[cfg(feature = "parallel")] +// use rayon::prelude::*; pub type Error = Box; @@ -88,9 +88,9 @@ pub fn cfg_multi_pairing(left: &[P::G1], right: &[P::G2]) -> Option< .collect::>(); // We want to process N chunks in parallel where N is the number of threads available - #[cfg(feature = "parallel")] - let num_chunks = rayon::current_num_threads(); - #[cfg(not(feature = "parallel"))] + // #[cfg(feature = "parallel")] + // let num_chunks = rayon::current_num_threads(); + // #[cfg(not(feature = "parallel"))] let num_chunks = 1; let chunk_size = if num_chunks <= left.len() { @@ -100,9 +100,9 @@ pub fn cfg_multi_pairing(left: &[P::G1], right: &[P::G2]) -> Option< 1 }; - #[cfg(feature = "parallel")] - let (left_chunks, right_chunks) = (left.par_chunks(chunk_size), right.par_chunks(chunk_size)); - #[cfg(not(feature = "parallel"))] + // #[cfg(feature = "parallel")] + // let (left_chunks, right_chunks) = (left.par_chunks(chunk_size), right.par_chunks(chunk_size)); + // #[cfg(not(feature = "parallel"))] let (left_chunks, right_chunks) = (left.chunks(chunk_size), right.chunks(chunk_size)); // Compute all the (partial) pairings and take the product. We have to take the product over From 3c7f124b84857552372144966e4c451ee1980e9c Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 14 Aug 2024 16:26:30 -0500 Subject: [PATCH 14/43] Utilities for Testing, Contracts, and Operators --- Cargo.lock | 1 + avs/incredible-squaring-avs/src/operator.rs | 5 +- avs/tangle-avs/src/lib.rs | 6 +- avs/tangle-avs/src/operator.rs | 20 +- test-utils/Cargo.toml | 2 +- .../src/anvil/{anvil.rs => anvil_node.rs} | 2 +- test-utils/src/anvil/local_chain.rs | 9 +- test-utils/src/anvil/mod.rs | 2 +- .../src/anvil/testnet/incredible_squaring.rs | 267 ++-------- test-utils/src/anvil/testnet/mod.rs | 1 + test-utils/src/anvil/testnet/tangle.rs | 499 ++++++++++++++++++ test-utils/src/incredible_squaring.rs | 127 ++--- test-utils/src/lib.rs | 1 + test-utils/src/tangle.rs | 190 +++++++ utils/src/avs_registry/writer.rs | 89 +--- utils/src/crypto/bls.rs | 56 +- utils/src/crypto/bn254.rs | 22 +- 17 files changed, 846 insertions(+), 453 deletions(-) rename test-utils/src/anvil/{anvil.rs => anvil_node.rs} (99%) create mode 100644 test-utils/src/anvil/testnet/tangle.rs create mode 100644 test-utils/src/tangle.rs diff --git a/Cargo.lock b/Cargo.lock index 4026692..a77ca10 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11722,6 +11722,7 @@ dependencies = [ "serde", "serde_json", "sha3", + "tangle-avs", "thiserror", "tokio", "url", diff --git a/avs/incredible-squaring-avs/src/operator.rs b/avs/incredible-squaring-avs/src/operator.rs index ea371b4..e080713 100644 --- a/avs/incredible-squaring-avs/src/operator.rs +++ b/avs/incredible-squaring-avs/src/operator.rs @@ -336,10 +336,7 @@ impl Operator { let operator_is_registered = self .avs_registry_contract_manager .is_operator_registered(self.operator_addr) - .await; //?; - // if !operator_is_registered { - // return Err(OperatorError::OperatorNotRegistered); - // } + .await; log::info!("Operator registration status: {:?}", operator_is_registered); if self.config.enable_node_api { diff --git a/avs/tangle-avs/src/lib.rs b/avs/tangle-avs/src/lib.rs index 31daf96..b740c42 100644 --- a/avs/tangle-avs/src/lib.rs +++ b/avs/tangle-avs/src/lib.rs @@ -7,7 +7,7 @@ sol!( #[derive(Debug)] #[sol(rpc)] TangleValidatorTaskManager, - "./contracts/out/TangleValidatorTaskManager.sol/TangleValidatorTaskManager.json" + "contracts/out/TangleValidatorTaskManager.sol/TangleValidatorTaskManager.json" ); sol!( @@ -15,7 +15,7 @@ sol!( #[derive(Debug)] #[sol(rpc)] TangleValidatorServiceManager, - "./contracts/out/TangleValidatorServiceManager.sol/TangleValidatorServiceManager.json" + "contracts/out/TangleValidatorServiceManager.sol/TangleValidatorServiceManager.json" ); sol!( @@ -23,5 +23,5 @@ sol!( #[derive(Debug)] #[sol(rpc)] ITangleValidatorTaskManager, - "./contracts/out/ITangleValidatorTaskManager.sol/ITangleValidatorTaskManager.json" + "contracts/out/ITangleValidatorTaskManager.sol/ITangleValidatorTaskManager.json" ); diff --git a/avs/tangle-avs/src/operator.rs b/avs/tangle-avs/src/operator.rs index 5e12dd7..f2ac8aa 100644 --- a/avs/tangle-avs/src/operator.rs +++ b/avs/tangle-avs/src/operator.rs @@ -1,5 +1,5 @@ use alloy_contract::private::Ethereum; -use alloy_primitives::{ruint, Address, ChainId, FixedBytes, Signature, B256}; +use alloy_primitives::{Address, ChainId, Signature, B256}; use alloy_provider::{Provider, RootProvider}; use alloy_signer_local::PrivateKeySigner; use alloy_transport::BoxTransport; @@ -10,15 +10,11 @@ use eigen_utils::crypto::bls::KeyPair; use eigen_utils::node_api::NodeApi; use eigen_utils::types::AvsError; use eigen_utils::Config; -use gadget_common::subxt_signer::bip39::rand; -use gadget_common::subxt_signer::bip39::rand::Rng; use k256::ecdsa::SigningKey; use log::error; -use ruint::aliases; use std::future::Future; use std::pin::Pin; use std::str::FromStr; -use std::time::{SystemTime, UNIX_EPOCH}; use thiserror::Error; const AVS_NAME: &str = "incredible-squaring"; @@ -247,21 +243,9 @@ impl Operator { // ); // } - let mut salt = [0u8; 32]; - rand::thread_rng().fill(&mut salt); - let sig_salt = FixedBytes::from_slice(&salt); - let expiry = aliases::U256::from( - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_secs() - + 3600, - ); let _register_result = avs_registry_contract_manager - .register_operator_in_quorum_with_avs_registry_coordinator( + .register_operator( &ecdsa_signing_key, - sig_salt, - expiry, &bls_keypair, alloy_primitives::Bytes::from(vec![0]), "127.0.0.1:8545".to_string(), diff --git a/test-utils/Cargo.toml b/test-utils/Cargo.toml index ab3eda5..81e41b1 100644 --- a/test-utils/Cargo.toml +++ b/test-utils/Cargo.toml @@ -35,7 +35,7 @@ aws-sdk-kms.workspace = true eigen-contracts.workspace = true eigen-utils.workspace = true incredible-squaring-avs.workspace = true -#tangle-avs.workspace = true +tangle-avs.workspace = true aws-kms.workspace = true gadget-common = { workspace = true, default-features = false, features = ["default"] } # gadget-common = { workspace = true, features = ["tangle-testnet"] } diff --git a/test-utils/src/anvil/anvil.rs b/test-utils/src/anvil/anvil_node.rs similarity index 99% rename from test-utils/src/anvil/anvil.rs rename to test-utils/src/anvil/anvil_node.rs index c1a0b46..e3c3f2b 100644 --- a/test-utils/src/anvil/anvil.rs +++ b/test-utils/src/anvil/anvil_node.rs @@ -41,7 +41,7 @@ impl AnvilInstance { /// Returns the chain of the anvil instance pub fn chain_id(&self) -> u64 { - self.chain_id.unwrap_or_else(|| 0u64) + self.chain_id.unwrap_or(0u64) } /// Returns the HTTP endpoint of this instance diff --git a/test-utils/src/anvil/local_chain.rs b/test-utils/src/anvil/local_chain.rs index c861c8e..8350171 100644 --- a/test-utils/src/anvil/local_chain.rs +++ b/test-utils/src/anvil/local_chain.rs @@ -1,4 +1,4 @@ -use crate::anvil::anvil::{Anvil, AnvilInstance}; +use crate::anvil::anvil_node::{Anvil, AnvilInstance}; use crate::anvil::random_port; use ethers::signers::Signer; use std::sync::Arc; @@ -94,10 +94,9 @@ impl LocalEvmChain { state_dir: Option<&std::path::Path>, port: Option, ) -> AnvilInstance { - let port = if port.is_some() { - port.unwrap() - } else { - random_port::random_port() + let port = match port { + None => random_port::random_port(), + Some(port) => port, }; let mut anvil = Anvil::new() .port(port) diff --git a/test-utils/src/anvil/mod.rs b/test-utils/src/anvil/mod.rs index 040dc1b..1d0298e 100644 --- a/test-utils/src/anvil/mod.rs +++ b/test-utils/src/anvil/mod.rs @@ -1,5 +1,5 @@ pub mod abi; -pub mod anvil; +pub mod anvil_node; pub mod local_chain; mod random_port; pub mod testnet; diff --git a/test-utils/src/anvil/testnet/incredible_squaring.rs b/test-utils/src/anvil/testnet/incredible_squaring.rs index f7e5b41..52e6403 100644 --- a/test-utils/src/anvil/testnet/incredible_squaring.rs +++ b/test-utils/src/anvil/testnet/incredible_squaring.rs @@ -1,6 +1,6 @@ use crate::encode_params; use alloy_primitives::{address, Address, Bytes, Keccak256, U256}; -use alloy_provider::{Provider, ProviderBuilder}; +use alloy_provider::ProviderBuilder; use alloy_sol_types::{abi, SolValue}; use anvil::spawn; use eigen_contracts::{ @@ -10,7 +10,6 @@ use eigen_contracts::{ use incredible_squaring_avs::avs::{ IncredibleSquaringServiceManager, IncredibleSquaringTaskManager, }; -use url::Url; pub static BLS_PASSWORD: &str = "BLS_PASSWORD"; pub static ECDSA_PASSWORD: &str = "ECDSA_PASSWORD"; @@ -28,7 +27,9 @@ pub struct ContractAddresses { pub avs_directory: Address, pub operator: Address, } -pub async fn run_anvil_testnet() -> ContractAddresses { + +/// Spawns and runs an Anvil Node, deploying the Smart Contracts that are relevant to the Incredible Squaring AVS to it. +pub async fn run_incredible_squaring_testnet() -> ContractAddresses { // Initialize the logger let _ = env_logger::try_init(); @@ -42,12 +43,6 @@ pub async fn run_anvil_testnet() -> ContractAddresses { .await; api.anvil_auto_impersonate_account(true).await.unwrap(); - let _http_provider = ProviderBuilder::new() - .on_http(Url::parse(&handle.http_endpoint()).unwrap()) - .root() - .clone(); - // todo: http_provider is unused - let provider = ProviderBuilder::new() .on_builtin(&handle.ws_endpoint()) .await @@ -55,42 +50,10 @@ pub async fn run_anvil_testnet() -> ContractAddresses { let accounts = handle.dev_wallets().collect::>(); let from = accounts[0].address(); - let _to = accounts[1].address(); let dev_account = accounts[0].address(); - let _amount = handle - .genesis_balance() - .checked_div(U256::from(2u64)) - .unwrap(); - - let _gas_price = provider.get_gas_price().await.unwrap(); - - // Empty address for initial deployment of all contracts - let _empty_address = Address::default(); - - // let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); - // let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); - // let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); - // let proxy_admin_addr = address!("5FbDB2315678afecb367f032d93F642f64180aa3"); - // let pauser_registry_addr = address!("e7f1725E7734CE288F8367e1Bb143E90bb3F0512"); - // let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); - - // Deploy Eigenlayer Contracts - // let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9"); - // let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"); - // let avs_directory_addr = address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"); - // let proxy_admin_addr = address!("5FbDB2315678afecb367f032d93F642f64180aa3"); - // let pauser_registry_addr = address!("e7f1725E7734CE288F8367e1Bb143E90bb3F0512"); - // let base_strategy_addr = address!("322813Fd9A801c5507c9de605d63CEA4f2CE6c44"); - - // let istrategy_manager = IStrategyManager::new(strategy_manager_addr, provider.clone()); - // let idelegation_manager = - // IDelegationManager::new(delegation_manager_addr, provider.clone()); - // let iavs_directory = IAVSDirectory::new(avs_directory_addr, provider.clone()); - // let proxy_admin = ProxyAdmin::new(proxy_admin_addr, provider.clone()); - // let pauser_registry = PauserRegistry::new(pauser_registry_addr, provider.clone()); - // let base_strategy = StrategyBaseTVLLimits::new(base_strategy_addr, provider.clone()); + // Deploy initial contracts that don't depend on others let istrategy_manager = IStrategyManager::deploy(provider.clone()).await.unwrap(); let &strategy_manager_addr = istrategy_manager.address(); @@ -112,7 +75,6 @@ pub async fn run_anvil_testnet() -> ContractAddresses { .contract_address .unwrap(); let proxy_admin_addr = proxy_admin; - // let &proxy_admin_addr = proxy_admin.address(); let pauser_registry = PauserRegistry::deploy(provider.clone()).await.unwrap(); let &pauser_registry_addr = pauser_registry.address(); @@ -128,49 +90,15 @@ pub async fn run_anvil_testnet() -> ContractAddresses { let ierc20 = IERC20::new(erc20_mock_addr, provider.clone()); let &ierc20_addr = ierc20.address(); + // Begin deploying with Proxies + // Function with signature initialize(uint256,uint256,address,address) and selector 0x019e2729. let function_signature = "initialize(uint256,uint256,address,address)"; - // let params = vec![ - // 1.tokenize(), - // 100.tokenize(), - // ierc20_addr.tokenize(), - // pauser_registry_addr.tokenize(), - // // WordToken(Word::from(1)), - // // WordToken(Word::from(100)), - // // WordToken(Word::from(ierc20_addr.as_slice())), - // // WordToken(Word::from(pauser_registry_addr.as_slice())), - // ]; - // let encoded_data = encode_with_selector(function_signature, params); - // let encoded_data = encode_params!(function_signature, 1, 100, ierc20_addr, pauser_registry_addr); - let mut hasher = Keccak256::new(); hasher.update(function_signature); let function_selector = &hasher.finalize()[..4]; - let hex_selector = hex::encode(function_selector); - log::info!("Function selector as hex: {:?}", hex_selector); - let mut data = Vec::from(function_selector); - // let encoded_param = SolValue::abi_encode(&1); - // data.extend_from_slice(&encoded_param); - // let encoded_param = SolValue::abi_encode(&100); - // data.extend_from_slice(&encoded_param); - // let encoded_param = SolValue::abi_encode(&ierc20_addr); - // data.extend_from_slice(&encoded_param); - // let encoded_param = SolValue::abi_encode(&pauser_registry_addr); - // data.extend_from_slice(&encoded_param); - let token = 1.tokenize(); - let encoded_param = abi::encode(&token); - data.extend(&encoded_param); - let token = 100.tokenize(); - let encoded_param = abi::encode(&token); - data.extend(&encoded_param); - let token = ierc20_addr.tokenize(); - let encoded_param = abi::encode(&token); - data.extend(&encoded_param); - let token = pauser_registry_addr.tokenize(); - let encoded_param = abi::encode(&token); - data.extend(&encoded_param); - - let encoded_data = alloy_primitives::Bytes::from(data); + + let encoded_data = encode_params!(function_selector, 1, 100, ierc20_addr, pauser_registry_addr); let strategy_proxy = TransparentUpgradeableProxy::deploy( provider.clone(), @@ -197,7 +125,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { .get_receipt() .await .unwrap(); - println!("Add Strategies Receipt: {:?}", add_strategies); + assert!(add_strategies.status()); // Deploy Incredible Squaring Contracts let number_of_strategies = strategies.len(); @@ -212,63 +140,25 @@ pub async fn run_anvil_testnet() -> ContractAddresses { .unwrap() .get_receipt() .await - .unwrap() - .contract_address .unwrap(); + assert!(incredible_squaring_proxy_admin.status()); + + let incredible_squaring_proxy_admin = incredible_squaring_proxy_admin.contract_address.unwrap(); let incredible_squaring_proxy_admin_addr = incredible_squaring_proxy_admin; let incredible_squaring_proxy_admin = ProxyAdmin::new(incredible_squaring_proxy_admin_addr, provider.clone()); - let owner = incredible_squaring_proxy_admin - .owner() - .call() - .await - .unwrap() - ._0; - println!("Owner: {:?}", owner); - - let pausers = vec![dev_account, dev_account]; - - // let incredible_squaring_pauser_registry_addr = - // PauserRegistry::deploy_builder(provider.clone()) - // .from(dev_account) - // .send() - // .await - // .unwrap() - // .get_receipt() - // .await - // .unwrap() - // .contract_address - // .unwrap(); - // println!("Pauser Registry Address: {:?}", incredible_squaring_pauser_registry_addr); - // let incredible_squaring_pauser_registry = - // PauserRegistry::new(incredible_squaring_pauser_registry_addr, provider.clone()); - // incredible_squaring_pauser_registry.address(); - // println!("Pauser Registry: {:?}", incredible_squaring_pauser_registry); + + let pausers = [dev_account, dev_account]; let incredible_squaring_pauser_registry = PauserRegistry::deploy(provider.clone()).await.unwrap(); - let &incredible_squaring_pauser_registry_addr = incredible_squaring_pauser_registry.address(); - println!( - "Pauser Registry Address: {:?}", - incredible_squaring_pauser_registry_addr - ); - - // let unpauser = incredible_squaring_pauser_registry.unpauser().from(dev_account).call().await.unwrap()._0; - // println!("Unpauser: {:?}", unpauser); - // - // let is_pauser = incredible_squaring_pauser_registry - // .isPauser(dev_account) - // .from(dev_account) - // .call() - // .await - // .unwrap(); - // println!("Is Dev Account 0 Pauser: {:?}", is_pauser._0); + let &_incredible_squaring_pauser_registry_addr = incredible_squaring_pauser_registry.address(); let empty_contract = EmptyContract::deploy(provider.clone()).await.unwrap(); let &empty_contract_addr = empty_contract.address(); let incredible_squaring_service_manager = IncredibleSquaringServiceManager::new( - TransparentUpgradeableProxy::deploy( + *TransparentUpgradeableProxy::deploy( provider.clone(), empty_contract_addr, incredible_squaring_proxy_admin_addr, @@ -276,14 +166,13 @@ pub async fn run_anvil_testnet() -> ContractAddresses { ) .await .unwrap() - .address() - .clone(), + .address(), provider.clone(), ); let &incredible_squaring_service_manager_addr = incredible_squaring_service_manager.address(); let incredible_squaring_task_manager = IncredibleSquaringTaskManager::new( - TransparentUpgradeableProxy::deploy( + *TransparentUpgradeableProxy::deploy( provider.clone(), empty_contract_addr, incredible_squaring_proxy_admin_addr, @@ -291,14 +180,13 @@ pub async fn run_anvil_testnet() -> ContractAddresses { ) .await .unwrap() - .address() - .clone(), + .address(), provider.clone(), ); let &incredible_squaring_task_manager_addr = incredible_squaring_task_manager.address(); let registry_coordinator = RegistryCoordinator::new( - TransparentUpgradeableProxy::deploy( + *TransparentUpgradeableProxy::deploy( provider.clone(), empty_contract_addr, incredible_squaring_proxy_admin_addr, @@ -306,29 +194,13 @@ pub async fn run_anvil_testnet() -> ContractAddresses { ) .await .unwrap() - .address() - .clone(), + .address(), provider.clone(), ); let ®istry_coordinator_addr = registry_coordinator.address(); - // let bls_apk_registry = BlsApkRegistry::new( - // TransparentUpgradeableProxy::deploy( - // provider.clone(), - // empty_contract_addr, - // incredible_squaring_proxy_admin_addr, - // Bytes::from(""), - // ) - // .await - // .unwrap() - // .address() - // .clone(), - // provider.clone(), - // ); - // let &bls_apk_registry_addr = bls_apk_registry.address(); - let bls_apk_registry = IBlsApkRegistry::new( - TransparentUpgradeableProxy::deploy( + *TransparentUpgradeableProxy::deploy( provider.clone(), empty_contract_addr, incredible_squaring_proxy_admin_addr, @@ -336,14 +208,13 @@ pub async fn run_anvil_testnet() -> ContractAddresses { ) .await .unwrap() - .address() - .clone(), + .address(), provider.clone(), ); let &bls_apk_registry_addr = bls_apk_registry.address(); let index_registry = IIndexRegistry::new( - TransparentUpgradeableProxy::deploy( + *TransparentUpgradeableProxy::deploy( provider.clone(), empty_contract_addr, incredible_squaring_proxy_admin_addr, @@ -351,14 +222,13 @@ pub async fn run_anvil_testnet() -> ContractAddresses { ) .await .unwrap() - .address() - .clone(), + .address(), provider.clone(), ); let &index_registry_addr = index_registry.address(); let stake_registry = IStakeRegistry::new( - TransparentUpgradeableProxy::deploy( + *TransparentUpgradeableProxy::deploy( provider.clone(), empty_contract_addr, incredible_squaring_proxy_admin_addr, @@ -366,8 +236,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { ) .await .unwrap() - .address() - .clone(), + .address(), provider.clone(), ); let &stake_registry_addr = stake_registry.address(); @@ -394,10 +263,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { .get_receipt() .await .unwrap(); - log::info!( - "Stake Registry Upgrade Receipt: {:?}", - stake_registry_upgrade - ); + assert!(stake_registry_upgrade.status()); let bls_apk_registry_implementation = BlsApkRegistry::deploy(provider.clone(), registry_coordinator_addr) @@ -412,10 +278,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { .get_receipt() .await .unwrap(); - log::info!( - "Bls Apk Registry Upgrade Receipt: {:?}", - bls_apk_registry_upgrade - ); + assert!(bls_apk_registry_upgrade.status()); let index_registry_implementation = IndexRegistry::deploy(provider.clone(), registry_coordinator_addr) @@ -430,10 +293,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { .get_receipt() .await .unwrap(); - log::info!( - "Index Registry Upgrade Receipt: {:?}", - index_registry_upgrade - ); + assert!(index_registry_upgrade.status()); let registry_coordinator_implementation = RegistryCoordinator::deploy( provider.clone(), @@ -516,10 +376,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { .get_receipt() .await .unwrap(); - log::info!( - "Registry Coordinator Initialization Receipt: {:?}", - registry_coordinator_initialization - ); + assert!(registry_coordinator_initialization.status()); let incredible_squaring_service_manager_implementation = IncredibleSquaringServiceManager::deploy( @@ -544,22 +401,10 @@ pub async fn run_anvil_testnet() -> ContractAddresses { .get_receipt() .await .unwrap(); - log::info!( - "Incredible Squaring Service Manager Upgrade Receipt: {:?}", - incredible_squaring_service_manager_upgrade - ); + assert!(incredible_squaring_service_manager_upgrade.status()); // Function with signature initialize(address,address,address,address) and selector 0xf8c8765e. let function_signature = "initialize(address,address,address,address)"; - // let params = vec![ - // pauser_registry_addr.tokenize(), - // pausers[0].tokenize(), - // AGGREGATOR_ADDR.tokenize(), - // TASK_GENERATOR_ADDR.tokenize(), - // ]; - // let encoded_data = - // eigen_utils::test_utils::abi::encode_with_selector(function_signature, params); - let encoded_data = encode_params!( function_signature, pauser_registry_addr, @@ -568,42 +413,30 @@ pub async fn run_anvil_testnet() -> ContractAddresses { TASK_GENERATOR_ADDR ); - println!( - "Registry Coordinator Address: {:?}", - registry_coordinator_addr - ); - // let incredible_squaring_task_manager_implementation = - // IncredibleSquaringTaskManager::deploy( - // provider.clone(), - // registry_coordinator_addr, - // // TASK_RESPONSE_WINDOW_BLOCK, - // 100u32, - // ) - // .await - // .unwrap(); - let incredible_squaring_task_manager_implementation_addr = + let incredible_squaring_task_manager_implementation = IncredibleSquaringTaskManager::deploy_builder( provider.clone(), registry_coordinator_addr, TASK_RESPONSE_WINDOW_BLOCK, ) - // .from(dev_account) .send() .await .unwrap() .get_receipt() .await - .unwrap() - .contract_address .unwrap(); + assert!(incredible_squaring_task_manager_implementation.status()); + + let incredible_squaring_task_manager_implementation_addr = + incredible_squaring_task_manager_implementation + .contract_address + .unwrap(); - // let &incredible_squaring_task_manager_implementation_addr = - // incredible_squaring_task_manager_implementation.address(); let incredible_squaring_task_manager_upgrade = incredible_squaring_proxy_admin .upgradeAndCall( incredible_squaring_task_manager_addr, incredible_squaring_task_manager_implementation_addr, - alloy_primitives::Bytes::from(encoded_data), + encoded_data, ) .send() .await @@ -611,10 +444,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses { .get_receipt() .await .unwrap(); - log::info!( - "Incredible Squaring Task Manager Upgrade Receipt: {:?}", - incredible_squaring_task_manager_upgrade - ); + assert!(incredible_squaring_task_manager_upgrade.status()); let eigen_pod_manager = EigenPodManager::deploy( provider.clone(), @@ -676,18 +506,6 @@ pub async fn run_anvil_testnet() -> ContractAddresses { ); log::info!("DELEGATION MANAGER ADDRESS: {:?}", delegation_manager_addr); - // let _block = provider - // .get_block(BlockId::latest(), false.into()) - // .await - // .unwrap() - // .unwrap(); - // - // api.anvil_set_auto_mine(true).await.unwrap(); - // let run_testnet = async move { - // let serv = handle.servers.pop().unwrap(); - // let res = serv.await.unwrap(); - // res.unwrap(); - // }; // let spawner_task_manager_address = task_manager_addr.clone(); // // let spawner_provider = provider.clone(); // let spawner_provider = provider; @@ -716,7 +534,6 @@ pub async fn run_anvil_testnet() -> ContractAddresses { // // log::info!("Task info: {:?}", task_hash); // } // }; - // tokio::spawn(run_testnet); // tokio::spawn(task_spawner); ContractAddresses { diff --git a/test-utils/src/anvil/testnet/mod.rs b/test-utils/src/anvil/testnet/mod.rs index 284a9a8..e859aa4 100644 --- a/test-utils/src/anvil/testnet/mod.rs +++ b/test-utils/src/anvil/testnet/mod.rs @@ -1 +1,2 @@ pub mod incredible_squaring; +pub(crate) mod tangle; diff --git a/test-utils/src/anvil/testnet/tangle.rs b/test-utils/src/anvil/testnet/tangle.rs new file mode 100644 index 0000000..cbb7c14 --- /dev/null +++ b/test-utils/src/anvil/testnet/tangle.rs @@ -0,0 +1,499 @@ +#![allow(dead_code)] +use crate::encode_params; +use alloy_primitives::{address, Address, Bytes, Keccak256, U256}; +use alloy_provider::ProviderBuilder; +use alloy_sol_types::{abi, SolValue}; +use anvil::spawn; +use eigen_contracts::{ + RegistryCoordinator::{OperatorSetParam, StrategyParams}, + *, +}; +use tangle_avs::{TangleValidatorServiceManager, TangleValidatorTaskManager}; + +pub static BLS_PASSWORD: &str = "BLS_PASSWORD"; +pub static ECDSA_PASSWORD: &str = "ECDSA_PASSWORD"; +pub static TASK_RESPONSE_WINDOW_BLOCK: u32 = 10; +pub static TASK_DURATION_BLOCKS: u32 = 0; +pub static AGGREGATOR_ADDR: Address = address!("a0Ee7A142d267C1f36714E4a8F75612F20a79720"); +pub static TASK_GENERATOR_ADDR: Address = address!("a0Ee7A142d267C1f36714E4a8F75612F20a79720"); + +pub struct ContractAddresses { + pub service_manager: Address, + pub registry_coordinator: Address, + pub operator_state_retriever: Address, + pub delegation_manager: Address, + pub avs_directory: Address, + pub operator: Address, +} + +/// Spawns and runs an Anvil node, deploying the Smart Contracts that are relevant to the Tangle AVS to it. +pub async fn run_tangle_testnet() -> ContractAddresses { + // Initialize the logger + let _ = env_logger::try_init(); + + let (api, handle) = spawn( + anvil::NodeConfig::test() + .with_port(8545) + .with_print_logs(true) + .disable_block_gas_limit(true) + .with_steps_tracing(true), + ) + .await; + api.anvil_auto_impersonate_account(true).await.unwrap(); + + let provider = ProviderBuilder::new() + .on_builtin(&handle.ws_endpoint()) + .await + .unwrap(); + + let accounts = handle.dev_wallets().collect::>(); + let from = accounts[0].address(); + + let dev_account = accounts[0].address(); + + // Deploy initial contracts that don't depend on others + + let istrategy_manager = IStrategyManager::deploy(provider.clone()).await.unwrap(); + let &strategy_manager_addr = istrategy_manager.address(); + + let idelegation_manager = IDelegationManager::deploy(provider.clone()).await.unwrap(); + let &delegation_manager_addr = idelegation_manager.address(); + + let iavs_directory = IAVSDirectory::deploy(provider.clone()).await.unwrap(); + let &avs_directory_addr = iavs_directory.address(); + + let proxy_admin = ProxyAdmin::deploy_builder(provider.clone()) + .from(dev_account) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap() + .contract_address + .unwrap(); + let proxy_admin_addr = proxy_admin; + + let pauser_registry = PauserRegistry::deploy(provider.clone()).await.unwrap(); + let &pauser_registry_addr = pauser_registry.address(); + + let base_strategy = StrategyBaseTVLLimits::deploy(provider.clone(), Default::default()) + .await + .unwrap(); + let &base_strategy_addr = base_strategy.address(); + + let erc20_mock = ERC20Mock::deploy(provider.clone()).await.unwrap(); + let &erc20_mock_addr = erc20_mock.address(); + + let ierc20 = IERC20::new(erc20_mock_addr, provider.clone()); + let &ierc20_addr = ierc20.address(); + + // Begin deploying with Proxies + + // Function with signature initialize(uint256,uint256,address,address) and selector 0x019e2729. + let function_signature = "initialize(uint256,uint256,address,address)"; + let mut hasher = Keccak256::new(); + hasher.update(function_signature); + let function_selector = &hasher.finalize()[..4]; + + let encoded_data = encode_params!(function_selector, 1, 100, ierc20_addr, pauser_registry_addr); + + let strategy_proxy = TransparentUpgradeableProxy::deploy( + provider.clone(), + base_strategy_addr, + proxy_admin_addr, + encoded_data, + ) + .await + .unwrap(); + let &strategy_proxy_addr = strategy_proxy.address(); + + let erc20_mock_strategy = StrategyBaseTVLLimits::deploy(provider.clone(), strategy_proxy_addr) + .await + .unwrap(); + let &erc20_mock_strategy_addr = erc20_mock_strategy.address(); + + let strategies = vec![erc20_mock_strategy_addr]; + + let add_strategies = istrategy_manager + .addStrategiesToDepositWhitelist(strategies.clone(), vec![false]) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(add_strategies.status()); + + // Deploy Incredible Squaring Contracts + let number_of_strategies = strategies.len(); + + let tangle_validator_proxy_admin = ProxyAdmin::deploy_builder(provider.clone()) + .from(dev_account) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(tangle_validator_proxy_admin.status()); + + let tangle_validator_proxy_admin = tangle_validator_proxy_admin.contract_address.unwrap(); + let tangle_validator_proxy_admin_addr = tangle_validator_proxy_admin; + let tangle_validator_proxy_admin = + ProxyAdmin::new(tangle_validator_proxy_admin_addr, provider.clone()); + + let pausers = [dev_account, dev_account]; + + let tangle_validator_pauser_registry = PauserRegistry::deploy(provider.clone()).await.unwrap(); + let &_tangle_validator_pauser_registry_addr = tangle_validator_pauser_registry.address(); + + let empty_contract = EmptyContract::deploy(provider.clone()).await.unwrap(); + let &empty_contract_addr = empty_contract.address(); + + let tangle_validator_service_manager = TangleValidatorServiceManager::new( + *TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + tangle_validator_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address(), + provider.clone(), + ); + let &tangle_validator_service_manager_addr = tangle_validator_service_manager.address(); + + let tangle_validator_task_manager = TangleValidatorTaskManager::new( + *TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + tangle_validator_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address(), + provider.clone(), + ); + let &tangle_validator_task_manager_addr = tangle_validator_task_manager.address(); + + let registry_coordinator = RegistryCoordinator::new( + *TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + tangle_validator_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address(), + provider.clone(), + ); + let ®istry_coordinator_addr = registry_coordinator.address(); + + let bls_apk_registry = IBlsApkRegistry::new( + *TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + tangle_validator_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address(), + provider.clone(), + ); + let &bls_apk_registry_addr = bls_apk_registry.address(); + + let index_registry = IIndexRegistry::new( + *TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + tangle_validator_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address(), + provider.clone(), + ); + let &index_registry_addr = index_registry.address(); + + let stake_registry = IStakeRegistry::new( + *TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + tangle_validator_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address(), + provider.clone(), + ); + let &stake_registry_addr = stake_registry.address(); + + let operator_state_retriever = OperatorStateRetriever::deploy(provider.clone()) + .await + .unwrap(); + let &operator_state_retriever_addr = operator_state_retriever.address(); + + // Now, deploy the implementation contracts using the proxy contracts as inputs + let stake_registry_implementation = StakeRegistry::deploy( + provider.clone(), + registry_coordinator_addr, + delegation_manager_addr, + ) + .await + .unwrap(); + let &stake_registry_implementation_addr = stake_registry_implementation.address(); + let stake_registry_upgrade = tangle_validator_proxy_admin + .upgrade(stake_registry_addr, stake_registry_implementation_addr) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(stake_registry_upgrade.status()); + + let bls_apk_registry_implementation = + BlsApkRegistry::deploy(provider.clone(), registry_coordinator_addr) + .await + .unwrap(); + let &bls_apk_registry_implementation_addr = bls_apk_registry_implementation.address(); + let bls_apk_registry_upgrade = tangle_validator_proxy_admin + .upgrade(bls_apk_registry_addr, bls_apk_registry_implementation_addr) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(bls_apk_registry_upgrade.status()); + + let index_registry_implementation = + IndexRegistry::deploy(provider.clone(), registry_coordinator_addr) + .await + .unwrap(); + let &index_registry_implementation_addr = index_registry_implementation.address(); + let index_registry_upgrade = tangle_validator_proxy_admin + .upgrade(index_registry_addr, index_registry_implementation_addr) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(index_registry_upgrade.status()); + + let registry_coordinator_implementation = RegistryCoordinator::deploy( + provider.clone(), + tangle_validator_service_manager_addr, + stake_registry_addr, + bls_apk_registry_addr, + index_registry_addr, + ) + .await + .unwrap(); + let ®istry_coordinator_implementation_addr = registry_coordinator_implementation.address(); + + let number_of_quorums = 1; + // For each quorum we want to set up, we must define QuorumOperatorSetParam, minimumStakeForQuorum, and strategyParams + let mut quorum_operator_set_params = Vec::::new(); + for i in 0..number_of_quorums { + log::info!("Deploying quorum {}", i); + quorum_operator_set_params.push(OperatorSetParam { + maxOperatorCount: 10000, + kickBIPsOfOperatorStake: 15000, + kickBIPsOfTotalStake: 100, + }); + } + // Set to 0 for each quorum + let mut quorums_minimum_stake = Vec::::new(); + let mut quorums_strategy_params = Vec::>::new(); + for j in 0..number_of_quorums { + quorums_strategy_params.push(Vec::::new()); + quorums_minimum_stake.push(0); + for _k in 0..number_of_strategies { + quorums_strategy_params[j].push(StrategyParams { + strategy: strategies[j], + multiplier: 1, + }); + } + } + + // Function with signature initialize(address,address,address,address,uint256,(uint32,uint16,uint16)[],uint96[],(address,uint96)[][]) and selector 0xdd8283f3. + let function_signature = "initialize(address,address,address,address,uint256,(uint32,uint16,uint16)[],uint96[],(address,uint96)[][])"; + let _encoded_data = encode_params!( + function_signature, + pausers[0], + pausers[0], + pausers[0], + pausers[1], + 0, + quorum_operator_set_params, + quorums_minimum_stake, + quorums_strategy_params + ); + + let registry_coordinator_upgrade = tangle_validator_proxy_admin + .upgrade( + registry_coordinator_addr, + registry_coordinator_implementation_addr, + ) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(registry_coordinator_upgrade.status()); + + let registry_coordinator_initialization = registry_coordinator + .initialize( + pausers[0], + pausers[0], + pausers[0], + pausers[1], + U256::from(0), + quorum_operator_set_params, + quorums_minimum_stake, + quorums_strategy_params, + ) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(registry_coordinator_initialization.status()); + + let tangle_validator_service_manager_implementation = TangleValidatorServiceManager::deploy( + provider.clone(), + avs_directory_addr, + registry_coordinator_addr, + stake_registry_addr, + tangle_validator_task_manager_addr, + ) + .await + .unwrap(); + let &tangle_validator_service_manager_implementation_addr = + tangle_validator_service_manager_implementation.address(); + let tangle_validator_service_manager_upgrade = tangle_validator_proxy_admin + .upgrade( + tangle_validator_service_manager_addr, + tangle_validator_service_manager_implementation_addr, + ) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(tangle_validator_service_manager_upgrade.status()); + + // Function with signature initialize(address,address) and selector 0x485cc955 + let function_signature = "initialize(address,address)"; + let encoded_data = encode_params!(function_signature, pauser_registry_addr, pausers[0]); + + let tangle_validator_task_manager_implementation = + TangleValidatorTaskManager::deploy_builder(provider.clone(), registry_coordinator_addr) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(tangle_validator_task_manager_implementation.status()); + + let tangle_validator_task_manager_implementation_addr = + tangle_validator_task_manager_implementation + .contract_address + .unwrap(); + + let tangle_validator_task_manager_upgrade = tangle_validator_proxy_admin + .upgradeAndCall( + tangle_validator_task_manager_addr, + tangle_validator_task_manager_implementation_addr, + encoded_data, + ) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(tangle_validator_task_manager_upgrade.status()); + + let eigen_pod_manager = EigenPodManager::deploy( + provider.clone(), + empty_contract_addr, + empty_contract_addr, + strategy_manager_addr, + from, + delegation_manager_addr, + ) + .await + .unwrap(); + let &eigen_pod_manager_addr = eigen_pod_manager.address(); + + let slasher_addr = dev_account; + let delegation_manager = DelegationManager::deploy( + provider.clone(), + strategy_manager_addr, + slasher_addr, + eigen_pod_manager_addr, + ) + .await + .unwrap(); + let &delegation_manager_addr = delegation_manager.address(); + + let avs_directory = AVSDirectory::deploy(provider.clone(), delegation_manager_addr) + .await + .unwrap(); + let &avs_directory_addr = avs_directory.address(); + + log::info!("ERC20MOCK ADDRESS: {:?}", erc20_mock_addr); + log::info!("ERC20MOCK STRATEGY ADDRESS: {:?}", erc20_mock_strategy_addr); + log::info!( + "TANGLE VALIDATOR TASK MANAGER ADDRESS: {:?}", + tangle_validator_task_manager_addr + ); + log::info!( + "TANGLE VALIDATOR TASK MANAGER IMPLEMENTATION ADDRESS: {:?}", + tangle_validator_task_manager_implementation_addr + ); + log::info!( + "TANGLE VALIDATOR SERVICE MANAGER ADDRESS: {:?}", + tangle_validator_service_manager_addr + ); + log::info!( + "TANGLE VALIDATOR SERVICE MANAGER IMPLEMENTATION ADDRESS: {:?}", + tangle_validator_service_manager_implementation_addr + ); + log::info!( + "REGISTRY COORDINATOR ADDRESS: {:?}", + registry_coordinator_addr + ); + log::info!( + "REGISTRY COORDINATOR IMPLEMENTATION ADDRESS: {:?}", + registry_coordinator_implementation_addr + ); + log::info!( + "OPERATOR STATE RETRIEVER ADDRESS: {:?}", + operator_state_retriever_addr + ); + log::info!("DELEGATION MANAGER ADDRESS: {:?}", delegation_manager_addr); + + ContractAddresses { + service_manager: tangle_validator_service_manager_addr, + registry_coordinator: registry_coordinator_addr, + operator_state_retriever: operator_state_retriever_addr, + delegation_manager: delegation_manager_addr, + avs_directory: avs_directory_addr, + operator: from, + } +} diff --git a/test-utils/src/incredible_squaring.rs b/test-utils/src/incredible_squaring.rs index 2d48eaa..00f8021 100644 --- a/test-utils/src/incredible_squaring.rs +++ b/test-utils/src/incredible_squaring.rs @@ -1,4 +1,4 @@ -#[allow(dead_code)] +#![allow(dead_code)] use crate::anvil::testnet::incredible_squaring::*; use alloy_provider::Provider; use alloy_provider::ProviderBuilder; @@ -14,49 +14,10 @@ async fn main() { run_full_incredible_squaring_test().await; } -/// THIS FUNCTION IS FOR TESTING ONLY -/// -/// Runs the Incredible Squaring Testnet and then creates an Operator that connects and registers. -async fn run_full_incredible_squaring_test() { - let _ = env_logger::try_init(); - - // Runs new Anvil Testnet - used for deploying programmatically in rust - let contract_addresses = run_anvil_testnet().await; - - // // Runs saved Anvil Testnet - loads from saved chain state JSON file - // let chain = eigen_utils::test_utils::local_chain::LocalEvmChain::new_with_chain_state( - // 31337, - // String::from("eigen-testnet"), - // Path::new("../../eigen-utils/saved-anvil-state.json"), - // Some(8545u16), - // ); - // let chain_id = chain.chain_id(); - // let chain_name = chain.name(); - // println!("chain_id: {:?}", chain_id); - // println!("chain_name: {:?}", chain_name); - - // let account_one = address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"); - // let account_two = address!("70997970C51812dc3A010C7d01b50e0d17dc79C8"); - - // let contract_addresses = ContractAddresses { - // service_manager: address!("84eA74d481Ee0A5332c457a4d796187F6Ba67fEB"), - // registry_coordinator: address!("a82fF9aFd8f496c3d6ac40E2a0F282E47488CFc9"), - // operator_state_retriever: address!("95401dc811bb5740090279Ba06cfA8fcF6113778"), - // delegation_manager: address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"), - // avs_directory: address!("5FC8d32690cc91D4c39d9d3abcBD16989F875707"), - // operator: account_two, - // }; - - // Implementation version of addresses - // let contract_addresses = ContractAddresses { - // service_manager: address!("84eA74d481Ee0A5332c457a4d796187F6Ba67fEB"), - // registry_coordinator: address!("9d4454B023096f34B160D6B654540c56A1F81688"), - // operator_state_retriever: address!("95401dc811bb5740090279Ba06cfA8fcF6113778"), - // delegation_manager: address!("B7f8BC63BbcaD18155201308C8f3540b07f84F5e"), - // avs_directory: address!("0DCd1Bf9A1b36cE34237eEaFef220932846BCD82"), - // operator: address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), - // }; - +/// Sets up an Operator, given the [ContractAddresses] for the running Testnet you would like utilize +async fn operator_setup( + contract_addresses: ContractAddresses, +) -> Operator { let http_endpoint = "http://127.0.0.1:8545"; let ws_endpoint = "ws://127.0.0.1:8545"; let node_config = NodeConfig { @@ -109,7 +70,7 @@ async fn run_full_incredible_squaring_test() { println!("Now setting up Operator!"); - let operator = Operator::::new_from_config( + Operator::::new_from_config( node_config.clone(), EigenGadgetProvider { provider: http_provider, @@ -121,7 +82,19 @@ async fn run_full_incredible_squaring_test() { signer, ) .await - .unwrap(); + .unwrap() +} + +/// THIS FUNCTION IS FOR TESTING ONLY +/// +/// Runs the Incredible Squaring Testnet and then creates an Operator that connects and registers. +async fn run_full_incredible_squaring_test() { + let _ = env_logger::try_init(); + + // Runs new Anvil Testnet - used for deploying programmatically in rust + let contract_addresses = run_incredible_squaring_testnet().await; + + let operator = operator_setup(contract_addresses).await; operator.start().await.unwrap(); } @@ -129,46 +102,54 @@ async fn run_full_incredible_squaring_test() { #[cfg(test)] mod tests { use super::*; - use alloy::signers::Signer; - use alloy_provider::network::TransactionBuilder; use eigen_utils::crypto::bls::KeyPair; use k256::ecdsa::VerifyingKey; use k256::elliptic_curve::SecretKey; use std::env; - use std::path::Path; - use std::time::Duration; + + // #[tokio::test] + // async fn test_full_incredible_squaring() { + // if env::var("RUST_LOG").is_err() { + // env::set_var("RUST_LOG", "info"); + // } + // env::set_var("BLS_PASSWORD", "BLS_PASSWORD"); + // env::set_var("ECDSA_PASSWORD", "ECDSA_PASSWORD"); + // env_logger::init(); + // run_full_incredible_squaring_test().await; + // } #[tokio::test] - async fn test_full_incredible_squaring() { + async fn test_incredible_squaring_deployment() { if env::var("RUST_LOG").is_err() { env::set_var("RUST_LOG", "info"); } env::set_var("BLS_PASSWORD", "BLS_PASSWORD"); env::set_var("ECDSA_PASSWORD", "ECDSA_PASSWORD"); - env_logger::init(); - run_full_incredible_squaring_test().await; + let _ = env_logger::try_init(); + run_incredible_squaring_testnet().await; } - #[tokio::test] - async fn test_start_chain_from_state() { - env_logger::init(); - - let chain = crate::anvil::local_chain::LocalEvmChain::new_with_chain_state( - 31337, - String::from("eigen-testnet"), - Path::new("../../eigen-utils/eigen-gadget-anvil-state.json"), - Some(8545u16), - ); - let chain_id = chain.chain_id(); - let chain_name = chain.name(); - println!("chain_id: {:?}", chain_id); - println!("chain_name: {:?}", chain_name); - let addresses = chain.addresses(); - println!("addresses: {:?}", addresses); - tokio::time::sleep(Duration::from_secs(5)).await; - println!("Now shutting down..."); - chain.shutdown(); - } + // TODO: Get test for loading from state working + // #[tokio::test] + // async fn test_start_chain_from_state() { + // env_logger::init(); + // + // let chain = crate::anvil::local_chain::LocalEvmChain::new_with_chain_state( + // 31337, + // String::from("eigen-testnet"), + // Path::new("../../eigen-utils/eigen-gadget-anvil-state.json"), + // Some(8545u16), + // ); + // let chain_id = chain.chain_id(); + // let chain_name = chain.name(); + // println!("chain_id: {:?}", chain_id); + // println!("chain_name: {:?}", chain_name); + // let addresses = chain.addresses(); + // println!("addresses: {:?}", addresses); + // tokio::time::sleep(Duration::from_secs(5)).await; + // println!("Now shutting down..."); + // chain.shutdown(); + // } #[tokio::test] async fn test_generate_keys() { diff --git a/test-utils/src/lib.rs b/test-utils/src/lib.rs index 2cdfd09..d621112 100644 --- a/test-utils/src/lib.rs +++ b/test-utils/src/lib.rs @@ -1,2 +1,3 @@ pub mod anvil; pub mod incredible_squaring; +pub mod tangle; diff --git a/test-utils/src/tangle.rs b/test-utils/src/tangle.rs new file mode 100644 index 0000000..e5d7d71 --- /dev/null +++ b/test-utils/src/tangle.rs @@ -0,0 +1,190 @@ +#![allow(dead_code)] +use crate::anvil::testnet::tangle::*; +use alloy_provider::Provider; +use alloy_provider::ProviderBuilder; +use alloy_signer_local::PrivateKeySigner; +use alloy_transport_ws::WsConnect; +use k256::ecdsa::SigningKey; +use k256::elliptic_curve::SecretKey; +use tangle_avs::operator::*; + +#[tokio::main] +async fn main() { + let _ = env_logger::try_init(); + run_full_tangle_test().await; +} + +/// Sets up an Operator, given the [ContractAddresses] for the running Testnet you would like utilize +async fn operator_setup(contract_addresses: ContractAddresses) -> Operator { + let http_endpoint = "http://127.0.0.1:8545"; + let ws_endpoint = "ws://127.0.0.1:8545"; + let node_config = NodeConfig { + node_api_ip_port_address: "127.0.0.1:9808".to_string(), + eth_rpc_url: http_endpoint.to_string(), + eth_ws_url: ws_endpoint.to_string(), + bls_private_key_store_path: "./keystore/bls".to_string(), + ecdsa_private_key_store_path: "./keystore/ecdsa".to_string(), + avs_registry_coordinator_address: contract_addresses.registry_coordinator.to_string(), + eigen_metrics_ip_port_address: "127.0.0.1:9100".to_string(), + tangle_validator_service_manager_address: contract_addresses.service_manager.to_string(), + delegation_manager_address: contract_addresses.delegation_manager.to_string(), + operator_address: contract_addresses.operator.to_string(), + enable_metrics: false, + enable_node_api: false, + operator_state_retriever_address: contract_addresses.operator_state_retriever.to_string(), + avs_directory_address: contract_addresses.avs_directory.to_string(), + }; + + let hex_key = + hex::decode("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80").unwrap(); + let secret_key = SecretKey::from_slice(&hex_key).unwrap(); + let signing_key = SigningKey::from(secret_key.clone()); + let signer = EigenTangleSigner { + signer: PrivateKeySigner::from_signing_key(signing_key), + }; + + println!("Creating HTTP Provider..."); + + let http_provider = ProviderBuilder::new() + .with_recommended_fillers() + .on_http(http_endpoint.parse().unwrap()) + .root() + .clone() + .boxed(); + + println!("Creating WS Provider..."); + + let ws_provider = ProviderBuilder::new() + .with_recommended_fillers() + .on_ws(WsConnect::new(ws_endpoint)) + .await + .unwrap() + .root() + .clone() + .boxed(); + + println!("Now setting up Operator!"); + + Operator::::new_from_config( + node_config.clone(), + EigenTangleProvider { + provider: http_provider, + }, + EigenTangleProvider { + provider: ws_provider, + }, + signer, + ) + .await + .unwrap() +} + +/// THIS FUNCTION IS FOR TESTING ONLY +/// +/// Runs the Tangle Testnet and then creates an Operator that connects and registers. +async fn run_full_tangle_test() { + let _ = env_logger::try_init(); + + // Runs new Anvil Testnet - used for deploying programmatically in rust + let contract_addresses = run_tangle_testnet().await; + + let operator = operator_setup(contract_addresses).await; + + operator.start().await.unwrap(); +} + +#[cfg(test)] +mod tests { + use super::*; + use eigen_utils::crypto::bls::KeyPair; + use k256::ecdsa::VerifyingKey; + use k256::elliptic_curve::SecretKey; + use std::env; + + // #[tokio::test] + // async fn test_full_tangle() { + // if env::var("RUST_LOG").is_err() { + // env::set_var("RUST_LOG", "info"); + // } + // env::set_var("BLS_PASSWORD", "BLS_PASSWORD"); + // env::set_var("ECDSA_PASSWORD", "ECDSA_PASSWORD"); + // env_logger::init(); + // run_full_tangle_test().await; + // } + + #[tokio::test] + async fn test_tangle_deployment() { + if env::var("RUST_LOG").is_err() { + env::set_var("RUST_LOG", "info"); + } + env::set_var("BLS_PASSWORD", "BLS_PASSWORD"); + env::set_var("ECDSA_PASSWORD", "ECDSA_PASSWORD"); + let _ = env_logger::try_init(); + let _ = run_tangle_testnet().await; + } + + // TODO: Get test for loading from state working + // #[tokio::test] + // async fn test_start_chain_from_state() { + // env_logger::init(); + // + // let chain = crate::anvil::local_chain::LocalEvmChain::new_with_chain_state( + // 31337, + // String::from("eigen-testnet"), + // Path::new("../../eigen-utils/eigen-gadget-anvil-state.json"), + // Some(8545u16), + // ); + // let chain_id = chain.chain_id(); + // let chain_name = chain.name(); + // println!("chain_id: {:?}", chain_id); + // println!("chain_name: {:?}", chain_name); + // let addresses = chain.addresses(); + // println!("addresses: {:?}", addresses); + // tokio::time::sleep(Duration::from_secs(5)).await; + // println!("Now shutting down..."); + // chain.shutdown(); + // } + + #[tokio::test] + async fn test_generate_keys() { + env_logger::init(); + + // ---------------- BLS ---------------- + let bls_pair = KeyPair::gen_random().unwrap(); + bls_pair + .save_to_file("./keystore/bls", BLS_PASSWORD) + .unwrap(); + let bls_keys = KeyPair::read_private_key_from_file("./keystore/bls", BLS_PASSWORD).unwrap(); + assert_eq!(bls_pair.priv_key, bls_keys.priv_key); + assert_eq!(bls_pair.pub_key, bls_keys.pub_key); + + //---------------- ECDSA ---------------- + // First Account + let hex_key = + hex::decode("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80") + .unwrap(); + + // Second Account + // let hex_key = + // hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d") + // .unwrap(); + + let secret_key = SecretKey::from_slice(&hex_key).unwrap(); + let signing_key = SigningKey::from(secret_key.clone()); + let public_key = secret_key.public_key(); + let verifying_key = VerifyingKey::from(public_key); + eigen_utils::crypto::ecdsa::write_key("./keystore/ecdsa", &secret_key, ECDSA_PASSWORD) + .unwrap(); + + let read_ecdsa_secret_key = + eigen_utils::crypto::ecdsa::read_key("./keystore/ecdsa", ECDSA_PASSWORD).unwrap(); + let read_ecdsa_public_key = read_ecdsa_secret_key.public_key(); + let read_ecdsa_signing_key = SigningKey::from(&read_ecdsa_secret_key); + let read_ecdsa_verifying_key = VerifyingKey::from(&read_ecdsa_signing_key); + + assert_eq!(secret_key, read_ecdsa_secret_key); + assert_eq!(public_key, read_ecdsa_public_key); + assert_eq!(signing_key, read_ecdsa_signing_key); + assert_eq!(verifying_key, read_ecdsa_verifying_key); + } +} diff --git a/utils/src/avs_registry/writer.rs b/utils/src/avs_registry/writer.rs index 5db547b..b337308 100644 --- a/utils/src/avs_registry/writer.rs +++ b/utils/src/avs_registry/writer.rs @@ -1,8 +1,6 @@ #![allow(async_fn_in_trait)] - use super::{AvsRegistryContractManager, AvsRegistryContractResult}; -use crate::crypto::bls::{g1_point_to_ark_point, g1_point_to_g1_projective, G1Point, KeyPair}; -use crate::crypto::bn254::get_g2_generator; +use crate::crypto::bls::{G1Point, KeyPair}; use crate::crypto::ecdsa::ToAddress; use crate::el_contracts::reader::ElReader; use crate::{types::*, Config}; @@ -11,8 +9,6 @@ use alloy_provider::Provider; use alloy_rpc_types::TransactionReceipt; use alloy_signer::k256::ecdsa; use alloy_signer::Signer as alloySigner; -use ark_ec::pairing::Pairing; -use ark_ec::CurveGroup; use eigen_contracts::RegistryCoordinator; use eigen_contracts::RegistryCoordinator::SignatureWithSaltAndExpiry; use k256::ecdsa::VerifyingKey; @@ -66,41 +62,24 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { let registry_coordinator = RegistryCoordinator::new(self.registry_coordinator_addr, self.eth_client_http.clone()); - // params to register bls pubkey with bls apk registry let g1_hashed_msg_to_sign = registry_coordinator .pubkeyRegistrationMessageHash(operator_addr) + .from(operator_addr) .call() .await .map(|x| x._0) .map_err(AvsError::from)?; - log::info!( - "G1 HASHED MESSAGE TO SIGN: X: {:?}, Y: {:?}", - g1_hashed_msg_to_sign.X, - g1_hashed_msg_to_sign.Y - ); - let g1_point = G1Point { x: g1_hashed_msg_to_sign.X, y: g1_hashed_msg_to_sign.Y, }; - log::info!( - "G1 POINT MESSAGE TO SIGN: X: {:?}, Y: {:?}", - g1_point.x, - g1_point.y - ); - let signed_msg = bls_key_pair .sign_hashed_to_curve_message(&g1_point) .g1_point; let g1_pubkey_bn254 = bls_key_pair.get_pub_key_g1(); let g2_pubkey_bn254 = bls_key_pair.get_pub_key_g2(); - log::info!( - "SIGNED MESSAGE G1POINT: X: {:?}, Y: {:?}", - signed_msg.x, - signed_msg.y - ); let pubkey_reg_params = RegistryCoordinator::PubkeyRegistrationParams { pubkeyRegistrationSignature: RegistryCoordinator::G1Point { @@ -116,22 +95,6 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { Y: g2_pubkey_bn254.y, }, }; - log::info!( - "REGISTRY COORDINATOR G1POINT: X: {:?}, Y: {:?}", - pubkey_reg_params.pubkeyRegistrationSignature.X, - pubkey_reg_params.pubkeyRegistrationSignature.Y - ); - - let signature = g1_point_to_g1_projective(&signed_msg); - // PAIRING TEST - let e1 = ark_bn254::Bn254::pairing(signature.into_affine(), get_g2_generator().unwrap()); - - let e2 = ark_bn254::Bn254::pairing( - g1_point_to_ark_point(&g1_point), - bls_key_pair.get_pub_key_g2().to_ark_g2(), - ); - - assert_eq!(e1, e2); // Generate a random salt and 1 hour expiry for the signature let mut rng = rand::thread_rng(); @@ -176,13 +139,6 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { operator_signature_bytes ); - // let wallet = alloy_signer_local::PrivateKeySigner::from(operator_ecdsa_private_key.clone()); - // let operator_signature = wallet.sign_hash_sync(&msg_to_sign).unwrap(); - // let operator_signature_bytes = operator_signature.as_bytes(); - // log::info!("Operator Wallet Hash signature as bytes: {:?}", operator_signature_bytes); - // let operator_signature_bytes = Bytes::from(operator_signature_bytes); - // log::info!("Operator Wallet Hash signature in Alloy Bytes: {:?}", operator_signature_bytes); - let operator_signature_with_salt_and_expiry = SignatureWithSaltAndExpiry { signature: operator_signature_bytes, salt: operator_to_avs_registration_sig_salt, @@ -226,25 +182,15 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { .await .map(|x| x._0) .map_err(AvsError::from)?; - log::info!( - "G1 Hashed msg to sign: X: {:?}, Y: {:?}", - g1_hashed_msg_to_sign.X, - g1_hashed_msg_to_sign.Y - ); let g1_point = G1Point { x: g1_hashed_msg_to_sign.X, y: g1_hashed_msg_to_sign.Y, }; - log::info!("G1 Point: {:?}", g1_point); let signed_msg = bls_key_pair.sign_hashed_to_curve_message(&g1_point); - let g1_pubkey_bn254 = bls_key_pair.get_pub_key_g1(); - log::info!("G1 Pubkey: {:?}", g1_pubkey_bn254); - let g2_pubkey_bn254 = bls_key_pair.get_pub_key_g2(); - log::info!("G2 Pubkey: {:?}", g2_pubkey_bn254); let pubkey_reg_params = RegistryCoordinator::PubkeyRegistrationParams { pubkeyRegistrationSignature: RegistryCoordinator::G1Point { @@ -293,18 +239,6 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { salt: operator_to_avs_registration_sig_salt, expiry: operator_to_avs_registration_sig_expiry, }; - log::info!( - "Operator signature: {:?}", - operator_signature_with_salt_and_expiry.signature - ); - log::info!( - "Operator salt: {:?}", - operator_signature_with_salt_and_expiry.salt - ); - log::info!( - "Operator expiry: {:?}", - operator_signature_with_salt_and_expiry.expiry - ); let registry_coordinator = RegistryCoordinator::new(self.registry_coordinator_addr, self.eth_client_http.clone()); @@ -315,25 +249,8 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { operator_signature_with_salt_and_expiry, ); - let quorum_count = registry_coordinator.quorumCount().call().await.unwrap(); - log::info!("Quorum count: {:?}", quorum_count._0); - - let bitmap = registry_coordinator - .getCurrentQuorumBitmap(operator_id_from_key_pair(bls_key_pair)) - .call() - .await - .unwrap(); - log::info!("Bitmap: {:?}", bitmap._0); - - let _call = builder.call().await.unwrap(); - let tx = builder.send().await?; let watch = tx.watch().await?; - log::info!( - "Registered operator with the AVS's registry coordinator: {:?}", - watch - ); - let receipt = self .eth_client_http .get_transaction_receipt(watch) @@ -341,8 +258,6 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { .unwrap() .unwrap(); - log::info!("Successfully registered operator with AVS registry coordinator"); - Ok(receipt) } diff --git a/utils/src/crypto/bls.rs b/utils/src/crypto/bls.rs index 7d5a2cd..ea79418 100644 --- a/utils/src/crypto/bls.rs +++ b/utils/src/crypto/bls.rs @@ -1,5 +1,6 @@ use super::bn254::{ - get_g2_generator, map_to_curve, mul_by_generator_g1, point_to_u256, u256_to_point, + get_g1_generator, get_g2_generator, map_to_curve, mul_by_generator_g1, point_to_u256, + u256_to_point, }; use crate::types::AvsError; use alloy_primitives::U256; @@ -22,7 +23,7 @@ use scrypt::{password_hash, Params, Scrypt}; use serde::{Deserialize, Serialize}; use std::fmt::Write; use std::fs; -use std::ops::Neg; +use std::ops::{Add, Neg, Sub}; use std::path::Path; #[derive(Clone, Debug, Serialize, Deserialize)] @@ -73,9 +74,8 @@ impl CanonicalDeserialize for G1Point { impl G1Point { pub fn new(x: F, y: F) -> Self { - // let point = G1Projective::new(x, y, Fq::one()); - let x = U256::from_limbs(x.0 .0); - let y = U256::from_limbs(y.0 .0); + let x = point_to_u256(x); + let y = point_to_u256(y); G1Point { x, y } } @@ -96,28 +96,30 @@ impl G1Point { } pub fn generator() -> Self { - let gen = G1Affine::generator(); + // let gen = G1Affine::generator(); + let gen = get_g1_generator().unwrap(); ark_point_to_g1_point(&gen) } pub fn add(&mut self, other: &G1Point) { let affine_p1 = g1_point_to_ark_point(self); let affine_p2 = g1_point_to_ark_point(other); - let pt = (affine_p1 + affine_p2).into_affine(); - *self = ark_point_to_g1_point(&pt); + // let pt = (affine_p1 + affine_p2).into_affine(); + let pt = affine_p1.add(affine_p2); + *self = g1_projective_to_g1_point(&pt); } pub fn sub(&mut self, other: &G1Point) { let affine_p1 = g1_point_to_ark_point(self); let affine_p2 = g1_point_to_ark_point(other); - let pt = (affine_p1 - affine_p2).into_affine(); - *self = ark_point_to_g1_point(&pt); + let pt = affine_p1.sub(affine_p2); + *self = g1_projective_to_g1_point(&pt); } pub fn mul(&mut self, scalar: Fr) { let affine = g1_point_to_ark_point(self); - let pt = affine.mul_bigint(scalar.0).into_affine(); - *self = ark_point_to_g1_point(&pt); + let pt = affine.mul_bigint(scalar.0); + *self = g1_projective_to_g1_point(&pt); } pub fn mul_bigint(&mut self, bigint: U256) { @@ -178,10 +180,9 @@ impl CanonicalDeserialize for G2Point { impl G2Point { /// Create a new [G2Point] from [Field] components. This is unchecked and will not verify that the point is on the curve. pub fn new(x: [F; 2], y: [F; 2]) -> Self { - Self { - x: [U256::from_limbs(x[0].0 .0), U256::from_limbs(x[1].0 .0)], - y: [U256::from_limbs(y[0].0 .0), U256::from_limbs(y[1].0 .0)], - } + let x = [point_to_u256(x[0]), point_to_u256(x[1])]; + let y = [point_to_u256(y[0]), point_to_u256(y[1])]; + Self { x, y } } /// Returns the bytes representation of a [G2Point] as a [Vec] of [u8]. @@ -194,7 +195,7 @@ impl G2Point { /// Negates a [G2Point]. pub fn neg(&self) -> Self { let affine = g2_point_to_ark_point(self); - let neg_affine = -affine; + let neg_affine = affine.neg(); ark_point_to_g2_point(&neg_affine) } @@ -205,7 +206,8 @@ impl G2Point { /// Uses the fixed [G2Affine::generator] to generate a [G2Point]. pub fn generator() -> Self { - let gen = G2Affine::generator(); + // let gen = G2Affine::generator(); + let gen = get_g2_generator().unwrap(); ark_point_to_g2_point(&gen) } @@ -214,8 +216,9 @@ impl G2Point { let affine_p1 = g2_point_to_ark_point(self); let affine_p2 = g2_point_to_ark_point(other); - let pt = (affine_p1 + affine_p2).into_affine(); - *self = ark_point_to_g2_point(&pt); + // let pt = (affine_p1 + affine_p2).into_affine(); + let pt = affine_p1.add(affine_p2); + *self = ark_point_to_g2_point(&pt.into_affine()); } /// Subtraction Operation for [G2Point]. @@ -223,8 +226,9 @@ impl G2Point { let affine_p1 = g2_point_to_ark_point(self); let affine_p2 = g2_point_to_ark_point(other); - let pt = (affine_p1 - affine_p2).into_affine(); - *self = ark_point_to_g2_point(&pt); + // let pt = (affine_p1 - affine_p2).into_affine(); + let pt = affine_p1.sub(affine_p2); + *self = ark_point_to_g2_point(&pt.into_affine()); } /// Multiplication Operation for [G2Point]. @@ -528,7 +532,13 @@ impl KeyPair { } pub fn sign_hashed_to_curve_message(&self, g1_hashed_msg: &G1Point) -> Signature { - let sig_point = g1_point_to_g1_projective(g1_hashed_msg); + // let sig_point = g1_point_to_g1_projective(g1_hashed_msg); + // let sig = sig_point.mul_bigint(self.priv_key.0); + // Signature { + // g1_point: ark_point_to_g1_point(&sig.into_affine()), + // } + // + let sig_point = g1_point_to_ark_point(g1_hashed_msg); let sig = sig_point.mul_bigint(self.priv_key.0); Signature { g1_point: ark_point_to_g1_point(&sig.into_affine()), diff --git a/utils/src/crypto/bn254.rs b/utils/src/crypto/bn254.rs index d1af2b5..c80a4b9 100644 --- a/utils/src/crypto/bn254.rs +++ b/utils/src/crypto/bn254.rs @@ -1,12 +1,10 @@ use crate::types::AvsError; use alloy_primitives::U256; +use ark_bn254::Fq as F; use ark_bn254::{Fr, G1Affine, G1Projective, G2Affine, G2Projective}; +use ark_ec::AffineRepr; use ark_ff::{BigInteger, BigInteger256}; use ark_ff::{Field, One, PrimeField}; -use std::ops::Mul; - -use ark_bn254::Fq as F; -use ark_ec::AffineRepr; pub fn map_to_curve(digest: &[u8; 32]) -> G1Projective { let one = F::one(); @@ -68,14 +66,14 @@ pub fn biginteger256_to_u256(bi: BigInteger256) -> U256 { } pub fn get_g1_generator() -> Result { - // let g1_affine = G1Affine::new(G1_GENERATOR_X, G1_GENERATOR_Y); - let g1_affine = G1Affine::generator(); + let g1_affine = G1Affine::new(ark_bn254::g1::G1_GENERATOR_X, ark_bn254::g1::G1_GENERATOR_Y); + // let g1_affine = G1Affine::generator(); Ok(g1_affine) } pub fn get_g2_generator() -> Result { - // let g2_affine = G2Affine::new(G2_GENERATOR_X, G2_GENERATOR_Y); - let g2_affine = G2Affine::generator(); + let g2_affine = G2Affine::new(ark_bn254::g2::G2_GENERATOR_X, ark_bn254::g2::G2_GENERATOR_Y); + // let g2_affine = G2Affine::generator(); Ok(g2_affine) } @@ -84,8 +82,8 @@ pub fn mul_by_generator_g1(pvt_key: Fr) -> Result { match g1_gen_result { Ok(g1_gen) => { - let s: G1Projective = g1_gen.into(); - Ok(s.mul(pvt_key)) + // let s: G1Projective = g1_gen.into(); + Ok(g1_gen.mul_bigint(pvt_key.0)) } Err(_) => Err(AvsError::KeyError( "Invalid G1 Generator Result".to_string(), @@ -98,8 +96,8 @@ pub fn mul_by_generator_g2(pvt_key: Fr) -> Result { match g2_gen_result { Ok(g2_gen) => { - let s: G2Projective = g2_gen.into(); - Ok(s.mul(pvt_key)) + // let s: G2Projective = g2_gen.into(); + Ok(g2_gen.mul_bigint(pvt_key.0)) } Err(_) => Err(AvsError::KeyError( "Invalid G2 Generator Result".to_string(), From 165c45710c1f7e32eb987ed114d80bb395a86713 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 14 Aug 2024 17:22:09 -0500 Subject: [PATCH 15/43] Workflow, testing readme, and build script --- .github/workflows/validate_pr.yml | 28 +++++++ test-utils/Cargo.toml | 18 +++-- test-utils/README.md | 75 +++++++++++++++++++ test-utils/scripts/build.sh | 22 ++++++ test-utils/src/anvil/testnet/mod.rs | 2 +- .../src/{ => bin}/incredible_squaring.rs | 22 +++--- test-utils/src/{ => bin}/tangle.rs | 22 +++--- test-utils/src/lib.rs | 2 - 8 files changed, 159 insertions(+), 32 deletions(-) create mode 100644 test-utils/README.md create mode 100644 test-utils/scripts/build.sh rename test-utils/src/{ => bin}/incredible_squaring.rs (93%) rename test-utils/src/{ => bin}/tangle.rs (94%) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index cb49f5f..710a727 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -16,6 +16,34 @@ env: CARGO_TERM_COLOR: always jobs: + forge: + name: Forge + runs-on: macos-latest + steps: + - name: Install Foundry + run: | + curl -L https://foundry.paradigm.xyz | bash + foundryup + + - name: Verify Forge installation + run: forge --version + + - name: Set up Foundry cache + run: | + forge install + + - name: Run build script + run: | + chmod +x ./test-utils/scripts/build.sh + ./test-utils/scripts/build.sh + + - name: Upload Build Artifacts + if: success() + uses: actions/upload-artifact@v3 + with: + name: build-artifacts + path: ./out/ + formatting: name: Rustfmt runs-on: ubuntu-latest diff --git a/test-utils/Cargo.toml b/test-utils/Cargo.toml index 81e41b1..e5d19ed 100644 --- a/test-utils/Cargo.toml +++ b/test-utils/Cargo.toml @@ -7,13 +7,17 @@ license.workspace = true homepage.workspace = true repository.workspace = true -#[lib] -#name = "test_utils" -#path = "src/lib.rs" -# -#[[bin]] -#name = "incredible_squaring" -#path = "src/incredible_squaring.rs" +[lib] +name = "test_utils" +path = "src/lib.rs" + +[[bin]] +name = "incredible_squaring" +path = "src/bin/incredible_squaring.rs" + +[[bin]] +name = "tangle" +path = "src/bin/tangle.rs" [dependencies] alloy-abi.workspace = true diff --git a/test-utils/README.md b/test-utils/README.md new file mode 100644 index 0000000..dbef63e --- /dev/null +++ b/test-utils/README.md @@ -0,0 +1,75 @@ +# EigenSDK-RS Test Utilities + +[![Validate PR](https://github.com/webb-tools/eigensdk-rs/actions/workflows/validate_pr.yml/badge.svg)](https://github.com/webb-tools/eigensdk-rs/actions/workflows/validate_pr.yml) +[![Rust Version](https://img.shields.io/badge/rust-1.74.0%2B-blue.svg)](https://www.rust-lang.org) +--- + +## Overview + +Utilities designed to streamline and enhance the testing process of EigenSDK-RS and any projects that utilize it. + +## Getting Started + +To use `test-utils` in your own workspace, add it as a dev-dependency. Using these tools in EigenSDK-RS work out-of-the-box: + +```toml +[dev-dependencies] +test-utils = { path = "https://github.com/webb-tools/eigensdk-rs/tree/main/test-utils" } +``` +## Features + +--- +### Scripts + +To automatically set the Environment variables required for testing: +```bash +. ./scripts/env_setup.sh +``` + +If you are building your own AVS, you may be frequently rebuilding your Contracts. You can automatically clean and rebuild the contracts in `/contracts` with: +```bash +./scripts/rebuild_contracts.sh +``` +To rebuild the contracts in the AVS directory: +```bash +./scripts/rebuild_contracts.sh +``` + +--- + +### Test Binaries + +To run the included Testnets as binaries, build the project and then run the testnet you need: +```bash +cargo build -r +./target/release/incredible-squaring +``` +or +```bash +cargo build -r +./target/release/tangle +``` + +--- + +### Cargo tests + +To run the tests for the included AVSs (from the test-utils directory): + +#### Tangle +```bash +# To just run the deployment test, running the Testnet +cargo test test_tangle_deployment + +# To run the testnet and test connecting an Operator to it +cargo test test_full_tangle +``` + +#### Incredible Squaring +```bash +# To just run the deployment test, running the Testnet +cargo test test_incredible_squaring_deployment + +# To run the testnet and test connecting an Operator to it +cargo test test_full_incredible_squaring +``` diff --git a/test-utils/scripts/build.sh b/test-utils/scripts/build.sh new file mode 100644 index 0000000..4ea3fcc --- /dev/null +++ b/test-utils/scripts/build.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +# Define the directories +DIR1="./../contracts/lib/eigenlayer-middleware" +DIR2="./../contracts" +DIR3="./../avs/incredible-squaring-avs/contracts" +DIR4="./../avs/tangle-avs/contract" + +# Function to run forge commands in a directory +run_forge_commands() { + local dir=$1 + echo "Running forge commands in $dir" + cd "$dir" || exit + forge build + cd - || exit +} + +# Run forge commands in both directories +run_forge_commands "$DIR1" +run_forge_commands "$DIR2" +run_forge_commands "$DIR3" +run_forge_commands "$DIR4" \ No newline at end of file diff --git a/test-utils/src/anvil/testnet/mod.rs b/test-utils/src/anvil/testnet/mod.rs index e859aa4..07d8149 100644 --- a/test-utils/src/anvil/testnet/mod.rs +++ b/test-utils/src/anvil/testnet/mod.rs @@ -1,2 +1,2 @@ pub mod incredible_squaring; -pub(crate) mod tangle; +pub mod tangle; diff --git a/test-utils/src/incredible_squaring.rs b/test-utils/src/bin/incredible_squaring.rs similarity index 93% rename from test-utils/src/incredible_squaring.rs rename to test-utils/src/bin/incredible_squaring.rs index 00f8021..3ac0c2e 100644 --- a/test-utils/src/incredible_squaring.rs +++ b/test-utils/src/bin/incredible_squaring.rs @@ -1,5 +1,4 @@ #![allow(dead_code)] -use crate::anvil::testnet::incredible_squaring::*; use alloy_provider::Provider; use alloy_provider::ProviderBuilder; use alloy_signer_local::PrivateKeySigner; @@ -7,6 +6,7 @@ use alloy_transport_ws::WsConnect; use incredible_squaring_avs::operator::*; use k256::ecdsa::SigningKey; use k256::elliptic_curve::SecretKey; +use test_utils::anvil::testnet::incredible_squaring::*; #[tokio::main] async fn main() { @@ -107,16 +107,16 @@ mod tests { use k256::elliptic_curve::SecretKey; use std::env; - // #[tokio::test] - // async fn test_full_incredible_squaring() { - // if env::var("RUST_LOG").is_err() { - // env::set_var("RUST_LOG", "info"); - // } - // env::set_var("BLS_PASSWORD", "BLS_PASSWORD"); - // env::set_var("ECDSA_PASSWORD", "ECDSA_PASSWORD"); - // env_logger::init(); - // run_full_incredible_squaring_test().await; - // } + #[tokio::test] + async fn test_full_incredible_squaring() { + if env::var("RUST_LOG").is_err() { + env::set_var("RUST_LOG", "info"); + } + env::set_var("BLS_PASSWORD", "BLS_PASSWORD"); + env::set_var("ECDSA_PASSWORD", "ECDSA_PASSWORD"); + env_logger::init(); + run_full_incredible_squaring_test().await; + } #[tokio::test] async fn test_incredible_squaring_deployment() { diff --git a/test-utils/src/tangle.rs b/test-utils/src/bin/tangle.rs similarity index 94% rename from test-utils/src/tangle.rs rename to test-utils/src/bin/tangle.rs index e5d7d71..774d4b8 100644 --- a/test-utils/src/tangle.rs +++ b/test-utils/src/bin/tangle.rs @@ -1,5 +1,4 @@ #![allow(dead_code)] -use crate::anvil::testnet::tangle::*; use alloy_provider::Provider; use alloy_provider::ProviderBuilder; use alloy_signer_local::PrivateKeySigner; @@ -7,6 +6,7 @@ use alloy_transport_ws::WsConnect; use k256::ecdsa::SigningKey; use k256::elliptic_curve::SecretKey; use tangle_avs::operator::*; +use test_utils::anvil::testnet::tangle::*; #[tokio::main] async fn main() { @@ -101,16 +101,16 @@ mod tests { use k256::elliptic_curve::SecretKey; use std::env; - // #[tokio::test] - // async fn test_full_tangle() { - // if env::var("RUST_LOG").is_err() { - // env::set_var("RUST_LOG", "info"); - // } - // env::set_var("BLS_PASSWORD", "BLS_PASSWORD"); - // env::set_var("ECDSA_PASSWORD", "ECDSA_PASSWORD"); - // env_logger::init(); - // run_full_tangle_test().await; - // } + #[tokio::test] + async fn test_full_tangle() { + if env::var("RUST_LOG").is_err() { + env::set_var("RUST_LOG", "info"); + } + env::set_var("BLS_PASSWORD", "BLS_PASSWORD"); + env::set_var("ECDSA_PASSWORD", "ECDSA_PASSWORD"); + env_logger::init(); + run_full_tangle_test().await; + } #[tokio::test] async fn test_tangle_deployment() { diff --git a/test-utils/src/lib.rs b/test-utils/src/lib.rs index d621112..ff59a3b 100644 --- a/test-utils/src/lib.rs +++ b/test-utils/src/lib.rs @@ -1,3 +1 @@ pub mod anvil; -pub mod incredible_squaring; -pub mod tangle; From 9fd1a64289a9cbae9793efaa8e72e468d38a0614 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Mon, 19 Aug 2024 21:50:23 -0500 Subject: [PATCH 16/43] BLS Pairing Debugging and Fix --- avs/incredible-squaring-avs/src/operator.rs | 15 +- .../src/anvil/testnet/incredible_squaring.rs | 74 +++--- test-utils/src/bin/incredible_squaring.rs | 5 +- utils/src/avs_registry/writer.rs | 2 + utils/src/crypto/bls.rs | 216 ++++++++++++++++-- utils/src/crypto/bn254.rs | 15 +- 6 files changed, 267 insertions(+), 60 deletions(-) diff --git a/avs/incredible-squaring-avs/src/operator.rs b/avs/incredible-squaring-avs/src/operator.rs index e080713..951d69e 100644 --- a/avs/incredible-squaring-avs/src/operator.rs +++ b/avs/incredible-squaring-avs/src/operator.rs @@ -278,7 +278,14 @@ impl Operator { .await .unwrap(); - let quorum_nums = Bytes::from(vec![0]); + let quorum_nums = Bytes::from([0x00]); + let bls_keypair = KeyPair::new( + eigen_utils::crypto::bls::PrivateKey::from_str( + "12248929636257230549931416853095037629726205319386239410403476017439825112537", + ) + .unwrap(), + ) + .unwrap(); let register_result = avs_registry_contract_manager .register_operator( &ecdsa_signing_key, @@ -358,7 +365,7 @@ impl Operator { log::info!("Received new task: {:?}", value); loop { - log::info!("About to wait for a new task submissions"); + log::info!("Waiting for new task submissions"); tokio::select! { Ok(new_task_created_log) = sub.recv() => { log::info!("Received new task: {:?}", new_task_created_log); @@ -376,6 +383,10 @@ impl Operator { } } + pub fn config(&self) -> NodeConfig { + self.config.clone() + } + fn process_new_task_created_log( &self, new_task_created_log: &Log, diff --git a/test-utils/src/anvil/testnet/incredible_squaring.rs b/test-utils/src/anvil/testnet/incredible_squaring.rs index 52e6403..a6f04c8 100644 --- a/test-utils/src/anvil/testnet/incredible_squaring.rs +++ b/test-utils/src/anvil/testnet/incredible_squaring.rs @@ -52,6 +52,7 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { let from = accounts[0].address(); let dev_account = accounts[0].address(); + let task_account = address!("a0Ee7A142d267C1f36714E4a8F75612F20a79720"); // This is the last Dev Account `accounts[9]` // Deploy initial contracts that don't depend on others @@ -94,11 +95,17 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { // Function with signature initialize(uint256,uint256,address,address) and selector 0x019e2729. let function_signature = "initialize(uint256,uint256,address,address)"; - let mut hasher = Keccak256::new(); - hasher.update(function_signature); - let function_selector = &hasher.finalize()[..4]; + // let mut hasher = Keccak256::new(); + // hasher.update(function_signature); + // let function_selector = &hasher.finalize()[..4]; - let encoded_data = encode_params!(function_selector, 1, 100, ierc20_addr, pauser_registry_addr); + let encoded_data = encode_params!( + function_signature, + 1, + 100, + ierc20_addr, + pauser_registry_addr + ); let strategy_proxy = TransparentUpgradeableProxy::deploy( provider.clone(), @@ -506,35 +513,36 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { ); log::info!("DELEGATION MANAGER ADDRESS: {:?}", delegation_manager_addr); - // let spawner_task_manager_address = task_manager_addr.clone(); - // // let spawner_provider = provider.clone(); - // let spawner_provider = provider; - // let task_spawner = async move { - // let manager = IncredibleSquaringTaskManager::new( - // spawner_task_manager_address, - // spawner_provider.clone(), - // ); - // loop { - // api.mine_one().await; - // log::info!("About to create new task"); - // tokio::time::sleep(std::time::Duration::from_millis(5000)).await; - // let result = manager - // .createNewTask(U256::from(2), 100u32, Bytes::from("0")) - // .send() - // .await - // .unwrap() - // .watch() - // .await - // .unwrap(); - // api.mine_one().await; - // log::info!("Created new task: {:?}", result); - // // let latest_task = manager.latestTaskNum().call().await.unwrap()._0; - // // log::info!("Latest task: {:?}", latest_task); - // // let task_hash = manager.allTaskHashes(latest_task).call().await.unwrap()._0; - // // log::info!("Task info: {:?}", task_hash); - // } - // }; - // tokio::spawn(task_spawner); + let spawner_task_manager_address = incredible_squaring_task_manager_addr.clone(); + // let spawner_provider = provider.clone(); + let spawner_provider = provider.clone(); + let task_spawner = async move { + let manager = IncredibleSquaringTaskManager::new( + spawner_task_manager_address, + spawner_provider.clone(), + ); + loop { + api.mine_one().await; + log::info!("About to create new task"); + tokio::time::sleep(std::time::Duration::from_millis(5000)).await; + let result = manager + .createNewTask(U256::from(2), 100u32, Bytes::from(vec![0])) + .from(task_account) + .send() + .await + .unwrap() + .watch() + .await + .unwrap(); + api.mine_one().await; + log::info!("Created new task: {:?}", result); + // let latest_task = manager.latestTaskNum().call().await.unwrap()._0; + // log::info!("Latest task: {:?}", latest_task); + // let task_hash = manager.allTaskHashes(latest_task).call().await.unwrap()._0; + // log::info!("Task info: {:?}", task_hash); + } + }; + tokio::spawn(task_spawner); ContractAddresses { service_manager: incredible_squaring_service_manager_addr, diff --git a/test-utils/src/bin/incredible_squaring.rs b/test-utils/src/bin/incredible_squaring.rs index 3ac0c2e..daf6761 100644 --- a/test-utils/src/bin/incredible_squaring.rs +++ b/test-utils/src/bin/incredible_squaring.rs @@ -3,6 +3,9 @@ use alloy_provider::Provider; use alloy_provider::ProviderBuilder; use alloy_signer_local::PrivateKeySigner; use alloy_transport_ws::WsConnect; +use ethers::prelude::contract; +use incredible_squaring_avs::aggregator::Aggregator; +use incredible_squaring_avs::avs::SetupConfig; use incredible_squaring_avs::operator::*; use k256::ecdsa::SigningKey; use k256::elliptic_curve::SecretKey; @@ -35,7 +38,7 @@ async fn operator_setup( operator_address: contract_addresses.operator.to_string(), enable_metrics: false, enable_node_api: false, - server_ip_port_address: "".to_string(), + server_ip_port_address: "127.0.0.1:8673".to_string(), }; let operator_info_service = OperatorInfoService {}; diff --git a/utils/src/avs_registry/writer.rs b/utils/src/avs_registry/writer.rs index b337308..dde34b2 100644 --- a/utils/src/avs_registry/writer.rs +++ b/utils/src/avs_registry/writer.rs @@ -93,6 +93,8 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { pubkeyG2: RegistryCoordinator::G2Point { X: g2_pubkey_bn254.x, Y: g2_pubkey_bn254.y, + //X: [g2_pubkey_bn254.x[1], g2_pubkey_bn254.x[0]], + //Y: [g2_pubkey_bn254.y[1], g2_pubkey_bn254.y[0]], }, }; diff --git a/utils/src/crypto/bls.rs b/utils/src/crypto/bls.rs index ea79418..9b3ce51 100644 --- a/utils/src/crypto/bls.rs +++ b/utils/src/crypto/bls.rs @@ -180,8 +180,8 @@ impl CanonicalDeserialize for G2Point { impl G2Point { /// Create a new [G2Point] from [Field] components. This is unchecked and will not verify that the point is on the curve. pub fn new(x: [F; 2], y: [F; 2]) -> Self { - let x = [point_to_u256(x[0]), point_to_u256(x[1])]; - let y = [point_to_u256(y[0]), point_to_u256(y[1])]; + let x = [point_to_u256(x[1]), point_to_u256(x[0])]; + let y = [point_to_u256(y[1]), point_to_u256(y[0])]; Self { x, y } } @@ -279,12 +279,12 @@ pub fn ark_point_to_g1_point(pt: &G1Affine) -> G1Point { pub fn g2_point_to_ark_point(pt: &G2Point) -> G2Affine { G2Affine::new( QuadExtField { - c0: u256_to_point(pt.x[0]), - c1: u256_to_point(pt.x[1]), + c0: u256_to_point(pt.x[1]), + c1: u256_to_point(pt.x[0]), }, QuadExtField { - c0: u256_to_point(pt.y[0]), - c1: u256_to_point(pt.y[1]), + c0: u256_to_point(pt.y[1]), + c1: u256_to_point(pt.y[0]), }, ) } @@ -292,8 +292,8 @@ pub fn g2_point_to_ark_point(pt: &G2Point) -> G2Affine { /// Converts a [G2Affine] to a [G2Point]. pub fn ark_point_to_g2_point(pt: &G2Affine) -> G2Point { G2Point { - x: [point_to_u256(pt.x.c0), point_to_u256(pt.x.c1)], - y: [point_to_u256(pt.y.c0), point_to_u256(pt.y.c1)], + x: [point_to_u256(pt.x.c1), point_to_u256(pt.x.c0)], + y: [point_to_u256(pt.y.c1), point_to_u256(pt.y.c0)], } } @@ -349,9 +349,13 @@ impl Signature { self.g1_point.add(&other.g1_point); } - pub fn verify(&self, pubkey: &G2Point, message: &[u8; 32]) -> Result { - let g2_gen = G2Point::generator(); - let msg_affine = map_to_curve(message).into_affine(); + pub fn verify( + &self, + pubkey: &G2Point, + pre_hashed_message: &[u8; 32], + ) -> Result { + let g2_gen = ark_point_to_g2_point(&get_g2_generator()?); + let msg_affine = map_to_curve(pre_hashed_message).into_affine(); let msg_point = ark_point_to_g1_point(&msg_affine); let neg_sig = self.g1_point.neg(); @@ -524,22 +528,16 @@ impl KeyPair { } pub fn sign_message(&self, message: &[u8; 32]) -> Signature { - let sig_point = map_to_curve(message); - let sig = sig_point.mul_bigint(self.priv_key.0); + let hashed_point = map_to_curve(message); + let sig = hashed_point.mul_bigint(self.priv_key.0); Signature { g1_point: ark_point_to_g1_point(&sig.into_affine()), } } pub fn sign_hashed_to_curve_message(&self, g1_hashed_msg: &G1Point) -> Signature { - // let sig_point = g1_point_to_g1_projective(g1_hashed_msg); - // let sig = sig_point.mul_bigint(self.priv_key.0); - // Signature { - // g1_point: ark_point_to_g1_point(&sig.into_affine()), - // } - // - let sig_point = g1_point_to_ark_point(g1_hashed_msg); - let sig = sig_point.mul_bigint(self.priv_key.0); + let hashed_point = g1_point_to_ark_point(g1_hashed_msg); + let sig = hashed_point.mul_bigint(self.priv_key.0); Signature { g1_point: ark_point_to_g1_point(&sig.into_affine()), } @@ -561,6 +559,7 @@ impl KeyPair { #[cfg(test)] mod tests { + use super::{ark_point_to_g1_point, ark_point_to_g2_point, PrivateKey, U256}; use crate::crypto::bls::{g1_point_to_g1_projective, G1Point, G2Point, KeyPair}; use ark_bn254::Fq as F; use ark_bn254::{Fr, G1Affine, G1Projective, G2Affine, G2Projective}; @@ -568,6 +567,7 @@ mod tests { use ark_ff::UniformRand; use ark_ff::{BigInt, Field, One, PrimeField, Zero}; use rand::{thread_rng, Rng}; + use std::str::FromStr; #[tokio::test] async fn test_keypair_generation() { @@ -664,4 +664,178 @@ mod tests { let keypair_from_new = keypair_result_normal.unwrap(); assert_eq!(keypair_from_new.priv_key, keypair_from_string.priv_key); } + // + // #[tokio::test] + // async fn test_convert_to_g1_point() { + // let x_point = F::from_str( + // "17709620697113958145616918533531128159269167719799793368595970620022661612059", + // ) + // .unwrap(); + // let y_point = F::from_str( + // "9890439522434691655532127414660267222813910180198976870423582442696952349816", + // ) + // .unwrap(); + // let g1_affine = G1Affine::new(x_point, y_point); + // + // let alloy_g1_point = ark_point_to_g1_point(&g1_affine); + // assert_eq!( + // alloy_g1_point.x, + // U256::from_str( + // "17709620697113958145616918533531128159269167719799793368595970620022661612059" + // ) + // .unwrap() + // ); + // assert_eq!( + // alloy_g1_point.y, + // U256::from_str( + // "9890439522434691655532127414660267222813910180198976870423582442696952349816" + // ) + // .unwrap() + // ); + // } + // + // #[tokio::test] + // async fn test_convert_to_g2_point() { + // let x_point_c0 = F::from_str( + // "6834287759893774453556191528501556195232162436167606874229072410417955767882", + // ) + // .unwrap(); + // let x_point_c1 = F::from_str( + // "15529400123788596166111036611862227541174221446291015207340396747864347375335", + // ) + // .unwrap(); + // + // let y_point_c0 = F::from_str( + // "7616309349481520605447660298084926776417001188005125143383153219707218450524", + // ) + // .unwrap(); + // let y_point_c1 = F::from_str( + // "19775028091101520702581412350510183088819198056772055625089714355379667714558", + // ) + // .unwrap(); + // + // let x_point = ark_bn254::Fq2::new(x_point_c0, x_point_c1); + // let y_point = ark_bn254::Fq2::new(y_point_c0, y_point_c1); + // + // let g2_affine = G2Affine::new(x_point, y_point); + // + // let alloy_g2_point = ark_point_to_g2_point(&g2_affine); + // assert_eq!( + // alloy_g2_point.x[0], + // U256::from_str( + // "15529400123788596166111036611862227541174221446291015207340396747864347375335" + // ) + // .unwrap() + // ); + // assert_eq!( + // alloy_g2_point.x[1], + // U256::from_str( + // "6834287759893774453556191528501556195232162436167606874229072410417955767882" + // ) + // .unwrap() + // ); + // assert_eq!( + // alloy_g2_point.y[0], + // U256::from_str( + // "19775028091101520702581412350510183088819198056772055625089714355379667714558" + // ) + // .unwrap() + // ); + // assert_eq!( + // alloy_g2_point.y[1], + // U256::from_str( + // "7616309349481520605447660298084926776417001188005125143383153219707218450524" + // ) + // .unwrap() + // ); + // } + // + // #[tokio::test] + // async fn test_bls_key_pair() { + // let bls_priv_key = + // "12248929636257230549931416853095037629726205319386239410403476017439825112537"; + // let bls_key_pair = KeyPair::new(PrivateKey::from_str(bls_priv_key).unwrap()).unwrap(); + // + // assert_eq!( + // U256::from_limbs(*bls_key_pair.get_pub_key_g1().x.as_limbs()), + // U256::from_str( + // "277950648056014144722774518899051149098728246263316284984520891067822832300" + // ) + // .unwrap() + // ); + // assert_eq!( + // U256::from_limbs(*bls_key_pair.get_pub_key_g1().y.as_limbs()), + // U256::from_str( + // "16927236637669640540790285431111034664564710839671197540688155537113438534238" + // ) + // .unwrap() + // ); + // } + // + // #[test] + // fn test_map_to_curve() { + // let message: [u8; 32] = [ + // 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, + // ]; + // let g1 = crate::crypto::bn254::map_to_curve(&message); + // + // assert_eq!( + // U256::from_limbs(g1.x.into_bigint().0), + // U256::from_str( + // "455867356320691211509944977504407603390036387149619137164185182714736811811" + // ) + // .unwrap() + // ); + // assert_eq!( + // U256::from_limbs(g1.y.into_bigint().0), + // U256::from_str( + // "9802125641729881429496664198939823213610051907104384160271670136040620850981" + // ) + // .unwrap() + // ); + // } + // + // #[test] + // fn test_sign_message() { + // let message: [u8; 32] = [ + // 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, + // ]; + // let bls_priv_key = + // "12248929636257230549931416853095037629726205319386239410403476017439825112537"; + // let bls_key_pair = KeyPair::new(PrivateKey::from_str(bls_priv_key).unwrap()).unwrap(); + // + // + // let signature = bls_key_pair.sign_message(&message); + // assert_eq!( + // U256::from_limbs(*signature.g1_point.x.as_limbs()), + // U256::from_str( + // "6125087140203962697351933212367898471377426213402772883153680722977416765651" + // ) + // .unwrap() + // ); + // assert_eq!( + // U256::from_limbs(*signature.g1_point.y.as_limbs()), + // U256::from_str( + // "19120302240465611628345095276448175199636936878728446037184749040811421969742" + // ) + // .unwrap() + // ); + // } + // + // #[test] + // fn test_verify_message() { + // let message: [u8; 32] = [ + // 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, + // ]; + // let bls_priv_key = + // "12248929636257230549931416853095037629726205319386239410403476017439825112537"; + // let bls_key_pair = KeyPair::new(PrivateKey::from_str(bls_priv_key).unwrap()).unwrap(); + // + // let signature = bls_key_pair.sign_message(&message); + // + // assert!(signature.verify(&bls_key_pair.get_pub_key_g2(), &message).unwrap()) + // } } diff --git a/utils/src/crypto/bn254.rs b/utils/src/crypto/bn254.rs index c80a4b9..a6f9bab 100644 --- a/utils/src/crypto/bn254.rs +++ b/utils/src/crypto/bn254.rs @@ -5,6 +5,8 @@ use ark_bn254::{Fr, G1Affine, G1Projective, G2Affine, G2Projective}; use ark_ec::AffineRepr; use ark_ff::{BigInteger, BigInteger256}; use ark_ff::{Field, One, PrimeField}; +use std::ops::Neg; +use std::str::FromStr; pub fn map_to_curve(digest: &[u8; 32]) -> G1Projective { let one = F::one(); @@ -28,14 +30,14 @@ pub fn map_to_curve(digest: &[u8; 32]) -> G1Projective { } } -// Helper for converting a PrimeField to its U256 representation for Ethereum compatibility +/// Helper for converting a PrimeField to its U256 representation for Ethereum compatibility pub fn u256_to_point(point: U256) -> F { let le: [u8; 32] = point.to_le_bytes(); F::from_le_bytes_mod_order(&le[..]) } -// Helper for converting a PrimeField to its U256 representation for Ethereum compatibility -// (U256 reads data as big endian) +/// Helper for converting a PrimeField to its U256 representation for Ethereum compatibility +/// (U256 reads data as big endian) pub fn point_to_u256(point: F) -> U256 { let point = point.into_bigint(); let point_bytes = point.to_bytes_be(); @@ -77,6 +79,13 @@ pub fn get_g2_generator() -> Result { Ok(g2_affine) } +pub fn get_g2_generator_neg() -> Result { + // let g2_affine = G2Affine::new(ark_bn254::g2::G2_GENERATOR_X, ark_bn254::g2::G2_GENERATOR_Y); + // let g2_affine = G2Affine::generator(); + let g2_gen = get_g2_generator()?; + Ok(g2_gen.neg()) +} + pub fn mul_by_generator_g1(pvt_key: Fr) -> Result { let g1_gen_result = get_g1_generator(); From abc617b64e5df5a3a71f0dffe721b097e754f97c Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Tue, 20 Aug 2024 13:01:07 -0500 Subject: [PATCH 17/43] Operator metadata --- avs/incredible-squaring-avs/src/operator.rs | 77 +++++++++++-------- test-utils/metadata.json | 7 ++ test-utils/scripts/avs_rebuild_contracts.sh | 2 +- .../src/anvil/testnet/incredible_squaring.rs | 56 +++++++------- 4 files changed, 81 insertions(+), 61 deletions(-) create mode 100644 test-utils/metadata.json diff --git a/avs/incredible-squaring-avs/src/operator.rs b/avs/incredible-squaring-avs/src/operator.rs index 951d69e..074c895 100644 --- a/avs/incredible-squaring-avs/src/operator.rs +++ b/avs/incredible-squaring-avs/src/operator.rs @@ -20,6 +20,7 @@ use eigen_utils::avs_registry::writer::AvsRegistryChainWriterTrait; use eigen_utils::avs_registry::AvsRegistryContractManager; use eigen_utils::crypto::bls::KeyPair; use eigen_utils::crypto::ecdsa::ToAddress; +use eigen_utils::el_contracts::writer::ElWriter; use eigen_utils::el_contracts::ElChainContractManager; use eigen_utils::node_api::NodeApi; use eigen_utils::services::operator_info::OperatorInfoServiceTrait; @@ -278,30 +279,6 @@ impl Operator { .await .unwrap(); - let quorum_nums = Bytes::from([0x00]); - let bls_keypair = KeyPair::new( - eigen_utils::crypto::bls::PrivateKey::from_str( - "12248929636257230549931416853095037629726205319386239410403476017439825112537", - ) - .unwrap(), - ) - .unwrap(); - let register_result = avs_registry_contract_manager - .register_operator( - &ecdsa_signing_key, - &bls_keypair, - quorum_nums, - config.eth_rpc_url.clone(), - ) - .await; - log::info!("Register result: {:?}", register_result); - - let answer = avs_registry_contract_manager - .is_operator_registered(operator_address) - .await - .unwrap(); - log::info!("Is operator registered: {:?}", answer); - let operator_id = avs_registry_contract_manager .get_operator_id(operator_address) .await?; @@ -317,9 +294,9 @@ impl Operator { let operator = Operator { config: config.clone(), node_api, - avs_registry_contract_manager, + avs_registry_contract_manager: avs_registry_contract_manager.clone(), incredible_squaring_contract_manager, - eigenlayer_contract_manager, + eigenlayer_contract_manager: eigenlayer_contract_manager.clone(), bls_keypair, operator_id, operator_addr: operator_address, @@ -328,12 +305,48 @@ impl Operator { aggregator_rpc_client, }; - // if config.register_operator_on_startup { - // operator.register_operator_on_startup( - // operator_ecdsa_private_key, - // config.token_strategy_addr.parse()?, - // ); - // } + // Register Operator with EigenLayer + let register_operator = eigen_utils::types::Operator { + address: operator_address, + earnings_receiver_address: operator_address, + delegation_approver_address: Address::from([0u8; 20]), + staker_opt_out_window_blocks: 50400u32, // About 7 days in blocks on Ethereum + metadata_url: "https://github.com/webb-tools/eigensdk-rs/blob/donovan/eigen/test-utils/metadata.json".to_string(), + }; + let eigenlayer_register_result = eigenlayer_contract_manager + .register_as_operator(register_operator) + .await + .unwrap() + .status(); + log::info!( + "Eigenlayer Registration result: {:?}", + eigenlayer_register_result + ); + + // Register Operator with AVS + let quorum_nums = Bytes::from([0x00]); + let bls_keypair = KeyPair::new( + eigen_utils::crypto::bls::PrivateKey::from_str( + "12248929636257230549931416853095037629726205319386239410403476017439825112537", + ) + .unwrap(), + ) + .unwrap(); + let register_result = avs_registry_contract_manager + .register_operator( + &ecdsa_signing_key, + &bls_keypair, + quorum_nums, + config.eth_rpc_url.clone(), + ) + .await; + log::info!("AVS Registration result: {:?}", register_result); + + let answer = avs_registry_contract_manager + .is_operator_registered(operator_address) + .await + .unwrap(); + log::info!("Is operator registered: {:?}", answer); Ok(operator) } diff --git a/test-utils/metadata.json b/test-utils/metadata.json new file mode 100644 index 0000000..eac70c5 --- /dev/null +++ b/test-utils/metadata.json @@ -0,0 +1,7 @@ +{ + "name": "", + "website": "", + "description": "", + "logo": "", + "twitter": "" +} \ No newline at end of file diff --git a/test-utils/scripts/avs_rebuild_contracts.sh b/test-utils/scripts/avs_rebuild_contracts.sh index 30160fb..93ee1be 100644 --- a/test-utils/scripts/avs_rebuild_contracts.sh +++ b/test-utils/scripts/avs_rebuild_contracts.sh @@ -2,7 +2,7 @@ # Define the directories DIR1="./../avs/incredible-squaring-avs/contracts" -DIR2="./../avs/tangle-avs/contract" +DIR2="./../avs/tangle-avs/contracts" # Function to run forge commands in a directory run_forge_commands() { diff --git a/test-utils/src/anvil/testnet/incredible_squaring.rs b/test-utils/src/anvil/testnet/incredible_squaring.rs index a6f04c8..70ec503 100644 --- a/test-utils/src/anvil/testnet/incredible_squaring.rs +++ b/test-utils/src/anvil/testnet/incredible_squaring.rs @@ -385,6 +385,34 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { .unwrap(); assert!(registry_coordinator_initialization.status()); + let eigen_pod_manager = EigenPodManager::deploy( + provider.clone(), + empty_contract_addr, + empty_contract_addr, + strategy_manager_addr, + from, + delegation_manager_addr, + ) + .await + .unwrap(); + let &eigen_pod_manager_addr = eigen_pod_manager.address(); + + let slasher_addr = dev_account; + let delegation_manager = DelegationManager::deploy( + provider.clone(), + strategy_manager_addr, + slasher_addr, + eigen_pod_manager_addr, + ) + .await + .unwrap(); + let &delegation_manager_addr = delegation_manager.address(); + + let avs_directory = AVSDirectory::deploy(provider.clone(), delegation_manager_addr) + .await + .unwrap(); + let &avs_directory_addr = avs_directory.address(); + let incredible_squaring_service_manager_implementation = IncredibleSquaringServiceManager::deploy( provider.clone(), @@ -453,34 +481,6 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { .unwrap(); assert!(incredible_squaring_task_manager_upgrade.status()); - let eigen_pod_manager = EigenPodManager::deploy( - provider.clone(), - empty_contract_addr, - empty_contract_addr, - strategy_manager_addr, - from, - delegation_manager_addr, - ) - .await - .unwrap(); - let &eigen_pod_manager_addr = eigen_pod_manager.address(); - - let slasher_addr = dev_account; - let delegation_manager = DelegationManager::deploy( - provider.clone(), - strategy_manager_addr, - slasher_addr, - eigen_pod_manager_addr, - ) - .await - .unwrap(); - let &delegation_manager_addr = delegation_manager.address(); - - let avs_directory = AVSDirectory::deploy(provider.clone(), delegation_manager_addr) - .await - .unwrap(); - let &avs_directory_addr = avs_directory.address(); - log::info!("ERC20MOCK ADDRESS: {:?}", erc20_mock_addr); log::info!("ERC20MOCK STRATEGY ADDRESS: {:?}", erc20_mock_strategy_addr); log::info!( From c1cade12aaffed9fededfc8dfbdcdc3d26e0ac58 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Tue, 20 Aug 2024 13:03:32 -0500 Subject: [PATCH 18/43] Metadata format fix --- test-utils/metadata.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test-utils/metadata.json b/test-utils/metadata.json index eac70c5..d52e5ef 100644 --- a/test-utils/metadata.json +++ b/test-utils/metadata.json @@ -1,7 +1,7 @@ { - "name": "", - "website": "", - "description": "", - "logo": "", - "twitter": "" + "name": "TANGLE_OPERATOR_TEST", + "website": "https://www.tangle.tools/", + "description": "COMMONWEALTH ROCKS!", + "logo": "https://blog.webb.tools/content/images/2023/09/webb_profile.png", + "twitter": "https://x.com/webbprotocol?lang=en" } \ No newline at end of file From dc7bffe6e47e84aa598278291e6b9348f17e2d44 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Tue, 20 Aug 2024 15:23:08 -0500 Subject: [PATCH 19/43] Metadata description --- test-utils/metadata.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test-utils/metadata.json b/test-utils/metadata.json index d52e5ef..6e0ed1d 100644 --- a/test-utils/metadata.json +++ b/test-utils/metadata.json @@ -1,7 +1,7 @@ { "name": "TANGLE_OPERATOR_TEST", "website": "https://www.tangle.tools/", - "description": "COMMONWEALTH ROCKS!", + "description": "TANGLE ROCKS!", "logo": "https://blog.webb.tools/content/images/2023/09/webb_profile.png", "twitter": "https://x.com/webbprotocol?lang=en" } \ No newline at end of file From ac65b37341fa6974c06bcaaa51d7e838e18f7351 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Tue, 20 Aug 2024 15:31:49 -0500 Subject: [PATCH 20/43] Foundry workflow fix --- .github/workflows/validate_pr.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index 710a727..e46ef5b 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -23,6 +23,7 @@ jobs: - name: Install Foundry run: | curl -L https://foundry.paradigm.xyz | bash + source /Users/runner/.bashrc foundryup - name: Verify Forge installation From c42e1add204383d3905e564fa6ee916a03ac694a Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Tue, 20 Aug 2024 19:26:20 -0500 Subject: [PATCH 21/43] Contract Debugging for finishing Operator up --- contracts/src/lib.rs | 14 +++++ .../src/anvil/testnet/incredible_squaring.rs | 60 +++++++++++++++++-- utils/src/el_contracts/writer.rs | 1 + 3 files changed, 70 insertions(+), 5 deletions(-) diff --git a/contracts/src/lib.rs b/contracts/src/lib.rs index ab6955e..de04337 100644 --- a/contracts/src/lib.rs +++ b/contracts/src/lib.rs @@ -204,3 +204,17 @@ sol!( EIP1271SignatureUtils, "./out/EIP1271SignatureUtils.sol/EIP1271SignatureUtils.json" ); + +sol!( + #[allow(missing_docs)] + #[sol(rpc)] + IETHPOSDeposit, + "./out/IETHPOSDeposit.sol/IETHPOSDeposit.json" +); + +sol!( + #[allow(missing_docs)] + #[sol(rpc)] + IBeacon, + "./out/IBeacon.sol/IBeacon.json" +); diff --git a/test-utils/src/anvil/testnet/incredible_squaring.rs b/test-utils/src/anvil/testnet/incredible_squaring.rs index 70ec503..29b99d2 100644 --- a/test-utils/src/anvil/testnet/incredible_squaring.rs +++ b/test-utils/src/anvil/testnet/incredible_squaring.rs @@ -3,6 +3,7 @@ use alloy_primitives::{address, Address, Bytes, Keccak256, U256}; use alloy_provider::ProviderBuilder; use alloy_sol_types::{abi, SolValue}; use anvil::spawn; +use eigen_contracts::EigenPod::EigenPodCalls::{eigenPodManager, ethPOS}; use eigen_contracts::{ RegistryCoordinator::{OperatorSetParam, StrategyParams}, *, @@ -220,7 +221,7 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { ); let &bls_apk_registry_addr = bls_apk_registry.address(); - let index_registry = IIndexRegistry::new( + let index_registry = IndexRegistry::new( *TransparentUpgradeableProxy::deploy( provider.clone(), empty_contract_addr, @@ -234,7 +235,7 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { ); let &index_registry_addr = index_registry.address(); - let stake_registry = IStakeRegistry::new( + let stake_registry = StakeRegistry::new( *TransparentUpgradeableProxy::deploy( provider.clone(), empty_contract_addr, @@ -371,7 +372,7 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { pausers[0], pausers[0], pausers[0], - pausers[1], + pauser_registry_addr, U256::from(0), quorum_operator_set_params, quorums_minimum_stake, @@ -385,10 +386,30 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { .unwrap(); assert!(registry_coordinator_initialization.status()); + let eth_pos = IETHPOSDeposit::deploy(provider.clone()).await.unwrap(); + let ð_pos_addr = eth_pos.address(); + + let eigen_pod_beacon = IBeacon::deploy(provider.clone()).await.unwrap(); + let &eigen_pod_beacon_addr = eigen_pod_beacon.address(); + + let strategy_manager = StrategyManager::new( + *TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address(), + provider.clone(), + ); + let &strategy_manager_addr = strategy_manager.address(); + let eigen_pod_manager = EigenPodManager::deploy( provider.clone(), - empty_contract_addr, - empty_contract_addr, + eth_pos_addr, + eigen_pod_beacon_addr, strategy_manager_addr, from, delegation_manager_addr, @@ -408,6 +429,35 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { .unwrap(); let &delegation_manager_addr = delegation_manager.address(); + let strategy_manager_implementation = StrategyManager::deploy( + provider.clone(), + delegation_manager_addr, + eigen_pod_manager_addr, + slasher_addr, + ) + .await + .unwrap(); + let &strategy_manager_implementation_addr = strategy_manager_implementation.address(); + let strategy_manager_upgrade = incredible_squaring_proxy_admin + .upgrade(strategy_manager_addr, strategy_manager_implementation_addr) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(strategy_manager_upgrade.status()); + + let strategy_manager_initialization = strategy_manager + .initialize(pausers[0], pausers[0], pauser_registry_addr, U256::from(0)) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(strategy_manager_initialization.status()); + let avs_directory = AVSDirectory::deploy(provider.clone(), delegation_manager_addr) .await .unwrap(); diff --git a/utils/src/el_contracts/writer.rs b/utils/src/el_contracts/writer.rs index d86f4a9..dd47103 100644 --- a/utils/src/el_contracts/writer.rs +++ b/utils/src/el_contracts/writer.rs @@ -44,6 +44,7 @@ impl ElWriter for ElChainContractManager { DelegationManager::new(self.delegation_manager_addr, self.eth_client_http.clone()); let receipt = delegation_manager .registerAsOperator(op_details, operator.metadata_url) + .from(operator.address) .send() .await? .get_receipt() From 5c54adad6d61613b779a934d8c3644f4e0776035 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 21 Aug 2024 15:15:26 -0500 Subject: [PATCH 22/43] Registration and Aggregation Finalization --- .github/workflows/validate_pr.yml | 1 + .../src/aggregator/mod.rs | 50 +-- avs/incredible-squaring-avs/src/operator.rs | 33 +- avs/tangle-avs/src/operator.rs | 388 +----------------- contracts/src/lib.rs | 2 +- test-utils/keystore/bls | 2 +- test-utils/keystore/ecdsa | 2 +- test-utils/scripts/avs_rebuild_contracts.sh | 4 - test-utils/scripts/build.sh | 6 +- test-utils/scripts/env_setup.sh | 2 +- test-utils/scripts/rebuild_contracts.sh | 4 - .../src/anvil/testnet/incredible_squaring.rs | 170 ++++---- test-utils/src/bin/incredible_squaring.rs | 88 +--- test-utils/src/bin/tangle.rs | 85 +--- test-utils/src/lib.rs | 52 +++ utils/src/avs_registry/writer.rs | 2 +- utils/src/crypto/bls.rs | 2 - utils/src/crypto/bn254.rs | 10 +- utils/src/curve_utils.rs | 311 -------------- 19 files changed, 199 insertions(+), 1015 deletions(-) mode change 100644 => 100755 test-utils/scripts/avs_rebuild_contracts.sh mode change 100644 => 100755 test-utils/scripts/build.sh mode change 100644 => 100755 test-utils/scripts/env_setup.sh mode change 100644 => 100755 test-utils/scripts/rebuild_contracts.sh delete mode 100644 utils/src/curve_utils.rs diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index e46ef5b..d6b2b8d 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -25,6 +25,7 @@ jobs: curl -L https://foundry.paradigm.xyz | bash source /Users/runner/.bashrc foundryup + forge --version - name: Verify Forge installation run: forge --version diff --git a/avs/incredible-squaring-avs/src/aggregator/mod.rs b/avs/incredible-squaring-avs/src/aggregator/mod.rs index f0c5814..516d218 100644 --- a/avs/incredible-squaring-avs/src/aggregator/mod.rs +++ b/avs/incredible-squaring-avs/src/aggregator/mod.rs @@ -39,7 +39,6 @@ use tokio::{ // Constants pub const TASK_CHALLENGE_WINDOW_BLOCK: u64 = 100; pub const BLOCK_TIME_SECONDS: u64 = 12; - pub const QUORUM_THRESHOLD_NUMERATOR: u8 = 100; pub const QUORUM_THRESHOLD_DENOMINATOR: u8 = 100; pub const QUERY_FILTER_FROM_BLOCK: u64 = 1; @@ -264,6 +263,12 @@ where let task_response_digest = get_task_response_digest(&task_response); let task_response_digest_u256 = U256::from_le_bytes(task_response_digest.0); + log::info!( + "Aggregator received task response: \n\tTask Index: {:?}\n\tResult: {:?}", + task_response.referenceTaskIndex, + task_response.numberSquared + ); + { let mut task_responses = self.task_responses.write().await; task_responses @@ -289,45 +294,17 @@ where )))) } - // async fn start_server(&self) -> Result<(), Box> { - // let listener = TcpListener::bind(self.server_ip_port_addr.clone()) - // .await - // .unwrap(); - // log::info!("Starting server at {}", self.server_ip_port_addr); - // loop { - // let (stream, _) = listener.accept().await.unwrap(); - // let io = TokioIo::new(stream); - // let aggregator = Arc::new(self.clone()); - // tokio::task::spawn(async move { - // if let Err(err) = http1::Builder::new() - // .serve_connection( - // io, - // service_fn(move |req| { - // let aggregator = Arc::clone(&aggregator); - // async move { - // match req.uri().path() { - // "/process_signed_task_response" => { - // aggregator.process_signed_task_response(req).await - // } - // _ => Ok(Response::new(Full::new(Bytes::from("404 Not Found")))), - // } - // } - // }), - // ) - // .await - // { - // println!("Error serving connection: {:?}", err); - // } - // }); - // } - // } - pub async fn start_server(self) -> Result<(), Box> { let listener = TcpListener::bind(&self.server_ip_port_addr).await?; loop { + log::info!( + "Aggregator server listening on {}", + self.server_ip_port_addr + ); let (stream, _) = listener.accept().await.unwrap(); let io = TokioIo::new(stream); let this = Arc::new(self.clone()); + log::info!("Aggregator serving connection..."); tokio::task::spawn(async move { if let Err(err) = http1::Builder::new() .serve_connection( @@ -339,7 +316,7 @@ where ) .await { - println!("Error serving connection: {:?}", err); + log::info!("Error serving connection: {:?}", err); } }); } @@ -349,8 +326,9 @@ where &self, req: Request, ) -> Result>, Infallible> { + log::info!("Routing Request: {:?}", req); match (req.method(), req.uri().path()) { - (&Method::POST, "/process_signed_task_response") => { + (&Method::POST, "/Aggregator.ProcessSignedTaskResponse") => { let _ = self.process_signed_task_response(req).await; Ok(Response::builder() .status(StatusCode::OK) diff --git a/avs/incredible-squaring-avs/src/operator.rs b/avs/incredible-squaring-avs/src/operator.rs index 074c895..8a5d93e 100644 --- a/avs/incredible-squaring-avs/src/operator.rs +++ b/avs/incredible-squaring-avs/src/operator.rs @@ -198,12 +198,6 @@ impl Operator { ) .map_err(OperatorError::from)?; - let _chain_id = eth_client_http - .get_chain_id() - .await - .map_err(|e| OperatorError::ChainIdError(e.to_string()))?; - // TODO: Chain id is not used - log::info!("About to read ECDSA key"); let ecdsa_key_password = std::env::var("OPERATOR_ECDSA_KEY_PASSWORD").unwrap_or_else(|_| "".to_string()); @@ -256,7 +250,7 @@ impl Operator { .await .unwrap(); - log::info!("About to build aggregator service"); + log::info!("Building Aggregator Service..."); let aggregator_service = Aggregator::build( &setup_config, operator_info_service, @@ -265,10 +259,10 @@ impl Operator { .await .unwrap(); - log::info!("About to build aggregator RPC client"); + log::info!("Building Aggregator RPC Client..."); let aggregator_rpc_client = AggregatorRpcClient::new(config.server_ip_port_address.clone()); - log::info!("About to build eigenlayer contract manager"); + log::info!("Building Eigenlayer Contract Manager..."); let eigenlayer_contract_manager = ElChainContractManager::build( setup_config.delegate_manager_addr, setup_config.avs_directory_addr, @@ -297,7 +291,7 @@ impl Operator { avs_registry_contract_manager: avs_registry_contract_manager.clone(), incredible_squaring_contract_manager, eigenlayer_contract_manager: eigenlayer_contract_manager.clone(), - bls_keypair, + bls_keypair: bls_keypair.clone(), operator_id, operator_addr: operator_address, aggregator_server_ip_port_addr: config.server_ip_port_address.clone(), @@ -325,13 +319,6 @@ impl Operator { // Register Operator with AVS let quorum_nums = Bytes::from([0x00]); - let bls_keypair = KeyPair::new( - eigen_utils::crypto::bls::PrivateKey::from_str( - "12248929636257230549931416853095037629726205319386239410403476017439825112537", - ) - .unwrap(), - ) - .unwrap(); let register_result = avs_registry_contract_manager .register_operator( &ecdsa_signing_key, @@ -356,7 +343,7 @@ impl Operator { let operator_is_registered = self .avs_registry_contract_manager .is_operator_registered(self.operator_addr) - .await; + .await?; log::info!("Operator registration status: {:?}", operator_is_registered); if self.config.enable_node_api { @@ -364,15 +351,19 @@ impl Operator { return Err(OperatorError::NodeApiError(e.to_string())); } } - let mut sub = self .incredible_squaring_contract_manager .subscribe_to_new_tasks() .await .unwrap(); + let server = self.aggregator_server.clone(); + let aggregator_server = async move { + server.start_server().await.unwrap(); + }; + tokio::spawn(aggregator_server); + log::info!("Subscribed to new tasks: {:?}", sub); - log::info!("Raw Subscription: {:?}", sub.inner()); let value = sub.recv().await.unwrap(); log::info!("Received new task: {:?}", value); @@ -385,7 +376,9 @@ impl Operator { // self.metrics.inc_num_tasks_received(); let log: Log = new_task_created_log.log_decode().unwrap(); let task_response = self.process_new_task_created_log(&log); + log::info!("Generated Task Response: {:?}", task_response); if let Ok(signed_task_response) = self.sign_task_response(&task_response) { + log::info!("Sending signed task response to aggregator: {:?}", signed_task_response); let agg_rpc_client = self.aggregator_rpc_client.clone(); tokio::spawn(async move { agg_rpc_client.send_signed_task_response_to_aggregator(signed_task_response).await; diff --git a/avs/tangle-avs/src/operator.rs b/avs/tangle-avs/src/operator.rs index f2ac8aa..5b11fc7 100644 --- a/avs/tangle-avs/src/operator.rs +++ b/avs/tangle-avs/src/operator.rs @@ -56,6 +56,8 @@ pub enum OperatorError { AvsSdkError(#[from] AvsError), #[error("Wallet error")] WalletError(#[from] alloy_signer_local::LocalSignerError), + #[error("Node API error: {0}")] + NodeApiError(String), } #[allow(dead_code)] @@ -279,387 +281,19 @@ impl Operator { .is_operator_registered(self.operator_addr) .await?; log::info!("Operator registration status: {:?}", operator_is_registered); - // if !operator_is_registered? { - // return Err(OperatorError::OperatorNotRegistered); - // } - // if self.config.enable_node_api { - // self.node_api.start(Default::default()).await?; - // } + if !operator_is_registered { + return Err(OperatorError::OperatorNotRegistered); + } + if self.config.enable_node_api { + if let Err(e) = self.node_api.start().await { + return Err(OperatorError::NodeApiError(e.to_string())); + } + } + log::info!("Starting Tangle Validator..."); gadget_executor::run_tangle_validator().await.unwrap(); Ok(()) } } - -#[cfg(test)] -mod tests { - use super::*; - use alloy_provider::ProviderBuilder; - use alloy_transport_ws::WsConnect; - use eigen_contracts::*; - use eigen_utils::crypto::bls::KeyPair; - use k256::ecdsa::VerifyingKey; - use k256::elliptic_curve::SecretKey; - use rand_core::OsRng; - - static BLS_PASSWORD: &str = "BLS_PASSWORD"; - static ECDSA_PASSWORD: &str = "ECDSA_PASSWORD"; - - // --------- IMPORTS FOR ANVIL TEST --------- - use crate::{ - ITangleValidatorTaskManager, TangleValidatorServiceManager, TangleValidatorTaskManager, - }; - use alloy_primitives::{address, Address, U256}; - use alloy_provider::Provider; - use alloy_rpc_types_eth::BlockId; - use alloy_signer_local::PrivateKeySigner; - use anvil::spawn; - - async fn run_anvil_testnet() { - env_logger::init(); - - let (api, mut handle) = spawn(anvil::NodeConfig::test().with_port(33125)).await; - api.anvil_auto_impersonate_account(true).await.unwrap(); - let provider = handle.http_provider(); - - let accounts = handle.dev_wallets().collect::>(); - let _from = accounts[0].address(); - let _to = accounts[1].address(); - - let _amount = handle - .genesis_balance() - .checked_div(U256::from(2u64)) - .unwrap(); - - let _gas_price = provider.get_gas_price().await.unwrap(); - // let registry_coordinator_addr = Address::from(address!("5fbdb2315678afecb367f032d93f642f64180aa3")); - - let tangle_service_manager_addr = - Address::from(address!("afbdb2315678afecb367f032d93f642f64180aa4")); - let delegation_manager_addr = - Address::from(address!("0165878a594ca255338adfa4d48449f69242eb8f")); - let service_manager_addr = - Address::from(address!("610178da211fef7d417bc0e6fed39f05609ad788")); - let stake_registry_addr = - Address::from(address!("cf7ed3acca5a467e9e704c703e8d87f634fb0fc9")); - let bls_apk_registry_addr = - Address::from(address!("9fe46736679d2d9a65f0992f2272de9f3c7fa6e0")); - let index_registry_addr = - Address::from(address!("e7f1725e7734ce288f8367e1bb143e90bb3f0512")); - let strategy_manager_addr = - Address::from(address!("8fbdb2318678afecb368f032d93f642f64180aa6")); - - let registry_coordinator = RegistryCoordinator::deploy( - provider.clone(), - service_manager_addr, - stake_registry_addr, - bls_apk_registry_addr, - index_registry_addr, - ) - .await - .unwrap(); - let registry_coordinator_addr = registry_coordinator.address(); - println!("Registry Coordinator returned"); - api.mine_one().await; - println!( - "Registry Coordinator deployed at: {:?}", - registry_coordinator_addr - ); - - let mut index_registry = IndexRegistry::deploy(provider.clone()).await.unwrap(); - let index_registry_addr = index_registry.address(); - println!("Index Registry returned"); - api.mine_one().await; - println!("Index Registry deployed at: {:?}", index_registry_addr); - - let mut bls_apk_registry = - BlsApkRegistry::deploy(provider.clone(), *registry_coordinator_addr) - .await - .unwrap(); - let bls_apk_registry_addr = bls_apk_registry.address(); - println!("BLS APK Registry returned"); - api.mine_one().await; - println!("BLS APK Registry deployed at: {:?}", bls_apk_registry_addr); - - let mut stake_registry = StakeRegistry::deploy( - provider.clone(), - *registry_coordinator_addr, - delegation_manager_addr, - ) - .await - .unwrap(); - let stake_registry_addr = stake_registry.address(); - println!("Stake Registry returned"); - api.mine_one().await; - println!("Stake Registry deployed at: {:?}", stake_registry_addr); - - let slasher = ISlasher::deploy(provider.clone()).await.unwrap(); - let slasher_addr = slasher.address(); - println!("Slasher deployed at: {:?}", slasher_addr); - - let eigen_pod_manager = EigenPodManager::deploy( - provider.clone(), - Address::from(address!("73e42f117e8643cc03a4197c6c3ab38d8e5bd281")), - Address::from(address!("83e42f117e8643cc01741973ac7cb3ad8e5bd282")), - strategy_manager_addr, - *slasher_addr, - delegation_manager_addr, - ) - .await - .unwrap(); - let eigen_pod_manager_addr = eigen_pod_manager.address(); - println!( - "Eigen Pod Manager deployed at: {:?}", - eigen_pod_manager_addr - ); - - let mut delegation_manager = DelegationManager::deploy( - provider.clone(), - strategy_manager_addr, - *slasher_addr, - *eigen_pod_manager_addr, - ) - .await - .unwrap(); - let delegation_manager_addr = delegation_manager.address(); - println!("Delegation Manager returned"); - api.mine_one().await; - println!( - "Delegation Manager deployed at: {:?}", - delegation_manager_addr - ); - - let avs_directory = AVSDirectory::deploy(provider.clone(), delegation_manager_addr.clone()) - .await - .unwrap(); - let avs_directory_addr = avs_directory.address(); - println!("AVS Directory returned"); - api.mine_one().await; - println!("AVS Directory deployed at: {:?}", avs_directory_addr); - - let state_retriever = OperatorStateRetriever::deploy(provider.clone()) - .await - .unwrap(); - let state_retriever_addr = state_retriever.address(); - println!("Operator State Retriever returned"); - api.mine_one().await; - println!( - "Operator State Retriever deployed at: {:?}", - state_retriever_addr - ); - - let tangle_task_manager = - TangleValidatorTaskManager::deploy(provider.clone(), *registry_coordinator_addr) - .await - .unwrap(); - let tangle_task_manager_addr = tangle_task_manager.address(); - println!("Tangle Validator Task Manager returned"); - api.mine_one().await; - println!( - "Tangle Validator Task Manager deployed at: {:?}", - tangle_task_manager_addr - ); - - let tangle_operator_manager = ITangleValidatorTaskManager::deploy(provider.clone()) - .await - .unwrap(); - let tangle_operator_manager_addr = tangle_operator_manager.address(); - println!("Tangle Validator Operator Manager returned"); - api.mine_one().await; - println!( - "Tangle Validator Operator Manager deployed at: {:?}", - tangle_operator_manager_addr - ); - - let mut tangle_service_manager = TangleValidatorServiceManager::deploy( - provider.clone(), - *avs_directory_addr, - *registry_coordinator_addr, - *stake_registry_addr, - *tangle_operator_manager_addr, - ) - .await - .unwrap(); - let tangle_service_manager_addr = tangle_service_manager.address(); - println!("Tangle Validator Service Manager returned"); - api.mine_one().await; - println!( - "Tangle Validator Service Manager deployed at: {:?}", - tangle_service_manager_addr - ); - - api.mine_one().await; - - let _block = provider - .get_block(BlockId::latest(), false.into()) - .await - .unwrap() - .unwrap(); - - let http_endpoint = "http://127.0.0.1:33125"; - let ws_endpoint = "ws://127.0.0.1:33125"; - let node_config = NodeConfig { - node_api_ip_port_address: "127.0.0.1:9808".to_string(), - eth_rpc_url: http_endpoint.to_string(), - eth_ws_url: ws_endpoint.to_string(), - bls_private_key_store_path: "./keystore/bls".to_string(), - ecdsa_private_key_store_path: "./keystore/ecdsa".to_string(), - avs_registry_coordinator_address: registry_coordinator_addr.to_string(), - operator_state_retriever_address: state_retriever_addr.to_string(), - eigen_metrics_ip_port_address: "127.0.0.1:9100".to_string(), - tangle_validator_service_manager_address: tangle_service_manager_addr.to_string(), - delegation_manager_address: delegation_manager_addr.to_string(), - avs_directory_address: avs_directory_addr.to_string(), - operator_address: "0x0000000000000000000000000000000000000006".to_string(), - enable_metrics: false, - enable_node_api: false, - }; - - let signer = EigenTangleSigner { - signer: PrivateKeySigner::random(), - }; - - let http_provider = ProviderBuilder::new() - .with_recommended_fillers() - .on_hyper_http(http_endpoint.parse().unwrap()) - .root() - .clone() - .boxed(); - - let ws_provider = ProviderBuilder::new() - .with_recommended_fillers() - .on_ws(WsConnect::new(ws_endpoint)) - .await - .unwrap() - .root() - .clone() - .boxed(); - - let operator = Operator::::new_from_config( - node_config.clone(), - EigenTangleProvider { - provider: http_provider, - }, - EigenTangleProvider { - provider: ws_provider, - }, - signer, - ) - .await - .unwrap(); - - println!( - "OPERATOR STARTING WITH ADDRESS: {:?}", - operator.operator_addr - ); - - operator.start().await.unwrap(); - - let serv = handle.servers.pop().unwrap(); - let res = serv.await.unwrap(); - res.unwrap(); - } - - #[tokio::test] - async fn test_anvil() { - run_anvil_testnet().await; - } - - #[tokio::test] - async fn test_generate_keys() { - // Initialize logging - env_logger::init(); - - // Generate and store BLS key pair - let bls_key_pair = KeyPair::gen_random().unwrap(); - bls_key_pair - .save_to_file("./keystore/bls", BLS_PASSWORD) - .unwrap(); - let bls_keys = KeyPair::read_private_key_from_file("./keystore/bls", BLS_PASSWORD).unwrap(); - assert_eq!(bls_key_pair.priv_key.key, bls_keys.priv_key.key); - assert_eq!(bls_key_pair.pub_key, bls_keys.pub_key); - - // Generate and store ECDSA keys - let signing_key = SigningKey::random(&mut OsRng); - let secret_key = SecretKey::from(signing_key.clone()); - let public_key = secret_key.public_key(); - let verifying_key = VerifyingKey::from(&signing_key); - eigen_utils::crypto::ecdsa::write_key("./keystore/ecdsa", &secret_key, ECDSA_PASSWORD) - .unwrap(); - - let read_ecdsa_secret_key = - eigen_utils::crypto::ecdsa::read_key("./keystore/ecdsa", ECDSA_PASSWORD).unwrap(); - let read_ecdsa_public_key = read_ecdsa_secret_key.public_key(); - let read_ecdsa_signing_key = SigningKey::from(&read_ecdsa_secret_key); - let read_ecdsa_verifying_key = VerifyingKey::from(&read_ecdsa_signing_key); - - // Assertion checks - assert_eq!(secret_key, read_ecdsa_secret_key); - assert_eq!(public_key, read_ecdsa_public_key); - assert_eq!(signing_key, read_ecdsa_signing_key); - assert_eq!(verifying_key, read_ecdsa_verifying_key); - } - - #[tokio::test] - async fn test_run_operator() { - env_logger::init(); - let http_endpoint = "http://127.0.0.1:33125"; - let ws_endpoint = "ws://127.0.0.1:33125"; - let node_config = NodeConfig { - node_api_ip_port_address: "127.0.0.1:9808".to_string(), - eth_rpc_url: http_endpoint.to_string(), - eth_ws_url: ws_endpoint.to_string(), - bls_private_key_store_path: "./keystore/bls".to_string(), - ecdsa_private_key_store_path: "./keystore/ecdsa".to_string(), - avs_registry_coordinator_address: "0x5fbdb2315678afecb367f032d93f642f64180aa3" - .to_string(), - operator_state_retriever_address: "0x0000000000000000000000000000000000000002" - .to_string(), - eigen_metrics_ip_port_address: "127.0.0.1:9100".to_string(), - tangle_validator_service_manager_address: "0x23e42f117e8643cc0174197c6c7cb38d8e5bd286" - .to_string(), - delegation_manager_address: "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512".to_string(), - avs_directory_address: "0x9fe46736679d2d9a65f0992f2272de9f3c7fa6e0".to_string(), - operator_address: "0x0000000000000000000000000000000000000006".to_string(), - enable_metrics: false, - enable_node_api: false, - }; - - let signer = EigenTangleSigner { - signer: PrivateKeySigner::random(), - }; - - let http_provider = ProviderBuilder::new() - .with_recommended_fillers() - .on_hyper_http(http_endpoint.parse().unwrap()) - .root() - .clone() - .boxed(); - - let ws_provider = ProviderBuilder::new() - .with_recommended_fillers() - .on_ws(WsConnect::new(ws_endpoint)) - .await - .unwrap() - .root() - .clone() - .boxed(); - - let operator = Operator::::new_from_config( - node_config.clone(), - EigenTangleProvider { - provider: http_provider, - }, - EigenTangleProvider { - provider: ws_provider, - }, - signer, - ) - .await - .unwrap(); - - operator.start().await.unwrap(); - } -} diff --git a/contracts/src/lib.rs b/contracts/src/lib.rs index de04337..0f36b1d 100644 --- a/contracts/src/lib.rs +++ b/contracts/src/lib.rs @@ -40,7 +40,7 @@ sol!( #[allow(missing_docs)] #[sol(rpc)] EigenStrategy, - "./lib/eigenlayer-middleware/lib/eigenlayer-contracts/out//EigenStrategy.sol/EigenStrategy.json" + "./lib/eigenlayer-middleware/lib/eigenlayer-contracts/out/EigenStrategy.sol/EigenStrategy.json" ); sol!( diff --git a/test-utils/keystore/bls b/test-utils/keystore/bls index efe69c8..6606767 100644 --- a/test-utils/keystore/bls +++ b/test-utils/keystore/bls @@ -1 +1 @@ -{"pub_key":{"x":"0x2ed159b38ebb1317b82c3a816202ff8b39788b7996164384f7b79eb06ccdb330","y":"0x7a559aedbd3b933c7dd94234b805419be6a22065e646d23b4b1fe8e92fcd823"},"crypto":{"encrypted_data":"MiC+DCC00z+Lg4J9HGfzZqOPnghgiqJiXQ2982hWSnBoLwdvR4+U+YzG7SIXXWh/","nonce":"q+YU8mhCLsll8KDk","password_hash":"JHNjcnlwdCRsbj0xNyxyPTgscD0xJHk5bUR4NGFxM0hmYXU4Ti94U3BiOWckZGhJYWpid1JwN3ZidmQvMDR1VTlITDc3cVNNNkd4YWpYcWZLSWVGb0ZxRQ=="}} \ No newline at end of file +{"pub_key":{"x":"0x139812bdcbacc20b7853ff184142dbe01c40d21ab53dc72374daffd69411ef1d","y":"0x11ed9bca0e43a08411f9b8edac71ad81d5672d37f7b11b67338879b3e5ec68da"},"crypto":{"encrypted_data":"s4Id3B28c2ZSwXJ5YomdnseNSZO9c0JBP8aE1QP8rUTvcxfqXpYlK44NkJh9p6dC","nonce":"1mztK/gTsWvLpJ5O","password_hash":"JHNjcnlwdCRsbj0xNyxyPTgscD0xJHBJcHRCcmJCMkRWaG9pbjQzZkJXdEEkTmNCUGJ5emRlS0Nleis1UDF0OExxaUxiR2hickZHOS94WHdJUm5NRnF5QQ=="}} \ No newline at end of file diff --git a/test-utils/keystore/ecdsa b/test-utils/keystore/ecdsa index a6ae8b0..b10020e 100644 --- a/test-utils/keystore/ecdsa +++ b/test-utils/keystore/ecdsa @@ -1 +1 @@ -{"address":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266","crypto":{"Cipher":"aes-128-ctr","CipherText":"1113254d033cc52729222bd5742459a4d054a449aff3def44ae3018fb8dc7748","CipherParams":{"IV":"7e85c58ecd9e5ecb8fc36fdaac3aab96"},"KDF":"scrypt","KDFParams":{"n":17,"r":8,"p":1,"dklen":32,"salt":"f480c3532ddbd9f2c23be95ad94072d3df15284c556d3ba6b0b6fa286ece18e0"},"MAC":"d55830a172e2ac50764a4426c96fe1f9e68ded4470cd234bc0b44a7eea981643"},"id":"99d8665f-eb45-49d0-936d-c69965cb5835","version":"3"} \ No newline at end of file +{"address":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266","crypto":{"Cipher":"aes-128-ctr","CipherText":"a1357357e32567ea7529302a6495d033c73ae5fd48bb5aa0b6b01e19dc7189f2","CipherParams":{"IV":"449a66a5d4b6dc73fbcf39d1bbda5bf2"},"KDF":"scrypt","KDFParams":{"n":17,"r":8,"p":1,"dklen":32,"salt":"c2e6873b8f52dcc8384c9245c849b07f502b9ed4c241ca1bfb44239491754e0e"},"MAC":"747076ed6644f017751cb5fc05228417e7543a725b3d34ade4e17f8051dc6e6e"},"id":"09ddc927-7607-4b4c-9ef3-016173b4bd6d","version":"3"} \ No newline at end of file diff --git a/test-utils/scripts/avs_rebuild_contracts.sh b/test-utils/scripts/avs_rebuild_contracts.sh old mode 100644 new mode 100755 index 93ee1be..9e83a46 --- a/test-utils/scripts/avs_rebuild_contracts.sh +++ b/test-utils/scripts/avs_rebuild_contracts.sh @@ -18,8 +18,4 @@ run_forge_commands() { run_forge_commands "$DIR1" run_forge_commands "$DIR2" -# Run cargo test in the starting directory -#echo "Running cargo test in the current directory" -#cargo test - echo "Rebuilt all AVS Smart Contracts!" \ No newline at end of file diff --git a/test-utils/scripts/build.sh b/test-utils/scripts/build.sh old mode 100644 new mode 100755 index 4ea3fcc..0e66b50 --- a/test-utils/scripts/build.sh +++ b/test-utils/scripts/build.sh @@ -1,10 +1,11 @@ #!/bin/bash # Define the directories +DIR0="./../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts" DIR1="./../contracts/lib/eigenlayer-middleware" DIR2="./../contracts" DIR3="./../avs/incredible-squaring-avs/contracts" -DIR4="./../avs/tangle-avs/contract" +DIR4="./../avs/tangle-avs/contracts" # Function to run forge commands in a directory run_forge_commands() { @@ -15,7 +16,8 @@ run_forge_commands() { cd - || exit } -# Run forge commands in both directories +# Run forge commands in all listed directories +run_forge_commands "$DIR0" run_forge_commands "$DIR1" run_forge_commands "$DIR2" run_forge_commands "$DIR3" diff --git a/test-utils/scripts/env_setup.sh b/test-utils/scripts/env_setup.sh old mode 100644 new mode 100755 index 769cee6..58f3636 --- a/test-utils/scripts/env_setup.sh +++ b/test-utils/scripts/env_setup.sh @@ -11,7 +11,7 @@ if [ $sourced -eq 0 ]; then exit 1 fi -#Export the environment variables +# Export the environment variables export OPERATOR_ECDSA_KEY_PASSWORD="ECDSA_PASSWORD" export OPERATOR_BLS_KEY_PASSWORD="BLS_PASSWORD" diff --git a/test-utils/scripts/rebuild_contracts.sh b/test-utils/scripts/rebuild_contracts.sh old mode 100644 new mode 100755 index 36116e0..d9a4300 --- a/test-utils/scripts/rebuild_contracts.sh +++ b/test-utils/scripts/rebuild_contracts.sh @@ -18,8 +18,4 @@ run_forge_commands() { run_forge_commands "$DIR1" run_forge_commands "$DIR2" -# Run cargo test in the starting directory -#echo "Running cargo test in the current directory" -#cargo test - echo "Rebuilt all Smart Contracts!" \ No newline at end of file diff --git a/test-utils/src/anvil/testnet/incredible_squaring.rs b/test-utils/src/anvil/testnet/incredible_squaring.rs index 29b99d2..60f37e2 100644 --- a/test-utils/src/anvil/testnet/incredible_squaring.rs +++ b/test-utils/src/anvil/testnet/incredible_squaring.rs @@ -3,7 +3,6 @@ use alloy_primitives::{address, Address, Bytes, Keccak256, U256}; use alloy_provider::ProviderBuilder; use alloy_sol_types::{abi, SolValue}; use anvil::spawn; -use eigen_contracts::EigenPod::EigenPodCalls::{eigenPodManager, ethPOS}; use eigen_contracts::{ RegistryCoordinator::{OperatorSetParam, StrategyParams}, *, @@ -58,13 +57,13 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { // Deploy initial contracts that don't depend on others let istrategy_manager = IStrategyManager::deploy(provider.clone()).await.unwrap(); - let &strategy_manager_addr = istrategy_manager.address(); + let &_strategy_manager_addr = istrategy_manager.address(); let idelegation_manager = IDelegationManager::deploy(provider.clone()).await.unwrap(); let &delegation_manager_addr = idelegation_manager.address(); let iavs_directory = IAVSDirectory::deploy(provider.clone()).await.unwrap(); - let &avs_directory_addr = iavs_directory.address(); + let &_avs_directory_addr = iavs_directory.address(); let proxy_admin = ProxyAdmin::deploy_builder(provider.clone()) .from(dev_account) @@ -254,6 +253,83 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { .unwrap(); let &operator_state_retriever_addr = operator_state_retriever.address(); + let eth_pos = IETHPOSDeposit::deploy(provider.clone()).await.unwrap(); + let ð_pos_addr = eth_pos.address(); + + let eigen_pod_beacon = IBeacon::deploy(provider.clone()).await.unwrap(); + let &eigen_pod_beacon_addr = eigen_pod_beacon.address(); + + let strategy_manager = StrategyManager::new( + *TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + incredible_squaring_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address(), + provider.clone(), + ); + let &strategy_manager_addr = strategy_manager.address(); + + let eigen_pod_manager = EigenPodManager::deploy( + provider.clone(), + eth_pos_addr, + eigen_pod_beacon_addr, + strategy_manager_addr, + from, + delegation_manager_addr, + ) + .await + .unwrap(); + let &eigen_pod_manager_addr = eigen_pod_manager.address(); + + let slasher_addr = dev_account; + let delegation_manager = DelegationManager::deploy( + provider.clone(), + strategy_manager_addr, + slasher_addr, + eigen_pod_manager_addr, + ) + .await + .unwrap(); + let &delegation_manager_addr = delegation_manager.address(); + + let strategy_manager_implementation = StrategyManager::deploy( + provider.clone(), + delegation_manager_addr, + eigen_pod_manager_addr, + slasher_addr, + ) + .await + .unwrap(); + let &strategy_manager_implementation_addr = strategy_manager_implementation.address(); + let strategy_manager_upgrade = incredible_squaring_proxy_admin + .upgrade(strategy_manager_addr, strategy_manager_implementation_addr) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(strategy_manager_upgrade.status()); + + let strategy_manager_initialization = strategy_manager + .initialize(pausers[0], pausers[0], pauser_registry_addr, U256::from(0)) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(strategy_manager_initialization.status()); + + let avs_directory = AVSDirectory::deploy(provider.clone(), delegation_manager_addr) + .await + .unwrap(); + let &avs_directory_addr = avs_directory.address(); + //Now, deploy the implementation contracts using the proxy contracts as inputs let stake_registry_implementation = StakeRegistry::deploy( provider.clone(), @@ -386,83 +462,6 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { .unwrap(); assert!(registry_coordinator_initialization.status()); - let eth_pos = IETHPOSDeposit::deploy(provider.clone()).await.unwrap(); - let ð_pos_addr = eth_pos.address(); - - let eigen_pod_beacon = IBeacon::deploy(provider.clone()).await.unwrap(); - let &eigen_pod_beacon_addr = eigen_pod_beacon.address(); - - let strategy_manager = StrategyManager::new( - *TransparentUpgradeableProxy::deploy( - provider.clone(), - empty_contract_addr, - incredible_squaring_proxy_admin_addr, - Bytes::from(""), - ) - .await - .unwrap() - .address(), - provider.clone(), - ); - let &strategy_manager_addr = strategy_manager.address(); - - let eigen_pod_manager = EigenPodManager::deploy( - provider.clone(), - eth_pos_addr, - eigen_pod_beacon_addr, - strategy_manager_addr, - from, - delegation_manager_addr, - ) - .await - .unwrap(); - let &eigen_pod_manager_addr = eigen_pod_manager.address(); - - let slasher_addr = dev_account; - let delegation_manager = DelegationManager::deploy( - provider.clone(), - strategy_manager_addr, - slasher_addr, - eigen_pod_manager_addr, - ) - .await - .unwrap(); - let &delegation_manager_addr = delegation_manager.address(); - - let strategy_manager_implementation = StrategyManager::deploy( - provider.clone(), - delegation_manager_addr, - eigen_pod_manager_addr, - slasher_addr, - ) - .await - .unwrap(); - let &strategy_manager_implementation_addr = strategy_manager_implementation.address(); - let strategy_manager_upgrade = incredible_squaring_proxy_admin - .upgrade(strategy_manager_addr, strategy_manager_implementation_addr) - .send() - .await - .unwrap() - .get_receipt() - .await - .unwrap(); - assert!(strategy_manager_upgrade.status()); - - let strategy_manager_initialization = strategy_manager - .initialize(pausers[0], pausers[0], pauser_registry_addr, U256::from(0)) - .send() - .await - .unwrap() - .get_receipt() - .await - .unwrap(); - assert!(strategy_manager_initialization.status()); - - let avs_directory = AVSDirectory::deploy(provider.clone(), delegation_manager_addr) - .await - .unwrap(); - let &avs_directory_addr = avs_directory.address(); - let incredible_squaring_service_manager_implementation = IncredibleSquaringServiceManager::deploy( provider.clone(), @@ -563,8 +562,7 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { ); log::info!("DELEGATION MANAGER ADDRESS: {:?}", delegation_manager_addr); - let spawner_task_manager_address = incredible_squaring_task_manager_addr.clone(); - // let spawner_provider = provider.clone(); + let spawner_task_manager_address = incredible_squaring_task_manager_addr; let spawner_provider = provider.clone(); let task_spawner = async move { let manager = IncredibleSquaringTaskManager::new( @@ -573,7 +571,7 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { ); loop { api.mine_one().await; - log::info!("About to create new task"); + log::info!("Task Spawner: Submitting a new task..."); tokio::time::sleep(std::time::Duration::from_millis(5000)).await; let result = manager .createNewTask(U256::from(2), 100u32, Bytes::from(vec![0])) @@ -585,11 +583,7 @@ pub async fn run_incredible_squaring_testnet() -> ContractAddresses { .await .unwrap(); api.mine_one().await; - log::info!("Created new task: {:?}", result); - // let latest_task = manager.latestTaskNum().call().await.unwrap()._0; - // log::info!("Latest task: {:?}", latest_task); - // let task_hash = manager.allTaskHashes(latest_task).call().await.unwrap()._0; - // log::info!("Task info: {:?}", task_hash); + log::info!("Task Spawner: New task created: {:?}", result); } }; tokio::spawn(task_spawner); diff --git a/test-utils/src/bin/incredible_squaring.rs b/test-utils/src/bin/incredible_squaring.rs index daf6761..252b55c 100644 --- a/test-utils/src/bin/incredible_squaring.rs +++ b/test-utils/src/bin/incredible_squaring.rs @@ -3,9 +3,6 @@ use alloy_provider::Provider; use alloy_provider::ProviderBuilder; use alloy_signer_local::PrivateKeySigner; use alloy_transport_ws::WsConnect; -use ethers::prelude::contract; -use incredible_squaring_avs::aggregator::Aggregator; -use incredible_squaring_avs::avs::SetupConfig; use incredible_squaring_avs::operator::*; use k256::ecdsa::SigningKey; use k256::elliptic_curve::SecretKey; @@ -105,95 +102,26 @@ async fn run_full_incredible_squaring_test() { #[cfg(test)] mod tests { use super::*; - use eigen_utils::crypto::bls::KeyPair; - use k256::ecdsa::VerifyingKey; - use k256::elliptic_curve::SecretKey; use std::env; - #[tokio::test] - async fn test_full_incredible_squaring() { + fn env_init() { if env::var("RUST_LOG").is_err() { env::set_var("RUST_LOG", "info"); } env::set_var("BLS_PASSWORD", "BLS_PASSWORD"); env::set_var("ECDSA_PASSWORD", "ECDSA_PASSWORD"); - env_logger::init(); - run_full_incredible_squaring_test().await; + let _ = env_logger::try_init(); } #[tokio::test] - async fn test_incredible_squaring_deployment() { - if env::var("RUST_LOG").is_err() { - env::set_var("RUST_LOG", "info"); - } - env::set_var("BLS_PASSWORD", "BLS_PASSWORD"); - env::set_var("ECDSA_PASSWORD", "ECDSA_PASSWORD"); - let _ = env_logger::try_init(); - run_incredible_squaring_testnet().await; + async fn test_full_incredible_squaring() { + env_init(); + run_full_incredible_squaring_test().await; } - // TODO: Get test for loading from state working - // #[tokio::test] - // async fn test_start_chain_from_state() { - // env_logger::init(); - // - // let chain = crate::anvil::local_chain::LocalEvmChain::new_with_chain_state( - // 31337, - // String::from("eigen-testnet"), - // Path::new("../../eigen-utils/eigen-gadget-anvil-state.json"), - // Some(8545u16), - // ); - // let chain_id = chain.chain_id(); - // let chain_name = chain.name(); - // println!("chain_id: {:?}", chain_id); - // println!("chain_name: {:?}", chain_name); - // let addresses = chain.addresses(); - // println!("addresses: {:?}", addresses); - // tokio::time::sleep(Duration::from_secs(5)).await; - // println!("Now shutting down..."); - // chain.shutdown(); - // } - #[tokio::test] - async fn test_generate_keys() { - env_logger::init(); - - // ---------------- BLS ---------------- - let bls_pair = KeyPair::gen_random().unwrap(); - bls_pair - .save_to_file("./keystore/bls", BLS_PASSWORD) - .unwrap(); - let bls_keys = KeyPair::read_private_key_from_file("./keystore/bls", BLS_PASSWORD).unwrap(); - assert_eq!(bls_pair.priv_key, bls_keys.priv_key); - assert_eq!(bls_pair.pub_key, bls_keys.pub_key); - - //---------------- ECDSA ---------------- - // First Account - let hex_key = - hex::decode("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80") - .unwrap(); - - // Second Account - // let hex_key = - // hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d") - // .unwrap(); - - let secret_key = SecretKey::from_slice(&hex_key).unwrap(); - let signing_key = SigningKey::from(secret_key.clone()); - let public_key = secret_key.public_key(); - let verifying_key = VerifyingKey::from(public_key); - eigen_utils::crypto::ecdsa::write_key("./keystore/ecdsa", &secret_key, ECDSA_PASSWORD) - .unwrap(); - - let read_ecdsa_secret_key = - eigen_utils::crypto::ecdsa::read_key("./keystore/ecdsa", ECDSA_PASSWORD).unwrap(); - let read_ecdsa_public_key = read_ecdsa_secret_key.public_key(); - let read_ecdsa_signing_key = SigningKey::from(&read_ecdsa_secret_key); - let read_ecdsa_verifying_key = VerifyingKey::from(&read_ecdsa_signing_key); - - assert_eq!(secret_key, read_ecdsa_secret_key); - assert_eq!(public_key, read_ecdsa_public_key); - assert_eq!(signing_key, read_ecdsa_signing_key); - assert_eq!(verifying_key, read_ecdsa_verifying_key); + async fn test_incredible_squaring_deployment() { + env_init(); + let _ = run_incredible_squaring_testnet().await; } } diff --git a/test-utils/src/bin/tangle.rs b/test-utils/src/bin/tangle.rs index 774d4b8..97a5e85 100644 --- a/test-utils/src/bin/tangle.rs +++ b/test-utils/src/bin/tangle.rs @@ -96,95 +96,26 @@ async fn run_full_tangle_test() { #[cfg(test)] mod tests { use super::*; - use eigen_utils::crypto::bls::KeyPair; - use k256::ecdsa::VerifyingKey; - use k256::elliptic_curve::SecretKey; use std::env; - #[tokio::test] - async fn test_full_tangle() { + fn env_init() { if env::var("RUST_LOG").is_err() { env::set_var("RUST_LOG", "info"); } env::set_var("BLS_PASSWORD", "BLS_PASSWORD"); env::set_var("ECDSA_PASSWORD", "ECDSA_PASSWORD"); - env_logger::init(); - run_full_tangle_test().await; + let _ = env_logger::try_init(); } #[tokio::test] - async fn test_tangle_deployment() { - if env::var("RUST_LOG").is_err() { - env::set_var("RUST_LOG", "info"); - } - env::set_var("BLS_PASSWORD", "BLS_PASSWORD"); - env::set_var("ECDSA_PASSWORD", "ECDSA_PASSWORD"); - let _ = env_logger::try_init(); - let _ = run_tangle_testnet().await; + async fn test_full_tangle() { + env_init(); + run_full_tangle_test().await; } - // TODO: Get test for loading from state working - // #[tokio::test] - // async fn test_start_chain_from_state() { - // env_logger::init(); - // - // let chain = crate::anvil::local_chain::LocalEvmChain::new_with_chain_state( - // 31337, - // String::from("eigen-testnet"), - // Path::new("../../eigen-utils/eigen-gadget-anvil-state.json"), - // Some(8545u16), - // ); - // let chain_id = chain.chain_id(); - // let chain_name = chain.name(); - // println!("chain_id: {:?}", chain_id); - // println!("chain_name: {:?}", chain_name); - // let addresses = chain.addresses(); - // println!("addresses: {:?}", addresses); - // tokio::time::sleep(Duration::from_secs(5)).await; - // println!("Now shutting down..."); - // chain.shutdown(); - // } - #[tokio::test] - async fn test_generate_keys() { - env_logger::init(); - - // ---------------- BLS ---------------- - let bls_pair = KeyPair::gen_random().unwrap(); - bls_pair - .save_to_file("./keystore/bls", BLS_PASSWORD) - .unwrap(); - let bls_keys = KeyPair::read_private_key_from_file("./keystore/bls", BLS_PASSWORD).unwrap(); - assert_eq!(bls_pair.priv_key, bls_keys.priv_key); - assert_eq!(bls_pair.pub_key, bls_keys.pub_key); - - //---------------- ECDSA ---------------- - // First Account - let hex_key = - hex::decode("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80") - .unwrap(); - - // Second Account - // let hex_key = - // hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d") - // .unwrap(); - - let secret_key = SecretKey::from_slice(&hex_key).unwrap(); - let signing_key = SigningKey::from(secret_key.clone()); - let public_key = secret_key.public_key(); - let verifying_key = VerifyingKey::from(public_key); - eigen_utils::crypto::ecdsa::write_key("./keystore/ecdsa", &secret_key, ECDSA_PASSWORD) - .unwrap(); - - let read_ecdsa_secret_key = - eigen_utils::crypto::ecdsa::read_key("./keystore/ecdsa", ECDSA_PASSWORD).unwrap(); - let read_ecdsa_public_key = read_ecdsa_secret_key.public_key(); - let read_ecdsa_signing_key = SigningKey::from(&read_ecdsa_secret_key); - let read_ecdsa_verifying_key = VerifyingKey::from(&read_ecdsa_signing_key); - - assert_eq!(secret_key, read_ecdsa_secret_key); - assert_eq!(public_key, read_ecdsa_public_key); - assert_eq!(signing_key, read_ecdsa_signing_key); - assert_eq!(verifying_key, read_ecdsa_verifying_key); + async fn test_tangle_deployment() { + env_init(); + let _ = run_tangle_testnet().await; } } diff --git a/test-utils/src/lib.rs b/test-utils/src/lib.rs index ff59a3b..288d376 100644 --- a/test-utils/src/lib.rs +++ b/test-utils/src/lib.rs @@ -1 +1,53 @@ pub mod anvil; + +#[cfg(test)] +mod tests { + use crate::anvil::testnet::incredible_squaring::*; + use eigen_utils::crypto::bls::KeyPair; + use k256::ecdsa::SigningKey; + use k256::ecdsa::VerifyingKey; + use k256::elliptic_curve::SecretKey; + + #[tokio::test] + async fn test_generate_keys() { + env_logger::init(); + + // ---------------- BLS ---------------- + let bls_pair = KeyPair::gen_random().unwrap(); + bls_pair + .save_to_file("./keystore/bls", BLS_PASSWORD) + .unwrap(); + let bls_keys = KeyPair::read_private_key_from_file("./keystore/bls", BLS_PASSWORD).unwrap(); + assert_eq!(bls_pair.priv_key, bls_keys.priv_key); + assert_eq!(bls_pair.pub_key, bls_keys.pub_key); + + //---------------- ECDSA ---------------- + // First Account + let hex_key = + hex::decode("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80") + .unwrap(); + + // Second Account + // let hex_key = + // hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d") + // .unwrap(); + + let secret_key = SecretKey::from_slice(&hex_key).unwrap(); + let signing_key = SigningKey::from(secret_key.clone()); + let public_key = secret_key.public_key(); + let verifying_key = VerifyingKey::from(public_key); + eigen_utils::crypto::ecdsa::write_key("./keystore/ecdsa", &secret_key, ECDSA_PASSWORD) + .unwrap(); + + let read_ecdsa_secret_key = + eigen_utils::crypto::ecdsa::read_key("./keystore/ecdsa", ECDSA_PASSWORD).unwrap(); + let read_ecdsa_public_key = read_ecdsa_secret_key.public_key(); + let read_ecdsa_signing_key = SigningKey::from(&read_ecdsa_secret_key); + let read_ecdsa_verifying_key = VerifyingKey::from(&read_ecdsa_signing_key); + + assert_eq!(secret_key, read_ecdsa_secret_key); + assert_eq!(public_key, read_ecdsa_public_key); + assert_eq!(signing_key, read_ecdsa_signing_key); + assert_eq!(verifying_key, read_ecdsa_verifying_key); + } +} diff --git a/utils/src/avs_registry/writer.rs b/utils/src/avs_registry/writer.rs index dde34b2..4acbe3d 100644 --- a/utils/src/avs_registry/writer.rs +++ b/utils/src/avs_registry/writer.rs @@ -161,7 +161,7 @@ impl AvsRegistryChainWriterTrait for AvsRegistryContractManager { Ok(receipt) } - /// TODO: This function is considered to be deprecated in original Go implementation + /// NOTICE: This function is considered to be deprecated in original Go implementation async fn register_operator_in_quorum_with_avs_registry_coordinator( &self, operator_ecdsa_private_key: &ecdsa::SigningKey, diff --git a/utils/src/crypto/bls.rs b/utils/src/crypto/bls.rs index 9b3ce51..ccb30ee 100644 --- a/utils/src/crypto/bls.rs +++ b/utils/src/crypto/bls.rs @@ -559,7 +559,6 @@ impl KeyPair { #[cfg(test)] mod tests { - use super::{ark_point_to_g1_point, ark_point_to_g2_point, PrivateKey, U256}; use crate::crypto::bls::{g1_point_to_g1_projective, G1Point, G2Point, KeyPair}; use ark_bn254::Fq as F; use ark_bn254::{Fr, G1Affine, G1Projective, G2Affine, G2Projective}; @@ -567,7 +566,6 @@ mod tests { use ark_ff::UniformRand; use ark_ff::{BigInt, Field, One, PrimeField, Zero}; use rand::{thread_rng, Rng}; - use std::str::FromStr; #[tokio::test] async fn test_keypair_generation() { diff --git a/utils/src/crypto/bn254.rs b/utils/src/crypto/bn254.rs index a6f9bab..40b0ab2 100644 --- a/utils/src/crypto/bn254.rs +++ b/utils/src/crypto/bn254.rs @@ -6,7 +6,6 @@ use ark_ec::AffineRepr; use ark_ff::{BigInteger, BigInteger256}; use ark_ff::{Field, One, PrimeField}; use std::ops::Neg; -use std::str::FromStr; pub fn map_to_curve(digest: &[u8; 32]) -> G1Projective { let one = F::one(); @@ -69,19 +68,15 @@ pub fn biginteger256_to_u256(bi: BigInteger256) -> U256 { pub fn get_g1_generator() -> Result { let g1_affine = G1Affine::new(ark_bn254::g1::G1_GENERATOR_X, ark_bn254::g1::G1_GENERATOR_Y); - // let g1_affine = G1Affine::generator(); Ok(g1_affine) } pub fn get_g2_generator() -> Result { let g2_affine = G2Affine::new(ark_bn254::g2::G2_GENERATOR_X, ark_bn254::g2::G2_GENERATOR_Y); - // let g2_affine = G2Affine::generator(); Ok(g2_affine) } pub fn get_g2_generator_neg() -> Result { - // let g2_affine = G2Affine::new(ark_bn254::g2::G2_GENERATOR_X, ark_bn254::g2::G2_GENERATOR_Y); - // let g2_affine = G2Affine::generator(); let g2_gen = get_g2_generator()?; Ok(g2_gen.neg()) } @@ -104,10 +99,7 @@ pub fn mul_by_generator_g2(pvt_key: Fr) -> Result { let g2_gen_result = get_g2_generator(); match g2_gen_result { - Ok(g2_gen) => { - // let s: G2Projective = g2_gen.into(); - Ok(g2_gen.mul_bigint(pvt_key.0)) - } + Ok(g2_gen) => Ok(g2_gen.mul_bigint(pvt_key.0)), Err(_) => Err(AvsError::KeyError( "Invalid G2 Generator Result".to_string(), )), diff --git a/utils/src/curve_utils.rs b/utils/src/curve_utils.rs deleted file mode 100644 index 2efac30..0000000 --- a/utils/src/curve_utils.rs +++ /dev/null @@ -1,311 +0,0 @@ -// use crate::types::AvsError; -// use alloy_primitives::U256; -// use ark_bn254::{Bn254, Fq, Fq2, Fr, G1Affine, G1Projective, G2Projective}; -// use ark_ec::{pairing::Pairing, CurveGroup}; -// use ark_ff::{BigInteger256, Field, One, PrimeField}; -// use hex::FromHex; -// use std::fmt::Write; -// use std::ops::{Add, Mul}; -// pub fn new_fp_element(x: BigInteger256) -> Fq { -// Fq::from(x) -// } -// -// fn new_fp2_element(a: BigInteger256, b: BigInteger256) -> Fq2 { -// Fq2::new(Fq::from(a), Fq::from(b)) -// } -// -// type PrivateKey = Fr; -// -// #[derive(Debug, Clone)] -// pub struct Signature { -// g1_point: G1Point, -// } -// -// impl Signature { -// pub fn new_zero_signature() -> Self { -// return Signature { -// g1_point: G1Point::new_zero_g1_point(), -// }; -// } -// -// pub fn get_g1_point(&self) -> G1Point { -// self.g1_point.clone() -// } -// -// pub fn sig(&self) -> G1Projective { -// self.g1_point.point -// } -// -// /// Verify BLS signature using BN254 -// /// TODO : test this . 99% this is wrong -// pub fn verify_signature(&self, pubkey: G2Projective, message: &[u8; 32]) -> bool { -// let msg_hash = hash_to_g1(message); -// let g1_affine = self.g1_point.point.into_affine(); -// -// let g2_affine = pubkey.into_affine(); -// -// let generator = get_g2_generator().unwrap(); -// let pairing_left = Bn254::pairing(g1_affine, generator); -// -// let pairing_right = Bn254::pairing(msg_hash, g2_affine); -// -// pairing_left == pairing_right -// } -// } -// -// fn hash_to_g1(digest: &[u8; 32]) -> G1Affine { -// let one = Fq::one(); -// let three = Fq::from(3u64); -// let mut x = Fq::from_le_bytes_mod_order(digest); -// -// loop { -// let x_cubed = x.square() * x; -// let y_squared = x_cubed + three; -// -// if let Some(y) = y_squared.sqrt() { -// let point = G1Projective::new(x, y, Fq::one()); -// return point.into_affine(); -// } else { -// x += &one; -// } -// } -// } -// pub struct KeyPair { -// priv_key: PrivateKey, -// pub_key: G1Projective, -// } -// -// impl KeyPair { -// pub fn new(key: PrivateKey) -> Result { -// let priv_key_projective_cconfig_result = mul_by_generator_g1(key); -// -// match priv_key_projective_cconfig_result { -// Ok(priv_key_projective_cconfig) => { -// return Ok(Self { -// priv_key: key, -// pub_key: priv_key_projective_cconfig, -// }); -// } -// Err(_) => return Err(BlsError::MulByG1Projective), -// } -// } -// -// pub fn from_string(s: String) -> Result { -// let bigint_key = hex_string_to_biginteger256(&s); -// let key = Fr::from(bigint_key); -// KeyPair::new(key) -// } -// -// pub fn sign_hashes_to_curve_message(&self, g1_hashes_msg: G1Projective) -> Signature { -// let sig = g1_hashes_msg.mul(self.priv_key); -// -// Signature { -// g1_point: G1Point { point: sig }, -// } -// } -// -// pub fn get_pub_key_g1(&self) -> G1Projective { -// self.pub_key -// } -// -// pub fn get_pub_key_g2(&self) -> Result { -// let mul_result = mul_by_generator_g2(self.priv_key); -// -// match mul_result { -// Ok(mul) => Ok(mul), -// Err(_) => return Err(BlsError::MulByG2Projective), -// } -// } -// } -// -// pub fn bigint_to_hex(bigint: &BigInteger256) -> String { -// let mut hex_string = String::new(); -// for part in bigint.0.iter().rev() { -// write!(&mut hex_string, "{:016x}", part).unwrap(); -// } -// hex_string -// } -// -// pub fn hex_string_to_biginteger256(hex_str: &str) -> BigInteger256 { -// let bytes = Vec::from_hex(hex_str).unwrap(); -// -// assert!(bytes.len() <= 32, "Byte length exceeds 32 bytes"); -// -// let mut padded_bytes = vec![0u8; 32]; -// let start = 32 - bytes.len(); -// padded_bytes[start..].copy_from_slice(&bytes); -// -// let mut limbs = [0u64; 4]; -// for (i, chunk) in padded_bytes.chunks(8).rev().enumerate() { -// let mut array = [0u8; 8]; -// let len = chunk.len().min(8); -// array[..len].copy_from_slice(&chunk[..len]); // Copy the bytes into the fixed-size array -// limbs[i] = u64::from_be_bytes(array); -// } -// -// BigInteger256::new(limbs) -// } -// -// #[derive(Debug, Clone)] -// pub struct G1Point { -// pub point: G1Projective, -// } -// -// #[derive(Debug, Clone)] -// pub struct G2Point { -// pub point: G2Projective, -// } -// -// impl G2Point { -// // Function to create a new G2Point from x and y coordinates, where each coordinate is a pair of BigIntegers -// pub fn new(x: (BigInteger256, BigInteger256), y: (BigInteger256, BigInteger256)) -> Self { -// // Convert x and y to Fq2 elements -// let x_elem = new_fp2_element(x.1, x.0); -// let y_elem = new_fp2_element(y.1, y.0); -// -// // Create a new G2 point in projective coordinates -// let point = G2Projective::new(x_elem, y_elem, Fq2::one()); // Z coordinate is set to 1 -// -// G2Point { point } -// } -// -// pub fn add(&mut self, p2: G2Point) -> G2Point { -// let added_point = self.point.add(p2.point); -// G2Point { point: added_point } -// } -// -// pub const fn zero() -> Self { -// G2Point::new( -// ( -// u256_to_bigint256(U256::from(0)), -// u256_to_bigint256(U256::from(0)), -// ), -// ( -// u256_to_bigint256(U256::from(0)), -// u256_to_bigint256(U256::from(0)), -// ), -// ) -// } -// } -// -// impl G1Point { -// // Function to create a new G1Point from x and y coordinates -// pub fn new(x: BigInteger256, y: BigInteger256) -> Self { -// // Convert x and y to field elements -// let x_elem = new_fp_element(x); -// let y_elem = new_fp_element(y); -// -// // Create a new G1 point in projective coordinates -// let point = G1Projective::new(x_elem, y_elem, Fq::one()); // Z coordinate is set to 1 -// -// G1Point { point } -// } -// -// pub fn add(&mut self, p2: G1Point) -> G1Point { -// let added_point = self.point.add(p2.point); -// G1Point { point: added_point } -// } -// -// pub const fn zero() -> Self { -// G1Point::new( -// u256_to_bigint256(U256::from(0)), -// u256_to_bigint256(U256::from(0)), -// ) -// } -// } -// -// #[cfg(test)] -// mod tests { -// use super::*; -// use ark_ff::UniformRand; -// use ark_ff::{BigInt, Zero}; -// use rand::{thread_rng, RngCore}; -// #[tokio::test] -// async fn test_keypair_generation() { -// let mut rng = thread_rng(); -// let private_key = Fr::rand(&mut rng); -// let keypair = KeyPair::new(private_key).unwrap(); -// let pub_key = keypair.get_pub_key_g1(); -// -// // Check that the public key is not zero -// assert_ne!(pub_key, G1Projective::zero()); -// } -// -// #[tokio::test] -// async fn test_signature_generation() { -// let mut rng = thread_rng(); -// let private_key = Fr::rand(&mut rng); -// let keypair = KeyPair::new(private_key).unwrap(); -// -// let message = [0u8; 32]; -// let msg_hash = hash_to_g1(&message); -// -// let signature = keypair.sign_hashes_to_curve_message(msg_hash.into()); -// -// // Check that the signature is not zero -// assert_ne!(signature.sig(), G1Projective::zero()); -// } -// -// #[tokio::test] -// async fn test_signature_verification() { -// let mut rng = thread_rng(); -// let private_key = Fr::rand(&mut rng); -// let keypair = KeyPair::new(private_key).unwrap(); -// let pub_key_g2 = keypair.get_pub_key_g2().unwrap(); -// // generate a random message -// let mut message = [0u8; 32]; -// rng.fill_bytes(&mut message); -// -// let msg_hash = hash_to_g1(&message); -// -// let signature = keypair.sign_hashes_to_curve_message(msg_hash.into()); -// -// // Check that the signature is not zero -// assert_ne!(signature.sig(), G1Projective::zero()); -// let mut wrong_message = [0u8; 32]; -// rng.fill_bytes(&mut wrong_message); -// // Check that the signature verifies -// assert!(signature.verify_signature(pub_key_g2, &message)); -// assert!(!signature.verify_signature(pub_key_g2, &wrong_message)) -// } -// -// #[tokio::test] -// async fn test_signature_verification_invalid() { -// let mut rng = thread_rng(); -// let private_key = Fr::rand(&mut rng); -// let keypair = KeyPair::new(private_key).unwrap(); -// -// let mut message = [0u8; 32]; -// rng.fill_bytes(&mut message); -// -// let msg_hash = hash_to_g1(&message); -// -// let signature = keypair.sign_hashes_to_curve_message(msg_hash.into()); -// -// // Check that the signature is not zero -// assert_ne!(signature.sig(), G1Projective::zero()); -// -// // Check that the signature does not verify with a different public key -// let different_pub_key = G2Projective::rand(&mut rng); -// assert!(!signature.verify_signature(different_pub_key, &message)); -// } -// -// #[tokio::test] -// async fn test_keypair_from_string() { -// let bigint = BigInt([ -// 12844100841192127628, -// 7068359412155877604, -// 5417847382009744817, -// 1586467664616413849, -// ]); -// let hex_string = bigint_to_hex(&bigint); -// let converted_bigint = hex_string_to_biginteger256(&hex_string); -// assert_eq!(bigint, converted_bigint); -// let keypair_result_from_string = KeyPair::from_string(hex_string); -// let keypair_result_normal = KeyPair::new(Fr::from(bigint)); -// -// let keypair_from_string = keypair_result_from_string.unwrap(); -// let keypair_from_new = keypair_result_normal.unwrap(); -// assert_eq!(keypair_from_new.priv_key, keypair_from_string.priv_key); -// } -// } From 5ff9d1569f8166083b97520d5f9fbf0f7062ab8d Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 21 Aug 2024 15:21:09 -0500 Subject: [PATCH 23/43] Workflow Fix --- .github/workflows/validate_pr.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index d6b2b8d..7555c76 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -25,7 +25,9 @@ jobs: curl -L https://foundry.paradigm.xyz | bash source /Users/runner/.bashrc foundryup - forge --version + + - name: Add Foundry to PATH + run: echo "${HOME}/.foundry/bin" >> $GITHUB_PATH - name: Verify Forge installation run: forge --version From 31a99e849f1a105ba26b734989007ce43ff0b29a Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 21 Aug 2024 15:28:48 -0500 Subject: [PATCH 24/43] Debugging --- .github/workflows/validate_pr.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index 7555c76..81dbfd8 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -20,6 +20,9 @@ jobs: name: Forge runs-on: macos-latest steps: + - name: Git setup + run: git config --global --add safe.directory "$GITHUB_WORKSPACE" + - name: Install Foundry run: | curl -L https://foundry.paradigm.xyz | bash From 04e36ac60c31773fc9f850c57bd71cfcc1a6d4f9 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 21 Aug 2024 15:31:52 -0500 Subject: [PATCH 25/43] Debugging --- .github/workflows/validate_pr.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index 81dbfd8..4f02f74 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -21,7 +21,10 @@ jobs: runs-on: macos-latest steps: - name: Git setup - run: git config --global --add safe.directory "$GITHUB_WORKSPACE" + run: | + git config --global --add safe.directory "$GITHUB_WORKSPACE" + which git + whereis git - name: Install Foundry run: | From 1d6f1a0560bdadfbe5e5245ec850ec66a9292194 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 21 Aug 2024 15:36:36 -0500 Subject: [PATCH 26/43] Debugging Workflow --- .github/workflows/validate_pr.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index 4f02f74..7b36010 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -20,11 +20,12 @@ jobs: name: Forge runs-on: macos-latest steps: - - name: Git setup + - name: Check Git Setup run: | git config --global --add safe.directory "$GITHUB_WORKSPACE" which git - whereis git + git --version + ls -a - name: Install Foundry run: | From 059e39f405b36302a95fbf26cc7e99357241e586 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 21 Aug 2024 15:53:22 -0500 Subject: [PATCH 27/43] Fix GH workflow --- .github/workflows/validate_pr.yml | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index 7b36010..26080e7 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -20,12 +20,8 @@ jobs: name: Forge runs-on: macos-latest steps: - - name: Check Git Setup - run: | - git config --global --add safe.directory "$GITHUB_WORKSPACE" - which git - git --version - ls -a + - name: Checkout Code + uses: actions/checkout@v2 - name: Install Foundry run: | @@ -40,8 +36,7 @@ jobs: run: forge --version - name: Set up Foundry cache - run: | - forge install + run: forge install - name: Run build script run: | From 2b3a2412f6f44da1d101351ceb3e1f38cf816023 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 21 Aug 2024 15:55:02 -0500 Subject: [PATCH 28/43] Debugging Forge steps --- .github/workflows/validate_pr.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index 26080e7..802187b 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -35,9 +35,6 @@ jobs: - name: Verify Forge installation run: forge --version - - name: Set up Foundry cache - run: forge install - - name: Run build script run: | chmod +x ./test-utils/scripts/build.sh From f54ea59d67bea665672dd8439aecad02b41b3f8c Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 21 Aug 2024 15:56:50 -0500 Subject: [PATCH 29/43] Debugging Forge steps --- test-utils/scripts/avs_rebuild_contracts.sh | 4 ++-- test-utils/scripts/build.sh | 10 +++++----- test-utils/scripts/rebuild_contracts.sh | 4 ++-- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/test-utils/scripts/avs_rebuild_contracts.sh b/test-utils/scripts/avs_rebuild_contracts.sh index 9e83a46..8578fdf 100755 --- a/test-utils/scripts/avs_rebuild_contracts.sh +++ b/test-utils/scripts/avs_rebuild_contracts.sh @@ -1,8 +1,8 @@ #!/bin/bash # Define the directories -DIR1="./../avs/incredible-squaring-avs/contracts" -DIR2="./../avs/tangle-avs/contracts" +DIR1="./avs/incredible-squaring-avs/contracts" +DIR2="./avs/tangle-avs/contracts" # Function to run forge commands in a directory run_forge_commands() { diff --git a/test-utils/scripts/build.sh b/test-utils/scripts/build.sh index 0e66b50..c699246 100755 --- a/test-utils/scripts/build.sh +++ b/test-utils/scripts/build.sh @@ -1,11 +1,11 @@ #!/bin/bash # Define the directories -DIR0="./../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts" -DIR1="./../contracts/lib/eigenlayer-middleware" -DIR2="./../contracts" -DIR3="./../avs/incredible-squaring-avs/contracts" -DIR4="./../avs/tangle-avs/contracts" +DIR0="./contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts" +DIR1="./contracts/lib/eigenlayer-middleware" +DIR2="./contracts" +DIR3="./avs/incredible-squaring-avs/contracts" +DIR4="./avs/tangle-avs/contracts" # Function to run forge commands in a directory run_forge_commands() { diff --git a/test-utils/scripts/rebuild_contracts.sh b/test-utils/scripts/rebuild_contracts.sh index d9a4300..47017e0 100755 --- a/test-utils/scripts/rebuild_contracts.sh +++ b/test-utils/scripts/rebuild_contracts.sh @@ -1,8 +1,8 @@ #!/bin/bash # Define the directories -DIR1="./../contracts/lib/eigenlayer-middleware" -DIR2="./../contracts" +DIR1="./contracts/lib/eigenlayer-middleware" +DIR2="./contracts" # Function to run forge commands in a directory run_forge_commands() { From 70f73a9934154d553552464a353fb0d9f85c30e5 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 21 Aug 2024 17:19:57 -0500 Subject: [PATCH 30/43] Build Script Fix --- .github/workflows/validate_pr.yml | 31 ----------------------- avs/incredible-squaring-avs/build.rs | 9 ++++--- avs/tangle-avs/build.rs | 7 +++--- contracts/build.rs | 35 ++++++++++++++++++++++++++ test-utils/build.rs | 37 ++++++++++++++++++++++++++++ test-utils/scripts/clean.sh | 24 ++++++++++++++++++ 6 files changed, 105 insertions(+), 38 deletions(-) create mode 100644 contracts/build.rs create mode 100644 test-utils/build.rs create mode 100755 test-utils/scripts/clean.sh diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index 802187b..cb49f5f 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -16,37 +16,6 @@ env: CARGO_TERM_COLOR: always jobs: - forge: - name: Forge - runs-on: macos-latest - steps: - - name: Checkout Code - uses: actions/checkout@v2 - - - name: Install Foundry - run: | - curl -L https://foundry.paradigm.xyz | bash - source /Users/runner/.bashrc - foundryup - - - name: Add Foundry to PATH - run: echo "${HOME}/.foundry/bin" >> $GITHUB_PATH - - - name: Verify Forge installation - run: forge --version - - - name: Run build script - run: | - chmod +x ./test-utils/scripts/build.sh - ./test-utils/scripts/build.sh - - - name: Upload Build Artifacts - if: success() - uses: actions/upload-artifact@v3 - with: - name: build-artifacts - path: ./out/ - formatting: name: Rustfmt runs-on: ubuntu-latest diff --git a/avs/incredible-squaring-avs/build.rs b/avs/incredible-squaring-avs/build.rs index 6ad9d8b..bf567d6 100644 --- a/avs/incredible-squaring-avs/build.rs +++ b/avs/incredible-squaring-avs/build.rs @@ -5,9 +5,10 @@ use std::process::Command; fn main() { // List of directories containing Solidity contracts let contract_dirs = vec![ - "../../contracts", - "../../contracts/lib/eigenlayer-middleware", - "contracts", + "./../../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", + "./../../contracts/lib/eigenlayer-middleware", + "./../../contracts/", + "./contracts", ]; // Get the project root directory @@ -19,7 +20,7 @@ fn main() { if full_path.exists() { println!("cargo:rerun-if-changed={}", full_path.display()); - let status = Command::new("/home/tjemmmic/.foundry/bin/forge") + let status = Command::new("forge") .current_dir(&full_path) .arg("build") .status() diff --git a/avs/tangle-avs/build.rs b/avs/tangle-avs/build.rs index 6ad9d8b..88998ed 100644 --- a/avs/tangle-avs/build.rs +++ b/avs/tangle-avs/build.rs @@ -5,9 +5,10 @@ use std::process::Command; fn main() { // List of directories containing Solidity contracts let contract_dirs = vec![ - "../../contracts", - "../../contracts/lib/eigenlayer-middleware", - "contracts", + "./../../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", + "./../../contracts/lib/eigenlayer-middleware", + "./../../contracts/", + "./contracts", ]; // Get the project root directory diff --git a/contracts/build.rs b/contracts/build.rs new file mode 100644 index 0000000..fc00640 --- /dev/null +++ b/contracts/build.rs @@ -0,0 +1,35 @@ +use std::env; +use std::path::Path; +use std::process::Command; + +fn main() { + // List of directories containing Solidity contracts + let contract_dirs = vec![ + "./lib/eigenlayer-middleware/lib/eigenlayer-contracts", + "./lib/eigenlayer-middleware", + "./", + ]; + + // Get the project root directory + let root = env::var("CARGO_MANIFEST_DIR").unwrap(); + + for dir in contract_dirs { + let full_path = Path::new(&root).join(dir).canonicalize().unwrap(); + + if full_path.exists() { + println!("cargo:rerun-if-changed={}", full_path.display()); + + let status = Command::new("forge") + .current_dir(&full_path) + .arg("build") + .status() + .expect("Failed to execute Forge build"); + + if !status.success() { + panic!("Forge build failed for directory: {}", full_path.display()); + } + } else { + println!("Directory not found: {}", full_path.display()); + } + } +} diff --git a/test-utils/build.rs b/test-utils/build.rs new file mode 100644 index 0000000..8b78068 --- /dev/null +++ b/test-utils/build.rs @@ -0,0 +1,37 @@ +use std::env; +use std::path::Path; +use std::process::Command; + +fn main() { + // List of directories containing Solidity contracts + let contract_dirs = vec![ + "./../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", + "./../contracts/lib/eigenlayer-middleware", + "./../contracts/", + "./../avs/tangle-avs/contracts", + "./../avs/incredible-squaring-avs/contracts", + ]; + + // Get the project root directory + let root = env::var("CARGO_MANIFEST_DIR").unwrap(); + + for dir in contract_dirs { + let full_path = Path::new(&root).join(dir).canonicalize().unwrap(); + + if full_path.exists() { + println!("cargo:rerun-if-changed={}", full_path.display()); + + let status = Command::new("forge") + .current_dir(&full_path) + .arg("build") + .status() + .expect("Failed to execute Forge build"); + + if !status.success() { + panic!("Forge build failed for directory: {}", full_path.display()); + } + } else { + println!("Directory not found: {}", full_path.display()); + } + } +} diff --git a/test-utils/scripts/clean.sh b/test-utils/scripts/clean.sh new file mode 100755 index 0000000..8342a7e --- /dev/null +++ b/test-utils/scripts/clean.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +# Define the directories +DIR0="./contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts" +DIR1="./contracts/lib/eigenlayer-middleware" +DIR2="./contracts" +DIR3="./avs/incredible-squaring-avs/contracts" +DIR4="./avs/tangle-avs/contracts" + +# Function to run forge commands in a directory +run_forge_commands() { + local dir=$1 + echo "Running forge commands in $dir" + cd "$dir" || exit + forge clean + cd - || exit +} + +# Run forge commands in all listed directories +run_forge_commands "$DIR0" +run_forge_commands "$DIR1" +run_forge_commands "$DIR2" +run_forge_commands "$DIR3" +run_forge_commands "$DIR4" \ No newline at end of file From 724f1e5586af4655c4e61de447d72e7f5abd8adb Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 21 Aug 2024 17:38:42 -0500 Subject: [PATCH 31/43] Workflow WIP --- .github/workflows/validate_pr.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index cb49f5f..38ef75e 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -44,6 +44,15 @@ jobs: steps: - name: checkout code uses: actions/checkout@v2 + with: + submodules: true + fetch-depth: 0 + + - name: Print current directory + run: pwd + + - name: List files + run: ls -al - name: install rust uses: actions-rs/toolchain@v1 From bbf4fdcbc58c7bd16887c7b1581f7e6a4877cfeb Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Wed, 21 Aug 2024 18:00:29 -0500 Subject: [PATCH 32/43] Workflow WIP --- avs/incredible-squaring-avs/build.rs | 25 +++++++++++++++---- avs/tangle-avs/build.rs | 25 +++++++++++++++---- contracts/build.rs | 25 +++++++++++++++---- test-utils/build.rs | 36 +++++++++++++++++++--------- 4 files changed, 85 insertions(+), 26 deletions(-) diff --git a/avs/incredible-squaring-avs/build.rs b/avs/incredible-squaring-avs/build.rs index bf567d6..15f35c7 100644 --- a/avs/incredible-squaring-avs/build.rs +++ b/avs/incredible-squaring-avs/build.rs @@ -1,5 +1,5 @@ use std::env; -use std::path::Path; +use std::path::PathBuf; use std::process::Command; fn main() { @@ -12,15 +12,30 @@ fn main() { ]; // Get the project root directory - let root = env::var("CARGO_MANIFEST_DIR").unwrap(); + let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); + + // Try to find the `forge` executable dynamically + let forge_executable = match Command::new("which").arg("forge").output() { + Ok(output) => { + let path = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if path.is_empty() { + panic!("Forge executable not found. Make sure Foundry is installed."); + } + path + }, + Err(_) => panic!("Failed to locate `forge` executable. Make sure Foundry is installed."), + }; for dir in contract_dirs { - let full_path = Path::new(&root).join(dir).canonicalize().unwrap(); + let full_path = root.join(dir).canonicalize().unwrap_or_else(|_| { + println!("Directory not found or inaccessible: {}", root.join(dir).display()); + root.join(dir) + }); if full_path.exists() { println!("cargo:rerun-if-changed={}", full_path.display()); - let status = Command::new("forge") + let status = Command::new(&forge_executable) .current_dir(&full_path) .arg("build") .status() @@ -30,7 +45,7 @@ fn main() { panic!("Forge build failed for directory: {}", full_path.display()); } } else { - println!("Directory not found: {}", full_path.display()); + println!("Directory not found or does not exist: {}", full_path.display()); } } } diff --git a/avs/tangle-avs/build.rs b/avs/tangle-avs/build.rs index 88998ed..15f35c7 100644 --- a/avs/tangle-avs/build.rs +++ b/avs/tangle-avs/build.rs @@ -1,5 +1,5 @@ use std::env; -use std::path::Path; +use std::path::PathBuf; use std::process::Command; fn main() { @@ -12,15 +12,30 @@ fn main() { ]; // Get the project root directory - let root = env::var("CARGO_MANIFEST_DIR").unwrap(); + let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); + + // Try to find the `forge` executable dynamically + let forge_executable = match Command::new("which").arg("forge").output() { + Ok(output) => { + let path = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if path.is_empty() { + panic!("Forge executable not found. Make sure Foundry is installed."); + } + path + }, + Err(_) => panic!("Failed to locate `forge` executable. Make sure Foundry is installed."), + }; for dir in contract_dirs { - let full_path = Path::new(&root).join(dir).canonicalize().unwrap(); + let full_path = root.join(dir).canonicalize().unwrap_or_else(|_| { + println!("Directory not found or inaccessible: {}", root.join(dir).display()); + root.join(dir) + }); if full_path.exists() { println!("cargo:rerun-if-changed={}", full_path.display()); - let status = Command::new("/home/tjemmmic/.foundry/bin/forge") + let status = Command::new(&forge_executable) .current_dir(&full_path) .arg("build") .status() @@ -30,7 +45,7 @@ fn main() { panic!("Forge build failed for directory: {}", full_path.display()); } } else { - println!("Directory not found: {}", full_path.display()); + println!("Directory not found or does not exist: {}", full_path.display()); } } } diff --git a/contracts/build.rs b/contracts/build.rs index fc00640..ccd39b8 100644 --- a/contracts/build.rs +++ b/contracts/build.rs @@ -1,5 +1,5 @@ use std::env; -use std::path::Path; +use std::path::PathBuf; use std::process::Command; fn main() { @@ -11,15 +11,30 @@ fn main() { ]; // Get the project root directory - let root = env::var("CARGO_MANIFEST_DIR").unwrap(); + let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); + + // Try to find the `forge` executable dynamically + let forge_executable = match Command::new("which").arg("forge").output() { + Ok(output) => { + let path = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if path.is_empty() { + panic!("Forge executable not found. Make sure Foundry is installed."); + } + path + }, + Err(_) => panic!("Failed to locate `forge` executable. Make sure Foundry is installed."), + }; for dir in contract_dirs { - let full_path = Path::new(&root).join(dir).canonicalize().unwrap(); + let full_path = root.join(dir).canonicalize().unwrap_or_else(|_| { + println!("Directory not found or inaccessible: {}", root.join(dir).display()); + root.join(dir) + }); if full_path.exists() { println!("cargo:rerun-if-changed={}", full_path.display()); - let status = Command::new("forge") + let status = Command::new(&forge_executable) .current_dir(&full_path) .arg("build") .status() @@ -29,7 +44,7 @@ fn main() { panic!("Forge build failed for directory: {}", full_path.display()); } } else { - println!("Directory not found: {}", full_path.display()); + println!("Directory not found or does not exist: {}", full_path.display()); } } } diff --git a/test-utils/build.rs b/test-utils/build.rs index 8b78068..ec8cbc8 100644 --- a/test-utils/build.rs +++ b/test-utils/build.rs @@ -1,27 +1,41 @@ use std::env; -use std::path::Path; +use std::path::PathBuf; use std::process::Command; fn main() { // List of directories containing Solidity contracts let contract_dirs = vec![ - "./../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", - "./../contracts/lib/eigenlayer-middleware", - "./../contracts/", - "./../avs/tangle-avs/contracts", - "./../avs/incredible-squaring-avs/contracts", + "./../../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", + "./../../contracts/lib/eigenlayer-middleware", + "./../../contracts/", + "./contracts", ]; // Get the project root directory - let root = env::var("CARGO_MANIFEST_DIR").unwrap(); + let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); + + // Try to find the `forge` executable dynamically + let forge_executable = match Command::new("which").arg("forge").output() { + Ok(output) => { + let path = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if path.is_empty() { + panic!("Forge executable not found. Make sure Foundry is installed."); + } + path + }, + Err(_) => panic!("Failed to locate `forge` executable. Make sure Foundry is installed."), + }; for dir in contract_dirs { - let full_path = Path::new(&root).join(dir).canonicalize().unwrap(); + let full_path = root.join(dir).canonicalize().unwrap_or_else(|_| { + println!("Directory not found or inaccessible: {}", root.join(dir).display()); + root.join(dir) + }); if full_path.exists() { println!("cargo:rerun-if-changed={}", full_path.display()); - let status = Command::new("forge") + let status = Command::new(&forge_executable) .current_dir(&full_path) .arg("build") .status() @@ -31,7 +45,7 @@ fn main() { panic!("Forge build failed for directory: {}", full_path.display()); } } else { - println!("Directory not found: {}", full_path.display()); + println!("Directory not found or does not exist: {}", full_path.display()); } } -} +} \ No newline at end of file From 420b73901c844fdfb43d31ec0273bad753d82c72 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Thu, 22 Aug 2024 08:51:29 -0500 Subject: [PATCH 33/43] Fmt and Fix --- .github/workflows/validate_pr.yml | 25 +++++++++++++++++++------ avs/incredible-squaring-avs/build.rs | 12 +++++++++--- avs/tangle-avs/build.rs | 12 +++++++++--- contracts/build.rs | 12 +++++++++--- test-utils/build.rs | 14 ++++++++++---- 5 files changed, 56 insertions(+), 19 deletions(-) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index 38ef75e..5737d60 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -14,6 +14,7 @@ env: RUST_BACKTRACE: full RUST_LOG: "info" CARGO_TERM_COLOR: always + CARGO_PROFILE_DEV_BUILD_OVERRIDE_DEBUG: true jobs: formatting: @@ -34,7 +35,7 @@ jobs: linting: timeout-minutes: 120 - name: cargo clippy + name: Cargo Clippy runs-on: macos-latest strategy: matrix: @@ -42,19 +43,31 @@ jobs: eigensdk-rs ] steps: - - name: checkout code + - name: Checkout Code uses: actions/checkout@v2 with: submodules: true fetch-depth: 0 - - name: Print current directory + - name: Install Foundry + run: | + curl -L https://foundry.paradigm.xyz | bash + source /Users/runner/.bashrc + foundryup + + - name: Add Foundry to PATH + run: echo "${HOME}/.foundry/bin" >> $GITHUB_PATH + + - name: Verify Forge installation + run: forge --version + + - name: Current Working Directory run: pwd - - name: List files + - name: List Files in Current Working Directory run: ls -al - - name: install rust + - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable @@ -68,7 +81,7 @@ jobs: testing: timeout-minutes: 90 - name: cargo test + name: Cargo Test if: false # temporarily disabled runs-on: macos-14 strategy: diff --git a/avs/incredible-squaring-avs/build.rs b/avs/incredible-squaring-avs/build.rs index 15f35c7..9507546 100644 --- a/avs/incredible-squaring-avs/build.rs +++ b/avs/incredible-squaring-avs/build.rs @@ -22,13 +22,16 @@ fn main() { panic!("Forge executable not found. Make sure Foundry is installed."); } path - }, + } Err(_) => panic!("Failed to locate `forge` executable. Make sure Foundry is installed."), }; for dir in contract_dirs { let full_path = root.join(dir).canonicalize().unwrap_or_else(|_| { - println!("Directory not found or inaccessible: {}", root.join(dir).display()); + println!( + "Directory not found or inaccessible: {}", + root.join(dir).display() + ); root.join(dir) }); @@ -45,7 +48,10 @@ fn main() { panic!("Forge build failed for directory: {}", full_path.display()); } } else { - println!("Directory not found or does not exist: {}", full_path.display()); + println!( + "Directory not found or does not exist: {}", + full_path.display() + ); } } } diff --git a/avs/tangle-avs/build.rs b/avs/tangle-avs/build.rs index 15f35c7..9507546 100644 --- a/avs/tangle-avs/build.rs +++ b/avs/tangle-avs/build.rs @@ -22,13 +22,16 @@ fn main() { panic!("Forge executable not found. Make sure Foundry is installed."); } path - }, + } Err(_) => panic!("Failed to locate `forge` executable. Make sure Foundry is installed."), }; for dir in contract_dirs { let full_path = root.join(dir).canonicalize().unwrap_or_else(|_| { - println!("Directory not found or inaccessible: {}", root.join(dir).display()); + println!( + "Directory not found or inaccessible: {}", + root.join(dir).display() + ); root.join(dir) }); @@ -45,7 +48,10 @@ fn main() { panic!("Forge build failed for directory: {}", full_path.display()); } } else { - println!("Directory not found or does not exist: {}", full_path.display()); + println!( + "Directory not found or does not exist: {}", + full_path.display() + ); } } } diff --git a/contracts/build.rs b/contracts/build.rs index ccd39b8..f2228b1 100644 --- a/contracts/build.rs +++ b/contracts/build.rs @@ -21,13 +21,16 @@ fn main() { panic!("Forge executable not found. Make sure Foundry is installed."); } path - }, + } Err(_) => panic!("Failed to locate `forge` executable. Make sure Foundry is installed."), }; for dir in contract_dirs { let full_path = root.join(dir).canonicalize().unwrap_or_else(|_| { - println!("Directory not found or inaccessible: {}", root.join(dir).display()); + println!( + "Directory not found or inaccessible: {}", + root.join(dir).display() + ); root.join(dir) }); @@ -44,7 +47,10 @@ fn main() { panic!("Forge build failed for directory: {}", full_path.display()); } } else { - println!("Directory not found or does not exist: {}", full_path.display()); + println!( + "Directory not found or does not exist: {}", + full_path.display() + ); } } } diff --git a/test-utils/build.rs b/test-utils/build.rs index ec8cbc8..9507546 100644 --- a/test-utils/build.rs +++ b/test-utils/build.rs @@ -22,13 +22,16 @@ fn main() { panic!("Forge executable not found. Make sure Foundry is installed."); } path - }, + } Err(_) => panic!("Failed to locate `forge` executable. Make sure Foundry is installed."), }; for dir in contract_dirs { let full_path = root.join(dir).canonicalize().unwrap_or_else(|_| { - println!("Directory not found or inaccessible: {}", root.join(dir).display()); + println!( + "Directory not found or inaccessible: {}", + root.join(dir).display() + ); root.join(dir) }); @@ -45,7 +48,10 @@ fn main() { panic!("Forge build failed for directory: {}", full_path.display()); } } else { - println!("Directory not found or does not exist: {}", full_path.display()); + println!( + "Directory not found or does not exist: {}", + full_path.display() + ); } } -} \ No newline at end of file +} From 41186196c1eee6f51957bec24a6ce0f5a99d8050 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Thu, 22 Aug 2024 09:36:33 -0500 Subject: [PATCH 34/43] Clippy workflow debugging --- avs/tangle-avs/contracts/remappings.txt | 1 + utils/src/avs_registry/reader.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/avs/tangle-avs/contracts/remappings.txt b/avs/tangle-avs/contracts/remappings.txt index e218db9..b655f80 100644 --- a/avs/tangle-avs/contracts/remappings.txt +++ b/avs/tangle-avs/contracts/remappings.txt @@ -1,5 +1,6 @@ @openzeppelin-upgrades/=lib/eigenlayer-middleware/lib/openzeppelin-contracts-upgradeable/ @openzeppelin/=lib/eigenlayer-middleware/lib/openzeppelin-contracts/ +@openzeppelin-interfaces/=lib/eigenlayer-middleware/lib/openzeppelin-contracts/interfaces/ ds-test/=lib/ds-test/src/ eigenlayer-contracts/=lib/eigenlayer-middleware/lib/eigenlayer-contracts eigenlayer-middleware/=lib/eigenlayer-middleware/ diff --git a/utils/src/avs_registry/reader.rs b/utils/src/avs_registry/reader.rs index 1209678..86bdfc6 100644 --- a/utils/src/avs_registry/reader.rs +++ b/utils/src/avs_registry/reader.rs @@ -337,7 +337,7 @@ impl AvsRegistryChainReaderTrait for AvsRegistryContractManager { let start = start_block; let mut end = stop_block; if start_block == 0 && stop_block == 0 { - end = self.eth_client_http.get_block_number().await? as u64; + end = self.eth_client_http.get_block_number().await?; } for i in (start..=end).step_by(block_range as usize) { From 36c84516d13315b4c428e2927e5365f21d56e1aa Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Thu, 22 Aug 2024 10:14:53 -0500 Subject: [PATCH 35/43] Contract path Debugging --- .github/workflows/validate_pr.yml | 12 ++++++++++++ avs/tangle-avs/contracts/remappings.txt | 1 - 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index 5737d60..b7d2ddf 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -67,6 +67,18 @@ jobs: - name: List Files in Current Working Directory run: ls -al + - name: Debugging Smart Contracts + run: | + ls avs/tangle-avs/contracts/ + ls avs/tangle-avs/contracts/lib/ + ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/ + ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/lib/ + ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts/ + ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts/lib/ + ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts/lib/openzeppelin-contracts + ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts/lib/openzeppelin-contracts/contracts/ + ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts/lib/openzeppelin-contracts/contracts/interfaces/ + - name: Install Rust uses: actions-rs/toolchain@v1 with: diff --git a/avs/tangle-avs/contracts/remappings.txt b/avs/tangle-avs/contracts/remappings.txt index b655f80..e218db9 100644 --- a/avs/tangle-avs/contracts/remappings.txt +++ b/avs/tangle-avs/contracts/remappings.txt @@ -1,6 +1,5 @@ @openzeppelin-upgrades/=lib/eigenlayer-middleware/lib/openzeppelin-contracts-upgradeable/ @openzeppelin/=lib/eigenlayer-middleware/lib/openzeppelin-contracts/ -@openzeppelin-interfaces/=lib/eigenlayer-middleware/lib/openzeppelin-contracts/interfaces/ ds-test/=lib/ds-test/src/ eigenlayer-contracts/=lib/eigenlayer-middleware/lib/eigenlayer-contracts eigenlayer-middleware/=lib/eigenlayer-middleware/ From 84a37389d187867bcbd46fc21cb63e4917dc939a Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Thu, 22 Aug 2024 10:56:35 -0500 Subject: [PATCH 36/43] Contract path Debugging --- avs/incredible-squaring-avs/contracts/remappings.txt | 1 + avs/incredible-squaring-avs/contracts/src/ERC20Mock.sol | 2 +- avs/tangle-avs/contracts/remappings.txt | 1 + avs/tangle-avs/contracts/src/ERC20Mock.sol | 2 +- 4 files changed, 4 insertions(+), 2 deletions(-) diff --git a/avs/incredible-squaring-avs/contracts/remappings.txt b/avs/incredible-squaring-avs/contracts/remappings.txt index e218db9..b74927b 100644 --- a/avs/incredible-squaring-avs/contracts/remappings.txt +++ b/avs/incredible-squaring-avs/contracts/remappings.txt @@ -1,5 +1,6 @@ @openzeppelin-upgrades/=lib/eigenlayer-middleware/lib/openzeppelin-contracts-upgradeable/ @openzeppelin/=lib/eigenlayer-middleware/lib/openzeppelin-contracts/ +@openzeppelin-interfaces/=lib/eigenlayer-middleware/lib/openzeppelin-contracts/contracts/interfaces/ ds-test/=lib/ds-test/src/ eigenlayer-contracts/=lib/eigenlayer-middleware/lib/eigenlayer-contracts eigenlayer-middleware/=lib/eigenlayer-middleware/ diff --git a/avs/incredible-squaring-avs/contracts/src/ERC20Mock.sol b/avs/incredible-squaring-avs/contracts/src/ERC20Mock.sol index df68eee..841ed7c 100644 --- a/avs/incredible-squaring-avs/contracts/src/ERC20Mock.sol +++ b/avs/incredible-squaring-avs/contracts/src/ERC20Mock.sol @@ -3,7 +3,7 @@ pragma solidity ^0.8.20; -import "@openzeppelin/contracts/interfaces/IERC20.sol"; +import "@openzeppelin-interfaces/IERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** diff --git a/avs/tangle-avs/contracts/remappings.txt b/avs/tangle-avs/contracts/remappings.txt index e218db9..b74927b 100644 --- a/avs/tangle-avs/contracts/remappings.txt +++ b/avs/tangle-avs/contracts/remappings.txt @@ -1,5 +1,6 @@ @openzeppelin-upgrades/=lib/eigenlayer-middleware/lib/openzeppelin-contracts-upgradeable/ @openzeppelin/=lib/eigenlayer-middleware/lib/openzeppelin-contracts/ +@openzeppelin-interfaces/=lib/eigenlayer-middleware/lib/openzeppelin-contracts/contracts/interfaces/ ds-test/=lib/ds-test/src/ eigenlayer-contracts/=lib/eigenlayer-middleware/lib/eigenlayer-contracts eigenlayer-middleware/=lib/eigenlayer-middleware/ diff --git a/avs/tangle-avs/contracts/src/ERC20Mock.sol b/avs/tangle-avs/contracts/src/ERC20Mock.sol index df68eee..841ed7c 100644 --- a/avs/tangle-avs/contracts/src/ERC20Mock.sol +++ b/avs/tangle-avs/contracts/src/ERC20Mock.sol @@ -3,7 +3,7 @@ pragma solidity ^0.8.20; -import "@openzeppelin/contracts/interfaces/IERC20.sol"; +import "@openzeppelin-interfaces/IERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** From 0c1475811d340cfc45233149e29df60f644a5b93 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Thu, 22 Aug 2024 11:00:11 -0500 Subject: [PATCH 37/43] Recursively checkout submodules --- .github/workflows/validate_pr.yml | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index b7d2ddf..c3a7f74 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -46,7 +46,7 @@ jobs: - name: Checkout Code uses: actions/checkout@v2 with: - submodules: true + submodules: recursive fetch-depth: 0 - name: Install Foundry @@ -67,18 +67,6 @@ jobs: - name: List Files in Current Working Directory run: ls -al - - name: Debugging Smart Contracts - run: | - ls avs/tangle-avs/contracts/ - ls avs/tangle-avs/contracts/lib/ - ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/ - ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/lib/ - ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts/ - ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts/lib/ - ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts/lib/openzeppelin-contracts - ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts/lib/openzeppelin-contracts/contracts/ - ls avs/tangle-avs/contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts/lib/openzeppelin-contracts/contracts/interfaces/ - - name: Install Rust uses: actions-rs/toolchain@v1 with: From 9e5d15460d7b9fc12570aed2f5e38fece6f46c20 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Thu, 22 Aug 2024 11:15:07 -0500 Subject: [PATCH 38/43] Contract Building WIP --- avs/incredible-squaring-avs/build.rs | 6 +++--- avs/tangle-avs/build.rs | 6 +++--- test-utils/build.rs | 9 ++++----- 3 files changed, 10 insertions(+), 11 deletions(-) diff --git a/avs/incredible-squaring-avs/build.rs b/avs/incredible-squaring-avs/build.rs index 9507546..9f8b1b2 100644 --- a/avs/incredible-squaring-avs/build.rs +++ b/avs/incredible-squaring-avs/build.rs @@ -5,9 +5,9 @@ use std::process::Command; fn main() { // List of directories containing Solidity contracts let contract_dirs = vec![ - "./../../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", - "./../../contracts/lib/eigenlayer-middleware", - "./../../contracts/", + // "./../../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", + // "./../../contracts/lib/eigenlayer-middleware", + // "./../../contracts/", "./contracts", ]; diff --git a/avs/tangle-avs/build.rs b/avs/tangle-avs/build.rs index 9507546..9f8b1b2 100644 --- a/avs/tangle-avs/build.rs +++ b/avs/tangle-avs/build.rs @@ -5,9 +5,9 @@ use std::process::Command; fn main() { // List of directories containing Solidity contracts let contract_dirs = vec![ - "./../../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", - "./../../contracts/lib/eigenlayer-middleware", - "./../../contracts/", + // "./../../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", + // "./../../contracts/lib/eigenlayer-middleware", + // "./../../contracts/", "./contracts", ]; diff --git a/test-utils/build.rs b/test-utils/build.rs index 9507546..bd228f9 100644 --- a/test-utils/build.rs +++ b/test-utils/build.rs @@ -4,11 +4,10 @@ use std::process::Command; fn main() { // List of directories containing Solidity contracts - let contract_dirs = vec![ - "./../../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", - "./../../contracts/lib/eigenlayer-middleware", - "./../../contracts/", - "./contracts", + let contract_dirs: Vec<&str> = vec![ + // "./../../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", + // "./../../contracts/lib/eigenlayer-middleware", + // "./../../contracts/", ]; // Get the project root directory From af5047e9e458ef9bb0470ada80ce22261a2b21b8 Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Thu, 22 Aug 2024 15:12:57 -0500 Subject: [PATCH 39/43] Update Tests --- Cargo.lock | 1 + avs/incredible-squaring-avs/build.rs | 7 +- avs/incredible-squaring-avs/src/operator.rs | 53 +++++---- avs/tangle-avs/build.rs | 7 +- avs/tangle-avs/src/operator.rs | 91 +++++++++------ test-utils/Cargo.toml | 3 +- test-utils/build.rs | 56 --------- test-utils/src/anvil/anvil_node.rs | 2 +- test-utils/src/anvil/testnet/tangle.rs | 123 ++++++++++++++------ test-utils/src/bin/incredible_squaring.rs | 34 +++--- test-utils/src/bin/tangle.rs | 34 +++--- 11 files changed, 212 insertions(+), 199 deletions(-) delete mode 100644 test-utils/build.rs diff --git a/Cargo.lock b/Cargo.lock index a77ca10..61107a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11714,6 +11714,7 @@ dependencies = [ "hyper 1.4.1", "incredible-squaring-avs", "k256", + "lazy_static", "log", "nix 0.28.0", "prometheus", diff --git a/avs/incredible-squaring-avs/build.rs b/avs/incredible-squaring-avs/build.rs index 9f8b1b2..122809f 100644 --- a/avs/incredible-squaring-avs/build.rs +++ b/avs/incredible-squaring-avs/build.rs @@ -4,12 +4,7 @@ use std::process::Command; fn main() { // List of directories containing Solidity contracts - let contract_dirs = vec![ - // "./../../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", - // "./../../contracts/lib/eigenlayer-middleware", - // "./../../contracts/", - "./contracts", - ]; + let contract_dirs = vec!["./contracts"]; // Get the project root directory let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); diff --git a/avs/incredible-squaring-avs/src/operator.rs b/avs/incredible-squaring-avs/src/operator.rs index 8a5d93e..0e84bd0 100644 --- a/avs/incredible-squaring-avs/src/operator.rs +++ b/avs/incredible-squaring-avs/src/operator.rs @@ -277,28 +277,6 @@ impl Operator { .get_operator_id(operator_address) .await?; - log::info!( - "Operator info: operatorId={}, operatorAddr={}, operatorG1Pubkey={:?}, operatorG2Pubkey={:?}", - hex::encode(operator_id), - operator_address, - bls_keypair.clone().get_pub_key_g1(), - bls_keypair.clone().get_pub_key_g2(), - ); - - let operator = Operator { - config: config.clone(), - node_api, - avs_registry_contract_manager: avs_registry_contract_manager.clone(), - incredible_squaring_contract_manager, - eigenlayer_contract_manager: eigenlayer_contract_manager.clone(), - bls_keypair: bls_keypair.clone(), - operator_id, - operator_addr: operator_address, - aggregator_server_ip_port_addr: config.server_ip_port_address.clone(), - aggregator_server: aggregator_service, - aggregator_rpc_client, - }; - // Register Operator with EigenLayer let register_operator = eigen_utils::types::Operator { address: operator_address, @@ -335,9 +313,40 @@ impl Operator { .unwrap(); log::info!("Is operator registered: {:?}", answer); + log::info!( + "Operator info: operatorId={}, operatorAddr={}, operatorG1Pubkey={:?}, operatorG2Pubkey={:?}", + hex::encode(operator_id), + operator_address, + bls_keypair.clone().get_pub_key_g1(), + bls_keypair.clone().get_pub_key_g2(), + ); + + let operator = Operator { + config: config.clone(), + node_api, + avs_registry_contract_manager: avs_registry_contract_manager.clone(), + incredible_squaring_contract_manager, + eigenlayer_contract_manager: eigenlayer_contract_manager.clone(), + bls_keypair, + operator_id, + operator_addr: operator_address, + aggregator_server_ip_port_addr: config.server_ip_port_address.clone(), + aggregator_server: aggregator_service, + aggregator_rpc_client, + }; + Ok(operator) } + pub async fn is_registered(&self) -> Result { + let operator_is_registered = self + .avs_registry_contract_manager + .is_operator_registered(self.operator_addr) + .await?; + log::info!("Operator registration status: {:?}", operator_is_registered); + Ok(operator_is_registered) + } + pub async fn start(self) -> Result<(), OperatorError> { log::info!("Starting operator."); let operator_is_registered = self diff --git a/avs/tangle-avs/build.rs b/avs/tangle-avs/build.rs index 9f8b1b2..122809f 100644 --- a/avs/tangle-avs/build.rs +++ b/avs/tangle-avs/build.rs @@ -4,12 +4,7 @@ use std::process::Command; fn main() { // List of directories containing Solidity contracts - let contract_dirs = vec![ - // "./../../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", - // "./../../contracts/lib/eigenlayer-middleware", - // "./../../contracts/", - "./contracts", - ]; + let contract_dirs = vec!["./contracts"]; // Get the project root directory let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); diff --git a/avs/tangle-avs/src/operator.rs b/avs/tangle-avs/src/operator.rs index 5b11fc7..b3c6d2f 100644 --- a/avs/tangle-avs/src/operator.rs +++ b/avs/tangle-avs/src/operator.rs @@ -1,5 +1,5 @@ use alloy_contract::private::Ethereum; -use alloy_primitives::{Address, ChainId, Signature, B256}; +use alloy_primitives::{Address, Bytes, ChainId, Signature, B256}; use alloy_provider::{Provider, RootProvider}; use alloy_signer_local::PrivateKeySigner; use alloy_transport::BoxTransport; @@ -7,6 +7,8 @@ use eigen_utils::avs_registry::reader::AvsRegistryChainReaderTrait; use eigen_utils::avs_registry::writer::AvsRegistryChainWriterTrait; use eigen_utils::avs_registry::AvsRegistryContractManager; use eigen_utils::crypto::bls::KeyPair; +use eigen_utils::el_contracts::writer::ElWriter; +use eigen_utils::el_contracts::ElChainContractManager; use eigen_utils::node_api::NodeApi; use eigen_utils::types::AvsError; use eigen_utils::Config; @@ -42,6 +44,8 @@ pub enum OperatorError { OperatorIdError(String), #[error("Error in Operator Address: {0}")] OperatorAddressError(String), + #[error("Error while Starting Operator: {0}")] + OperatorStartError(String), #[error( "Operator is not registered. Register using the operator-cli before starting operator." )] @@ -146,15 +150,6 @@ impl Config for NodeConfig { type S = EigenTangleSigner; } -#[derive(Clone)] -pub struct TangleValidatorContractManager { - pub task_manager_addr: Address, - pub service_manager_addr: Address, - pub eth_client_http: T::PH, - pub eth_client_ws: T::PW, - pub signer: T::S, -} - #[derive(Debug, Clone)] pub struct SetupConfig { pub registry_coordinator_addr: Address, @@ -229,30 +224,52 @@ impl Operator { Address::from_str(&config.tangle_validator_service_manager_address) .map_err(|err| OperatorError::ServiceManagerAddressError(err.to_string()))?; - // let tangle_validator_contract_manager = TangleValidatorContractManager::build( - // setup_config.registry_coordinator_addr, - // setup_config.operator_state_retriever_addr, - // eth_client_http.clone(), - // eth_client_ws.clone(), - // signer.clone(), - // ) - // .await?; - - // if config.register_operator_on_startup { - // operator.register_operator_on_startup( - // operator_ecdsa_private_key, - // config.token_strategy_addr.parse()?, - // ); - // } - - let _register_result = avs_registry_contract_manager + log::info!("Building Eigenlayer Contract Manager..."); + let eigenlayer_contract_manager: ElChainContractManager = ElChainContractManager::build( + setup_config.delegate_manager_addr, + setup_config.avs_directory_addr, + eth_client_http.clone(), + eth_client_ws.clone(), + signer.clone(), + ) + .await + .unwrap(); + + // Register Operator with EigenLayer + let register_operator = eigen_utils::types::Operator { + address: operator_addr, + earnings_receiver_address: operator_addr, + delegation_approver_address: Address::from([0u8; 20]), + staker_opt_out_window_blocks: 50400u32, // About 7 days in blocks on Ethereum + metadata_url: "https://github.com/webb-tools/eigensdk-rs/blob/donovan/eigen/test-utils/metadata.json".to_string(), + }; + let eigenlayer_register_result = eigenlayer_contract_manager + .register_as_operator(register_operator) + .await + .unwrap() + .status(); + log::info!( + "Eigenlayer Registration result: {:?}", + eigenlayer_register_result + ); + + // Register Operator with AVS + let quorum_nums = Bytes::from([0x00]); + let register_result = avs_registry_contract_manager .register_operator( &ecdsa_signing_key, &bls_keypair, - alloy_primitives::Bytes::from(vec![0]), - "127.0.0.1:8545".to_string(), + quorum_nums, + config.eth_rpc_url.clone(), ) .await; + log::info!("AVS Registration result: {:?}", register_result); + + let answer = avs_registry_contract_manager + .is_operator_registered(operator_addr) + .await + .unwrap(); + log::info!("Is operator registered: {:?}", answer); let operator = Operator { config: config.clone(), @@ -274,17 +291,19 @@ impl Operator { Ok(operator) } - pub async fn start(&self) -> Result<(), OperatorError> { - log::info!("Starting operator."); + pub async fn is_registered(&self) -> Result { let operator_is_registered = self .avs_registry_contract_manager .is_operator_registered(self.operator_addr) .await?; log::info!("Operator registration status: {:?}", operator_is_registered); + Ok(operator_is_registered) + } + + pub async fn start(&self) -> Result<(), OperatorError> { + log::info!("Starting operator."); + self.is_registered().await?; - if !operator_is_registered { - return Err(OperatorError::OperatorNotRegistered); - } if self.config.enable_node_api { if let Err(e) = self.node_api.start().await { return Err(OperatorError::NodeApiError(e.to_string())); @@ -292,7 +311,9 @@ impl Operator { } log::info!("Starting Tangle Validator..."); - gadget_executor::run_tangle_validator().await.unwrap(); + gadget_executor::run_tangle_validator() + .await + .map_err(|e| OperatorError::OperatorStartError(e.to_string()))?; Ok(()) } diff --git a/test-utils/Cargo.toml b/test-utils/Cargo.toml index e5d19ed..7fd52ba 100644 --- a/test-utils/Cargo.toml +++ b/test-utils/Cargo.toml @@ -75,4 +75,5 @@ url.workspace = true #ark-ff.workspace = true ark-bn254.workspace = true sha3 = "0.10.8" -nix = "0.28.0" \ No newline at end of file +nix = "0.28.0" +lazy_static = "1.5.0" \ No newline at end of file diff --git a/test-utils/build.rs b/test-utils/build.rs deleted file mode 100644 index bd228f9..0000000 --- a/test-utils/build.rs +++ /dev/null @@ -1,56 +0,0 @@ -use std::env; -use std::path::PathBuf; -use std::process::Command; - -fn main() { - // List of directories containing Solidity contracts - let contract_dirs: Vec<&str> = vec![ - // "./../../contracts/lib/eigenlayer-middleware/lib/eigenlayer-contracts", - // "./../../contracts/lib/eigenlayer-middleware", - // "./../../contracts/", - ]; - - // Get the project root directory - let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); - - // Try to find the `forge` executable dynamically - let forge_executable = match Command::new("which").arg("forge").output() { - Ok(output) => { - let path = String::from_utf8_lossy(&output.stdout).trim().to_string(); - if path.is_empty() { - panic!("Forge executable not found. Make sure Foundry is installed."); - } - path - } - Err(_) => panic!("Failed to locate `forge` executable. Make sure Foundry is installed."), - }; - - for dir in contract_dirs { - let full_path = root.join(dir).canonicalize().unwrap_or_else(|_| { - println!( - "Directory not found or inaccessible: {}", - root.join(dir).display() - ); - root.join(dir) - }); - - if full_path.exists() { - println!("cargo:rerun-if-changed={}", full_path.display()); - - let status = Command::new(&forge_executable) - .current_dir(&full_path) - .arg("build") - .status() - .expect("Failed to execute Forge build"); - - if !status.success() { - panic!("Forge build failed for directory: {}", full_path.display()); - } - } else { - println!( - "Directory not found or does not exist: {}", - full_path.display() - ); - } - } -} diff --git a/test-utils/src/anvil/anvil_node.rs b/test-utils/src/anvil/anvil_node.rs index e3c3f2b..bd5257a 100644 --- a/test-utils/src/anvil/anvil_node.rs +++ b/test-utils/src/anvil/anvil_node.rs @@ -309,7 +309,7 @@ mod tests { #[test] fn assert_chain_id_without_rpc() { - let anvil = Anvil::new().spawn(); + let anvil = Anvil::new().chain_id(31337u64).spawn(); assert_eq!(anvil.chain_id(), 31337); } } diff --git a/test-utils/src/anvil/testnet/tangle.rs b/test-utils/src/anvil/testnet/tangle.rs index cbb7c14..8a3796b 100644 --- a/test-utils/src/anvil/testnet/tangle.rs +++ b/test-utils/src/anvil/testnet/tangle.rs @@ -27,6 +27,8 @@ pub struct ContractAddresses { } /// Spawns and runs an Anvil node, deploying the Smart Contracts that are relevant to the Tangle AVS to it. +/// +/// NOTE: This function will Panic upon contract deployment failure. pub async fn run_tangle_testnet() -> ContractAddresses { // Initialize the logger let _ = env_logger::try_init(); @@ -54,13 +56,13 @@ pub async fn run_tangle_testnet() -> ContractAddresses { // Deploy initial contracts that don't depend on others let istrategy_manager = IStrategyManager::deploy(provider.clone()).await.unwrap(); - let &strategy_manager_addr = istrategy_manager.address(); + let &_strategy_manager_addr = istrategy_manager.address(); let idelegation_manager = IDelegationManager::deploy(provider.clone()).await.unwrap(); let &delegation_manager_addr = idelegation_manager.address(); let iavs_directory = IAVSDirectory::deploy(provider.clone()).await.unwrap(); - let &avs_directory_addr = iavs_directory.address(); + let &_avs_directory_addr = iavs_directory.address(); let proxy_admin = ProxyAdmin::deploy_builder(provider.clone()) .from(dev_account) @@ -92,11 +94,14 @@ pub async fn run_tangle_testnet() -> ContractAddresses { // Function with signature initialize(uint256,uint256,address,address) and selector 0x019e2729. let function_signature = "initialize(uint256,uint256,address,address)"; - let mut hasher = Keccak256::new(); - hasher.update(function_signature); - let function_selector = &hasher.finalize()[..4]; - let encoded_data = encode_params!(function_selector, 1, 100, ierc20_addr, pauser_registry_addr); + let encoded_data = encode_params!( + function_signature, + 1, + 100, + ierc20_addr, + pauser_registry_addr + ); let strategy_proxy = TransparentUpgradeableProxy::deploy( provider.clone(), @@ -127,6 +132,7 @@ pub async fn run_tangle_testnet() -> ContractAddresses { // Deploy Incredible Squaring Contracts let number_of_strategies = strategies.len(); + println!("Number of Strategies: {:?}", number_of_strategies); let tangle_validator_proxy_admin = ProxyAdmin::deploy_builder(provider.clone()) .from(dev_account) @@ -240,6 +246,83 @@ pub async fn run_tangle_testnet() -> ContractAddresses { .unwrap(); let &operator_state_retriever_addr = operator_state_retriever.address(); + let eth_pos = IETHPOSDeposit::deploy(provider.clone()).await.unwrap(); + let ð_pos_addr = eth_pos.address(); + + let eigen_pod_beacon = IBeacon::deploy(provider.clone()).await.unwrap(); + let &eigen_pod_beacon_addr = eigen_pod_beacon.address(); + + let strategy_manager = StrategyManager::new( + *TransparentUpgradeableProxy::deploy( + provider.clone(), + empty_contract_addr, + tangle_validator_proxy_admin_addr, + Bytes::from(""), + ) + .await + .unwrap() + .address(), + provider.clone(), + ); + let &strategy_manager_addr = strategy_manager.address(); + + let eigen_pod_manager = EigenPodManager::deploy( + provider.clone(), + eth_pos_addr, + eigen_pod_beacon_addr, + strategy_manager_addr, + from, + delegation_manager_addr, + ) + .await + .unwrap(); + let &eigen_pod_manager_addr = eigen_pod_manager.address(); + + let slasher_addr = dev_account; + let delegation_manager = DelegationManager::deploy( + provider.clone(), + strategy_manager_addr, + slasher_addr, + eigen_pod_manager_addr, + ) + .await + .unwrap(); + let &delegation_manager_addr = delegation_manager.address(); + + let strategy_manager_implementation = StrategyManager::deploy( + provider.clone(), + delegation_manager_addr, + eigen_pod_manager_addr, + slasher_addr, + ) + .await + .unwrap(); + let &strategy_manager_implementation_addr = strategy_manager_implementation.address(); + let strategy_manager_upgrade = tangle_validator_proxy_admin + .upgrade(strategy_manager_addr, strategy_manager_implementation_addr) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(strategy_manager_upgrade.status()); + + let strategy_manager_initialization = strategy_manager + .initialize(pausers[0], pausers[0], pauser_registry_addr, U256::from(0)) + .send() + .await + .unwrap() + .get_receipt() + .await + .unwrap(); + assert!(strategy_manager_initialization.status()); + + let avs_directory = AVSDirectory::deploy(provider.clone(), delegation_manager_addr) + .await + .unwrap(); + let &avs_directory_addr = avs_directory.address(); + // Now, deploy the implementation contracts using the proxy contracts as inputs let stake_registry_implementation = StakeRegistry::deploy( provider.clone(), @@ -428,34 +511,6 @@ pub async fn run_tangle_testnet() -> ContractAddresses { .unwrap(); assert!(tangle_validator_task_manager_upgrade.status()); - let eigen_pod_manager = EigenPodManager::deploy( - provider.clone(), - empty_contract_addr, - empty_contract_addr, - strategy_manager_addr, - from, - delegation_manager_addr, - ) - .await - .unwrap(); - let &eigen_pod_manager_addr = eigen_pod_manager.address(); - - let slasher_addr = dev_account; - let delegation_manager = DelegationManager::deploy( - provider.clone(), - strategy_manager_addr, - slasher_addr, - eigen_pod_manager_addr, - ) - .await - .unwrap(); - let &delegation_manager_addr = delegation_manager.address(); - - let avs_directory = AVSDirectory::deploy(provider.clone(), delegation_manager_addr) - .await - .unwrap(); - let &avs_directory_addr = avs_directory.address(); - log::info!("ERC20MOCK ADDRESS: {:?}", erc20_mock_addr); log::info!("ERC20MOCK STRATEGY ADDRESS: {:?}", erc20_mock_strategy_addr); log::info!( diff --git a/test-utils/src/bin/incredible_squaring.rs b/test-utils/src/bin/incredible_squaring.rs index 252b55c..7c51667 100644 --- a/test-utils/src/bin/incredible_squaring.rs +++ b/test-utils/src/bin/incredible_squaring.rs @@ -11,7 +11,7 @@ use test_utils::anvil::testnet::incredible_squaring::*; #[tokio::main] async fn main() { let _ = env_logger::try_init(); - run_full_incredible_squaring_test().await; + run_incredible_squaring_testnet().await; } /// Sets up an Operator, given the [ContractAddresses] for the running Testnet you would like utilize @@ -85,20 +85,6 @@ async fn operator_setup( .unwrap() } -/// THIS FUNCTION IS FOR TESTING ONLY -/// -/// Runs the Incredible Squaring Testnet and then creates an Operator that connects and registers. -async fn run_full_incredible_squaring_test() { - let _ = env_logger::try_init(); - - // Runs new Anvil Testnet - used for deploying programmatically in rust - let contract_addresses = run_incredible_squaring_testnet().await; - - let operator = operator_setup(contract_addresses).await; - - operator.start().await.unwrap(); -} - #[cfg(test)] mod tests { use super::*; @@ -114,14 +100,24 @@ mod tests { } #[tokio::test] - async fn test_full_incredible_squaring() { + async fn test_incredible_squaring_deployment() { env_init(); - run_full_incredible_squaring_test().await; + let _ = run_incredible_squaring_testnet().await; } #[tokio::test] - async fn test_incredible_squaring_deployment() { + async fn test_incredible_squaring_full() { env_init(); - let _ = run_incredible_squaring_testnet().await; + + // Runs new Anvil Testnet - used for deploying programmatically in rust + let contract_addresses = run_incredible_squaring_testnet().await; + + // Sets up the Operator + let operator = operator_setup(contract_addresses).await; + + // Check that the operator has registered successfully + assert!(operator.is_registered().await.unwrap()); + + log::info!("Operator Successfully Registered. The Tangle Validator would now start."); } } diff --git a/test-utils/src/bin/tangle.rs b/test-utils/src/bin/tangle.rs index 97a5e85..8b5c4f3 100644 --- a/test-utils/src/bin/tangle.rs +++ b/test-utils/src/bin/tangle.rs @@ -11,7 +11,7 @@ use test_utils::anvil::testnet::tangle::*; #[tokio::main] async fn main() { let _ = env_logger::try_init(); - run_full_tangle_test().await; + run_tangle_testnet().await; } /// Sets up an Operator, given the [ContractAddresses] for the running Testnet you would like utilize @@ -79,20 +79,6 @@ async fn operator_setup(contract_addresses: ContractAddresses) -> Operator Date: Thu, 22 Aug 2024 15:20:41 -0500 Subject: [PATCH 40/43] Add tests to CI --- .github/workflows/validate_pr.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index c3a7f74..12254aa 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -82,12 +82,14 @@ jobs: testing: timeout-minutes: 90 name: Cargo Test - if: false # temporarily disabled runs-on: macos-14 strategy: matrix: package: [ - eigensdk-rs, + test-utils, + tangle-avs, + incredible-squaring-avs, + eigen-utils, ] steps: - name: checkout code @@ -111,4 +113,4 @@ jobs: run: cargo install cargo-nextest --locked - name: tests - run: cargo nextest run --release --nocapture --package ${{ matrix.package }} \ No newline at end of file + run: cargo nextest run --release --test-threads 1 --package ${{ matrix.package }} \ No newline at end of file From 7ec39d43060f4845e6e7c009506f916ece1a0c9f Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Thu, 22 Aug 2024 15:44:39 -0500 Subject: [PATCH 41/43] Add forge to workflow testing job --- .github/workflows/validate_pr.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index 12254aa..2443038 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -95,6 +95,15 @@ jobs: - name: checkout code uses: actions/checkout@v2 + - name: Install Foundry + run: | + curl -L https://foundry.paradigm.xyz | bash + source /Users/runner/.bashrc + foundryup + + - name: Add Foundry to PATH + run: echo "${HOME}/.foundry/bin" >> $GITHUB_PATH + - name: install rust uses: dtolnay/rust-toolchain@nightly with: From 3eef19645fe8ac088b2c00d0fca6c55d2195d40c Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Thu, 22 Aug 2024 15:53:20 -0500 Subject: [PATCH 42/43] Run build scripts before tests --- .github/workflows/validate_pr.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index 2443038..9491171 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -118,6 +118,9 @@ jobs: export LIBRARY_PATH=$LIBRARY_PATH:/opt/homebrew/lib export INCLUDE_PATH=$INCLUDE_PATH:/opt/homebrew/include + - name: Cargo Check and Build Scripts + run: cargo check + - name: install cargo-nextest run: cargo install cargo-nextest --locked From d7cf7a5cd0bb7000a0e6e1055cc6b31923dff93f Mon Sep 17 00:00:00 2001 From: Tjemmmic Date: Thu, 22 Aug 2024 16:33:05 -0500 Subject: [PATCH 43/43] README and Licenses --- LICENSE-APACHE | 201 +++++++++++++++++++++++++++++++++++++++++++++++++ LICENSE-MIT | 21 ++++++ README.md | 85 +++++++++++++++------ 3 files changed, 283 insertions(+), 24 deletions(-) create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..d8a477e --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 webb + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..a80aa83 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 webb + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 909723d..aa12535 100644 --- a/README.md +++ b/README.md @@ -2,29 +2,28 @@ [![Validate PR](https://github.com/webb-tools/eigensdk-rs/actions/workflows/validate_pr.yml/badge.svg)](https://github.com/webb-tools/eigensdk-rs/actions/workflows/validate_pr.yml) [![Rust Version](https://img.shields.io/badge/rust-1.74.0%2B-blue.svg)](https://www.rust-lang.org) ---- - -[//]: # ([![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/Apache-2.0)) +[![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/Apache-2.0) -[//]: # (---) +--- -EigenSDK-RS is a Rust implementation of Layr-Lab's eigensdk-go. Additionally, it incorporates features for interacting with Tangle and utilizing Gadgets, offering a comprehensive solution for building applications with both Eigenlayer and Tangle. This SDK is a high-performance, reliable, and efficient library that integrates seamlessly with Eigen's ecosystem while leveraging the many advantages of Rust. +`eigensdk-rs` is a Rust SDK for interacting with Eigenlayer and building AVS tooling. Additionally, it incorporates features for interacting with Tangle and utilizing our [gadget](https://github.com/webb-tools/gadget), an augmented SDK for building task based AVS. Together, these two offer a comprehensive solution for building applications with both Eigenlayer and Tangle. This SDK is a high-performance, reliable, and efficient library that integrates seamlessly with Eigenlayer's ecosystem while leveraging the many advantages of Rust. -It should be noted that this SDK is still being actively developed. +It should be noted that this SDK is still being actively developed and has not undergone a professional audit. Please use at your own risk in production. --- ## Table of Contents - [**Features**](#features) - [**Getting** Started](#getting-started) - [**Installation**](#installation) - - [**Running an AVS**](#running-an-avs) +- [**Building**](#building) +- [**Usage**](#usage) + - [**Running an AVS**](#running-an-avs) - [**Testing**](#testing) - [**Running the Included Tests**](#running-the-included-tests) - [**Testing Custom Implementations**](#testing-custom-implementations) - [**Documentation**](#documentation) - [**Contributing**](#contributing) - -[//]: # (- [**License**](#license)) + - [**License**](#license) --- ## Features @@ -50,13 +49,14 @@ git clone https://github.com/webb-tools/eigensdk-rs/ cd eigensdk-rs ``` -Build the project: +--- +## Usage +### Building ```bash cargo build --release ``` - -To use EigenSDK-RS in your own Rust project, just add the following dependency to your `Cargo.toml`: +or to use EigenSDK-RS in your own Rust project, just add the following dependency to your `Cargo.toml`: ```toml [dependencies] eigensdk-rs = { git = "https://github.com/webb-tools/eigensdk-rs" } @@ -65,7 +65,7 @@ eigensdk-rs = { git = "https://github.com/webb-tools/eigensdk-rs" } ### Running an AVS To programmatically start an AVS operator: -1. Create a new operator, supplying the necessary inputs (dependent upon the AVS you are running). The following is a general example that a real implementation would closely follow: +1. Create a new operator, supplying the necessary inputs (dependent upon the AVS you are running). The following is a general example that a real implementation would closely follow. The config is dependent upon the AVS you are running. ```rust let operator = Operator::new_from_config( config, @@ -85,14 +85,51 @@ operator.start().await?; This repository both contains tests for the included AVSs and provides the tools necessary to test custom AVSs you build with this SDK. ### Running the included tests -To run the tests, use the following command inside the root directory of the AVS you would like to test: +To run the tests from the command line, you can run the following commands in the root directory: + +1. You can manually build all smart contracts, though there are build scripts to automatically build them. + ```bash -RUST_LOG=info cargo test test_anvil +./test-utils/scripts/build.sh ``` -This test starts a local Anvil testnet, deploys all the required contracts to it, and then starts an operator. -### Testing custom implementations -We include testing utilities that make it easy to run tests for custom implementations. These tools are currently in development. +2. Set the environment variables for running the tests. + +```bash +. ./test-utils/scripts/env_setup.sh +``` + +3. Run the test for the AVS you would like to test. + +Tangle AVS +```bash +cargo test -p test-utils test_tangle_full +``` +Incredible Squaring AVS +```bash +cargo test -p test-utils test_incredible_squaring_full +``` + +These full test starts a local Anvil testnet, deploys all the required contracts to it, and then starts an operator. + +### Running the Testnets as binaries + +1. Build +```bash +cargo build --release +``` + +2. Run + +Incredible Squaring AVS's Testnet +```bash +./target/release/incredible-squaring +``` + +Tangle AVS'sTestnet +```bash +./target/release/tangle +``` --- ## Contributing @@ -104,9 +141,9 @@ To contribute: 3. Make your changes and ensure tests pass. 4. Submit a pull request with a detailed description of your changes. -[//]: # (## License) - ---- -## Contact - -If you have any questions or need further information, please contact the developers [here](https://webb.tools/) +## License +Gadget is licensed under either of the following: +* Apache License, Version 2.0 + ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) +* MIT license + ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)