Skip to content

Commit

Permalink
feat(CLI): Assembled Transaction that handle preparing transaction po…
Browse files Browse the repository at this point in the history
…st simulation (#1049)

* feat(CLI): Transaction Handler that handles the state transitions

* fix: assembly transaction after authorizing & improve txn error output

* feat: Handler->Assembled - simplify to assembled txn with simulation
  • Loading branch information
willemneal committed Nov 7, 2023
1 parent efe5916 commit c51c141
Show file tree
Hide file tree
Showing 2 changed files with 289 additions and 141 deletions.
219 changes: 106 additions & 113 deletions cmd/soroban-cli/src/rpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ use serde_aux::prelude::{deserialize_default_from_null, deserialize_number_from_
use sha2::{Digest, Sha256};
use soroban_env_host::xdr::{
self, AccountEntry, AccountId, ContractDataEntry, DiagnosticEvent, Error as XdrError,
ExpirationEntry, LedgerEntryData, LedgerFootprint, LedgerKey, LedgerKeyAccount,
LedgerKeyExpiration, PublicKey, ReadXdr, SequenceNumber, SorobanAuthorizationEntry,
SorobanResources, Transaction, TransactionEnvelope, TransactionMeta, TransactionMetaV3,
TransactionResult, TransactionV1Envelope, Uint256, VecM, WriteXdr,
LedgerEntryData, LedgerFootprint, LedgerKey, LedgerKeyAccount, LedgerKeyExpiration, PublicKey,
ReadXdr, SorobanAuthorizationEntry, SorobanResources, SorobanTransactionData, Transaction,
TransactionEnvelope, TransactionMeta, TransactionMetaV3, TransactionResult, Uint256, VecM,
WriteXdr,
};
use soroban_env_host::xdr::{DepthLimitedRead, SorobanAuthorizedFunction};
use soroban_env_host::xdr::{DepthLimitedRead, ExpirationEntry};
use soroban_sdk::token;
use std::{
fmt::Display,
Expand All @@ -23,10 +23,9 @@ use termcolor::{Color, ColorChoice, StandardStream, WriteColor};
use termcolor_output::colored;
use tokio::time::sleep;

use crate::utils::{self, contract_spec};
use crate::utils::contract_spec;

mod transaction;
use transaction::{assemble, build_restore_txn, sign_soroban_authorizations};
mod txn;

const VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION");

Expand Down Expand Up @@ -98,6 +97,8 @@ pub enum Error {
LargeFee(u64),
#[error("Failed to parse LedgerEntryData")]
FailedParseLedgerEntryData,
#[error("Cannot authorize raw transactions")]
CannotAuthorizeRawTransaction,
}

#[derive(serde::Deserialize, serde::Serialize, Debug)]
Expand All @@ -123,7 +124,7 @@ pub struct SendTransactionResponse {
}

#[derive(serde::Deserialize, serde::Serialize, Debug)]
pub struct GetTransactionResponse {
pub struct GetTransactionResponseRaw {
pub status: String,
#[serde(
rename = "envelopeXdr",
Expand All @@ -142,6 +143,33 @@ pub struct GetTransactionResponse {
// TODO: add ledger info and application order
}

#[derive(serde::Deserialize, serde::Serialize, Debug)]
pub struct GetTransactionResponse {
pub status: String,
pub envelope: Option<xdr::TransactionEnvelope>,
pub result: Option<xdr::TransactionResult>,
pub result_meta: Option<xdr::TransactionMeta>,
}

impl TryInto<GetTransactionResponse> for GetTransactionResponseRaw {
type Error = xdr::Error;

fn try_into(self) -> Result<GetTransactionResponse, Self::Error> {
Ok(GetTransactionResponse {
status: self.status,
envelope: self
.envelope_xdr
.map(ReadXdr::from_xdr_base64)
.transpose()?,
result: self.result_xdr.map(ReadXdr::from_xdr_base64).transpose()?,
result_meta: self
.result_meta_xdr
.map(ReadXdr::from_xdr_base64)
.transpose()?,
})
}
}

#[derive(serde::Deserialize, serde::Serialize, Debug)]
pub struct LedgerEntryResult {
pub key: String,
Expand Down Expand Up @@ -202,12 +230,18 @@ pub struct Cost {
}

#[derive(serde::Deserialize, serde::Serialize, Debug)]
pub struct SimulateHostFunctionResult {
pub struct SimulateHostFunctionResultRaw {
#[serde(deserialize_with = "deserialize_default_from_null")]
pub auth: Vec<String>,
pub xdr: String,
}

#[derive(Debug)]
pub struct SimulateHostFunctionResult {
pub auth: Vec<SorobanAuthorizationEntry>,
pub xdr: xdr::ScVal,
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Default)]
pub struct SimulateTransactionResponse {
#[serde(
Expand All @@ -219,7 +253,7 @@ pub struct SimulateTransactionResponse {
#[serde(default)]
pub cost: Cost,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub results: Vec<SimulateHostFunctionResult>,
pub results: Vec<SimulateHostFunctionResultRaw>,
#[serde(rename = "transactionData", default)]
pub transaction_data: String,
#[serde(
Expand All @@ -243,6 +277,37 @@ pub struct SimulateTransactionResponse {
pub error: Option<String>,
}

impl SimulateTransactionResponse {
pub fn results(&self) -> Result<Vec<SimulateHostFunctionResult>, Error> {
self.results
.iter()
.map(|r| {
Ok(SimulateHostFunctionResult {
auth: r
.auth
.iter()
.map(|a| Ok(SorobanAuthorizationEntry::from_xdr_base64(a)?))
.collect::<Result<_, Error>>()?,
xdr: xdr::ScVal::from_xdr_base64(&r.xdr)?,
})
})
.collect()
}

pub fn events(&self) -> Result<Vec<DiagnosticEvent>, Error> {
self.events
.iter()
.map(|e| Ok(DiagnosticEvent::from_xdr_base64(e)?))
.collect()
}

pub fn transaction_data(&self) -> Result<SorobanTransactionData, Error> {
Ok(SorobanTransactionData::from_xdr_base64(
&self.transaction_data,
)?)
}
}

#[derive(serde::Deserialize, serde::Serialize, Debug, Default)]
pub struct RestorePreamble {
#[serde(rename = "transactionData")]
Expand Down Expand Up @@ -557,7 +622,7 @@ soroban config identity fund {address} --helper-url <url>"#
tx: &TransactionEnvelope,
) -> Result<(TransactionResult, TransactionMeta, Vec<DiagnosticEvent>), Error> {
let client = self.client()?;
tracing::trace!(?tx);
tracing::trace!("Sending:\n{tx:#?}");
let SendTransactionResponse {
hash,
error_result_xdr,
Expand All @@ -566,7 +631,9 @@ soroban config identity fund {address} --helper-url <url>"#
} = client
.request("sendTransaction", rpc_params![tx.to_xdr_base64()?])
.await
.map_err(|err| Error::TransactionSubmissionFailed(format!("{err:#?}")))?;
.map_err(|err| {
Error::TransactionSubmissionFailed(format!("No status yet:\n {err:#?}"))
})?;

if status == "ERROR" {
let error = error_result_xdr
Expand All @@ -579,35 +646,35 @@ soroban config identity fund {address} --helper-url <url>"#
.map_err(|_| Error::InvalidResponse)
})
.map(|r| r.result);
tracing::error!(?error);
tracing::error!("TXN failed:\n {error:#?}");
return Err(Error::TransactionSubmissionFailed(format!("{:#?}", error?)));
}
// even if status == "success" we need to query the transaction status in order to get the result

// Poll the transaction status
let start = Instant::now();
loop {
let response = self.get_transaction(&hash).await?;
let response: GetTransactionResponse = self.get_transaction(&hash).await?.try_into()?;
match response.status.as_str() {
"SUCCESS" => {
// TODO: the caller should probably be printing this
tracing::trace!(?response);
let result = TransactionResult::from_xdr_base64(
response.result_xdr.clone().ok_or(Error::MissingResult)?,
)?;
let meta = TransactionMeta::from_xdr_base64(
response
.result_meta_xdr
.clone()
.ok_or(Error::MissingResult)?,
)?;
tracing::trace!("{response:#?}");
let GetTransactionResponse {
result,
result_meta,
..
} = response;
let meta = result_meta.ok_or(Error::MissingResult)?;
let events = extract_events(&meta);
return Ok((result, meta, events));
return Ok((result.ok_or(Error::MissingResult)?, meta, events));
}
"FAILED" => {
tracing::error!(?response);
tracing::error!("{response:#?}");
// TODO: provide a more elaborate error
return Err(Error::TransactionSubmissionFailed(format!("{response:#?}")));
return Err(Error::TransactionSubmissionFailed(format!(
"{:#?}",
response.result
)));
}
"NOT_FOUND" => (),
_ => {
Expand All @@ -627,13 +694,13 @@ soroban config identity fund {address} --helper-url <url>"#
&self,
tx: &TransactionEnvelope,
) -> Result<SimulateTransactionResponse, Error> {
tracing::trace!(?tx);
tracing::trace!("Simulating:\n{tx:#?}");
let base64_tx = tx.to_xdr_base64()?;
let response: SimulateTransactionResponse = self
.client()?
.request("simulateTransaction", rpc_params![base64_tx])
.await?;
tracing::trace!(?response);
tracing::trace!("Simulation response:\n {response:#?}");
match response.error {
None => Ok(response),
Some(e) => {
Expand All @@ -643,31 +710,6 @@ soroban config identity fund {address} --helper-url <url>"#
}
}

// Simulate a transaction, then assemble the result of the simulation into the envelope, so it
// is ready for sending to the network.
pub async fn prepare_transaction(
&self,
tx: &Transaction,
) -> Result<(Transaction, Option<RestorePreamble>, Vec<DiagnosticEvent>), Error> {
tracing::trace!(?tx);
let sim_response = self
.simulate_transaction(&TransactionEnvelope::Tx(TransactionV1Envelope {
tx: tx.clone(),
signatures: VecM::default(),
}))
.await?;
let events = sim_response
.events
.iter()
.map(DiagnosticEvent::from_xdr_base64)
.collect::<Result<Vec<_>, _>>()?;
Ok((
assemble(tx, &sim_response)?,
sim_response.restore_preamble,
events,
))
}

pub async fn prepare_and_send_transaction(
&self,
tx_without_preflight: &Transaction,
Expand All @@ -677,68 +719,19 @@ soroban config identity fund {address} --helper-url <url>"#
log_events: Option<LogEvents>,
log_resources: Option<LogResources>,
) -> Result<(TransactionResult, TransactionMeta, Vec<DiagnosticEvent>), Error> {
let GetLatestLedgerResponse { sequence, .. } = self.get_latest_ledger().await?;
let (mut unsigned_tx, restore_preamble, events) =
self.prepare_transaction(tx_without_preflight).await?;
if let Some(restore) = restore_preamble {
// Build and submit the restore transaction
self.send_transaction(&utils::sign_transaction(
source_key,
&build_restore_txn(&unsigned_tx, &restore)?,
network_passphrase,
)?)
let txn = txn::Assembled::new(tx_without_preflight, self).await?;
let seq_num = txn.sim_res().latest_ledger + 60; //5 min;
let authorized = txn
.handle_restore(self, source_key, network_passphrase)
.await?
.authorize(self, source_key, signers, seq_num, network_passphrase)
.await?;
// Increment the original txn's seq_num so it doesn't conflict
unsigned_tx.seq_num = SequenceNumber(unsigned_tx.seq_num.0 + 1);
}
let (part_signed_tx, signed_auth_entries) = sign_soroban_authorizations(
&unsigned_tx,
source_key,
signers,
sequence + 60, // ~5 minutes of ledgers
network_passphrase,
)?;
let (fee_ready_txn, events) = if signed_auth_entries.is_empty()
|| (signed_auth_entries.len() == 1
&& matches!(
signed_auth_entries[0].root_invocation.function,
SorobanAuthorizedFunction::CreateContractHostFn(_)
)) {
(part_signed_tx, events)
} else {
// re-simulate to calculate the new fees
let (tx, _, events) = self.prepare_transaction(&part_signed_tx).await?;
(tx, events)
};

// Try logging stuff if requested
if let Transaction {
ext: xdr::TransactionExt::V1(xdr::SorobanTransactionData { resources, .. }),
..
} = fee_ready_txn.clone()
{
if let Some(log) = log_events {
if let xdr::Operation {
body:
xdr::OperationBody::InvokeHostFunction(xdr::InvokeHostFunctionOp {
auth, ..
}),
..
} = &fee_ready_txn.operations[0]
{
log(&resources.footprint, &[auth.clone()], &events);
}
}
if let Some(log) = log_resources {
log(&resources);
}
}

let tx = utils::sign_transaction(source_key, &fee_ready_txn, network_passphrase)?;
authorized.log(log_events, log_resources)?;
let tx = authorized.sign(source_key, network_passphrase)?;
self.send_transaction(&tx).await
}

pub async fn get_transaction(&self, tx_id: &str) -> Result<GetTransactionResponse, Error> {
pub async fn get_transaction(&self, tx_id: &str) -> Result<GetTransactionResponseRaw, Error> {
Ok(self
.client()?
.request("getTransaction", rpc_params![tx_id])
Expand Down
Loading

0 comments on commit c51c141

Please sign in to comment.