Skip to content

Commit

Permalink
replace all references to old FieldElement
Browse files Browse the repository at this point in the history
  • Loading branch information
kariy committed Jun 26, 2024
1 parent 49b4da3 commit 9b7b72e
Show file tree
Hide file tree
Showing 13 changed files with 52 additions and 52 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ for different languages (backends).
- **cli**: inside `src/bin/cli`, the cainome CLI binary can be built using `cargo build`: [README](./src/bin/cli/README.md).
- **lib**: inside `src/lib.rs`, the cainome library can be built using `cargo build --lib`.
- **parser**: a run-time library to parse an ABI file into `Token`s [README](./crates/parser/README.md).
- **cairo-serde**: a compile-time library that implements serialization for native Rust types from `FieldElement` buffer [README](./crates/cairo-serde/README.md).
- **cairo-serde**: a compile-time library that implements serialization for native Rust types from `Felt` buffer [README](./crates/cairo-serde/README.md).
- **rs-macro**: a compile-time library backend for the `abigen` macro to generate rust bindings [README](./crates/rs-macro/README.md).
- **rs**: a a run-time library to generated rust bindings [README](./crates/rs/README.md).
- **ts**: a compile-time library backend to generate `TypeScript` bindings (coming soon).
Expand Down
26 changes: 13 additions & 13 deletions crates/cairo-serde/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Cairo Serde

Cairo serde is a compile-time library that implement a trait `CairoSerde` on Rust native types.
By implementing this trait, the Rust type becomes (de)serializable from / into an array of `FieldElement`.
By implementing this trait, the Rust type becomes (de)serializable from / into an array of `Felt`.

## Built-in types

Expand All @@ -27,7 +27,7 @@ All those types, even if they are represented in the ABI as an `enum` or a `stru
Cairo Serde provides serialization support for the following types:

- `boolean` -> `bool`.
- `felt252` -> `starknet::core::types::FieldElement`.
- `felt252` -> `starknet::core::types::Felt`.
- `integers (signed and unsigned)` -> `u[8,16,32,64,128], i[8,16,32,64,128], usize`.
- `Option` -> `Option`
- `Result` -> `Result`
Expand All @@ -48,25 +48,25 @@ pub trait CairoSerde {
type RustType;

fn serialized_size(_rust: &Self::RustType) -> usize;
fn serialize(rust: &Self::RustType) -> Vec<FieldElement>;
fn deserialize(felts: &[FieldElement], offset: usize) -> Result<Self::RustType>;
fn serialize(rust: &Self::RustType) -> Vec<Felt>;
fn deserialize(felts: &[Felt], offset: usize) -> Result<Self::RustType>;
}
```

For now, while using the `deserilialize` method, you must provide the index in the buffer.

Some work that is in the roadmap:

- Adding a `serialize_to(rust: &Self::RustType, out: &mut Vec<FieldElement>)` to avoid allocating a new array for each type in a big felt buffer.
- Adding/modifying to `deserialize(felts: &[FieldElement]) -> Result<Self::RustType>` without the offset using rust slice. The motivation of using an explicit offset in the first version was to keep the context of the current deserialization operation in the global buffer.
- Adding a `serialize_to(rust: &Self::RustType, out: &mut Vec<Felt>)` to avoid allocating a new array for each type in a big felt buffer.
- Adding/modifying to `deserialize(felts: &[Felt]) -> Result<Self::RustType>` without the offset using rust slice. The motivation of using an explicit offset in the first version was to keep the context of the current deserialization operation in the global buffer.

## Examples

