Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/sozo/src/commands/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use super::options::world::WorldOptions;
use crate::utils::{self, CALLDATA_DOC};

#[derive(Debug, Args)]
#[command(about = "Execute one or several systems with the given calldata.")]
#[command(about = "Execute one or several systems in the world context with the given calldata.")]
pub struct ExecuteArgs {
#[arg(num_args = 1..)]
#[arg(required = true)]
Expand Down
130 changes: 130 additions & 0 deletions bin/sozo/src/commands/invoke.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
use anyhow::{anyhow, bail, Context, Result};
use clap::Args;
use dojo_utils::{Invoker, TxnConfig};
use dojo_world::config::calldata_decoder;
use sozo_ui::SozoUi;
use starknet::core::types::{Call, Felt};
use starknet::core::utils::get_selector_from_name;
use tracing::trace;

use super::options::account::AccountOptions;
use super::options::starknet::StarknetOptions;
use super::options::transaction::TransactionOptions;
use crate::utils::{get_account_from_env, CALLDATA_DOC};

#[derive(Debug, Args)]
#[command(about = "Invoke a contract entrypoint on Starknet. This command does not require the \
world context to be loaded. Use the execute command to execute systems in the \
world context.")]
pub struct InvokeArgs {
#[arg(
num_args = 1..,
required = true,
help = format!(
"Calls to invoke, separated by '/'. \
Each call follows the format <CONTRACT> <ENTRYPOINT> [CALLDATA...]\n\n{}",
CALLDATA_DOC
)
)]
pub calls: Vec<String>,

#[command(flatten)]
pub transaction: TransactionOptions,

#[command(flatten)]
pub starknet: StarknetOptions,

#[arg(long, default_value = "0x0", help = "Selector for the entrypoint in felt form.")]
pub selector: Option<Felt>,
Comment on lines +37 to +38

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

The selector field is defined but never used, sensei.

This argument is declared with a default value of 0x0 and help text suggesting it's for passing an entrypoint selector in felt form. However, in the run() method (line 69), the selector is always computed from the entrypoint name using get_selector_from_name(&entrypoint).

Either:

  1. Remove the unused field if it's not needed, or
  2. Implement the intended behavior where users can optionally pass a raw selector instead of an entrypoint name.

If removal is intended:

-    #[arg(long, default_value = "0x0", help = "Selector for the entrypoint in felt form.")]
-    pub selector: Option<Felt>,
-

If the feature should work, the logic would need to check if a custom selector is provided and use it instead of computing from the entrypoint name.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#[arg(long, default_value = "0x0", help = "Selector for the entrypoint in felt form.")]
pub selector: Option<Felt>,
🤖 Prompt for AI Agents
In bin/sozo/src/commands/invoke.rs around lines 37-38, the selector field is
declared but never used; update the run() logic to honor this optional CLI
selector: if self.selector is Some(use that Felt) then use it as the entrypoint
selector, otherwise compute the selector with
get_selector_from_name(&entrypoint). Also remove or adjust the default_value
"0x0" (so the arg truly behaves as optional) and update help text if needed;
alternatively, if the field is not required, delete the selector arg and any
associated docs instead of wiring it into run().


#[command(flatten)]
#[command(next_help_heading = "Account options")]
pub account: AccountOptions,
}

