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

fix(fmt): apply cargo fmt #23

Open
wants to merge 5 commits into
base: solis-v0.7.0-alpha
Choose a base branch
from
Open
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
7 changes: 7 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions bin/solis/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ clap_complete.workspace = true
common.workspace = true
console.workspace = true
dojo-metrics.workspace = true
dotenv = "0.15.0"
katana-core.workspace = true
katana-executor.workspace = true
katana-primitives.workspace = true
Expand Down
5 changes: 3 additions & 2 deletions bin/solis/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
//! and leak detection functionality. See [jemalloc's opt.prof](https://jemalloc.net/jemalloc.3.html#opt.prof)
//! documentation for usage details. This is **not recommended on Windows**. See [here](https://rust-lang.github.io/rfcs/1974-global-allocators.html#jemalloc)
//! for more info.

use std::env;
use std::net::SocketAddr;
use std::path::PathBuf;

Expand Down Expand Up @@ -230,7 +230,8 @@ impl KatanaArgs {
}

pub fn server_config(&self) -> ServerConfig {
let mut apis = vec![ApiKind::Starknet, ApiKind::Katana, ApiKind::Torii, ApiKind::Saya, ApiKind::Solis];
let mut apis =
vec![ApiKind::Starknet, ApiKind::Katana, ApiKind::Torii, ApiKind::Saya, ApiKind::Solis];
// only enable `katana` API in dev mode
if self.dev {
apis.push(ApiKind::Dev);
Expand Down
25 changes: 7 additions & 18 deletions bin/solis/src/contracts/account.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
use starknet::{
accounts::{ExecutionEncoding, SingleOwnerAccount},
core::types::FieldElement,
providers::{jsonrpc::HttpTransport, AnyProvider, JsonRpcClient, Provider},
signers::{LocalWallet, SigningKey},
};

use starknet::accounts::{ExecutionEncoding, SingleOwnerAccount};
use starknet::core::types::FieldElement;
use starknet::providers::jsonrpc::HttpTransport;
use starknet::providers::{AnyProvider, JsonRpcClient, Provider};
use starknet::signers::{LocalWallet, SigningKey};
use url::Url;

/// Initializes a new account to interact with Starknet.
Expand All @@ -25,18 +23,9 @@ pub async fn new_account(
AnyProvider::JsonRpcHttp(JsonRpcClient::new(HttpTransport::new(rpc_url.clone())));

// TODO: need error instead of expect.
let chain_id = provider
.chain_id()
.await
.expect("couldn't get chain_id from provider");
let chain_id = provider.chain_id().await.expect("couldn't get chain_id from provider");

let signer = LocalWallet::from(SigningKey::from_secret_scalar(private_key));

SingleOwnerAccount::new(
provider,
signer,
account_address,
chain_id,
ExecutionEncoding::Legacy,
)
SingleOwnerAccount::new(provider, signer, account_address, chain_id, ExecutionEncoding::Legacy)
}
3 changes: 2 additions & 1 deletion bin/solis/src/contracts/orderbook.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use cainome::rs::abigen;
use starknet::{accounts::ConnectedAccount, core::types::FieldElement};
use starknet::accounts::ConnectedAccount;
use starknet::core::types::FieldElement;

abigen!(OrderbookContract, "./artifacts/orderbook.abi.json");

Expand Down
8 changes: 3 additions & 5 deletions bin/solis/src/contracts/starknet_utils.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use cainome::rs::abigen;
use starknet::{
core::types::FieldElement,
providers::{jsonrpc::HttpTransport, AnyProvider, JsonRpcClient},
};

use starknet::core::types::FieldElement;
use starknet::providers::jsonrpc::HttpTransport;
use starknet::providers::{AnyProvider, JsonRpcClient};
use url::Url;

abigen!(StarknetUtils, "./artifacts/starknet_utils.json");
Expand Down
120 changes: 47 additions & 73 deletions bin/solis/src/hooker.rs
Original file line number Diff line number Diff line change
@@ -1,55 +1,50 @@
//! Solis hooker on Katana transaction lifecycle.
//!
use crate::contracts::starknet_utils::{ExecutionInfo, U256};
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::path::Path;
use std::sync::Arc;

use async_trait::async_trait;
use cainome::cairo_serde::CairoSerde;
use cainome::rs::abigen;
use katana_core::hooker::{HookerAddresses, KatanaHooker};
use katana_core::sequencer::KatanaSequencer;
use katana_executor::ExecutorFactory;

use katana_primitives::chain::ChainId;
use katana_primitives::contract::ContractAddress;
use katana_primitives::transaction::{ExecutableTx, ExecutableTxWithHash, L1HandlerTx};
use katana_primitives::utils::transaction::compute_l1_message_hash;
use serde_json::{json, Value};
use starknet::accounts::Call;
use starknet::core::types::BroadcastedInvokeTransaction;
use starknet::core::types::FieldElement;
use starknet::core::types::{BroadcastedInvokeTransaction, FieldElement};
use starknet::macros::selector;
use starknet::providers::Provider;
use std::sync::Arc;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::Write;
use std::io::Read;
use serde_json::Value;
use std::path::Path;
use serde_json::json;

use crate::contracts::starknet_utils::{ExecutionInfo, U256};

const FILE_PATH_ADDRESSES: &str = "addresses.json";

use tracing::info;

use crate::contracts::orderbook::{OrderV1, RouteType};
use crate::contracts::starknet_utils::StarknetUtilsReader;
use crate::CHAIN_ID_SOLIS;
use tracing::info;

#[allow(dead_code)]
pub enum CancelStatus {
CancelledUser,
CancelledByNewOrder,
CancelledAssetFault,
CancelledOwnership,
User,
ByNewOrder,
AssetFault,
Ownership,
}

impl CancelStatus {
fn to_u32(&self) -> u32 {
match self {
CancelStatus::CancelledUser => 1,
CancelStatus::CancelledByNewOrder => 2,
CancelStatus::CancelledAssetFault => 3,
CancelStatus::CancelledOwnership => 4,
CancelStatus::User => 1,
CancelStatus::ByNewOrder => 2,
CancelStatus::AssetFault => 3,
CancelStatus::Ownership => 4,
}
}
}
Expand Down Expand Up @@ -92,10 +87,7 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>
);

// check the current owner of the token.
let owner = sn_utils_reader_nft_address
.ownerOf(&ownership_verifier.token_id)
.call()
.await;
let owner = sn_utils_reader_nft_address.ownerOf(&ownership_verifier.token_id).call().await;

if let Ok(owner_address) = owner {
if owner_address != ownership_verifier.current_owner {
Expand Down Expand Up @@ -145,10 +137,8 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>
}

// check the balance
let balance = sn_utils_reader_erc20_address
.balanceOf(&balance_verifier.offerer)
.call()
.await;
let balance =
sn_utils_reader_erc20_address.balanceOf(&balance_verifier.offerer).call().await;
if let Ok(balance) = balance {
if balance < balance_verifier.start_amount {
tracing::trace!(
Expand Down Expand Up @@ -179,10 +169,7 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>
// ERC721 to ERC20
if order.route == RouteType::Erc721ToErc20 {
let token_id = order.token_id.clone().unwrap();
let n_token_id = U256 {
low: token_id.low,
high: token_id.high,
};
let n_token_id = U256 { low: token_id.low, high: token_id.high };

let verifier = OwnershipVerifier {
token_address: ContractAddress(order.token_address.into()),
Expand All @@ -197,8 +184,8 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>
}

// ERC20 to ERC721 : we check the allowance and the offerer balance.
if order.route == RouteType::Erc20ToErc721 {
if !self
if order.route == RouteType::Erc20ToErc721
&& !self
.verify_balance(&BalanceVerifier {
currency_address: ContractAddress(order.currency_address.into()),
offerer: cainome::cairo_serde::ContractAddress(order.offerer.into()),
Expand All @@ -208,19 +195,19 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>
},
})
.await
{
println!("verify balance for starknet before failed");
return false;
}
{
println!("verify balance for starknet before failed");
return false;
}
return true;
true
}
}

impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>
SolisHooker<P, EF>
{
fn get_addresses_from_file() -> Result<(FieldElement, FieldElement), Box<dyn std::error::Error>> {
fn get_addresses_from_file() -> Result<(FieldElement, FieldElement), Box<dyn std::error::Error>>
{
let mut file = match File::open(FILE_PATH_ADDRESSES) {
Ok(file) => file,
Err(_) => return Err("File not found".into()),
Expand Down Expand Up @@ -264,7 +251,9 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>
orderbook_address: FieldElement,
sn_executor_address: FieldElement,
) -> Self {
let (orderbook_address, sn_executor_address) = if orderbook_address == FieldElement::ZERO && sn_executor_address == FieldElement::ZERO {
let (orderbook_address, sn_executor_address) = if orderbook_address == FieldElement::ZERO
&& sn_executor_address == FieldElement::ZERO
{
match Self::get_addresses_from_file() {
Ok((orderbook, executor)) => (orderbook, executor),
Err(e) => {
Expand All @@ -276,22 +265,15 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>
(orderbook_address, sn_executor_address)
};

Self {
orderbook_address,
sn_utils_reader,
sn_executor_address,
sequencer: None,
}
Self { orderbook_address, sn_utils_reader, sn_executor_address, sequencer: None }
}

/// Retrieves a reference to the sequencer.
#[allow(dead_code)]
pub fn sequencer_ref(&self) -> &Arc<KatanaSequencer<EF>> {
// The expect is used here as it must always be set by Katana core.
// If not set, the merge on Katana may be revised.
self.sequencer
.as_ref()
.expect("Sequencer must be set to get a reference to it")
self.sequencer.as_ref().expect("Sequencer must be set to get a reference to it")
}

/// Adds a `L1HandlerTransaction` to the transaction pool that is directed to the
Expand All @@ -301,8 +283,8 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>
///
/// In the case of Solis, `L1HandlerTransaction` are sent by Solis for two purposes:
/// 1. A message was collected from the L2, and it must be executed.
/// 2. A transaction has been rejected by Solis (asset faults), and the order
/// must then be updated.
/// 2. A transaction has been rejected by Solis (asset faults), and the order must then be
/// updated.
///
/// This function is used for the scenario 2. For this reason, the `from_address`
/// field is automatically filled up by the sequencer to use the executor address
Expand All @@ -329,7 +311,7 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>

// The calldata always starts with the from_address.
let mut calldata: Vec<FieldElement> = vec![from_address];
for p in payload.into_iter() {
for p in payload.iter() {
calldata.push(*p);
}

Expand Down Expand Up @@ -369,10 +351,7 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>
self.sn_executor_address = addresses.executor_starknet;

let path = Path::new(FILE_PATH_ADDRESSES);
let file = OpenOptions::new()
.write(true)
.create(true)
.open(&path);
let file = OpenOptions::new().write(true).create(true).open(path);

match file {
Ok(mut file) => {
Expand All @@ -381,7 +360,7 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>
"sn_executor_address": format!("{:#x}", self.sn_executor_address)
});

if let Err(e) = writeln!(file, "{}", data.to_string()) {
if let Err(e) = writeln!(file, "{}", data) {
eprintln!("Error writing file : {}", e);
}
}
Expand Down Expand Up @@ -412,25 +391,19 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>

/// Verifies an invoke transaction that is:
/// 1. Directed to the orderbook only.
/// 2. With the selector `create_order` only as the fulfill
/// is verified by `verify_message_to_starknet_before_tx`.
/// 2. With the selector `create_order` only as the fulfill is verified by
/// `verify_message_to_starknet_before_tx`.
async fn verify_invoke_tx_before_pool(
&self,
transaction: BroadcastedInvokeTransaction,
) -> bool {
info!(
"HOOKER: verify_invoke_tx_before_pool called with transaction: {:?}",
transaction
);
info!("HOOKER: verify_invoke_tx_before_pool called with transaction: {:?}", transaction);

let calldata = match transaction {
BroadcastedInvokeTransaction::V1(v1_transaction) => v1_transaction.calldata,
BroadcastedInvokeTransaction::V3(v3_transaction) => v3_transaction.calldata,
};
info!(
"HOOKER: cairo_deserialize called with transaction: {:?}",
calldata
);
info!("HOOKER: cairo_deserialize called with transaction: {:?}", calldata);

let calls = match Vec::<TxCall>::cairo_deserialize(&calldata, 0) {
Ok(calls) => calls,
Expand Down Expand Up @@ -482,7 +455,7 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>
let owner_ship_verification = self.verify_ownership(&verifier).await;
if !owner_ship_verification {
// rollback the status
let status = CancelStatus::CancelledOwnership;
let status = CancelStatus::Ownership;

self.add_l1_handler_transaction_for_orderbook(
selector!("rollback_status_order"),
Expand All @@ -503,7 +476,7 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>
.await
{
// rollback the status
let status = CancelStatus::CancelledAssetFault;
let status = CancelStatus::AssetFault;

self.add_l1_handler_transaction_for_orderbook(
selector!("rollback_status_order"),
Expand Down Expand Up @@ -536,9 +509,10 @@ impl<P: Provider + Sync + Send + 'static + std::fmt::Debug, EF: ExecutorFactory>

#[cfg(test)]
mod test {
use super::*;
use starknet::macros::{felt, selector};

use super::*;

#[test]
fn test_calldata_calls_parsing_new_encoding() {
// Calldata for a transaction to starkgate:
Expand Down
Loading
Loading