Skip to content

Commit

Permalink
Get rid of either
Browse files Browse the repository at this point in the history
  • Loading branch information
Ifropc committed Dec 10, 2024
1 parent 19ae5ba commit 2523975
Show file tree
Hide file tree
Showing 8 changed files with 49 additions and 69 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

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

1 change: 0 additions & 1 deletion cmd/crates/soroban-test/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ sep5 = { workspace = true }
soroban-cli = { workspace = true }
soroban-rpc = { workspace = true }

either = "1.13.0"
thiserror = "1.0.31"
sha2 = "0.10.6"
assert_cmd = "2.0.4"
Expand Down
8 changes: 3 additions & 5 deletions cmd/crates/soroban-test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ use std::{ffi::OsString, fmt::Display, path::Path};

use assert_cmd::{assert::Assert, Command};
use assert_fs::{fixture::FixtureError, prelude::PathChild, TempDir};
use either::Either;
use fs_extra::dir::CopyOptions;

use soroban_cli::{
Expand Down Expand Up @@ -203,10 +202,9 @@ impl TestEnv {
source: &str,
) -> Result<String, invoke::Error> {
let cmd = self.cmd_with_config::<I, invoke::Cmd>(command_str, None);
self.run_cmd_with(cmd, source).await.map(|r| match r {
Either::Left(help) => help,
Either::Right(tx) => tx.into_result().unwrap(),
})
self.run_cmd_with(cmd, source)
.await
.map(|tx| tx.into_result().unwrap())
}

/// A convenience method for using the invoke command.
Expand Down
8 changes: 7 additions & 1 deletion cmd/crates/soroban-test/tests/it/help.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
use soroban_cli::commands::contract::arg_parsing::Error::HelpMessage;
use soroban_cli::commands::contract::invoke::Error::ArgParsing;
use soroban_cli::commands::contract::{self, arg_parsing};
use soroban_test::TestEnv;

use crate::util::{invoke_custom as invoke, CUSTOM_TYPES, DEFAULT_CONTRACT_ID};

async fn invoke_custom(func: &str, args: &str) -> Result<String, contract::invoke::Error> {
let e = &TestEnv::default();
invoke(e, DEFAULT_CONTRACT_ID, func, args, &CUSTOM_TYPES.path()).await
let r = invoke(e, DEFAULT_CONTRACT_ID, func, args, &CUSTOM_TYPES.path()).await;
if let Err(ArgParsing(HelpMessage(e))) = r {
return Ok(e);
}
r
}

#[tokio::test]
Expand Down
6 changes: 1 addition & 5 deletions cmd/crates/soroban-test/tests/it/util.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use either::Either;
use soroban_cli::{
commands::contract,
config::{locator::KeyType, secret::Secret},
Expand Down Expand Up @@ -55,10 +54,7 @@ pub async fn invoke_custom(
sandbox.cmd_with_config(&["--id", id, "--", func, arg], None);
i.wasm = Some(wasm.to_path_buf());
let s = sandbox.run_cmd_with(i, TEST_ACCOUNT).await;
s.map(|r| match r {
Either::Left(help) => help,
Either::Right(tx) => tx.into_result().unwrap(),
})
s.map(|tx| tx.into_result().unwrap())
}

pub const DEFAULT_CONTRACT_ID: &str = "CDR6QKTWZQYW6YUJ7UP7XXZRLWQPFRV6SWBLQS4ZQOSAF4BOUD77OO5Z";
Expand Down
22 changes: 10 additions & 12 deletions cmd/soroban-cli/src/commands/contract/arg_parsing.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use crate::commands::contract::arg_parsing::Error::HelpMessage;
use crate::commands::txn_result::TxnResult;
use crate::config::{self};
use crate::xdr::{
self, Hash, InvokeContractArgs, ScAddress, ScSpecEntry, ScSpecFunctionV0, ScSpecTypeDef, ScVal,
ScVec,
Expand All @@ -6,17 +9,13 @@ use clap::error::ErrorKind::DisplayHelp;
use clap::value_parser;
use ed25519_dalek::SigningKey;
use heck::ToKebabCase;
use soroban_spec_tools::Spec;
use std::collections::HashMap;
use std::convert::TryInto;
use std::ffi::OsString;
use std::fmt::Debug;
use std::path::PathBuf;

use crate::commands::contract::arg_parsing::HostFunctionParameters::{HelpMessage, Params};
use crate::commands::txn_result::TxnResult;
use crate::config::{self};
use soroban_spec_tools::Spec;

#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("parsing argument {arg}: {error}")]
Expand All @@ -43,13 +42,12 @@ pub enum Error {
MissingArgument(String),
#[error("")]
MissingFileArg(PathBuf),
}

pub enum HostFunctionParameters {
Params((String, Spec, InvokeContractArgs, Vec<SigningKey>)),
#[error("")]
HelpMessage(String),
}

pub type HostFunctionParameters = (String, Spec, InvokeContractArgs, Vec<SigningKey>);

pub fn build_host_function_parameters(
contract_id: &stellar_strkey::Contract,
slop: &[OsString],
Expand All @@ -76,12 +74,12 @@ pub fn build_host_function_parameters(
Err(e) => {
// to not exit immediately (to be able to fetch help message in tests), check for an error
if e.kind() == DisplayHelp {
return Ok(HelpMessage(e.to_string()));
return Err(HelpMessage(e.to_string()));
}
e.exit();
}
}) else {
return Ok(HelpMessage(format!("{long_help}")));
return Err(HelpMessage(format!("{long_help}")));
};

let func = spec.find_function(function)?;
Expand Down Expand Up @@ -158,7 +156,7 @@ pub fn build_host_function_parameters(
args: final_args,
};

Ok(Params((function.clone(), spec, invoke_args, signers)))
Ok((function.clone(), spec, invoke_args, signers))
}

fn build_custom_cmd(name: &str, spec: &Spec) -> Result<clap::Command, Error> {
Expand Down
33 changes: 14 additions & 19 deletions cmd/soroban-cli/src/commands/contract/deploy/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ use crate::xdr::{
VecM, WriteXdr,
};
use clap::{arg, command, Parser};
use itertools::Either;
use itertools::Either::{Left, Right};
use rand::Rng;
use regex::Regex;
use soroban_spec_tools::contract as contract_spec;
Expand All @@ -16,7 +14,8 @@ use std::ffi::OsString;
use std::fmt::Debug;
use std::num::ParseIntError;

use crate::commands::contract::arg_parsing::HostFunctionParameters;
use crate::commands::contract::arg_parsing::Error::HelpMessage;
use crate::commands::contract::deploy::wasm::Error::ArgParse;
use crate::{
assembled::simulate_and_assemble_transaction,
commands::{
Expand Down Expand Up @@ -129,12 +128,9 @@ pub enum Error {

impl Cmd {
pub async fn run(&self, global_args: &global::Args) -> Result<(), Error> {
let res = self.run_against_rpc_server(Some(global_args), None).await?;
let res = self.run_against_rpc_server(Some(global_args), None).await;
match res {
Left(help) => {
println!("{help}");
}
Right(res) => match res.to_envelope() {
Ok(res) => match res.to_envelope() {
TxnEnvelopeResult::TxnEnvelope(tx) => {
println!("{}", tx.to_xdr_base64(Limits::none())?);
}
Expand All @@ -152,6 +148,10 @@ impl Cmd {
println!("{contract}");
}
},
Err(ArgParse(HelpMessage(help))) => {
println!("{help}");
}
Err(e) => return Err(e),
}

Ok(())
Expand All @@ -173,14 +173,14 @@ fn alias_validator(alias: &str) -> Result<String, Error> {
#[async_trait::async_trait]
impl NetworkRunnable for Cmd {
type Error = Error;
type Result = Either<String, TxnResult<stellar_strkey::Contract>>;
type Result = TxnResult<stellar_strkey::Contract>;

#[allow(clippy::too_many_lines)]
async fn run_against_rpc_server(
&self,
global_args: Option<&global::Args>,
config: Option<&config::Args>,
) -> Result<Either<String, TxnResult<stellar_strkey::Contract>>, Error> {
) -> Result<TxnResult<stellar_strkey::Contract>, Error> {
let print = Print::new(global_args.map_or(false, |a| a.quiet));
let config = config.unwrap_or(&self.config);
let wasm_hash = if let Some(wasm) = &self.wasm {
Expand Down Expand Up @@ -260,12 +260,7 @@ impl NetworkRunnable for Cmd {
&entries,
config,
)?;
match params {
HostFunctionParameters::Params(p) => Some(p.2),
HostFunctionParameters::HelpMessage(h) => {
return Ok(Left(h));
}
}
Some(params.2)
}
} else {
None
Expand All @@ -285,7 +280,7 @@ impl NetworkRunnable for Cmd {

if self.fee.build_only {
print.checkln("Transaction built!");
return Ok(Right(TxnResult::Txn(txn)));
return Ok(TxnResult::Txn(txn));
}

print.infoln("Simulating deploy transaction…");
Expand All @@ -295,7 +290,7 @@ impl NetworkRunnable for Cmd {

if self.fee.sim_only {
print.checkln("Done!");
return Ok(Right(TxnResult::Txn(txn)));
return Ok(TxnResult::Txn(txn));
}

print.globeln("Submitting deploy transaction…");
Expand All @@ -316,7 +311,7 @@ impl NetworkRunnable for Cmd {

print.checkln("Deployed!");

Ok(Right(TxnResult::Res(contract_id)))
Ok(TxnResult::Res(contract_id))
}
}

Expand Down
39 changes: 14 additions & 25 deletions cmd/soroban-cli/src/commands/contract/invoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@ use std::str::FromStr;
use std::{fmt::Debug, fs, io};

use clap::{arg, command, Parser, ValueEnum};
use itertools::Either;
use itertools::Either::{Left, Right};
use soroban_rpc::{Client, SimulateHostFunctionResult, SimulateTransactionResponse};
use soroban_spec::read::FromWasmError;

use super::super::events;
use super::arg_parsing;
use crate::commands::contract::arg_parsing::HostFunctionParameters;
use crate::commands::contract::arg_parsing::HostFunctionParameters::HelpMessage;
use crate::commands::contract::arg_parsing::Error::HelpMessage;
use crate::commands::contract::invoke::Error::ArgParsing;
use crate::{
assembled::simulate_and_assemble_transaction,
commands::{
Expand Down Expand Up @@ -134,27 +132,25 @@ impl From<Infallible> for Error {

impl Cmd {
pub async fn run(&self, global_args: &global::Args) -> Result<(), Error> {
let res = self.invoke(global_args).await?;
let res = self.invoke(global_args).await;
match res {
Right(res) => match res.to_envelope() {
Ok(res) => match res.to_envelope() {
TxnEnvelopeResult::TxnEnvelope(tx) => {
println!("{}", tx.to_xdr_base64(Limits::none())?);
}
TxnEnvelopeResult::Res(output) => {
println!("{output}");
}
},
Left(help) => {
Err(ArgParsing(HelpMessage(help))) => {
println!("{help}");
}
Err(e) => return Err(e),
}
Ok(())
}

pub async fn invoke(
&self,
global_args: &global::Args,
) -> Result<Either<String, TxnResult<String>>, Error> {
pub async fn invoke(&self, global_args: &global::Args) -> Result<TxnResult<String>, Error> {
self.run_against_rpc_server(Some(global_args), None).await
}

Expand Down Expand Up @@ -217,13 +213,13 @@ impl Cmd {
#[async_trait::async_trait]
impl NetworkRunnable for Cmd {
type Error = Error;
type Result = Either<String, TxnResult<String>>;
type Result = TxnResult<String>;

async fn run_against_rpc_server(
&self,
global_args: Option<&global::Args>,
config: Option<&config::Args>,
) -> Result<Either<String, TxnResult<String>>, Error> {
) -> Result<TxnResult<String>, Error> {
let config = config.unwrap_or(&self.config);
let network = config.get_network()?;
tracing::trace!(?network);
Expand All @@ -234,11 +230,7 @@ impl NetworkRunnable for Cmd {
let spec_entries = self.spec_entries()?;
if let Some(spec_entries) = &spec_entries {
// For testing wasm arg parsing
let params =
build_host_function_parameters(&contract_id, &self.slop, spec_entries, config)?;
if let HelpMessage(s) = params {
return Ok(Left(s));
}
build_host_function_parameters(&contract_id, &self.slop, spec_entries, config)?;
}
let client = network.rpc_client()?;

Expand All @@ -255,10 +247,7 @@ impl NetworkRunnable for Cmd {
let params =
build_host_function_parameters(&contract_id, &self.slop, &spec_entries, config)?;

let (function, spec, host_function_params, signers) = match params {
HostFunctionParameters::Params(x) => x,
HelpMessage(s) => return Ok(Left(s)),
};
let (function, spec, host_function_params, signers) = params;

let should_send_tx = self
.should_send_after_sim(host_function_params.clone(), client.clone())
Expand All @@ -285,13 +274,13 @@ impl NetworkRunnable for Cmd {
account_id,
)?);
if self.fee.build_only {
return Ok(Right(TxnResult::Txn(tx)));
return Ok(TxnResult::Txn(tx));
}
let txn = simulate_and_assemble_transaction(&client, &tx).await?;
let assembled = self.fee.apply_to_assembled_txn(txn);
let mut txn = Box::new(assembled.transaction().clone());
if self.fee.sim_only {
return Ok(Right(TxnResult::Txn(txn)));
return Ok(TxnResult::Txn(txn));
}
let sim_res = assembled.sim_response();
if global_args.map_or(true, |a| !a.no_cache) {
Expand Down Expand Up @@ -326,7 +315,7 @@ impl NetworkRunnable for Cmd {
}
};
crate::log::events(&events);
Ok(Right(output_to_string(&spec, &return_value, &function)?))
Ok(output_to_string(&spec, &return_value, &function)?)
}
}

Expand Down

0 comments on commit 2523975

Please sign in to comment.