Skip to content

Commit

Permalink
chore: move Starknet core contract bindings and Anvil sandbox to Zaun (
Browse files Browse the repository at this point in the history
  • Loading branch information
m-kus authored Jan 29, 2024
1 parent 8b49fec commit 24f4cec
Show file tree
Hide file tree
Showing 31 changed files with 528 additions and 9,548 deletions.
3 changes: 0 additions & 3 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,3 @@
[submodule "madara-tsukuyomi"]
path = madara-tsukuyomi
url = https://github.com/keep-starknet-strange/madara-tsukuyomi
[submodule "zaun"]
path = zaun
url = https://github.com/keep-starknet-strange/zaun
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@
- dev: add avail and celestia crates behind a feature flag
- dev: replace md5 with sha3_256 hash function
- feat: fixing getNonce Rpc Call and adding a new test
- refactor: use Zaun crate for Starknet core contract bindings
- refactor: use Anvil sandbox from Zaun crate
- feat(rpc) : estimateMessageFee RPC call implementation

## v0.6.0
Expand Down
47 changes: 33 additions & 14 deletions Cargo.lock

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

5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,10 @@ cairo-lang-utils = { git = "https://github.com/keep-starknet-strange/cairo.git",
ethers = { git = "https://github.com/gakonst/ethers-rs", rev = "f0e5b194f09c533feb10d1a686ddb9e5946ec107" }
ethers-solc = { git = "https://github.com/gakonst/ethers-rs", rev = "f0e5b194f09c533feb10d1a686ddb9e5946ec107" }

# Zaun
zaun-sandbox = { git = "https://github.com/keep-starknet-strange/zaun", package = "sandbox" }
starknet-core-contract-client = { git = "https://github.com/keep-starknet-strange/zaun" }

# Other third party dependencies
anyhow = "1.0.75"
flate2 = "1.0.28"
Expand Down Expand Up @@ -270,6 +274,7 @@ assert_matches = "1.5.0"
async-lock = "3.1.0"
rustc-hex = { version = "2.0.0" }
itertools = "0.12.0"
tempfile = "3.2"

[patch."https://github.com/w3f/ring-vrf"]
bandersnatch_vrfs = { git = "https://github.com/w3f/ring-vrf?rev=3ddc20", version = "0.0.4", rev = "3ddc20" }
3 changes: 3 additions & 0 deletions crates/client/l1-messages/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ sp-runtime = { workspace = true, default-features = true }
sc-client-api = { workspace = true, default-features = true }
sc-transaction-pool-api = { workspace = true, default-features = true }

# Zaun
starknet-core-contract-client = { workspace = true }

# Other third party dependencies
ethers = { workspace = true }
serde = { workspace = true, default-features = true }
Expand Down
61 changes: 26 additions & 35 deletions crates/client/l1-messages/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
use ethers::contract::abigen;
use mp_felt::{Felt252Wrapper, Felt252WrapperError};
use mp_transactions::HandleL1MessageTransaction;

abigen!(
L1Contract,
r"[
event LogMessageToL2(address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce, uint256 fee)
]"
);
use starknet_core_contract_client::interfaces::LogMessageToL2Filter;

#[derive(thiserror::Error, Debug, PartialEq)]
#[allow(clippy::enum_variant_names)]
Expand All @@ -22,31 +15,29 @@ pub enum L1EventToTransactionError {
InvalidNonce(Felt252WrapperError),
}

impl TryFrom<LogMessageToL2Filter> for HandleL1MessageTransaction {
type Error = L1EventToTransactionError;

fn try_from(event: LogMessageToL2Filter) -> Result<Self, Self::Error> {
// L2 contract to call.
let contract_address = Felt252Wrapper::try_from(sp_core::U256(event.to_address.0))
.map_err(L1EventToTransactionError::InvalidContractAddress)?;

// Function of the contract to call.
let entry_point_selector = Felt252Wrapper::try_from(sp_core::U256(event.selector.0))
.map_err(L1EventToTransactionError::InvalidEntryPointSelector)?;

// L1 message nonce.
let nonce: u64 = Felt252Wrapper::try_from(sp_core::U256(event.nonce.0))
.map_err(L1EventToTransactionError::InvalidNonce)?
.try_into()
.map_err(L1EventToTransactionError::InvalidNonce)?;

let calldata: Vec<Felt252Wrapper> = event
.payload
.iter()
.map(|param| Felt252Wrapper::try_from(sp_core::U256(param.0)))
.collect::<Result<Vec<Felt252Wrapper>, Felt252WrapperError>>()
.map_err(L1EventToTransactionError::InvalidCalldata)?;

Ok(HandleL1MessageTransaction { nonce, contract_address, entry_point_selector, calldata })
}
pub fn parse_handle_l1_message_transaction(
event: LogMessageToL2Filter,
) -> Result<HandleL1MessageTransaction, L1EventToTransactionError> {
// L2 contract to call.
let contract_address = Felt252Wrapper::try_from(sp_core::U256(event.to_address.0))
.map_err(L1EventToTransactionError::InvalidContractAddress)?;

// Function of the contract to call.
let entry_point_selector = Felt252Wrapper::try_from(sp_core::U256(event.selector.0))
.map_err(L1EventToTransactionError::InvalidEntryPointSelector)?;

// L1 message nonce.
let nonce: u64 = Felt252Wrapper::try_from(sp_core::U256(event.nonce.0))
.map_err(L1EventToTransactionError::InvalidNonce)?
.try_into()
.map_err(L1EventToTransactionError::InvalidNonce)?;

let calldata: Vec<Felt252Wrapper> = event
.payload
.iter()
.map(|param| Felt252Wrapper::try_from(sp_core::U256(param.0)))
.collect::<Result<Vec<Felt252Wrapper>, Felt252WrapperError>>()
.map_err(L1EventToTransactionError::InvalidCalldata)?;

Ok(HandleL1MessageTransaction { nonce, contract_address, entry_point_selector, calldata })
}
13 changes: 8 additions & 5 deletions crates/client/l1-messages/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ use sp_runtime::traits::Block as BlockT;
use starknet_api::api_core::Nonce;
use starknet_api::hash::StarkFelt;
use starknet_api::transaction::Fee;
use starknet_core_contract_client::interfaces::{LogMessageToL2Filter, StarknetMessagingEvents};

use crate::config::L1MessagesWorkerConfig;
use crate::contract::{L1Contract, LogMessageToL2Filter};
use crate::contract::parse_handle_l1_message_transaction;
use crate::error::L1MessagesWorkerError;

const TX_SOURCE: TransactionSource = TransactionSource::External;
Expand All @@ -31,8 +32,10 @@ pub async fn run_worker<C, P, B>(
{
log::info!("⟠ Starting L1 Messages Worker with settings: {:?}", config);

let l1_contract =
L1Contract::new(*config.contract_address(), Arc::new(Provider::new(Http::new(config.provider().clone()))));
let event_listener = StarknetMessagingEvents::new(
*config.contract_address(),
Arc::new(Provider::new(Http::new(config.provider().clone()))),
);

let last_synced_event_block = match backend.messaging().last_synced_l1_block_with_event() {
Ok(blknum) => blknum,
Expand All @@ -42,7 +45,7 @@ pub async fn run_worker<C, P, B>(
}
};

let events = l1_contract.events().from_block(last_synced_event_block.block_number);
let events = event_listener.event::<LogMessageToL2Filter>().from_block(last_synced_event_block.block_number);
let mut event_stream = match events.stream_with_meta().await {
Ok(stream) => stream,
Err(e) => {
Expand Down Expand Up @@ -109,7 +112,7 @@ where
} else {
Fee(event.fee.as_u128())
};
let transaction: HandleL1MessageTransaction = event.try_into()?;
let transaction: HandleL1MessageTransaction = parse_handle_l1_message_transaction(event)?;

let best_block_hash = client.info().best_hash;

Expand Down
3 changes: 3 additions & 0 deletions crates/client/settlement/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ pallet-starknet-runtime-api = { workspace = true, default-features = true }
# Ethereum
ethers = { workspace = true }

# Zaun
starknet-core-contract-client = { workspace = true }

# Others
log = { workspace = true }
rustc-hex = { workspace = true }
Expand Down
22 changes: 6 additions & 16 deletions crates/client/settlement/src/ethereum/client.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use std::sync::Arc;
use std::time::Duration;

use ethers::prelude::{abigen, SignerMiddleware};
use ethers::prelude::SignerMiddleware;
use ethers::providers::{Http, Provider};
use ethers::signers::{LocalWallet, Signer};
use ethers::types::{Address, TransactionReceipt, I256, U256};
pub use mc_data_availability::ethereum::config::EthereumConfig;
use starknet_core_contract_client::interfaces::StarknetSovereignContract;
use starknet_core_contract_client::LocalWalletSignerMiddleware;

use crate::ethereum::errors::{Error, Result};

Expand Down Expand Up @@ -37,26 +39,14 @@ use crate::ethereum::errors::{Error, Result};
//
// Read this great overview to learn more about SNOS:
// https://hackmd.io/@pragma/ByP-iux1T
abigen!(
StarknetContract,
r#"[
function programHash() public view returns (uint256)
function stateBlockNumber() external view returns (int256)
function stateRoot() external view returns (uint256)
function configHash() public view returns (uint256)
function updateState(uint256[] calldata programOutput) external
]"#,
);

pub type LocalMiddleware = SignerMiddleware<Provider<Http>, LocalWallet>;

pub struct StarknetContractClient {
contract: StarknetContract<LocalMiddleware>,
contract: StarknetSovereignContract<LocalWalletSignerMiddleware>,
}

impl StarknetContractClient {
pub fn new(address: Address, client: Arc<LocalMiddleware>) -> Self {
Self { contract: StarknetContract::new(address, client) }
pub fn new(address: Address, client: Arc<LocalWalletSignerMiddleware>) -> Self {
Self { contract: StarknetSovereignContract::new(address, client) }
}

pub async fn state_block_number(&self) -> Result<I256> {
Expand Down
4 changes: 2 additions & 2 deletions crates/client/settlement/src/ethereum/errors.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::client::LocalMiddleware;
use starknet_core_contract_client::LocalWalletSignerMiddleware;

/// Ethereum client error type.
#[derive(thiserror::Error, Debug)]
Expand All @@ -14,7 +14,7 @@ pub enum Error {
HexParser(#[from] rustc_hex::FromHexError),

#[error("Error while interacting with contract: {0}")]
Contract(#[from] ethers::contract::ContractError<LocalMiddleware>),
Contract(#[from] ethers::contract::ContractError<LocalWalletSignerMiddleware>),

#[error("HTTP provider error: {0}")]
Provider(#[from] ethers::providers::ProviderError),
Expand Down
16 changes: 8 additions & 8 deletions crates/node/src/commands/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,14 +207,14 @@ pub fn run_node(mut cli: Cli) -> Result<()> {

let settlement_config: Option<(SettlementLayer, PathBuf)> = match cli.run.settlement {
Some(SettlementLayer::Ethereum) => {
let settlement_conf = cli.run.clone().settlement_conf.unwrap_or({
let path_sett_conf_json = chain_config_dir.join("settlement_conf.json");
if !path_sett_conf_json.exists() {
return Err(sc_cli::Error::Input("no file settlement_conf in base_path".to_string()));
}
path_sett_conf_json
});

let settlement_conf =
cli.run.clone().settlement_conf.unwrap_or_else(|| chain_config_dir.join("settlement_conf.json"));
if !settlement_conf.exists() {
return Err(sc_cli::Error::Input(format!(
"Settlement config does not exist: {}",
settlement_conf.display()
)));
}
Some((SettlementLayer::Ethereum, settlement_conf))
}

Expand Down
1 change: 1 addition & 0 deletions madara-test-runner/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ starknet-ff = { workspace = true }
starknet-providers = { workspace = true }
starknet-signers = { workspace = true }
starknet_api = { workspace = true, default-features = true }
tempfile = { workspace = true }
thiserror = { workspace = true }
tokio = { version = "1.29.1", features = ["rt", "macros", "parking_lot"] }
url = "2.4.1"
Expand Down
Loading

0 comments on commit 24f4cec

Please sign in to comment.