impl InvokeArgs {
pub async fn run(self, ui: &SozoUi) -> Result<()> {
trace!(args = ?self);

let account = get_account_from_env(self.account, &self.starknet).await?;
let txn_config: TxnConfig = self.transaction.try_into()?;
let mut invoker = Invoker::new(account, txn_config);

let mut calls_iter = self.calls.into_iter();
let mut call_index = 0usize;

while let Some(target) = calls_iter.next() {
if matches!(target.as_str(), "/" | "-" | "\\") {
continue;
}

let entrypoint = calls_iter.next().ok_or_else(|| {
anyhow!(
"Missing entrypoint for target `{target}`. Provide calls as `<CONTRACT> \
<ENTRYPOINT> [CALLDATA...]`."
)
})?;

let contract_address = parse_contract_address(&target)?;
let selector = get_selector_from_name(&entrypoint)?;

let mut calldata = Vec::new();
for arg in calls_iter.by_ref() {
match arg.as_str() {
"/" | "-" | "\\" => break,
_ => {
let felts =
calldata_decoder::decode_single_calldata(&arg).with_context(|| {
format!("Failed to parse calldata argument `{arg}`")
})?;
calldata.extend(felts);
}
}
}

call_index += 1;
ui.step(format!("Call #{call_index}: {entrypoint} @ {:#066x}", contract_address));
if calldata.is_empty() {
ui.verbose(" Calldata: <empty>");
} else {
ui.verbose(format!(" Calldata ({} felt(s))", calldata.len()));
}

invoker.add_call(Call { to: contract_address, selector, calldata });
}

if invoker.calls.is_empty() {
bail!("No calls provided to invoke.");
}

let results = invoker.multicall().await?;

for (idx, result) in results.iter().enumerate() {
let display_idx = idx + 1;
match result {
dojo_utils::TransactionResult::Noop => {
ui.result(format!("Call #{display_idx} noop (no transaction sent)."));
}
dojo_utils::TransactionResult::Hash(hash) => {
ui.result(format!("Call #{display_idx} sent.\n Tx hash : {hash:#066x}"));
}
dojo_utils::TransactionResult::HashReceipt(hash, receipt) => {
ui.result(format!("Call #{display_idx} included.\n Tx hash : {hash:#066x}"));
ui.debug(format!("Receipt: {:?}", receipt));
}
}
}
Comment on lines +102 to +116

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for the multicall method in invoker.rs
rg -n -A 20 "pub async fn multicall" crates/dojo/utils/src/tx/invoker.rs

Repository: dojoengine/dojo

Length of output: 864


🏁 Script executed:

#!/bin/bash
# Get more of the multicall implementation
rg -n -A 50 "pub async fn multicall" crates/dojo/utils/src/tx/invoker.rs | head -80

Repository: dojoengine/dojo

Length of output: 2202


🏁 Script executed:

#!/bin/bash
# Get the complete multicall implementation including the else branch
rg -n -A 70 "pub async fn multicall" crates/dojo/utils/src/tx/invoker.rs | tail -50

Repository: dojoengine/dojo

Length of output: 2312


🏁 Script executed:

#!/bin/bash
# Check the invoke.rs file around lines 102-116
cat -n bin/sozo/src/commands/invoke.rs | sed -n '85,125p'

Repository: dojoengine/dojo

Length of output: 1830


🏁 Script executed:

#!/bin/bash
# Search for max_calls configuration
rg -n "max_calls" crates/dojo/utils/src/tx/ -A 2 -B 2

Repository: dojoengine/dojo

Length of output: 2972


The UI output message is misleading about transaction batching—display_idx represents transaction/batch number, not individual call number.

The verification confirms the reviewer's concern:

  1. Default behavior (max_calls = None): multicall() returns a single TransactionResult for all calls bundled into one transaction.
  2. With chunking (max_calls = Some(n)): Returns one TransactionResult per chunk, not per individual call.
  3. The issue: The display says "Call #{display_idx} sent", which implies one result per user-provided call. However, display_idx actually represents the transaction or chunk number.

During input, users see "Call #1", "Call #2", "Call #3" (per individual call), but in the output they see "Call #1 sent" which appears to correspond to the same calls—when actually it represents the transaction/batch result.

Consider updating the output message to clarify this is a batched transaction result, such as:

  • "Transaction #{display_idx} sent..." or
  • "Batch #{display_idx} sent..." or
  • Add context like "All {n} calls in batch #{display_idx} sent..."
🤖 Prompt for AI Agents
In bin/sozo/src/commands/invoke.rs around lines 102 to 116, the UI text wrongly
calls each result "Call #{display_idx}" even though each result represents a
transaction/batch (one per multicall chunk), so update the messages to refer to
transactions/batches (e.g. "Transaction #{display_idx} ..." or "Batch
#{display_idx} ...") and, where possible, include the number of user calls in
that batch (e.g. "All {n} calls in batch #{display_idx} sent...") for the Noop,
Hash and HashReceipt branches so output clearly reflects transaction/chunk
semantics.


Ok(())
}
}

fn parse_contract_address(value: &str) -> Result<Felt> {
if let Ok(felt) = Felt::from_hex(value) {
return Ok(felt);
}

Felt::from_dec_str(value).map_err(|_| {
anyhow!("Invalid contract address `{value}`. Use hex (0x...) or decimal form.")
})
}
6 changes: 6 additions & 0 deletions bin/sozo/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub(crate) mod execute;
pub(crate) mod hash;
pub(crate) mod init;
pub(crate) mod inspect;
pub(crate) mod invoke;
pub(crate) mod mcp;
pub(crate) mod migrate;
pub(crate) mod model;
Expand All @@ -37,6 +38,7 @@ use execute::ExecuteArgs;
use hash::HashArgs;
use init::InitArgs;
use inspect::InspectArgs;
use invoke::InvokeArgs;
use mcp::McpArgs;
use migrate::MigrateArgs;
use model::ModelArgs;
Expand All @@ -59,6 +61,8 @@ pub enum Commands {
Events(Box<EventsArgs>),
#[command(about = "Execute one or several systems with the given calldata.")]
Execute(Box<ExecuteArgs>),
#[command(about = "Invoke a contract entrypoint on Starknet.")]
Invoke(Box<InvokeArgs>),
#[command(about = "Clean the build directory")]
Clean(Box<CleanArgs>),
#[command(about = "Computes hash with different hash functions")]
Expand Down Expand Up @@ -98,6 +102,7 @@ impl fmt::Display for Commands {
Commands::Events(_) => write!(f, "Events"),
Commands::Execute(_) => write!(f, "Execute"),
Commands::Hash(_) => write!(f, "Hash"),
Commands::Invoke(_) => write!(f, "Invoke"),
Commands::Declare(_) => write!(f, "Declare"),
Commands::Deploy(_) => write!(f, "Deploy"),
Commands::Init(_) => write!(f, "Init"),
Expand Down Expand Up @@ -126,6 +131,7 @@ pub async fn run(command: Commands, scarb_metadata: &Metadata, ui: &SozoUi) -> R
Commands::Clean(args) => args.run(scarb_metadata),
Commands::Events(args) => args.run(scarb_metadata, ui).await,
Commands::Execute(args) => args.run(scarb_metadata, ui).await,
Commands::Invoke(args) => args.run(ui).await,
Commands::Hash(args) => args.run(scarb_metadata),
Commands::Declare(args) => args.run(ui).await,
Commands::Deploy(args) => args.run(ui).await,
Expand Down
2 changes: 2 additions & 0 deletions bin/sozo/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ async fn cli_main(args: SozoArgs, ui: &SozoUi) -> Result<()> {
args.run(ui).await
} else if let Commands::Deploy(args) = args.command {
args.run(ui).await
} else if let Commands::Invoke(args) = args.command {
args.run(ui).await
} else {
// Default to the current directory to mimic how Scarb works.
let manifest_path = if let Some(manifest_path) = &args.manifest_path {
Expand Down
21 changes: 20 additions & 1 deletion crates/dojo/world/src/config/calldata_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use anyhow::{self, Result};
use cainome::cairo_serde::{ByteArray, CairoSerde};
use num_bigint::BigUint;
use starknet::core::types::{Felt, FromStrError};
use starknet::core::utils::cairo_short_string_to_felt;
use starknet::core::utils::{cairo_short_string_to_felt, get_selector_from_name};

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

/// Decodes a selector into a [`Felt`].
struct SelectorCalldataDecoder;
impl CalldataDecoder for SelectorCalldataDecoder {
fn decode(&self, input: &str) -> DecoderResult<Vec<Felt>> {
let felt_selector = match get_selector_from_name(input) {
Ok(felt) => felt,
Err(_) => {
return Err(CalldataDecoderError::ParseError(format!(
"Selector `{}` contains non-ASCII characters",
input
)));
}
};

Ok(vec![felt_selector])
}
}

/// Decodes a u256 string into a [`Felt`]s array representing
/// a u256 value split into two 128-bit words.
struct U256CalldataDecoder;
Expand Down Expand Up @@ -224,6 +242,7 @@ pub fn decode_single_calldata(item: &str) -> DecoderResult<Vec<Felt>> {

let felts = if let Some((prefix, value)) = item.split_once(ITEM_PREFIX_DELIMITER) {
match prefix {
"selector" => SelectorCalldataDecoder.decode(value)?,
"u256" => U256CalldataDecoder.decode(value)?,
"str" => StrCalldataDecoder.decode(value)?,
"sstr" => ShortStrCalldataDecoder.decode(value)?,
Expand Down
Loading