-
Notifications
You must be signed in to change notification settings - Fork 240
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(rpc): add
starknet_getCompiledCasm
- Loading branch information
Showing
8 changed files
with
206 additions
and
4 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
use num_bigint::BigUint; | ||
use num_traits::Num; | ||
use serde::{Deserialize, Serialize}; | ||
|
||
/// A contract in the Starknet network. | ||
#[derive(Debug, Serialize, Deserialize)] | ||
pub struct CasmContractClass { | ||
pub bytecode: Vec<BigUintAsHex>, | ||
pub bytecode_segment_lengths: Option<NestedIntList>, | ||
pub compiler_version: String, | ||
pub hints: serde_json::Value, | ||
pub entry_points_by_type: CasmContractEntryPoints, | ||
#[serde( | ||
serialize_with = "serialize_big_uint", | ||
deserialize_with = "deserialize_big_uint" | ||
)] | ||
pub prime: BigUint, | ||
} | ||
|
||
/// The entry points (functions) of a contract. | ||
#[derive(Debug, Serialize, Deserialize)] | ||
pub struct CasmContractEntryPoints { | ||
#[serde(rename = "EXTERNAL")] | ||
pub external: Vec<CasmContractEntryPoint>, | ||
#[serde(rename = "L1_HANDLER")] | ||
pub l1_handler: Vec<CasmContractEntryPoint>, | ||
#[serde(rename = "CONSTRUCTOR")] | ||
pub constructor: Vec<CasmContractEntryPoint>, | ||
} | ||
|
||
/// An entry point (function) of a contract. | ||
#[derive(Debug, Serialize, Deserialize)] | ||
pub struct CasmContractEntryPoint { | ||
/// A field element that encodes the signature of the called function. | ||
#[serde( | ||
serialize_with = "serialize_big_uint", | ||
deserialize_with = "deserialize_big_uint" | ||
)] | ||
pub selector: BigUint, | ||
/// The offset of the instruction that should be called within the contract | ||
/// bytecode. | ||
pub offset: usize, | ||
// List of builtins. | ||
pub builtins: Vec<String>, | ||
} | ||
|
||
/// A field element that encodes the signature of the called function. | ||
#[derive(Debug, Serialize, Deserialize)] | ||
#[serde(transparent)] | ||
pub struct BigUintAsHex { | ||
/// A field element that encodes the signature of the called function. | ||
#[serde( | ||
serialize_with = "serialize_big_uint", | ||
deserialize_with = "deserialize_big_uint" | ||
)] | ||
pub value: BigUint, | ||
} | ||
|
||
pub fn serialize_big_uint<S>(num: &BigUint, serializer: S) -> Result<S::Ok, S::Error> | ||
where | ||
S: serde::Serializer, | ||
{ | ||
serializer.serialize_str(&format!("{num:#x}")) | ||
} | ||
|
||
pub fn deserialize_big_uint<'a, D>(deserializer: D) -> Result<BigUint, D::Error> | ||
where | ||
D: serde::Deserializer<'a>, | ||
{ | ||
let s = &<String as serde::Deserialize>::deserialize(deserializer)?; | ||
match s.strip_prefix("0x") { | ||
Some(num_no_prefix) => BigUint::from_str_radix(num_no_prefix, 16) | ||
.map_err(|error| serde::de::Error::custom(format!("{error}"))), | ||
None => Err(serde::de::Error::custom(format!( | ||
"{s} does not start with `0x` is missing." | ||
))), | ||
} | ||
} | ||
|
||
/// NestedIntList is either a list of NestedIntList or an integer. | ||
/// E.g., `[0, [1, 2], [3, [4]]]`. | ||
/// | ||
/// Used to represents the lengths of the segments in a contract, which are in a | ||
/// form of a tree. | ||
/// | ||
/// For example, the contract may be segmented by functions, where each function | ||
/// is segmented by its branches. It is also possible to have the inner | ||
/// segmentation only for some of the functions, while others are kept as | ||
/// non-segmented leaves in the tree. | ||
#[derive(Debug, Serialize, Deserialize)] | ||
#[serde(untagged)] | ||
pub enum NestedIntList { | ||
Leaf(usize), | ||
Node(Vec<NestedIntList>), | ||
} | ||
|
||
impl TryFrom<&str> for CasmContractClass { | ||
type Error = serde_json::Error; | ||
|
||
fn try_from(value: &str) -> Result<Self, Self::Error> { | ||
serde_json::from_str(value) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
use anyhow::Context; | ||
use pathfinder_common::casm_class::CasmContractClass; | ||
use pathfinder_common::ClassHash; | ||
|
||
use crate::context::RpcContext; | ||
use crate::error::ApplicationError; | ||
|
||
#[derive(Debug)] | ||
pub struct Input { | ||
pub class_hash: ClassHash, | ||
} | ||
|
||
impl crate::dto::DeserializeForVersion for Input { | ||
fn deserialize(value: crate::dto::Value) -> Result<Self, serde_json::Error> { | ||
value.deserialize_map(|value| { | ||
Ok(Self { | ||
class_hash: ClassHash(value.deserialize("class_hash")?), | ||
}) | ||
}) | ||
} | ||
} | ||
|
||
#[derive(Debug)] | ||
pub struct Output(CasmContractClass); | ||
|
||
impl crate::dto::serialize::SerializeForVersion for Output { | ||
fn serialize( | ||
&self, | ||
serializer: crate::dto::serialize::Serializer, | ||
) -> Result<crate::dto::serialize::Ok, crate::dto::serialize::Error> { | ||
self.0.serialize(serializer) | ||
} | ||
} | ||
|
||
#[derive(Debug)] | ||
pub enum Error { | ||
CompilationFailed, | ||
ClassHashNotFound(ClassHash), | ||
Internal(anyhow::Error), | ||
} | ||
|
||
impl From<anyhow::Error> for Error { | ||
fn from(error: anyhow::Error) -> Self { | ||
Self::Internal(error) | ||
} | ||
} | ||
|
||
impl From<Error> for crate::jsonrpc::RpcError { | ||
fn from(error: Error) -> Self { | ||
match error { | ||
Error::CompilationFailed => Self::ApplicationError(ApplicationError::CompilationFailed), | ||
Error::ClassHashNotFound(_) => { | ||
Self::ApplicationError(ApplicationError::ClassHashNotFound) | ||
} | ||
Error::Internal(e) => Self::InternalError(e), | ||
} | ||
} | ||
} | ||
|
||
/// Get the compiled casm for a given class hash. | ||
pub async fn get_compiled_casm(context: RpcContext, input: Input) -> Result<Output, Error> { | ||
let span = tracing::Span::current(); | ||
let jh = tokio::task::spawn_blocking(move || -> Result<Output, Error> { | ||
let _g = span.enter(); | ||
|
||
let mut db = context | ||
.storage | ||
.connection() | ||
.context("Opening database connection") | ||
.map_err(Error::Internal)?; | ||
|
||
let tx = db | ||
.transaction() | ||
.context("Creating database transaction") | ||
.map_err(Error::Internal)?; | ||
|
||
// Get the class definition | ||
let casm_definition = tx | ||
.casm_definition(input.class_hash) | ||
.context("Fetching class definition") | ||
.map_err(Error::Internal)? | ||
.ok_or(Error::ClassHashNotFound(input.class_hash))?; | ||
|
||
// Convert to JSON string | ||
let casm_definition_str = String::from_utf8_lossy(&casm_definition); | ||
|
||
// Parse the casm definition | ||
let casm_contract_class = CasmContractClass::try_from(casm_definition_str.as_ref()) | ||
.context("Parsing casm definition") | ||
.map_err(|_| Error::CompilationFailed)?; | ||
|
||
Ok(Output(casm_contract_class)) | ||
}); | ||
|
||
jh.await.context("Fetching compiled casm")? | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters