Skip to content

Commit

Permalink
build with scarb for declare
Browse files Browse the repository at this point in the history
  • Loading branch information
Karol Bisztyga committed Jun 28, 2023
1 parent 03085c9 commit 5dce670
Show file tree
Hide file tree
Showing 7 changed files with 155 additions and 18 deletions.
70 changes: 69 additions & 1 deletion cast/Cargo.lock

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

2 changes: 2 additions & 0 deletions cast/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@ starknet = { git = "https://github.com/xJonathanLEI/starknet-rs" }
tokio = { version = "1.28.2", features = ["full"] }
url = "2.2.2"
rand = "0.8.5"
scarb-metadata = "1.4.2"
dirs = "5.0.1"
2 changes: 1 addition & 1 deletion cast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use camino::Utf8PathBuf;
use console::style;
use serde::{Deserialize, Serialize};
use starknet::core::types::BlockTag::{Latest, Pending};
use starknet::core::types::MaybePendingTransactionReceipt::{PendingReceipt, Receipt};
use starknet::core::types::MaybePendingTransactionReceipt::Receipt;
use starknet::core::types::TransactionReceipt::{
Declare, Deploy, DeployAccount, Invoke, L1Handler,
};
Expand Down
22 changes: 15 additions & 7 deletions cast/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use cast::{get_account, get_block_id, get_network, get_provider};
use clap::{Parser, Subcommand};
use console::style;

extern crate dirs;

mod starknet_commands;

#[derive(Parser)]
Expand All @@ -27,9 +29,8 @@ struct Cli {
#[clap(
short = 'f',
long = "accounts-file",
default_value = "~/.starknet_accounts/starknet_open_zeppelin_accounts.json"
)]
accounts_file_path: Utf8PathBuf,
accounts_file_path: Option<Utf8PathBuf>,

#[command(subcommand)]
command: Commands,
Expand All @@ -53,6 +54,10 @@ enum Commands {
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
let accounts_file_path = match cli.accounts_file_path {
Some(path) => path,
None => Utf8PathBuf::from(format!("{}/.starknet_accounts/starknet_open_zeppelin_accounts.json", dirs::home_dir().expect("failed to read the home directory").to_str().expect("failed to convert home directory to string"))),
};

// todo: #2052 take network from scarb config if flag not provided
let network_name = cli.network.unwrap_or_else(|| {
Expand All @@ -65,12 +70,15 @@ async fn main() -> Result<()> {

match cli.command {
Commands::Declare(declare) => {
let parent = accounts_file_path.parent().unwrap();
if !accounts_file_path.exists() {
anyhow::bail!("accounts file ({}) does not exist", parent);
}
let mut account =
get_account(&cli.account, &cli.accounts_file_path, &provider, &network)?;
get_account(&cli.account, &accounts_file_path, &provider, &network)?;

let declared_contract = starknet_commands::declare::declare(
&declare.sierra_contract_path,
&declare.casm_contract_path,
&declare.contract,
&mut account,
)
.await?;
Expand All @@ -80,7 +88,7 @@ async fn main() -> Result<()> {
Ok(())
}
Commands::Deploy(deploy) => {
let account = get_account(&cli.account, &cli.accounts_file_path, &provider, &network)?;
let account = get_account(&cli.account, &accounts_file_path, &provider, &network)?;

let (transaction_hash, contract_address) = starknet_commands::deploy::deploy(
&deploy.class_hash,
Expand Down Expand Up @@ -120,7 +128,7 @@ async fn main() -> Result<()> {
}
Commands::Invoke(invoke) => {
let mut account =
get_account(&cli.account, &cli.accounts_file_path, &provider, &network)?;
get_account(&cli.account, &accounts_file_path, &provider, &network)?;
starknet_commands::invoke::invoke(
&invoke.contract_address,
&invoke.entry_point_name,
Expand Down
46 changes: 37 additions & 9 deletions cast/src/starknet_commands/declare.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use anyhow::{Context, Result};
use camino::Utf8PathBuf;
use cast::wait_for_tx;
use clap::Args;
use starknet::accounts::ConnectedAccount;
Expand All @@ -13,31 +12,60 @@ use starknet::{
signers::LocalWallet,
};
use std::sync::Arc;
use std::process::Command;

#[derive(Args)]
#[command(about = "Declare a contract to starknet", long_about = None)]
pub struct Declare {
/// Path to the sierra compiled contract
pub sierra_contract_path: Utf8PathBuf,

/// Path to the casm compiled contract
pub casm_contract_path: Utf8PathBuf,
pub contract: String,
}

pub async fn declare(
sierra_contract_path: &Utf8PathBuf,
casm_contract_path: &Utf8PathBuf,
contract: &str,
account: &mut SingleOwnerAccount<&JsonRpcClient<HttpTransport>, LocalWallet>,
) -> Result<DeclareTransactionResult> {
let _ = Command::new("scarb")
.current_dir(std::env::current_dir().expect("failed to obtain current dir"))
.arg("build")
.output()
.expect("Failed to build contracts with Scarb");

let current_dir = std::env::current_dir().expect("failed to obtain current dir");
let paths = std::fs::read_dir(format!("{}/target/dev", current_dir.to_str().unwrap()))
.expect("failed to read the file maybe build failed");

let mut maybe_sierra_contract_path: Option<String> = None;
let mut maybe_casm_contract_path: Option<String> = None;
for path in paths {
let path_str = path
.expect("path not resolved properly")
.path()
.to_str()
.expect("failed to convert path to string")
.to_string();
println!("> loop: {:?}", path_str);
if path_str.contains(&contract[..]) {
if path_str.contains(".sierra.json") {
maybe_sierra_contract_path = Some(path_str);
} else if path_str.contains(".casm.json") {
maybe_casm_contract_path = Some(path_str);
}
}
}

let sierra_contract_path = maybe_sierra_contract_path.expect(&format!("no sierra found for contract: {}", contract)[..]);
let casm_contract_path = maybe_casm_contract_path.expect(&format!("no casm found for contract: {}", contract)[..]);

let contract_definition: SierraClass = {
let file_contents = std::fs::read(sierra_contract_path)
let file_contents = std::fs::read(sierra_contract_path.clone())
.with_context(|| format!("Failed to read contract file: {sierra_contract_path}"))?;
serde_json::from_slice(&file_contents).with_context(|| {
format!("Failed to parse contract definition: {sierra_contract_path}")
})?
};
let casm_contract_definition: CompiledClass = {
let file_contents = std::fs::read(casm_contract_path)
let file_contents = std::fs::read(casm_contract_path.clone())
.with_context(|| format!("Failed to read contract file: {casm_contract_path}"))?;
serde_json::from_slice(&file_contents)
.with_context(|| format!("Failed to parse contract definition: {casm_contract_path}"))?
Expand Down
12 changes: 12 additions & 0 deletions cast/tests/declare_test/Scarb.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "declare_test"
version = "0.1.0"

[[target.starknet-contract]]
sierra = true
casm = true

[dependencies]
starknet = "1.1.0"

[tool.protostar]
19 changes: 19 additions & 0 deletions cast/tests/declare_test/src/lib.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#[contract]
mod HelloStarknet {
struct Storage {
balance: felt252,
}

// Increases the balance by the given amount.
#[external]
fn increase_balance(amount: felt252) {
assert(amount != 0, 'Amount cannot be 0');
balance::write(balance::read() + amount);
}

// Returns the current balance.
#[view]
fn get_balance() -> felt252 {
balance::read()
}
}

0 comments on commit 5dce670

Please sign in to comment.