```rust
# Array/Span

# The length is automatically inserted as the first element of the `Vec`
# and all the values are converted into `FieldElement`.
# and all the values are converted into `Felt`.
let v: Vec<u32> = vec![1, 2, 3];
let felts = Vec::<u32>::serialize(&v);

Expand All @@ -80,21 +80,21 @@ let values = Vec::<u32>::deserialize(&felts, 0).unwrap();
let o: Option<u32> = None;
let felts = Option::<u32>::serialize(&o);

let felts = vec![FieldElement::ONE];
let felts = vec![Felt::ONE];
let o = Option::<u32>::deserialize(&felts, 0).unwrap();

let o = Some(u32::MAX);
let felts = Option::<u32>::serialize(&o);

let felts = vec![FieldElement::ZERO, FieldElement::from(u32::MAX)];
let felts = vec![Felt::ZERO, Felt::from(u32::MAX)];
let o = Option::<u32>::deserialize(&felts, 0).unwrap();
```

```rust
# Tuples
let v = (FieldElement::ONE, 128_u32);
let felts = <(FieldElement, u32)>::serialize(&v);
let v = (Felt::ONE, 128_u32);
let felts = <(Felt, u32)>::serialize(&v);

let felts = vec![FieldElement::THREE, 99_u32.into()];
let vals = <(FieldElement, u32)>::deserialize(&felts, 0).unwrap();
let felts = vec![Felt::THREE, 99_u32.into()];
let vals = <(Felt, u32)>::deserialize(&felts, 0).unwrap();
```
2 changes: 1 addition & 1 deletion crates/cairo-serde/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! This crate contains the definition of traits and types
//! that map to Cairo types that can then be (de)serializable from an array of `FieldElement`.
//! that map to Cairo types that can then be (de)serializable from an array of `Felt`.
//!
//! Some of the Cairo types are provided in the ABI event if they are very generic
//! like `Option`, `Result`, etc...
Expand Down
2 changes: 1 addition & 1 deletion crates/cairo-serde/src/types/byte_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ impl ByteArray {
///
/// # Arguments
///
/// * `felt` - The `FieldElement` to convert. In the context of `ByteArray` this
/// * `felt` - The `Felt` to convert. In the context of `ByteArray` this
/// felt always contains at most 31 bytes.
/// * `len` - The number of bytes in the felt, at most 31. In the context
/// of `ByteArray`, we don't need to check `len` as the `MAX_WORD_LEN`
Expand Down
14 changes: 7 additions & 7 deletions crates/rs-macro/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,24 +89,24 @@ The expansion of the macros generates the following:

// This will generate a rust struct with the make `MyStruct`:
MyStruct {
a: starknet::core::types::FieldElement,
a: starknet::core::types::Felt,
a: U256, // Note the `PascalCase` here. As `u256` is a struct, it follows the common rule.
}
```

- **Contract** type with the identifier of your choice (`MyContract` in the previous example). This type contains all the functions (externals and views) of your contract being exposed in the ABI. To initialize this type, you need the contract address and any type that implements `ConnectedAccount` from `starknet-rs`. Remember that `Arc<ConnectedAccount>` also implements `ConnectedAccount`.
```rust
let account = SingleOwnerAccount::new(...);
let contract_address = FieldElement::from_hex_be("0x1234...");
let contract_address = Felt::from_hex("0x1234...");
let contract = MyContract::new(contract_address, account);
```
- **Contract Reader** type with the identifier of your choice with the suffix `Reader` (`MyContractReader`) in the previous example. The reader contains only the views of your contract. To initialize a reader, you need the contract address and a provider from `starknet-rs`.
```rust
let provider = AnyProvider::JsonRpcHttp(...);
let contract_address = FieldElement::from_hex_be("0x1234...");
let contract_address = Felt::from_hex("0x1234...");
let contract_reader = MyContractReader::new(contract_address, &provider);
```
- For each **view**, the contract type and the contract reader type contain a function with the exact same arguments. Calling the function returns a `cainome_cairo_serde::call::FCall` struct to allow you to customize how you want the function to be called. Currently, the only setting is the `block_id`. Finally, to actually do the RPC call, you have to use `call()` method on the `FCall` struct.
- For each **view**, the contract type and the contract reader type contain a function with the exact same arguments. Calling the function returns a `cainome_cairo_serde::call::FCall` struct to allow you to customize how you want the function to be called. Currently, the only setting is the `block_id`. Finally, to actually do the RPC call, you have to use `call()` method on the `FCall` struct.
The default `block_id` value is `BlockTag::Pending`.
```rust
let my_struct = contract
Expand All @@ -120,7 +120,7 @@ The expansion of the macros generates the following:

```rust
let my_struct = MyStruct {
a: FieldElement::ONE,
a: Felt::ONE,
b: U256 {
low: 1,
high: 0,
Expand All @@ -140,7 +140,7 @@ The expansion of the macros generates the following:

```rust
// Gather the `Call`s.
let set_a_call = contract.set_a_getcall(&FieldElement::ONE);
let set_a_call = contract.set_a_getcall(&Felt::ONE);
let set_b_call = contract.set_b_getcall(&U256 { low: 0xff, high: 0 });

// Then use the account exposed by the `MyContract` type to realize the multicall.
Expand Down Expand Up @@ -191,7 +191,7 @@ The expansion of the macros generates the following:

```rust
pub struct GetBlockhashRegistryOutput {
pub address: starknet::core::types::FieldElement,
pub address: starknet::core::types::Felt,
}
```

Expand Down
12 changes: 6 additions & 6 deletions crates/rs/src/expand/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,17 @@ impl CairoContract {

#[derive(Debug)]
pub struct #contract_name<A: #snrs_accounts::ConnectedAccount + Sync> {
pub address: #snrs_types::FieldElement,
pub address: #snrs_types::Felt,
pub account: A,
pub block_id: #snrs_types::BlockId,
}

impl<A: #snrs_accounts::ConnectedAccount + Sync> #contract_name<A> {
pub fn new(address: #snrs_types::FieldElement, account: A) -> Self {
pub fn new(address: #snrs_types::Felt, account: A) -> Self {
Self { address, account, block_id: #snrs_types::BlockId::Tag(#snrs_types::BlockTag::Pending) }
}

pub fn set_contract_address(&mut self, address: #snrs_types::FieldElement) {
pub fn set_contract_address(&mut self, address: #snrs_types::Felt) {
self.address = address;
}

Expand All @@ -47,20 +47,20 @@ impl CairoContract {

#[derive(Debug)]
pub struct #reader<P: #snrs_providers::Provider + Sync> {
pub address: #snrs_types::FieldElement,
pub address: #snrs_types::Felt,
pub provider: P,
pub block_id: #snrs_types::BlockId,
}

impl<P: #snrs_providers::Provider + Sync> #reader<P> {
pub fn new(
address: #snrs_types::FieldElement,
address: #snrs_types::Felt,
provider: P,
) -> Self {
Self { address, provider, block_id: #snrs_types::BlockId::Tag(#snrs_types::BlockTag::Pending) }
}

pub fn set_contract_address(&mut self, address: #snrs_types::FieldElement) {
pub fn set_contract_address(&mut self, address: #snrs_types::Felt) {
self.address = address;
}

Expand Down
4 changes: 2 additions & 2 deletions crates/rs/src/expand/enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,13 @@ impl CairoEnum {
}
}

fn cairo_serialize(__rust: &Self::RustType) -> Vec<starknet::core::types::FieldElement> {
fn cairo_serialize(__rust: &Self::RustType) -> Vec<starknet::core::types::Felt> {
match __rust {
#(#serializations),*
}
}

fn cairo_deserialize(__felts: &[starknet::core::types::FieldElement], __offset: usize) -> #ccs::Result<Self::RustType> {
fn cairo_deserialize(__felts: &[starknet::core::types::Felt], __offset: usize) -> #ccs::Result<Self::RustType> {
let __index:u128 = __felts[__offset].try_into().unwrap();
match __index as usize {
#(#deserializations),*
Expand Down
6 changes: 3 additions & 3 deletions crates/rs/src/expand/struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,13 +184,13 @@ impl CairoStruct {
__size
}

fn cairo_serialize(__rust: &Self::RustType) -> Vec<starknet::core::types::FieldElement> {
let mut __out: Vec<starknet::core::types::FieldElement> = vec![];
fn cairo_serialize(__rust: &Self::RustType) -> Vec<starknet::core::types::Felt> {
let mut __out: Vec<starknet::core::types::Felt> = vec![];
#(#sers)*
__out
}

fn cairo_deserialize(__felts: &[starknet::core::types::FieldElement], __offset: usize) -> #ccs::Result<Self::RustType> {
fn cairo_deserialize(__felts: &[starknet::core::types::Felt], __offset: usize) -> #ccs::Result<Self::RustType> {
let mut __offset = __offset;
#(#desers)*
Ok(#struct_name {
Expand Down
4 changes: 2 additions & 2 deletions crates/rs/src/expand/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,8 @@ fn basic_types_to_rust(type_name: &str) -> String {
"ClassHash" => format!("{ccsp}::ClassHash"),
"ContractAddress" => format!("{ccsp}::ContractAddress"),
"EthAddress" => format!("{ccsp}::EthAddress"),
"felt252" => "starknet::core::types::FieldElement".to_string(),
"felt" => "starknet::core::types::FieldElement".to_string(),
"felt252" => "starknet::core::types::Felt".to_string(),
"felt" => "starknet::core::types::Felt".to_string(),
"bytes31" => format!("{ccsp}::Bytes31"),
"ByteArray" => format!("{ccsp}::ByteArray"),
"NonZero" => format!("{ccsp}::NonZero"),
Expand Down
10 changes: 5 additions & 5 deletions examples/byte_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use cainome::cairo_serde::ByteArray;
use cainome::rs::abigen;
use starknet::{
accounts::{ExecutionEncoding, SingleOwnerAccount},
core::types::FieldElement,
core::types::Felt,
providers::{jsonrpc::HttpTransport, AnyProvider, JsonRpcClient},
signers::{LocalWallet, SigningKey},
};
Expand All @@ -22,18 +22,18 @@ async fn main() {
let provider =
AnyProvider::JsonRpcHttp(JsonRpcClient::new(HttpTransport::new(rpc_url.clone())));

let contract_address = FieldElement::from_hex_be(CONTRACT_ADDRESS).unwrap();
let contract_address = Felt::from_hex(CONTRACT_ADDRESS).unwrap();

let signer = LocalWallet::from(SigningKey::from_secret_scalar(
FieldElement::from_hex_be(KATANA_PRIVKEY_0).unwrap(),
Felt::from_hex(KATANA_PRIVKEY_0).unwrap(),
));
let address = FieldElement::from_hex_be(KATANA_ACCOUNT_0).unwrap();
let address = Felt::from_hex(KATANA_ACCOUNT_0).unwrap();

let account = Arc::new(SingleOwnerAccount::new(
provider,
signer,
address,
FieldElement::from_hex_be(KATANA_CHAIN_ID).unwrap(),
Felt::from_hex(KATANA_CHAIN_ID).unwrap(),
ExecutionEncoding::New,
));

Expand Down
2 changes: 1 addition & 1 deletion examples/components_events.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use cainome::rs::abigen;
// use starknet::{
// accounts::{Account, ConnectedAccount, ExecutionEncoding, SingleOwnerAccount},
// core::types::{BlockId, BlockTag, FieldElement},
// core::types::{BlockId, BlockTag, Felt},
// providers::{jsonrpc::HttpTransport, AnyProvider, JsonRpcClient},
// signers::{LocalWallet, SigningKey},
// };
Expand Down
2 changes: 1 addition & 1 deletion examples/opt_res.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use cainome::rs::abigen;
// use starknet::{
// accounts::{Account, ConnectedAccount, ExecutionEncoding, SingleOwnerAccount},
// core::types::{BlockId, BlockTag, FieldElement},
// core::types::{BlockId, BlockTag, Felt},
// providers::{jsonrpc::HttpTransport, AnyProvider, JsonRpcClient},
// signers::{LocalWallet, SigningKey},
// };
Expand Down
18 changes: 9 additions & 9 deletions examples/simple_get_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use cainome::cairo_serde::U256;
use cainome::rs::abigen;
use starknet::{
accounts::{Account, ConnectedAccount, ExecutionEncoding, SingleOwnerAccount},
core::types::{BlockId, BlockTag, FieldElement},
core::types::{BlockId, BlockTag, Felt},
providers::{jsonrpc::HttpTransport, AnyProvider, JsonRpcClient},
signers::{LocalWallet, SigningKey},
};
Expand Down Expand Up @@ -30,7 +30,7 @@ async fn main() {
let provider =
AnyProvider::JsonRpcHttp(JsonRpcClient::new(HttpTransport::new(rpc_url.clone())));

let contract_address = FieldElement::from_hex_be(CONTRACT_ADDRESS).unwrap();
let contract_address = Felt::from_hex(CONTRACT_ADDRESS).unwrap();

// If you only plan to call views functions, you can use the `Reader`, which
// only requires a provider along with your contract address.
Expand Down Expand Up @@ -62,15 +62,15 @@ async fn main() {

// If you want to do some invoke for external functions, you must use an account.
let signer = LocalWallet::from(SigningKey::from_secret_scalar(
FieldElement::from_hex_be(KATANA_PRIVKEY_0).unwrap(),
Felt::from_hex(KATANA_PRIVKEY_0).unwrap(),
));
let address = FieldElement::from_hex_be(KATANA_ACCOUNT_0).unwrap();
let address = Felt::from_hex(KATANA_ACCOUNT_0).unwrap();

let account = Arc::new(SingleOwnerAccount::new(
provider,
signer,
address,
FieldElement::from_hex_be(KATANA_CHAIN_ID).unwrap(),
Felt::from_hex(KATANA_CHAIN_ID).unwrap(),
ExecutionEncoding::New,
));

Expand All @@ -82,7 +82,7 @@ async fn main() {
// You can before that configure the fees, or even only run an estimation of the
// fees without actually sending the transaction.
let _tx_res = contract
.set_a(&(a + FieldElement::ONE))
.set_a(&(a + Felt::ONE))
.max_fee(1000000000000000_u128.into())
.send()
.await
Expand All @@ -101,7 +101,7 @@ async fn main() {
// Now let's say we want to do multicall, and in one transaction we want to set a and b.
// You can call the same function name with `_getcall` prefix to get the
// call only, ready to be added in a multicall array.
let set_a_call = contract.set_a_getcall(&FieldElement::from_hex_be("0xee").unwrap());
let set_a_call = contract.set_a_getcall(&Felt::from_hex("0xee").unwrap());
let set_b_call = contract.set_b_getcall(&U256 { low: 0xff, high: 0 });

// Then, we use the account exposed by the contract to execute the multicall.
Expand Down Expand Up @@ -153,7 +153,7 @@ async fn other_func<A: ConnectedAccount + Sync + 'static>(contract: Arc<MyContra

// Use the estimated fees as a base.
let _tx_res = set_b
.max_fee(estimated_fee * FieldElement::TWO)
.max_fee(estimated_fee * Felt::TWO)
.send()
.await
.expect("invoke failed");
Expand All @@ -167,7 +167,7 @@ async fn other_func<A: ConnectedAccount + Sync + 'static>(contract: Arc<MyContra
.expect("Call to `get_b` failed");
println!("b set in task: {:?}", b);

let arr = vec![FieldElement::THREE, FieldElement::ONE, FieldElement::ZERO];
let arr = vec![Felt::THREE, Felt::ONE, Felt::ZERO];

let tx_res = contract
.set_array(&arr)
Expand Down

0 comments on commit 9b7b72e

Please sign in to comment.