Skip to content

Commit d4cd04e

Browse files
authored
feat(sozo): add invoke command for standalone contract (#3384)
* feat(sozo): add invoke command that doesn't require the world context * fix: ensure correct calldata decoding
1 parent 9b36053 commit d4cd04e

File tree

5 files changed

+159
-2
lines changed

5 files changed

+159
-2
lines changed

bin/sozo/src/commands/execute.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use super::options::world::WorldOptions;
1919
use crate::utils::{self, CALLDATA_DOC};
2020

2121
#[derive(Debug, Args)]
22-
#[command(about = "Execute one or several systems with the given calldata.")]
22+
#[command(about = "Execute one or several systems in the world context with the given calldata.")]
2323
pub struct ExecuteArgs {
2424
#[arg(num_args = 1..)]
2525
#[arg(required = true)]

bin/sozo/src/commands/invoke.rs

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
use anyhow::{anyhow, bail, Context, Result};
2+
use clap::Args;
3+
use dojo_utils::{Invoker, TxnConfig};
4+
use dojo_world::config::calldata_decoder;
5+
use sozo_ui::SozoUi;
6+
use starknet::core::types::{Call, Felt};
7+
use starknet::core::utils::get_selector_from_name;
8+
use tracing::trace;
9+
10+
use super::options::account::AccountOptions;
11+
use super::options::starknet::StarknetOptions;
12+
use super::options::transaction::TransactionOptions;
13+
use crate::utils::{get_account_from_env, CALLDATA_DOC};
14+
15+
#[derive(Debug, Args)]
16+
#[command(about = "Invoke a contract entrypoint on Starknet. This command does not require the \
17+
world context to be loaded. Use the execute command to execute systems in the \
18+
world context.")]
19+
pub struct InvokeArgs {
20+
#[arg(
21+
num_args = 1..,
22+
required = true,
23+
help = format!(
24+
"Calls to invoke, separated by '/'. \
25+
Each call follows the format <CONTRACT> <ENTRYPOINT> [CALLDATA...]\n\n{}",
26+
CALLDATA_DOC
27+
)
28+
)]
29+
pub calls: Vec<String>,
30+
31+
#[command(flatten)]
32+
pub transaction: TransactionOptions,
33+
34+
#[command(flatten)]
35+
pub starknet: StarknetOptions,
36+
37+
#[arg(long, default_value = "0x0", help = "Selector for the entrypoint in felt form.")]
38+
pub selector: Option<Felt>,
39+
40+
#[command(flatten)]
41+
#[command(next_help_heading = "Account options")]
42+
pub account: AccountOptions,
43+
}
44+
45+
impl InvokeArgs {
46+
pub async fn run(self, ui: &SozoUi) -> Result<()> {
47+
trace!(args = ?self);
48+
49+
let account = get_account_from_env(self.account, &self.starknet).await?;
50+
let txn_config: TxnConfig = self.transaction.try_into()?;
51+
let mut invoker = Invoker::new(account, txn_config);
52+
53+
let mut calls_iter = self.calls.into_iter();
54+
let mut call_index = 0usize;
55+
56+
while let Some(target) = calls_iter.next() {
57+
if matches!(target.as_str(), "/" | "-" | "\\") {
58+
continue;
59+
}
60+
61+
let entrypoint = calls_iter.next().ok_or_else(|| {
62+
anyhow!(
63+
"Missing entrypoint for target `{target}`. Provide calls as `<CONTRACT> \
64+
<ENTRYPOINT> [CALLDATA...]`."
65+
)
66+
})?;
67+
68+
let contract_address = parse_contract_address(&target)?;
69+
let selector = get_selector_from_name(&entrypoint)?;
70+
71+
let mut calldata = Vec::new();
72+
for arg in calls_iter.by_ref() {
73+
match arg.as_str() {
74+
"/" | "-" | "\\" => break,
75+
_ => {
76+
let felts =
77+
calldata_decoder::decode_single_calldata(&arg).with_context(|| {
78+
format!("Failed to parse calldata argument `{arg}`")
79+
})?;
80+
calldata.extend(felts);
81+
}
82+
}
83+
}
84+
85+
call_index += 1;
86+
ui.step(format!("Call #{call_index}: {entrypoint} @ {:#066x}", contract_address));
87+
if calldata.is_empty() {
88+
ui.verbose(" Calldata: <empty>");
89+
} else {
90+
ui.verbose(format!(" Calldata ({} felt(s))", calldata.len()));
91+
}
92+
93+
invoker.add_call(Call { to: contract_address, selector, calldata });
94+
}
95+
96+
if invoker.calls.is_empty() {
97+
bail!("No calls provided to invoke.");
98+
}
99+
100+
let results = invoker.multicall().await?;
101+
102+
for (idx, result) in results.iter().enumerate() {
103+
let display_idx = idx + 1;
104+
match result {
105+
dojo_utils::TransactionResult::Noop => {
106+
ui.result(format!("Call #{display_idx} noop (no transaction sent)."));
107+
}
108+
dojo_utils::TransactionResult::Hash(hash) => {
109+
ui.result(format!("Call #{display_idx} sent.\n Tx hash : {hash:#066x}"));
110+
}
111+
dojo_utils::TransactionResult::HashReceipt(hash, receipt) => {
112+
ui.result(format!("Call #{display_idx} included.\n Tx hash : {hash:#066x}"));
113+
ui.debug(format!("Receipt: {:?}", receipt));
114+
}
115+
}
116+
}
117+
118+
Ok(())
119+
}
120+
}
121+
122+
fn parse_contract_address(value: &str) -> Result<Felt> {
123+
if let Ok(felt) = Felt::from_hex(value) {
124+
return Ok(felt);
125+
}
126+
127+
Felt::from_dec_str(value).map_err(|_| {
128+
anyhow!("Invalid contract address `{value}`. Use hex (0x...) or decimal form.")
129+
})
130+
}

bin/sozo/src/commands/mod.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ pub(crate) mod execute;
1818
pub(crate) mod hash;
1919
pub(crate) mod init;
2020
pub(crate) mod inspect;
21+
pub(crate) mod invoke;
2122
pub(crate) mod mcp;
2223
pub(crate) mod migrate;
2324
pub(crate) mod model;
@@ -37,6 +38,7 @@ use execute::ExecuteArgs;
3738
use hash::HashArgs;
3839
use init::InitArgs;
3940
use inspect::InspectArgs;
41+
use invoke::InvokeArgs;
4042
use mcp::McpArgs;
4143
use migrate::MigrateArgs;
4244
use model::ModelArgs;
@@ -59,6 +61,8 @@ pub enum Commands {
5961
Events(Box<EventsArgs>),
6062
#[command(about = "Execute one or several systems with the given calldata.")]
6163
Execute(Box<ExecuteArgs>),
64+
#[command(about = "Invoke a contract entrypoint on Starknet.")]
65+
Invoke(Box<InvokeArgs>),
6266
#[command(about = "Clean the build directory")]
6367
Clean(Box<CleanArgs>),
6468
#[command(about = "Computes hash with different hash functions")]
@@ -98,6 +102,7 @@ impl fmt::Display for Commands {
98102
Commands::Events(_) => write!(f, "Events"),
99103
Commands::Execute(_) => write!(f, "Execute"),
100104
Commands::Hash(_) => write!(f, "Hash"),
105+
Commands::Invoke(_) => write!(f, "Invoke"),
101106
Commands::Declare(_) => write!(f, "Declare"),
102107
Commands::Deploy(_) => write!(f, "Deploy"),
103108
Commands::Init(_) => write!(f, "Init"),
@@ -126,6 +131,7 @@ pub async fn run(command: Commands, scarb_metadata: &Metadata, ui: &SozoUi) -> R
126131
Commands::Clean(args) => args.run(scarb_metadata),
127132
Commands::Events(args) => args.run(scarb_metadata, ui).await,
128133
Commands::Execute(args) => args.run(scarb_metadata, ui).await,
134+
Commands::Invoke(args) => args.run(ui).await,
129135
Commands::Hash(args) => args.run(scarb_metadata),
130136
Commands::Declare(args) => args.run(ui).await,
131137
Commands::Deploy(args) => args.run(ui).await,

bin/sozo/src/main.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ async fn cli_main(args: SozoArgs, ui: &SozoUi) -> Result<()> {
4747
args.run(ui).await
4848
} else if let Commands::Deploy(args) = args.command {
4949
args.run(ui).await
50+
} else if let Commands::Invoke(args) = args.command {
51+
args.run(ui).await
5052
} else {
5153
// Default to the current directory to mimic how Scarb works.
5254
let manifest_path = if let Some(manifest_path) = &args.manifest_path {

crates/dojo/world/src/config/calldata_decoder.rs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use anyhow::{self, Result};
22
use cainome::cairo_serde::{ByteArray, CairoSerde};
33
use num_bigint::BigUint;
44
use starknet::core::types::{Felt, FromStrError};
5-
use starknet::core::utils::cairo_short_string_to_felt;
5+
use starknet::core::utils::{cairo_short_string_to_felt, get_selector_from_name};
66

77
/// An error that occurs while decoding calldata.
88
#[derive(thiserror::Error, Debug)]
@@ -33,6 +33,24 @@ trait CalldataDecoder {
3333
fn decode(&self, input: &str) -> DecoderResult<Vec<Felt>>;
3434
}
3535

36+
/// Decodes a selector into a [`Felt`].
37+
struct SelectorCalldataDecoder;
38+
impl CalldataDecoder for SelectorCalldataDecoder {
39+
fn decode(&self, input: &str) -> DecoderResult<Vec<Felt>> {
40+
let felt_selector = match get_selector_from_name(input) {
41+
Ok(felt) => felt,
42+
Err(_) => {
43+
return Err(CalldataDecoderError::ParseError(format!(
44+
"Selector `{}` contains non-ASCII characters",
45+
input
46+
)));
47+
}
48+
};
49+
50+
Ok(vec![felt_selector])
51+
}
52+
}
53+
3654
/// Decodes a u256 string into a [`Felt`]s array representing
3755
/// a u256 value split into two 128-bit words.
3856
struct U256CalldataDecoder;
@@ -224,6 +242,7 @@ pub fn decode_single_calldata(item: &str) -> DecoderResult<Vec<Felt>> {
224242

225243
let felts = if let Some((prefix, value)) = item.split_once(ITEM_PREFIX_DELIMITER) {
226244
match prefix {
245+
"selector" => SelectorCalldataDecoder.decode(value)?,
227246
"u256" => U256CalldataDecoder.decode(value)?,
228247
"str" => StrCalldataDecoder.decode(value)?,
229248
"sstr" => ShortStrCalldataDecoder.decode(value)?,

0 commit comments

Comments
 (0)