Skip to content

Commit ab4fecd

Browse files
authored
Merge pull request #109 from KasarLabs/sync
Sync
2 parents 848da7c + 3646b4d commit ab4fecd

File tree

20 files changed

+194
-72
lines changed

20 files changed

+194
-72
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ git # Madara Changelog
33
## Next release
44

55
- feat: store events in block, return events in call get_transaction_receipt
6+
- feat(client): on `add_declare_transaction` store sierra contract classes in
7+
the madara backend
8+
- chore: use struct error in client/db
69
- fix: don't ignore Sierra to CASM mapping in genesis config
710
- refacto: early exit txs fee estimation when one fails
811
- dev: fix linter warning in README.md

Cargo.lock

Lines changed: 3 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,6 @@ starknet-core-contract-client = { git = "https://github.com/keep-starknet-strang
232232
# Other third party dependencies
233233
anyhow = "1.0.75"
234234
flate2 = "1.0.28"
235-
scale-codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false }
236235
parity-scale-codec = { version = "3.2.2", default-features = false }
237236
scale-info = { version = "2.10.0", default-features = false }
238237
lazy_static = { version = "1.4.0", default-features = false }

crates/client/db/Cargo.toml

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,16 @@ ethers = { workspace = true }
2020
kvdb-rocksdb = { version = "0.19.0", optional = true }
2121
log = { workspace = true, default-features = true }
2222
parity-db = { version = "0.4.12", optional = true }
23-
sc-client-db = { workspace = true, default-features = true }
24-
scale-codec = { workspace = true, default-features = true, features = [
23+
parity-scale-codec = { workspace = true, default-features = true, features = [
2524
"derive",
2625
] }
26+
sc-client-db = { workspace = true, default-features = true }
2727
sp-core = { workspace = true, default-features = true }
2828
sp-database = { workspace = true, default-features = true }
2929
sp-runtime = { workspace = true, default-features = true }
30-
starknet_api = { workspace = true, default-features = true }
30+
starknet_api = { workspace = true, default-features = true, features = [
31+
"parity-scale-codec",
32+
] }
3133
thiserror = { workspace = true }
3234
uuid = "1.4.1"
3335

crates/client/db/src/da_db.rs

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@ use std::sync::Arc;
33

44
use ethers::types::U256;
55
// Substrate
6-
use scale_codec::{Decode, Encode};
6+
use parity_scale_codec::{Decode, Encode};
77
use sp_database::Database;
88
use sp_runtime::traits::Block as BlockT;
99
// Starknet
1010
use starknet_api::block::BlockHash;
1111
use starknet_api::hash::StarkFelt;
1212
use uuid::Uuid;
1313

14-
use crate::DbHash;
14+
use crate::{DbError, DbHash};
1515

1616
// The fact db stores DA facts that need to be written to L1
1717
pub struct DaDb<B: BlockT> {
@@ -21,56 +21,60 @@ pub struct DaDb<B: BlockT> {
2121

2222
// TODO: purge old cairo job keys
2323
impl<B: BlockT> DaDb<B> {
24-
pub fn state_diff(&self, block_hash: &BlockHash) -> Result<Vec<U256>, String> {
24+
pub fn state_diff(&self, block_hash: &BlockHash) -> Result<Option<Vec<U256>>, DbError> {
2525
match self.db.get(crate::columns::DA, block_hash.0.bytes()) {
26-
Some(raw) => Ok(Vec::<U256>::decode(&mut &raw[..]).map_err(|e| format!("{:?}", e))?),
27-
None => Err(String::from("can't write state diff")),
26+
Some(raw) => Ok(Some(Vec::<U256>::decode(&mut &raw[..])?)),
27+
None => Ok(None),
2828
}
2929
}
3030

31-
pub fn store_state_diff(&self, block_hash: &BlockHash, diff: Vec<U256>) -> Result<(), String> {
31+
pub fn store_state_diff(&self, block_hash: &BlockHash, diff: Vec<U256>) -> Result<(), DbError> {
3232
let mut transaction = sp_database::Transaction::new();
3333

3434
transaction.set(crate::columns::DA, block_hash.0.bytes(), &diff.encode());
3535

36-
self.db.commit(transaction).map_err(|e| format!("{:?}", e))?;
36+
self.db.commit(transaction)?;
3737

3838
Ok(())
3939
}
4040

41-
pub fn cairo_job(&self, block_hash: &BlockHash) -> Result<Uuid, String> {
41+
pub fn cairo_job(&self, block_hash: &BlockHash) -> Result<Option<Uuid>, DbError> {
4242
match self.db.get(crate::columns::DA, block_hash.0.bytes()) {
43-
Some(raw) => Ok(Uuid::from_slice(&raw[..]).map_err(|e| format!("{:?}", e))?),
44-
None => Err(String::from("can't locate cairo job")),
43+
Some(raw) => Ok(Some(Uuid::from_slice(&raw[..])?)),
44+
None => Ok(None),
4545
}
4646
}
4747

48-
pub fn update_cairo_job(&self, block_hash: &BlockHash, job_id: Uuid) -> Result<(), String> {
48+
pub fn update_cairo_job(&self, block_hash: &BlockHash, job_id: Uuid) -> Result<(), DbError> {
4949
let mut transaction = sp_database::Transaction::new();
5050

5151
transaction.set(crate::columns::DA, block_hash.0.bytes(), &job_id.into_bytes());
5252

53-
self.db.commit(transaction).map_err(|e| format!("{:?}", e))?;
53+
self.db.commit(transaction)?;
5454

5555
Ok(())
5656
}
5757

58-
pub fn last_proved_block(&self) -> Result<BlockHash, String> {
58+
pub fn last_proved_block(&self) -> Result<BlockHash, DbError> {
5959
match self.db.get(crate::columns::DA, crate::static_keys::LAST_PROVED_BLOCK) {
6060
Some(raw) => {
61-
let felt = StarkFelt::deserialize(&raw[..]).ok_or("Failed to deserialize block hash")?;
61+
let felt = StarkFelt::decode(&mut &raw[..])?;
6262
Ok(BlockHash(felt))
6363
}
64-
None => Err(String::from("can't locate last proved block")),
64+
None => Err(DbError::ValueNotInitialized(
65+
crate::columns::DA,
66+
// Safe coze `LAST_PROVED_BLOCK` is utf8
67+
unsafe { std::str::from_utf8_unchecked(crate::static_keys::LAST_PROVED_BLOCK) }.to_string(),
68+
)),
6569
}
6670
}
6771

68-
pub fn update_last_proved_block(&self, block_hash: &BlockHash) -> Result<(), String> {
72+
pub fn update_last_proved_block(&self, block_hash: &BlockHash) -> Result<(), DbError> {
6973
let mut transaction = sp_database::Transaction::new();
7074

71-
transaction.set(crate::columns::DA, crate::static_keys::LAST_PROVED_BLOCK, block_hash.0.bytes());
75+
transaction.set(crate::columns::DA, crate::static_keys::LAST_PROVED_BLOCK, &block_hash.0.encode());
7276

73-
self.db.commit(transaction).map_err(|e| format!("{:?}", e))?;
77+
self.db.commit(transaction)?;
7478

7579
Ok(())
7680
}

crates/client/db/src/error.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,9 @@ pub enum DbError {
33
#[error("Failed to commit DB Update: `{0}`")]
44
CommitError(#[from] sp_database::error::DatabaseError),
55
#[error("Failed to deserialize DB Data: `{0}`")]
6-
DeserializeError(#[from] scale_codec::Error),
6+
DeserializeError(#[from] parity_scale_codec::Error),
7+
#[error("Failed to build Uuid: `{0}`")]
8+
Uuid(#[from] uuid::Error),
9+
#[error("A value was queryied that was not initialized at column: `{0}` key: `{1}`")]
10+
ValueNotInitialized(u32, String),
711
}

crates/client/db/src/lib.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,12 @@ pub use error::DbError;
1616

1717
mod mapping_db;
1818
pub use mapping_db::MappingCommitment;
19+
use sierra_classes_db::SierraClassesDb;
1920
use starknet_api::hash::StarkHash;
2021
mod da_db;
2122
mod db_opening_utils;
2223
mod messaging_db;
24+
mod sierra_classes_db;
2325
pub use messaging_db::LastSyncedEventBlock;
2426
mod meta_db;
2527

@@ -49,13 +51,14 @@ pub(crate) mod columns {
4951
// ===== /!\ ===================================================================================
5052
// MUST BE INCREMENTED WHEN A NEW COLUMN IN ADDED
5153
// ===== /!\ ===================================================================================
52-
pub const NUM_COLUMNS: u32 = 7;
54+
pub const NUM_COLUMNS: u32 = 8;
5355

5456
pub const META: u32 = 0;
5557
pub const BLOCK_MAPPING: u32 = 1;
5658
pub const TRANSACTION_MAPPING: u32 = 2;
5759
pub const SYNCED_MAPPING: u32 = 3;
5860
pub const DA: u32 = 4;
61+
5962
/// This column is used to map starknet block hashes to a list of transaction hashes that are
6063
/// contained in the block.
6164
///
@@ -64,6 +67,9 @@ pub(crate) mod columns {
6467

6568
/// This column contains last synchronized L1 block.
6669
pub const MESSAGING: u32 = 6;
70+
71+
/// This column contains the Sierra contract classes
72+
pub const SIERRA_CONTRACT_CLASSES: u32 = 7;
6773
}
6874

6975
pub mod static_keys {
@@ -82,6 +88,7 @@ pub struct Backend<B: BlockT> {
8288
mapping: Arc<MappingDb<B>>,
8389
da: Arc<DaDb<B>>,
8490
messaging: Arc<MessagingDb<B>>,
91+
sierra_classes: Arc<SierraClassesDb<B>>,
8592
}
8693

8794
/// Returns the Starknet database directory.
@@ -123,6 +130,7 @@ impl<B: BlockT> Backend<B> {
123130
meta: Arc::new(MetaDb { db: db.clone(), _marker: PhantomData }),
124131
da: Arc::new(DaDb { db: db.clone(), _marker: PhantomData }),
125132
messaging: Arc::new(MessagingDb { db: db.clone(), _marker: PhantomData }),
133+
sierra_classes: Arc::new(SierraClassesDb { db: db.clone(), _marker: PhantomData }),
126134
})
127135
}
128136

@@ -146,6 +154,11 @@ impl<B: BlockT> Backend<B> {
146154
&self.messaging
147155
}
148156

157+
/// Return the sierra classes database manager
158+
pub fn sierra_classes(&self) -> &Arc<SierraClassesDb<B>> {
159+
&self.sierra_classes
160+
}
161+
149162
/// In the future, we will compute the block global state root asynchronously in the client,
150163
/// using the Starknet-Bonzai-trie.
151164
/// That what replaces it for now :)

crates/client/db/src/mapping_db.rs

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@ use std::marker::PhantomData;
22
use std::sync::{Arc, Mutex};
33

44
// Substrate
5-
use scale_codec::{Decode, Encode};
5+
use parity_scale_codec::{Decode, Encode};
66
use sp_core::H256;
77
use sp_database::Database;
88
use sp_runtime::traits::Block as BlockT;
99

10-
use crate::DbHash;
10+
use crate::{DbError, DbHash};
1111

1212
/// The mapping to write in db
1313
#[derive(Debug)]
@@ -33,9 +33,9 @@ impl<B: BlockT> MappingDb<B> {
3333
}
3434

3535
/// Check if the given block hash has already been processed
36-
pub fn is_synced(&self, block_hash: &B::Hash) -> Result<bool, String> {
36+
pub fn is_synced(&self, block_hash: &B::Hash) -> Result<bool, DbError> {
3737
match self.db.get(crate::columns::SYNCED_MAPPING, &block_hash.encode()) {
38-
Some(raw) => Ok(bool::decode(&mut &raw[..]).map_err(|e| format!("{:?}", e))?),
38+
Some(raw) => Ok(bool::decode(&mut &raw[..])?),
3939
None => Ok(false),
4040
}
4141
}
@@ -44,28 +44,28 @@ impl<B: BlockT> MappingDb<B> {
4444
///
4545
/// Under some circumstances it can return multiples blocks hashes, meaning that the result has
4646
/// to be checked against the actual blockchain state in order to find the good one.
47-
pub fn block_hash(&self, starknet_block_hash: &H256) -> Result<Option<Vec<B::Hash>>, String> {
47+
pub fn block_hash(&self, starknet_block_hash: &H256) -> Result<Option<Vec<B::Hash>>, DbError> {
4848
match self.db.get(crate::columns::BLOCK_MAPPING, &starknet_block_hash.encode()) {
49-
Some(raw) => Ok(Some(Vec::<B::Hash>::decode(&mut &raw[..]).map_err(|e| format!("{:?}", e))?)),
49+
Some(raw) => Ok(Some(Vec::<B::Hash>::decode(&mut &raw[..])?)),
5050
None => Ok(None),
5151
}
5252
}
5353

5454
/// Register that a Substrate block has been seen, without it containing a Starknet one
55-
pub fn write_none(&self, block_hash: B::Hash) -> Result<(), String> {
55+
pub fn write_none(&self, block_hash: B::Hash) -> Result<(), DbError> {
5656
let _lock = self.write_lock.lock();
5757

5858
let mut transaction = sp_database::Transaction::new();
5959

6060
transaction.set(crate::columns::SYNCED_MAPPING, &block_hash.encode(), &true.encode());
6161

62-
self.db.commit(transaction).map_err(|e| format!("{:?}", e))?;
62+
self.db.commit(transaction)?;
6363

6464
Ok(())
6565
}
6666

6767
/// Register that a Substate block has been seen and map it to the Statknet block it contains
68-
pub fn write_hashes(&self, commitment: MappingCommitment<B>) -> Result<(), String> {
68+
pub fn write_hashes(&self, commitment: MappingCommitment<B>) -> Result<(), DbError> {
6969
let _lock = self.write_lock.lock();
7070

7171
let mut transaction = sp_database::Transaction::new();
@@ -108,7 +108,7 @@ impl<B: BlockT> MappingDb<B> {
108108
);
109109
}
110110

111-
self.db.commit(transaction).map_err(|e| format!("{:?}", e))?;
111+
self.db.commit(transaction)?;
112112

113113
Ok(())
114114
}
@@ -121,9 +121,9 @@ impl<B: BlockT> MappingDb<B> {
121121
/// * `transaction_hash` - the transaction hash to search for. H256 is used here because it's a
122122
/// native type of substrate, and we are sure it's SCALE encoding is optimized and will not
123123
/// change.
124-
pub fn block_hash_from_transaction_hash(&self, transaction_hash: H256) -> Result<Option<B::Hash>, String> {
124+
pub fn block_hash_from_transaction_hash(&self, transaction_hash: H256) -> Result<Option<B::Hash>, DbError> {
125125
match self.db.get(crate::columns::TRANSACTION_MAPPING, &transaction_hash.encode()) {
126-
Some(raw) => Ok(Some(<B::Hash>::decode(&mut &raw[..]).map_err(|e| format!("{:?}", e))?)),
126+
Some(raw) => Ok(Some(<B::Hash>::decode(&mut &raw[..])?)),
127127
None => Ok(None),
128128
}
129129
}
@@ -142,14 +142,14 @@ impl<B: BlockT> MappingDb<B> {
142142
///
143143
/// - The cache is disabled.
144144
/// - The provided `starknet_hash` is not present in the cache.
145-
pub fn cached_transaction_hashes_from_block_hash(&self, starknet_hash: H256) -> Result<Option<Vec<H256>>, String> {
145+
pub fn cached_transaction_hashes_from_block_hash(&self, starknet_hash: H256) -> Result<Option<Vec<H256>>, DbError> {
146146
if !self.cache_more_things {
147147
// The cache is not enabled, no need to even touch the database.
148148
return Ok(None);
149149
}
150150

151151
match self.db.get(crate::columns::STARKNET_TRANSACTION_HASHES_CACHE, &starknet_hash.encode()) {
152-
Some(raw) => Ok(Some(Vec::<H256>::decode(&mut &raw[..]).map_err(|e| format!("{:?}", e))?)),
152+
Some(raw) => Ok(Some(Vec::<H256>::decode(&mut &raw[..])?)),
153153
None => Ok(None),
154154
}
155155
}

crates/client/db/src/messaging_db.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::marker::PhantomData;
22
use std::sync::Arc;
33

44
// Substrate
5-
use scale_codec::{Decode, Encode};
5+
use parity_scale_codec::{Decode, Encode};
66
use sp_database::Database;
77
use sp_runtime::traits::Block as BlockT;
88

crates/client/db/src/meta_db.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ use std::marker::PhantomData;
22
use std::sync::Arc;
33

44
// Substrate
5-
use scale_codec::{Decode, Encode};
5+
use parity_scale_codec::{Decode, Encode};
66
use sp_database::Database;
77
use sp_runtime::traits::Block as BlockT;
88

9-
use crate::DbHash;
9+
use crate::{DbError, DbHash};
1010

1111
/// Allow interaction with the meta db
1212
///
@@ -19,20 +19,20 @@ pub struct MetaDb<B: BlockT> {
1919

2020
impl<B: BlockT> MetaDb<B> {
2121
/// Retrieve the current tips of the synced chain
22-
pub fn current_syncing_tips(&self) -> Result<Vec<B::Hash>, String> {
22+
pub fn current_syncing_tips(&self) -> Result<Vec<B::Hash>, DbError> {
2323
match self.db.get(crate::columns::META, crate::static_keys::CURRENT_SYNCING_TIPS) {
24-
Some(raw) => Ok(Vec::<B::Hash>::decode(&mut &raw[..]).map_err(|e| format!("{:?}", e))?),
24+
Some(raw) => Ok(Vec::<B::Hash>::decode(&mut &raw[..])?),
2525
None => Ok(Vec::new()),
2626
}
2727
}
2828

2929
/// Store the current tips of the synced chain
30-
pub fn write_current_syncing_tips(&self, tips: Vec<B::Hash>) -> Result<(), String> {
30+
pub fn write_current_syncing_tips(&self, tips: Vec<B::Hash>) -> Result<(), DbError> {
3131
let mut transaction = sp_database::Transaction::new();
3232

3333
transaction.set(crate::columns::META, crate::static_keys::CURRENT_SYNCING_TIPS, &tips.encode());
3434

35-
self.db.commit(transaction).map_err(|e| format!("{:?}", e))?;
35+
self.db.commit(transaction)?;
3636

3737
Ok(())
3838
}

0 commit comments

Comments
 (0)