Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main' into events
Browse files Browse the repository at this point in the history
  • Loading branch information
jbcaron committed Feb 10, 2024
2 parents b2add95 + f0f3373 commit 28782f6
Show file tree
Hide file tree
Showing 21 changed files with 166 additions and 404 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ git # Madara Changelog
## Next release

- fix: get_events paging with continuation_token
- fux(getStorageAt): #28
- fix(genesis): #107

- fix(class): #32 #33 #34
- fix(class): #116
- feat(class): download classes from sequencer
Expand Down
11 changes: 7 additions & 4 deletions Cargo.lock

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

3 changes: 0 additions & 3 deletions crates/client/deoxys/src/commitments/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,6 @@ where
let mut bonsai_storage =
BonsaiStorage::<_, _, Pedersen>::new(bonsai_db, config).expect("Failed to create bonsai storage");

let root_hash = bonsai_storage.root_hash().expect("Failed to get root hash");
println!("Root hash: {}", root_hash);
let mut id_builder = BasicIdBuilder::new();

let zero = id_builder.new_id();
Expand All @@ -86,7 +84,6 @@ where

let root_hash = bonsai_storage.root_hash().expect("Failed to get root hash");
bonsai_storage.revert_to(zero).unwrap();
println!("Root hash 2: {:?}", Felt252Wrapper::from(root_hash));

