Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

style: format code with Rustfmt #26

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 41 additions & 13 deletions crates/da-clients/ethereum/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use std::path::Path;
use std::str::FromStr;

use alloy::consensus::{
BlobTransactionSidecar, SignableTransaction, TxEip4844, TxEip4844Variant, TxEip4844WithSidecar, TxEnvelope,
BlobTransactionSidecar, SignableTransaction, TxEip4844, TxEip4844Variant, TxEip4844WithSidecar,
TxEnvelope,
};
use alloy::eips::eip2718::Encodable2718;
use alloy::eips::eip2930::AccessList;
Expand Down Expand Up @@ -44,16 +45,26 @@ impl DaClient for EthereumDaClient {
let wallet = &self.wallet;
let addr = wallet.address();

let (sidecar_blobs, sidecar_commitments, sidecar_proofs) = prepare_sidecar(&state_diff, trusted_setup).await?;
let sidecar = BlobTransactionSidecar::new(sidecar_blobs, sidecar_commitments, sidecar_proofs);
let (sidecar_blobs, sidecar_commitments, sidecar_proofs) =
prepare_sidecar(&state_diff, trusted_setup).await?;
let sidecar =
BlobTransactionSidecar::new(sidecar_blobs, sidecar_commitments, sidecar_proofs);

let eip1559_est = provider.estimate_eip1559_fees(None).await?;
let chain_id: u64 = provider.get_chain_id().await?.to_string().parse()?;

let max_fee_per_blob_gas: u128 = provider.get_blob_base_fee().await?.to_string().parse()?;
let max_priority_fee_per_gas: u128 = provider.get_max_priority_fee_per_gas().await?.to_string().parse()?;

let nonce = provider.get_transaction_count(addr, None).await?.to_string().parse()?;
let max_priority_fee_per_gas: u128 = provider
.get_max_priority_fee_per_gas()
.await?
.to_string()
.parse()?;

let nonce = provider
.get_transaction_count(addr, None)
.await?
.to_string()
.parse()?;
let to = FixedBytes(*to);

let tx = TxEip4844 {
Expand All @@ -69,7 +80,10 @@ impl DaClient for EthereumDaClient {
max_fee_per_blob_gas,
input: bytes!(),
};
let tx_sidecar = TxEip4844WithSidecar { tx: tx.clone(), sidecar: sidecar.clone() };
let tx_sidecar = TxEip4844WithSidecar {
tx: tx.clone(),
sidecar: sidecar.clone(),
};
let mut variant = TxEip4844Variant::from(tx_sidecar);

// Sign and submit
Expand Down Expand Up @@ -108,21 +122,33 @@ impl DaClient for EthereumDaClient {

impl From<EthereumDaConfig> for EthereumDaClient {
fn from(config: EthereumDaConfig) -> Self {
let client =
RpcClient::new_http(Url::from_str(config.rpc_url.as_str()).expect("Failed to parse ETHEREUM_RPC_URL"));
let client = RpcClient::new_http(
Url::from_str(config.rpc_url.as_str()).expect("Failed to parse ETHEREUM_RPC_URL"),
);
let provider = ProviderBuilder::<_, Ethereum>::new().on_client(client);
let wallet: LocalWallet = env::var("PK").expect("PK must be set").parse().expect("issue while parsing");
let wallet: LocalWallet = env::var("PK")
.expect("PK must be set")
.parse()
.expect("issue while parsing");
// let wallet: LocalWallet = config.private_key.as_str().parse();
let trusted_setup = KzgSettings::load_trusted_setup_file(Path::new("./trusted_setup.txt"))
.expect("issue while loading the trusted setup");
EthereumDaClient { provider, wallet, trusted_setup }
EthereumDaClient {
provider,
wallet,
trusted_setup,
}
}
}

async fn prepare_sidecar(
state_diff: &[Vec<u8>],
trusted_setup: &KzgSettings,
) -> Result<(Vec<FixedBytes<131072>>, Vec<FixedBytes<48>>, Vec<FixedBytes<48>>)> {
) -> Result<(
Vec<FixedBytes<131072>>,
Vec<FixedBytes<48>>,
Vec<FixedBytes<48>>,
)> {
let mut sidecar_blobs = vec![];
let mut sidecar_commitments = vec![];
let mut sidecar_proofs = vec![];
Expand Down Expand Up @@ -174,7 +200,9 @@ mod tests {

// creation of sidecar
let (_sidecar_blobs, sidecar_commitments, sidecar_proofs) =
prepare_sidecar(&[data_v8], &trusted_setup).await.expect("Error creating the sidecar blobs");
prepare_sidecar(&[data_v8], &trusted_setup)
.await
.expect("Error creating the sidecar blobs");

// blob commitment from L1
let commitment_vector = hex_string_to_u8_vec(
Expand Down
24 changes: 20 additions & 4 deletions crates/orchestrator/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,13 @@ pub async fn init_config() -> Config {
let settings_provider = DefaultSettingsProvider {};
let prover = create_prover_service(&settings_provider);

Config { starknet_client: Arc::new(provider), da_client: build_da_client(), prover_client: prover, database, queue }
Config {
starknet_client: Arc::new(provider),
da_client: build_da_client(),
prover_client: prover,
database,
queue,
}
}

impl Config {
Expand All @@ -65,7 +71,13 @@ impl Config {
database: Box<dyn Database>,
queue: Box<dyn QueueProvider>,
) -> Self {
Self { starknet_client, da_client, prover_client, database, queue }
Self {
starknet_client,
da_client,
prover_client,
database,
queue,
}
}

/// Returns the starknet client
Expand Down Expand Up @@ -103,7 +115,9 @@ pub static CONFIG: OnceCell<ArcSwap<Config>> = OnceCell::const_new();

/// Returns the app config. Initializes if not already done.
pub async fn config() -> Guard<Arc<Config>> {
let cfg = CONFIG.get_or_init(|| async { ArcSwap::from_pointee(init_config().await) }).await;
let cfg = CONFIG
.get_or_init(|| async { ArcSwap::from_pointee(init_config().await) })
.await;
cfg.load()
}

Expand All @@ -116,7 +130,9 @@ pub async fn config_force_init(config: Config) {
match CONFIG.get() {
Some(arc) => arc.store(Arc::new(config)),
None => {
CONFIG.get_or_init(|| async { ArcSwap::from_pointee(config) }).await;
CONFIG
.get_or_init(|| async { ArcSwap::from_pointee(config) })
.await;
}
}
}
Expand Down
5 changes: 4 additions & 1 deletion crates/orchestrator/src/controllers/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ impl IntoResponse for AppError {
fn into_response(self) -> axum::http::Response<axum::body::Body> {
log::error!("Error: {:?}", self);
let (status, err_msg) = match self {
Self::InternalServerError(msg) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, msg.to_string()),
Self::InternalServerError(msg) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
msg.to_string(),
),
};
(status, Json(json!({"message": err_msg }))).into_response()
}
Expand Down
14 changes: 11 additions & 3 deletions crates/orchestrator/src/database/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ pub mod mongodb;
pub trait Database: Send + Sync {
async fn create_job(&self, job: JobItem) -> Result<JobItem>;
async fn get_job_by_id(&self, id: Uuid) -> Result<Option<JobItem>>;
async fn get_job_by_internal_id_and_type(&self, internal_id: &str, job_type: &JobType) -> Result<Option<JobItem>>;
async fn get_job_by_internal_id_and_type(
&self,
internal_id: &str,
job_type: &JobType,
) -> Result<Option<JobItem>>;
async fn update_job_status(&self, job: &JobItem, new_status: JobStatus) -> Result<()>;
async fn update_external_id_and_status_and_metadata(
&self,
Expand All @@ -34,8 +38,12 @@ pub trait Database: Send + Sync {
new_status: JobStatus,
metadata: HashMap<String, String>,
) -> Result<()>;
async fn update_metadata(&self, job: &JobItem, metadata: HashMap<String, String>) -> Result<()>;
async fn get_latest_job_by_type_and_internal_id(&self, job_type: JobType) -> Result<Option<JobItem>>;
async fn update_metadata(&self, job: &JobItem, metadata: HashMap<String, String>)
-> Result<()>;
async fn get_latest_job_by_type_and_internal_id(
&self,
job_type: JobType,
) -> Result<Option<JobItem>>;
async fn get_jobs_without_successor(
&self,
job_a_type: JobType,
Expand Down
4 changes: 3 additions & 1 deletion crates/orchestrator/src/database/mongodb/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ pub struct MongoDbConfig {

impl DatabaseConfig for MongoDbConfig {
fn new_from_env() -> Self {
Self { url: get_env_var_or_panic("MONGODB_CONNECTION_STRING") }
Self {
url: get_env_var_or_panic("MONGODB_CONNECTION_STRING"),
}
}
}
46 changes: 37 additions & 9 deletions crates/orchestrator/src/database/mongodb/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,21 @@ pub struct MongoDb {

impl MongoDb {
pub async fn new(config: MongoDbConfig) -> Self {
let mut client_options = ClientOptions::parse(config.url).await.expect("Failed to parse MongoDB Url");
let mut client_options = ClientOptions::parse(config.url)
.await
.expect("Failed to parse MongoDB Url");
// Set the server_api field of the client_options object to set the version of the Stable API on the
// client
let server_api = ServerApi::builder().version(ServerApiVersion::V1).build();
client_options.server_api = Some(server_api);
// Get a handle to the cluster
let client = Client::with_options(client_options).expect("Failed to create MongoDB client");
// Ping the server to see if you can connect to the cluster
client.database("admin").run_command(doc! {"ping": 1}, None).await.expect("Failed to ping MongoDB deployment");
client
.database("admin")
.run_command(doc! {"ping": 1}, None)
.await
.expect("Failed to ping MongoDB deployment");
println!("Pinged your deployment. You successfully connected to MongoDB!");

MongoDb { client }
Expand All @@ -47,15 +53,24 @@ impl MongoDb {
/// Updates the job in the database optimistically. This means that the job is updated only if
/// the version of the job in the database is the same as the version of the job passed in.
/// If the version is different, the update fails.
async fn update_job_optimistically(&self, current_job: &JobItem, update: Document) -> Result<()> {
async fn update_job_optimistically(
&self,
current_job: &JobItem,
update: Document,
) -> Result<()> {
let filter = doc! {
"id": current_job.id,
"version": current_job.version,
};
let options = UpdateOptions::builder().upsert(false).build();
let result = self.get_job_collection().update_one(filter, update, options).await?;
let result = self
.get_job_collection()
.update_one(filter, update, options)
.await?;
if result.modified_count == 0 {
return Err(eyre!("Failed to update job. Job version is likely outdated"));
return Err(eyre!(
"Failed to update job. Job version is likely outdated"
));
}
Ok(())
}
Expand All @@ -75,7 +90,11 @@ impl Database for MongoDb {
Ok(self.get_job_collection().find_one(filter, None).await?)
}

async fn get_job_by_internal_id_and_type(&self, internal_id: &str, job_type: &JobType) -> Result<Option<JobItem>> {
async fn get_job_by_internal_id_and_type(
&self,
internal_id: &str,
job_type: &JobType,
) -> Result<Option<JobItem>> {
let filter = doc! {
"internal_id": internal_id,
"job_type": mongodb::bson::to_bson(&job_type)?,
Expand Down Expand Up @@ -111,7 +130,11 @@ impl Database for MongoDb {
Ok(())
}

async fn update_metadata(&self, job: &JobItem, metadata: HashMap<String, String>) -> Result<()> {
async fn update_metadata(
&self,
job: &JobItem,
metadata: HashMap<String, String>,
) -> Result<()> {
let update = doc! {
"$set": {
"metadata": mongodb::bson::to_document(&metadata)?
Expand All @@ -121,11 +144,16 @@ impl Database for MongoDb {
Ok(())
}

async fn get_latest_job_by_type_and_internal_id(&self, job_type: JobType) -> Result<Option<JobItem>> {
async fn get_latest_job_by_type_and_internal_id(
&self,
job_type: JobType,
) -> Result<Option<JobItem>> {
let filter = doc! {
"job_type": mongodb::bson::to_bson(&job_type)?,
};
let find_options = FindOneOptions::builder().sort(doc! { "internal_id": -1 }).build();
let find_options = FindOneOptions::builder()
.sort(doc! { "internal_id": -1 })
.build();
Ok(self
.get_job_collection()
.find_one(filter, find_options)
Expand Down
Loading
Loading