GeezerVison is showing github.com — Show diagnostic events when a transaction fails on-chain by fnando · Pull Request #2700 · stellar/stellar-cli
Show diagnostic events when a transaction fails on-chain
#2700
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.rs
(5)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -534,3 +534,48 @@ async fn invoke_auth_uses_hd_path_for_addr_alias() {
.stdout(format!("\"{addr_1}\"\n"))
.success();
}
// Capping `--instructions` to 1 passes simulation (which budgets the real
// instruction count) but fails on-chain with `ResourceLimitExceeded`, since the
// override is applied to the assembled transaction after simulation. This is the
// only reliable way to drive a transaction that fails *on-chain* rather than
// during simulation, which is exactly the path that recovers and prints the
// diagnostic events.
#[tokio::test]
async fn on_chain_failure_surfaces_diagnostic_events() {
let sandbox = &TestEnv::new();
let id = deploy_hello(sandbox).await;
sandbox
.new_assert_cmd("contract")
.arg("invoke")
.arg("--id")
.arg(&id)
.arg("--instructions")
.arg("1")
.arg("--")
.arg("inc")
.assert()
.failure()
.stderr(predicates::str::contains("Error event"));
}
#[tokio::test]
async fn on_chain_failure_diagnostic_events_suppressed_in_quiet_mode() {
let sandbox = &TestEnv::new();
let id = deploy_hello(sandbox).await;
sandbox
.new_assert_cmd("contract")
.arg("invoke")
.arg("--quiet")
.arg("--id")
.arg(&id)
.arg("--instructions")
.arg("1")
.arg("--")
.arg("inc")
.assert()
.failure()
.stderr(predicates::str::contains("Error event").not());
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -111,9 +111,15 @@ impl Args {
return Ok(TxnEnvelopeResult::TxnEnvelope(Box::new(tx.into())));
}
let txn_resp = client
.send_transaction_polling(&self.config.sign(tx, args.quiet).await?)
.await?;
let print = crate::print::Print::new(args.quiet);
let signed_tx = self.config.sign(tx, args.quiet).await?;
let txn_resp = crate::tx::send_transaction_polling_with_events(
&client,
&signed_tx,
&network.network_passphrase,
&print,
)
.await?;
if !args.no_cache {
data::write(txn_resp.clone().try_into().unwrap(), &network.rpc_uri()?)?;
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -64,12 +64,18 @@ impl Cmd {
let network = config.get_network()?;
let client = network.rpc_client()?;
let tx_env = super::xdr::tx_envelope_from_input(&self.tx_xdr)?;
let print = Print::new(quiet);
if let Ok(txn) = super::xdr::unwrap_envelope_v1(tx_env.clone()) {
let print = Print::new(quiet);
print.log_transaction(&txn, &network, true)?;
}
Ok(client.send_transaction_polling(&tx_env).await?)
Ok(crate::tx::send_transaction_polling_with_events(
&client,
&tx_env,
&network.network_passphrase,
&print,
)
.await?)
}
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -131,6 +131,44 @@ pub fn contract_with_spec(events: &[DiagnosticEvent], print: &Print, spec: Optio
}
}
/// Render an `error` diagnostic event as a readable line.
///
/// `topics` carries the error type/code (an `ScError`) and `data` carries the
/// message payload. Both are serialized as JSON, which escapes any control
/// bytes present in the payload.
fn format_error_event(topics: &[xdr::ScVal], data: &xdr::ScVal) -> String {
let topics_json = serde_json::to_string(topics).unwrap();
let data_json = serde_json::to_string(data).unwrap();
format!("Error event: {topics_json} = {data_json}")
}
/// Display diagnostic events for a failed transaction.
///
/// Reuses [`contract_with_spec`] to render contract events and `log` diagnostic
/// events, and additionally surfaces the `error` diagnostic event (the host or
/// contract error), which the success-path renderer intentionally drops. This is
/// the most actionable information when a submitted transaction fails.
pub fn failure(events: &[DiagnosticEvent], print: &Print) {
contract_with_spec(events, print, None);
for event in events.iter().cloned() {
if let DiagnosticEvent {
event:
ContractEvent {
body: ContractEventBody::V0(ContractEventV0 { topics, data, .. }),
type_: ContractEventType::Diagnostic,
..
},
..
} = event
{
if topics.first() == Some(&xdr::ScVal::Symbol(str_to_sc_symbol("error"))) {
print.errorln(format_error_event(topics.as_slice(), &data));
}
}
}
}
fn str_to_sc_symbol(s: &str) -> xdr::ScSymbol {
let inner: xdr::StringM<32> = s.try_into().unwrap();
xdr::ScSymbol(inner)
Expand All
@@ -147,6 +185,25 @@ mod tests {
use serde_json::json;
use soroban_spec_tools::test_utils::assert_no_control_chars;
#[test]
fn format_error_event_renders_code_and_message_without_control_bytes() {
let topics = vec![
xdr::ScVal::Symbol(str_to_sc_symbol("error")),
xdr::ScVal::Error(xdr::ScError::Contract(7)),
];
// A message payload carrying an ANSI control sequence to ensure it is escaped.
let data = xdr::ScVal::String(xdr::ScString("boom\x1b[31m".try_into().unwrap()));
let rendered = format_error_event(&topics, &data);
assert!(rendered.contains("boom"), "message payload should be shown");
assert!(
rendered.contains('7') || rendered.to_lowercase().contains("contract"),
"error code should be shown: {rendered}"
);
assert_no_control_chars(&rendered);
}
#[test]
fn format_decoded_event_strips_attacker_control_bytes() {
let mut params = IndexMap::new();
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -6,8 +6,8 @@ use crate::{
signer::{self, Signer},
utils::transaction_env_hash,
xdr::{
self, FeeBumpTransaction, FeeBumpTransactionExt, FeeBumpTransactionInnerTx, Transaction ,
TransactionEnvelope,
self, FeeBumpTransaction, FeeBumpTransactionExt, FeeBumpTransactionInnerTx, Hash ,
Transaction, TransactionEnvelope,
},
};
use soroban_rpc::GetTransactionResponse;
Expand All
@@ -24,7 +24,9 @@ pub const ONE_XLM: i64 = 10_000_000;
/// * Store results to the data cache when `no_cache` is false
/// * Logs a success message and block explorer link to stderr upon successful submission
///
/// Does not handle any logging related to the result, events, or effects of the transaction.
/// On failure, logs the transaction's diagnostic events to stderr (via
/// `send_transaction_polling_with_events`); it does not otherwise log the
/// result or effects of a successful transaction.
///
/// Returns the `GetTransactionResponse` from the network.
///
Expand Down
Expand Up
@@ -106,7 +108,13 @@ where
print.globeln("Sending transaction…");
// returns an error if the transaction fails
let res = client.send_transaction_polling(&signed_tx).await?;
let res = send_transaction_polling_with_events(
client,
&signed_tx,
&network.network_passphrase,
&print,
)
.await?;
print.checkln("Transaction submitted successfully!");
Expand All
@@ -122,3 +130,42 @@ where
Ok(res)
}
/// Submits a signed transaction and polls for its result, surfacing diagnostic
/// events when the transaction fails.
///
/// On failure the RPC client returns only the (decoded) result codes and discards
/// the transaction's diagnostic events. This helper best-effort re-fetches the
/// failed transaction to recover and print those events — the host/contract error,
/// its message, and any contract logs — which explain *why* the transaction
/// failed. The original error is always preserved and returned unchanged.
///
/// # Errors
/// Returns the underlying submission error if the transaction fails.
pub async fn send_transaction_polling_with_events(
client: &soroban_rpc::Client,
signed_tx: &TransactionEnvelope,
network_passphrase: &str,
print: &print::Print,
) -> Result<GetTransactionResponse, soroban_rpc::Error> {
match client.send_transaction_polling(signed_tx).await {
Comment thread
fnando marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
Ok(res) => Ok(res),
Err(e) => {
// Best-effort: recover the diagnostic events the submission error dropped.
//
// Since protocol 23 a failed transaction's diagnostic events are
// returned in the response's dedicated `diagnosticEventsXdr` field
// rather than embedded in the transaction meta, so read them from
// `events.diagnostic_events` (which the RPC client populates from that
// field) instead of from `result_meta`.
Comment thread
fnando marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
if let Ok(hash) = transaction_env_hash(signed_tx, network_passphrase) {
if let Ok(resp) = client.get_transaction(&Hash(hash)).await {
let events = &resp.events.diagnostic_events;
crate::log::event::all(events);
crate::log::event::failure(events, print);
}
}
Err(e)
}
}
}
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.