Ok(Felt252Wrapper::from(root_hash))
} else {
Expand Down
1 change: 1 addition & 0 deletions crates/client/deoxys/src/utils/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ fn deploy_transaction(tx: &p::DeployTransaction) -> mp_transactions::DeployTrans
mp_transactions::DeployTransaction {
version: starknet_api::transaction::TransactionVersion(felt(tx.version)),
class_hash: felt(tx.class_hash).into(),
contract_address: felt(tx.contract_address).into(),
contract_address_salt: felt(tx.contract_address_salt).into(),
constructor_calldata: tx.constructor_calldata.iter().copied().map(felt).map(Into::into).collect(),
}
Expand Down
4 changes: 2 additions & 2 deletions crates/client/genesis-data-provider/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
[package]
name = "mc-genesis-data-provider"
authors.workspace = true
edition.workspace = true
name = "mc-genesis-data-provider"
repository.workspace = true
version.workspace = true

[dependencies]
anyhow = { workspace = true }
jsonrpsee = { workspace = true, default-features = true }
log = { workspace = true, default-features = true }
mp-genesis-config = { workspace = true }
mp-genesis-config = { workspace = true, default-features = true }
pallet-starknet = { workspace = true, default-features = true }
serde = { workspace = true, default-features = true }
serde_json = { workspace = true, default-features = true }
Expand Down
14 changes: 0 additions & 14 deletions crates/client/rpc-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use serde_with::serde_as;
pub mod utils;

use mp_transactions::TransactionStatus;
use pallet_starknet::genesis_loader::PredeployedAccount;
use starknet_core::serde::unsigned_field_element::UfeHex;
use starknet_core::types::{
BlockHashAndNumber, BlockId, BroadcastedDeclareTransaction, BroadcastedDeployAccountTransaction,
Expand All @@ -30,19 +29,6 @@ use starknet_core::types::{
#[derive(Serialize, Deserialize)]
pub struct Felt(#[serde_as(as = "UfeHex")] pub FieldElement);

#[derive(Serialize, Deserialize)]
pub struct PredeployedAccountWithBalance {
pub account: PredeployedAccount,
pub balance: FieldElement,
}

/// Madara rpc interface for additional features.
#[rpc(server, namespace = "madara")]
pub trait MadaraRpcApi: StarknetReadRpcApi {
#[method(name = "predeployedAccounts")]
fn predeployed_accounts(&self) -> RpcResult<Vec<PredeployedAccountWithBalance>>;
}

/// Starknet write rpc interface.
#[rpc(server, namespace = "starknet")]
pub trait StarknetWriteRpcApi {
Expand Down
47 changes: 1 addition & 46 deletions crates/client/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,7 @@ use log::error;
use mc_deoxys::utility::get_highest_block_hash_and_number;
use mc_genesis_data_provider::GenesisProvider;
pub use mc_rpc_core::utils::*;
pub use mc_rpc_core::{
Felt, MadaraRpcApiServer, PredeployedAccountWithBalance, StarknetReadRpcApiServer, StarknetTraceRpcApiServer,
StarknetWriteRpcApiServer,
};
pub use mc_rpc_core::{Felt, StarknetReadRpcApiServer, StarknetTraceRpcApiServer, StarknetWriteRpcApiServer};
use mc_storage::OverrideHandle;
use mp_block::BlockStatus;
use mp_contract::class::ContractClassWrapper;
Expand Down Expand Up @@ -58,7 +55,6 @@ use starknet_core::types::{
MaybePendingTransactionReceipt, MsgFromL1, StateDiff, StateUpdate, SyncStatus, SyncStatusType, Transaction,
TransactionExecutionStatus, TransactionFinalityStatus, TransactionReceipt,
};
use starknet_core::utils::get_selector_from_name;

use crate::constants::{MAX_EVENTS_CHUNK_SIZE, MAX_EVENTS_KEYS};
use crate::types::RpcEventFilter;
Expand Down Expand Up @@ -259,47 +255,6 @@ where
/// Taken from https://github.com/paritytech/substrate/blob/master/client/rpc/src/author/mod.rs#L78
const TX_SOURCE: TransactionSource = TransactionSource::External;

impl<A, B, BE, G, C, P, H> MadaraRpcApiServer for Starknet<A, B, BE, G, C, P, H>
where
A: ChainApi<Block = B> + 'static,
B: BlockT,
BE: Backend<B> + 'static,
C: HeaderBackend<B> + BlockBackend<B> + StorageProvider<B, BE> + 'static,
C: ProvideRuntimeApi<B>,
G: GenesisProvider + Send + Sync + 'static,
C::Api: StarknetRuntimeApi<B> + ConvertTransactionRuntimeApi<B>,
P: TransactionPool<Block = B> + 'static,
H: HasherT + Send + Sync + 'static,
{
fn predeployed_accounts(&self) -> RpcResult<Vec<PredeployedAccountWithBalance>> {
let genesis_data = self.genesis_provider.load_genesis_data()?;
let block_id = BlockId::Tag(BlockTag::Latest);
let fee_token_address: FieldElement = genesis_data.fee_token_address.0;

Ok(genesis_data
.predeployed_accounts
.into_iter()
.map(|account| {
let contract_address: FieldElement = account.contract_address.into();
let balance_string = &self
.call(
FunctionCall {
contract_address: fee_token_address,
entry_point_selector: get_selector_from_name("balanceOf")
.expect("the provided method name should be a valid ASCII string."),
calldata: vec![contract_address],
},
block_id,
)
.expect("FunctionCall attributes should be correct.")[0];
let balance =
Felt252Wrapper::from_hex_be(balance_string).expect("`balanceOf` should return a Felt").into();
PredeployedAccountWithBalance { account, balance }
})
.collect::<Vec<_>>())
}
}

#[async_trait]
impl<A, B, BE, G, C, P, H> StarknetWriteRpcApiServer for Starknet<A, B, BE, G, C, P, H>
where
Expand Down
86 changes: 28 additions & 58 deletions crates/node/src/chain_spec.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
use std::path::PathBuf;

use madara_runtime::{AuraConfig, GrandpaConfig, RuntimeGenesisConfig, SealingMode, SystemConfig, WASM_BINARY};
use pallet_starknet::genesis_loader::{GenesisData, GenesisLoader};
use sc_service::{BasePath, ChainType};
use pallet_starknet::genesis_loader::GenesisData;
use pallet_starknet::GenesisConfig;
use sc_service::ChainType;
use serde::{Deserialize, Serialize};
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_consensus_grandpa::AuthorityId as GrandpaId;
use sp_core::storage::Storage;
use sp_core::{Pair, Public};
use sp_state_machine::BasicExternalities;
use starknet_providers::sequencer::models::BlockId;
use starknet_providers::SequencerGatewayProvider;
use tokio::runtime::Runtime;

use crate::constants::DEV_CHAIN_ID;

pub const GENESIS_ASSETS_DIR: &str = "genesis-assets/";
pub const GENESIS_ASSETS_FILE: &str = "genesis.json";

/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.
pub type ChainSpec = sc_service::GenericChainSpec<RuntimeGenesisConfig>;
Expand Down Expand Up @@ -54,9 +55,10 @@ pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) {
(get_from_seed::<AuraId>(s), get_from_seed::<GrandpaId>(s))
}

pub fn development_config(sealing: SealingMode, base_path: BasePath) -> Result<DevChainSpec, String> {
pub fn development_config(sealing: SealingMode) -> Result<DevChainSpec, String> {
let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?;
let chain_id = DEV_CHAIN_ID;
let genesis_loader = load_genesis()?;

Ok(DevChainSpec::from_genesis(
// Name
Expand All @@ -65,11 +67,9 @@ pub fn development_config(sealing: SealingMode, base_path: BasePath) -> Result<D
chain_id,
ChainType::Development,
move || {
let genesis_loader = load_genesis(base_path.config_dir(chain_id));

DevGenesisExt {
genesis_config: testnet_genesis(
genesis_loader,
genesis_loader.clone(),
wasm_binary,
// Initial PoA authorities
vec![authority_keys_from_seed("Alice")],
Expand All @@ -92,44 +92,9 @@ pub fn development_config(sealing: SealingMode, base_path: BasePath) -> Result<D
))
}

pub fn local_testnet_config(base_path: BasePath, chain_id: &str) -> Result<ChainSpec, String> {
pub fn deoxys_config(sealing: SealingMode, chain_id: &str) -> Result<DevChainSpec, String> {
let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?;

let owned_chain_id = chain_id.to_owned();

Ok(ChainSpec::from_genesis(
// Name
"Local Testnet",
// ID
chain_id,
ChainType::Local,
move || {
testnet_genesis(
load_genesis(base_path.config_dir(&owned_chain_id)),
wasm_binary,
// Initial PoA authorities
// Intended to be only 2
vec![authority_keys_from_seed("Alice"), authority_keys_from_seed("Bob")],
true,
)
},
// Bootnodes
vec![],
// Telemetry
None,
// Protocol ID
None,
// Properties
None,
None,
// Extensions
None,
))
}

pub fn deoxys_config(sealing: SealingMode, base_path: BasePath, chain_id: &str) -> Result<DevChainSpec, String> {
let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?;
let owned_chain_id = chain_id.to_owned();
let genesis_loader = load_genesis()?;

Ok(DevChainSpec::from_genesis(
// Name
Expand All @@ -138,11 +103,11 @@ pub fn deoxys_config(sealing: SealingMode, base_path: BasePath, chain_id: &str)
chain_id,
ChainType::Development,
move || {
let genesis_loader = load_genesis(base_path.config_dir(&owned_chain_id));
log::info!("🔃 Loading Deoxys config");

DevGenesisExt {
genesis_config: testnet_genesis(
genesis_loader,
genesis_loader.clone(),
wasm_binary,
// Initial PoA authorities
vec![authority_keys_from_seed("Alice")],
Expand All @@ -165,24 +130,29 @@ pub fn deoxys_config(sealing: SealingMode, base_path: BasePath, chain_id: &str)
))
}

fn load_genesis(data_path: PathBuf) -> GenesisLoader {
let genesis_path = data_path.join(GENESIS_ASSETS_DIR).join(GENESIS_ASSETS_FILE);
log::debug!("🧪 Loading genesis data at : {}", genesis_path.display());
let genesis_file_content = std::fs::read_to_string(genesis_path)
.expect("Failed to read genesis file. Please run `madara setup` before opening an issue.");
let genesis_data: GenesisData = serde_json::from_str(&genesis_file_content).expect("Failed loading genesis");

GenesisLoader::new(data_path, genesis_data)
fn load_genesis() -> Result<GenesisData, String> {
log::info!("🧪 Fetching genesis block");
let runtime = Runtime::new().unwrap();
let provider = SequencerGatewayProvider::starknet_alpha_mainnet();
let diff = runtime.block_on(async {
provider
.get_state_update(BlockId::Number(0))
.await
.map(|state_update| state_update.state_diff)
.map_err(|e| format!("Failed to get state update {e}"))
})?;

Ok(GenesisData::from(diff))
}

/// Configure initial storage state for FRAME modules.
fn testnet_genesis(
genesis_loader: GenesisLoader,
genesis_loader: GenesisData,
wasm_binary: &[u8],
initial_authorities: Vec<(AuraId, GrandpaId)>,
_enable_println: bool,
) -> RuntimeGenesisConfig {
let starknet_genesis_config: madara_runtime::pallet_starknet::GenesisConfig<_> = genesis_loader.into();
let starknet_genesis_config = GenesisConfig::from(genesis_loader);

RuntimeGenesisConfig {
system: SystemConfig {
Expand Down
14 changes: 2 additions & 12 deletions crates/node/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,11 @@ impl SubstrateCli for Cli {
Ok(match id {
DEV_CHAIN_ID => {
let sealing = self.run.sealing.map(Into::into).unwrap_or_default();
let base_path = self.run.base_path().map_err(|e| e.to_string())?;
Box::new(chain_spec::development_config(sealing, base_path)?)
}
#[cfg(feature = "sharingan")]
SHARINGAN_CHAIN_ID => Box::new(chain_spec::ChainSpec::from_json_bytes(
&include_bytes!("../../../configs/chain-specs/testnet-sharingan-raw.json")[..],
)?),
"" | "local" | "madara-local" => {
let base_path = self.run.base_path().map_err(|e| e.to_string())?;
Box::new(chain_spec::local_testnet_config(base_path, id)?)
Box::new(chain_spec::development_config(sealing)?)
}
"starknet" => {
let sealing = self.run.sealing.map(Into::into).unwrap_or_default();
let base_path = self.run.base_path().map_err(|e| e.to_string())?;
Box::new(chain_spec::deoxys_config(sealing, base_path, id)?)
Box::new(chain_spec::deoxys_config(sealing, id)?)
}
path_or_url => Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path_or_url))?),
})
Expand Down
Loading

0 comments on commit 28782f6

Please sign in to comment.