Skip to content

Commit

Permalink
soroban-cli: Update to latest XDR changes (stellar#813)
Browse files Browse the repository at this point in the history
  • Loading branch information
2opremio authored Jul 31, 2023
1 parent 762ea8c commit 485ebad
Show file tree
Hide file tree
Showing 8 changed files with 85 additions and 67 deletions.
20 changes: 12 additions & 8 deletions cmd/crates/soroban-spec-tools/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ use std::{
};

use stellar_xdr::{
ReadXdr, ScEnvMetaEntry, ScMetaEntry, ScMetaV0, ScSpecEntry, ScSpecFunctionV0, ScSpecUdtEnumV0,
ScSpecUdtErrorEnumV0, ScSpecUdtStructV0, ScSpecUdtUnionV0, StringM,
DepthLimitedRead, ReadXdr, ScEnvMetaEntry, ScMetaEntry, ScMetaV0, ScSpecEntry,
ScSpecFunctionV0, ScSpecUdtEnumV0, ScSpecUdtErrorEnumV0, ScSpecUdtStructV0, ScSpecUdtUnionV0,
StringM,
};

pub struct ContractSpec {
Expand Down Expand Up @@ -59,8 +60,9 @@ impl ContractSpec {
let mut env_meta_base64 = None;
let env_meta = if let Some(env_meta) = env_meta {
env_meta_base64 = Some(base64::encode(env_meta));
let mut cursor = Cursor::new(env_meta);
ScEnvMetaEntry::read_xdr_iter(&mut cursor)
let cursor = Cursor::new(env_meta);
let mut depth_limit_read = DepthLimitedRead::new(cursor, 100);
ScEnvMetaEntry::read_xdr_iter(&mut depth_limit_read)
.collect::<Result<Vec<_>, stellar_xdr::Error>>()?
} else {
vec![]
Expand All @@ -69,8 +71,9 @@ impl ContractSpec {
let mut meta_base64 = None;
let meta = if let Some(meta) = meta {
meta_base64 = Some(base64::encode(meta));
let mut cursor = Cursor::new(meta);
ScMetaEntry::read_xdr_iter(&mut cursor)
let cursor = Cursor::new(meta);
let mut depth_limit_read = DepthLimitedRead::new(cursor, 100);
ScMetaEntry::read_xdr_iter(&mut depth_limit_read)
.collect::<Result<Vec<_>, stellar_xdr::Error>>()?
} else {
vec![]
Expand All @@ -79,8 +82,9 @@ impl ContractSpec {
let mut spec_base64 = None;
let spec = if let Some(spec) = spec {
spec_base64 = Some(base64::encode(spec));
let mut cursor = Cursor::new(spec);
ScSpecEntry::read_xdr_iter(&mut cursor)
let cursor = Cursor::new(spec);
let mut depth_limit_read = DepthLimitedRead::new(cursor, 100);
ScSpecEntry::read_xdr_iter(&mut depth_limit_read)
.collect::<Result<Vec<_>, stellar_xdr::Error>>()?
} else {
vec![]
Expand Down
59 changes: 29 additions & 30 deletions cmd/soroban-cli/src/commands/contract/invoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ use soroban_env_host::{
events::HostEvent,
storage::Storage,
xdr::{
self, AccountId, Error as XdrError, Hash, HostFunction, InvokeHostFunctionOp,
LedgerEntryData, LedgerFootprint, LedgerKey, LedgerKeyAccount, Memo, MuxedAccount,
Operation, OperationBody, Preconditions, PublicKey, ScAddress, ScSpecEntry,
self, AccountId, Error as XdrError, Hash, HostFunction, InvokeContractArgs,
InvokeHostFunctionOp, LedgerEntryData, LedgerFootprint, LedgerKey, LedgerKeyAccount, Memo,
MuxedAccount, Operation, OperationBody, Preconditions, PublicKey, ScAddress, ScSpecEntry,
ScSpecFunctionV0, ScSpecTypeDef, ScVal, ScVec, SequenceNumber, SorobanAddressCredentials,
SorobanAuthorizationEntry, SorobanCredentials, Transaction, TransactionExt, Uint256, VecM,
},
Expand Down Expand Up @@ -166,7 +166,7 @@ impl Cmd {
&self,
contract_id: [u8; 32],
spec_entries: &[ScSpecEntry],
) -> Result<(String, Spec, ScVec), Error> {
) -> Result<(String, Spec, InvokeContractArgs), Error> {
let spec = Spec(Some(spec_entries.to_vec()));
let mut cmd = clap::Command::new(self.contract_id.clone())
.no_binary_name(true)
Expand Down Expand Up @@ -209,28 +209,27 @@ impl Cmd {
})
.collect::<Result<Vec<_>, Error>>()?;

// Add the contract ID and the function name to the arguments
let mut complete_args = vec![
ScVal::Address(ScAddress::Contract(Hash(contract_id))),
ScVal::Symbol(
function
.try_into()
.map_err(|_| Error::FunctionNameTooLong(function.clone()))?,
),
];
complete_args.extend_from_slice(parsed_args.as_slice());
let complete_args_len = complete_args.len();

Ok((
function.clone(),
spec,
complete_args
let contract_address_arg = ScAddress::Contract(Hash(contract_id));
let function_symbol_arg = function
.try_into()
.map_err(|_| Error::FunctionNameTooLong(function.clone()))?;

let final_args =
parsed_args
.clone()
.try_into()
.map_err(|_| Error::MaxNumberOfArgumentsReached {
current: complete_args_len,
current: parsed_args.len(),
maximum: ScVec::default().max_len(),
})?,
))
})?;

let invoke_args = InvokeContractArgs {
contract_address: contract_address_arg,
function_name: function_symbol_arg,
args: final_args,
};

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

pub async fn run(&self) -> Result<(), Error> {
Expand Down Expand Up @@ -332,20 +331,20 @@ impl Cmd {
};
let budget = Budget::default();
if self.unlimited_budget {
budget.reset_unlimited();
budget.reset_unlimited()?;
};
let h = Host::with_storage_and_budget(storage, budget);
h.switch_to_recording_auth();
h.set_source_account(source_account);
h.switch_to_recording_auth()?;
h.set_source_account(source_account)?;

let mut ledger_info = state.ledger_info();
ledger_info.sequence_number += 1;
ledger_info.timestamp += 5;
h.set_ledger_info(ledger_info.clone());
h.set_ledger_info(ledger_info.clone())?;

let (function, spec, host_function_params) =
self.build_host_function_parameters(contract_id, &spec_entries)?;
h.set_diagnostic_level(DiagnosticLevel::Debug);
h.set_diagnostic_level(DiagnosticLevel::Debug)?;
let resv = h
.invoke_function(HostFunction::InvokeContract(host_function_params))
.map_err(|host_error| {
Expand All @@ -370,7 +369,7 @@ impl Cmd {
address,
nonce,
signature_expiration_ledger: ledger_info.sequence_number + 1,
signature_args: ScVec::default(),
signature: ScVal::Void,
})
}
_ => SorobanCredentials::SourceAccount,
Expand Down Expand Up @@ -473,7 +472,7 @@ pub fn output_to_string(spec: &Spec, res: &ScVal, function: &str) -> Result<Stri
}

fn build_invoke_contract_tx(
parameters: ScVec,
parameters: InvokeContractArgs,
sequence: i64,
fee: u32,
key: &ed25519_dalek::Keypair,
Expand Down
5 changes: 3 additions & 2 deletions cmd/soroban-cli/src/commands/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ mod tests {

use assert_fs::NamedTempFile;
use soroban_env_host::events;
use soroban_sdk::xdr::VecM;

use super::*;

Expand All @@ -320,7 +321,7 @@ mod tests {
contract_id: Some(xdr::Hash([0; 32])),
type_: xdr::ContractEventType::Contract,
body: xdr::ContractEventBody::V0(xdr::ContractEventV0 {
topics: xdr::ScVec(vec![].try_into().unwrap()),
topics: VecM::default(),
data: xdr::ScVal::U32(12345),
}),
},
Expand All @@ -332,7 +333,7 @@ mod tests {
contract_id: Some(xdr::Hash([0x1; 32])),
type_: xdr::ContractEventType::Contract,
body: xdr::ContractEventBody::V0(xdr::ContractEventV0 {
topics: xdr::ScVec(vec![].try_into().unwrap()),
topics: VecM::default(),
data: xdr::ScVal::I32(67890),
}),
},
Expand Down
2 changes: 1 addition & 1 deletion cmd/soroban-cli/src/commands/lab/token/wrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ impl Cmd {
let mut ledger_info = state.ledger_info();
ledger_info.sequence_number += 1;
ledger_info.timestamp += 5;
h.set_ledger_info(ledger_info);
h.set_ledger_info(ledger_info)?;

let res = h.invoke_function(HostFunction::CreateContract(CreateContractArgs {
contract_id_preimage: ContractIdPreimage::Asset(asset.clone()),
Expand Down
11 changes: 8 additions & 3 deletions cmd/soroban-cli/src/rpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use jsonrpsee_core::params::ObjectParams;
use jsonrpsee_core::{self, client::ClientT, rpc_params};
use jsonrpsee_http_client::{HeaderMap, HttpClient, HttpClientBuilder};
use serde_aux::prelude::{deserialize_default_from_null, deserialize_number_from_string};
use soroban_env_host::xdr::DepthLimitedRead;
use soroban_env_host::{
budget::Budget,
events::HostEvent,
Expand Down Expand Up @@ -454,8 +455,9 @@ impl Client {
return Err(Error::NotFound("Account".to_string(), address.to_string()));
}
let ledger_entry = &entries[0];
let mut depth_limit_read = DepthLimitedRead::new(ledger_entry.xdr.as_bytes(), 100);
if let LedgerEntryData::Account(entry) =
LedgerEntryData::read_xdr_base64(&mut ledger_entry.xdr.as_bytes())?
LedgerEntryData::read_xdr_base64(&mut depth_limit_read)?
{
tracing::trace!(account=?entry);
Ok(entry)
Expand Down Expand Up @@ -484,8 +486,11 @@ impl Client {
let error = error_result_xdr
.ok_or(Error::MissingError)
.and_then(|x| {
TransactionResult::read_xdr_base64(&mut x.as_bytes())
.map_err(|_| Error::InvalidResponse)
TransactionResult::read_xdr_base64(&mut DepthLimitedRead::new(
x.as_bytes(),
100,
))
.map_err(|_| Error::InvalidResponse)
})
.map(|r| r.result);
tracing::error!(?error);
Expand Down
30 changes: 16 additions & 14 deletions cmd/soroban-cli/src/rpc/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,10 @@ mod tests {
use super::super::{Cost, SimulateHostFunctionResult};
use soroban_env_host::xdr::{
self, AccountId, ChangeTrustAsset, ChangeTrustOp, ExtensionPoint, Hash, HostFunction,
InvokeHostFunctionOp, LedgerFootprint, Memo, MuxedAccount, Operation, Preconditions,
PublicKey, ScAddress, ScSymbol, ScVal, ScVec, SequenceNumber,
SorobanAuthorizedContractFunction, SorobanAuthorizedFunction, SorobanAuthorizedInvocation,
SorobanResources, SorobanTransactionData, Uint256, WriteXdr,
InvokeContractArgs, InvokeHostFunctionOp, LedgerFootprint, Memo, MuxedAccount, Operation,
Preconditions, PublicKey, ScAddress, ScSymbol, ScVal, SequenceNumber,
SorobanAuthorizedFunction, SorobanAuthorizedInvocation, SorobanResources,
SorobanTransactionData, Uint256, WriteXdr,
};
use stellar_strkey::ed25519::PublicKey as Ed25519PublicKey;

Expand Down Expand Up @@ -126,16 +126,14 @@ mod tests {
)))),
nonce: 0,
signature_expiration_ledger: 0,
signature_args: ScVec(VecM::default()),
signature: ScVal::Void,
}),
root_invocation: SorobanAuthorizedInvocation {
function: SorobanAuthorizedFunction::ContractFn(
SorobanAuthorizedContractFunction {
contract_address: ScAddress::Contract(Hash([0; 32])),
function_name: ScSymbol("fn".try_into().unwrap()),
args: ScVec(VecM::default()),
},
),
function: SorobanAuthorizedFunction::ContractFn(InvokeContractArgs {
contract_address: ScAddress::Contract(Hash([0; 32])),
function_name: ScSymbol("fn".try_into().unwrap()),
args: VecM::default(),
}),
sub_invocations: VecM::default(),
},
};
Expand Down Expand Up @@ -168,7 +166,11 @@ mod tests {
operations: vec![Operation {
source_account: None,
body: OperationBody::InvokeHostFunction(InvokeHostFunctionOp {
host_function: HostFunction::InvokeContract(ScVec(VecM::default())),
host_function: HostFunction::InvokeContract(InvokeContractArgs {
contract_address: ScAddress::Contract(Hash([0x0; 32])),
function_name: ScSymbol::default(),
args: VecM::default(),
}),
auth: VecM::default(),
}),
}]
Expand Down Expand Up @@ -210,7 +212,7 @@ mod tests {
assert_eq!(1, op.auth.len());
let auth = &op.auth[0];

let xdr::SorobanAuthorizedFunction::ContractFn(xdr::SorobanAuthorizedContractFunction{ ref function_name, .. }) = auth.root_invocation.function else {
let xdr::SorobanAuthorizedFunction::ContractFn(InvokeContractArgs{ ref function_name, .. }) = auth.root_invocation.function else {
panic!("unexpected function type");
};
assert_eq!("fn".to_string(), format!("{}", function_name.0));
Expand Down
23 changes: 15 additions & 8 deletions cmd/soroban-cli/src/utils/contract_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ use std::{
};

use soroban_env_host::xdr::{
self, ReadXdr, ScEnvMetaEntry, ScMetaEntry, ScMetaV0, ScSpecEntry, ScSpecFunctionV0,
ScSpecUdtEnumV0, ScSpecUdtErrorEnumV0, ScSpecUdtStructV0, ScSpecUdtUnionV0, StringM,
self, DepthLimitedRead, ReadXdr, ScEnvMetaEntry, ScMetaEntry, ScMetaV0, ScSpecEntry,
ScSpecFunctionV0, ScSpecUdtEnumV0, ScSpecUdtErrorEnumV0, ScSpecUdtStructV0, ScSpecUdtUnionV0,
StringM,
};

pub struct ContractSpec {
Expand Down Expand Up @@ -57,26 +58,32 @@ impl ContractSpec {
let mut env_meta_base64 = None;
let env_meta = if let Some(env_meta) = env_meta {
env_meta_base64 = Some(base64::encode(env_meta));
let mut cursor = Cursor::new(env_meta);
ScEnvMetaEntry::read_xdr_iter(&mut cursor).collect::<Result<Vec<_>, xdr::Error>>()?
let cursor = Cursor::new(env_meta);
let mut depth_limit_read = DepthLimitedRead::new(cursor, 100);
ScEnvMetaEntry::read_xdr_iter(&mut depth_limit_read)
.collect::<Result<Vec<_>, xdr::Error>>()?
} else {
vec![]
};

let mut meta_base64 = None;
let meta = if let Some(meta) = meta {
meta_base64 = Some(base64::encode(meta));
let mut cursor = Cursor::new(meta);
ScMetaEntry::read_xdr_iter(&mut cursor).collect::<Result<Vec<_>, xdr::Error>>()?
let cursor = Cursor::new(meta);
let mut depth_limit_read = DepthLimitedRead::new(cursor, 100);
ScMetaEntry::read_xdr_iter(&mut depth_limit_read)
.collect::<Result<Vec<_>, xdr::Error>>()?
} else {
vec![]
};

let mut spec_base64 = None;
let spec = if let Some(spec) = spec {
spec_base64 = Some(base64::encode(spec));
let mut cursor = Cursor::new(spec);
ScSpecEntry::read_xdr_iter(&mut cursor).collect::<Result<Vec<_>, xdr::Error>>()?
let cursor = Cursor::new(spec);
let mut depth_limit_read = DepthLimitedRead::new(cursor, 100);
ScSpecEntry::read_xdr_iter(&mut depth_limit_read)
.collect::<Result<Vec<_>, xdr::Error>>()?
} else {
vec![]
};
Expand Down
Loading

0 comments on commit 485ebad

Please sign in to comment.