pub mod exceptions; mod submit_and_wait; use bigdecimal::{BigDecimal, RoundingMode}; pub use submit_and_wait::*; // `sign` lives in `crate::signing` (pure crypto, no async client required). // Re-exported here for backward compatibility. pub use crate::signing::sign; use crate::{ asynch::{ account::get_next_valid_seq_number, clients::{CommonFields, XRPLAsyncClient}, ledger::{get_fee, get_latest_validated_ledger_sequence}, transaction::exceptions::XRPLSignTransactionException, }, core::binarycodec::encode, models::{ requests::{ account_info::AccountInfo, ledger_entry::LedgerEntry, server_state::ServerState, submit::Submit, }, results::{ ledger_entry::LedgerEntry as LedgerEntryResult, server_state::ServerState as ServerStateResult, submit::Submit as SubmitResult, }, transactions::{ batch::{BatchSigner, RawTransaction}, Transaction, TransactionType, }, Model, XRPAmount, XRPLModelException, }, wallet::Wallet, }; use alloc::string::String; use alloc::string::ToString; use alloc::vec::Vec; use alloc::{borrow::Cow, collections::btree_map::BTreeMap}; use core::convert::TryInto; use core::fmt::Debug; use exceptions::XRPLTransactionHelperException; use serde::de::DeserializeOwned; use serde::Serialize; use strum::IntoEnumIterator; use super::exceptions::XRPLHelperResult; const OWNER_RESERVE: &str = "2000000"; // 2 XRP const RESTRICTED_NETWORKS: u16 = 1024; const REQUIRED_NETWORKID_VERSION: &str = "1.11.0"; const LEDGER_OFFSET: u8 = 20; /// ConfidentialMPT transactions pay 10× the reference base fee, covering the /// cost of verifying the transaction's zero-knowledge proof. rippled computes /// this *additively* — `base + base × kConfidentialFeeMultiplier` with /// `kConfidentialFeeMultiplier = 9`, for a total of `10 × base`. This constant /// names that total (10), so it is applied multiplicatively here; the on-ledger /// result is identical. const CONFIDENTIAL_MPT_FEE_MULTIPLIER: u64 = 10; pub async fn sign_and_submit<'a, 'b, T, F, C>( transaction: &mut T, client: &'b C, wallet: &Wallet, autofill: bool, check_fee: bool, ) -> XRPLHelperResult> where F: IntoEnumIterator + Serialize + Debug + PartialEq, T: Transaction<'a, F> + Model + Serialize + DeserializeOwned + Clone + Debug, C: XRPLAsyncClient, { if autofill { autofill_and_sign(transaction, client, wallet, check_fee).await?; } else { if check_fee { check_txn_fee(transaction, client).await?; } sign(transaction, wallet, false)?; } submit(transaction, client).await } pub async fn autofill<'a, 'b, F, T, C>( transaction: &mut T, client: &'b C, signers_count: Option, ) -> XRPLHelperResult<()> where T: Transaction<'a, F> + Model + Clone, F: IntoEnumIterator + Serialize + Debug + PartialEq, C: XRPLAsyncClient, { let txn = transaction.clone(); let txn_common_fields = transaction.get_mut_common_fields(); let common_fields = client.get_common_fields().await?; if txn_common_fields.network_id.is_none() && txn_needs_network_id(common_fields.clone())? { txn_common_fields.network_id = common_fields.network_id; } if txn_common_fields.sequence.is_none() { txn_common_fields.sequence = Some(get_next_valid_seq_number(txn_common_fields.account.clone(), client, None).await?); } if txn_common_fields.fee.is_none() { txn_common_fields.fee = Some(calculate_fee_per_transaction_type(&txn, Some(client), signers_count).await?); } if txn_common_fields.last_ledger_sequence.is_none() { let ledger_sequence = get_latest_validated_ledger_sequence(client).await?; txn_common_fields.last_ledger_sequence = Some(ledger_sequence + LEDGER_OFFSET as u32); } if matches!(transaction.get_transaction_type(), TransactionType::Batch) { autofill_raw_transactions(transaction, client).await?; } Ok(()) } pub async fn autofill_raw_transactions<'a, F, T, C>( transaction: &mut T, client: &C, ) -> XRPLHelperResult<()> where T: Transaction<'a, F>, F: IntoEnumIterator + Serialize + Debug + PartialEq, C: XRPLAsyncClient, { let outer_account = transaction.get_common_fields().account.to_string(); let outer_sequence = transaction .get_common_fields() .sequence .ok_or_else(|| XRPLModelException::MissingField("batch `sequence`".into()))?; let raw_txs = transaction .raw_transactions_mut() .ok_or_else(|| XRPLModelException::MissingField("RawTransactions".into()))?; // Next sequence to hand out, per account. let mut next_sequence: BTreeMap = BTreeMap::new(); next_sequence.insert( outer_account.to_string(), checked_next(outer_sequence, "sequence")?, ); let mut filled = Vec::with_capacity(raw_txs.len()); for raw in raw_txs.iter_mut() { let tx_type = raw.transaction_type()?; if tx_type == TransactionType::Batch { Err(XRPLModelException::InvalidValue { field: "raw_transactions".into(), expected: "no nested Batch".into(), found: "Batch".into(), })?; } let account = raw .get_field::("Account")? .ok_or_else(|| XRPLModelException::MissingField(format!("{}.Account", tx_type)))?; if raw.get_field::("Sequence")?.is_none() && raw.get_field::("TicketSequence")?.is_none() { let sequence = match next_sequence.get(&account).copied() { Some(sequence) => sequence, None => get_next_valid_seq_number(account.as_str().into(), client, None).await?, }; next_sequence.insert(account, checked_next(sequence, "Sequence")?); raw.set_field("Sequence", &sequence); } raw.set_field("Fee", &"0"); raw.set_field("SigningPubKey", &""); if raw.get_field::("LastLedgerSequence")?.is_some() { Err(XRPLModelException::InvalidValue { field: format!("{}.LastLedgerSequence", tx_type), expected: "no LastLedgerSequence".into(), found: "LastLedgerSequence".into(), })? } let common_fields = client.get_common_fields().await?; if raw.get_field::("NetworkID")?.is_none() && txn_needs_network_id(common_fields.clone())? { raw.set_field("NetworkID", &common_fields.network_id); } filled.push(raw.clone()); } *raw_txs = filled; Ok(()) } fn checked_next(sequence: u32, field: &str) -> XRPLHelperResult { let r = sequence .checked_add(1) .ok_or_else(|| XRPLModelException::InvalidValue { field: field.to_string(), expected: "a sequence below u32::MAX".to_string(), found: sequence.to_string(), })?; Ok(r) } pub async fn autofill_and_sign<'a, 'b, T, F, C>( transaction: &mut T, client: &'b C, wallet: &Wallet, check_fee: bool, ) -> XRPLHelperResult<()> where F: IntoEnumIterator + Serialize + Debug + PartialEq, T: Transaction<'a, F> + Model + Serialize + DeserializeOwned + Clone + Debug, C: XRPLAsyncClient, { if check_fee { check_txn_fee(transaction, client).await?; } autofill(transaction, client, None).await?; sign(transaction, wallet, false)?; Ok(()) } pub async fn submit<'a, T, F, C>(transaction: &T, client: &C) -> XRPLHelperResult> where F: IntoEnumIterator + Serialize + Debug + PartialEq, T: Transaction<'a, F> + Model + Serialize + DeserializeOwned + Clone + Debug, C: XRPLAsyncClient, { transaction.validate()?; let txn_blob = encode(transaction)?; let req = Submit::new(None, txn_blob.into(), None); let res = client.request(req.into()).await?; Ok(res.try_into()?) } pub async fn calculate_fee_per_transaction_type<'a, 'b, 'c, T, F, C>( transaction: &T, client: Option<&'b C>, signers_count: Option, ) -> XRPLHelperResult> where T: Transaction<'a, F>, F: IntoEnumIterator + Serialize + Debug + PartialEq, C: XRPLAsyncClient, { let mut net_fee = XRPAmount::from("10"); let base_fee; if let Some(client) = client { net_fee = get_fee(client, None, None).await?; base_fee = match transaction.get_transaction_type() { TransactionType::EscrowFinish => calculate_base_fee_for_escrow_finish( net_fee.clone(), transaction .get_field_value("fulfillment")? .map(|fulfillment| fulfillment.into()), )?, TransactionType::AMMCreate | TransactionType::AccountDelete => { get_owner_reserve_from_response(client).await? } TransactionType::Batch => { calculate_base_fee_for_batch(transaction, &net_fee, Some(client)).await? } TransactionType::ConfidentialMPTConvert | TransactionType::ConfidentialMPTConvertBack | TransactionType::ConfidentialMPTSend | TransactionType::ConfidentialMPTClawback | TransactionType::ConfidentialMPTMergeInbox => { calculate_base_fee_for_confidential_mpt(net_fee.clone())? } _ => net_fee.clone(), }; } else { base_fee = match transaction.get_transaction_type() { TransactionType::EscrowFinish => calculate_base_fee_for_escrow_finish( net_fee.clone(), transaction .get_field_value("fulfillment")? .map(|fulfillment| fulfillment.into()), )?, TransactionType::AMMCreate | TransactionType::AccountDelete => { XRPAmount::from(OWNER_RESERVE) } TransactionType::Batch => { calculate_base_fee_for_batch(transaction, &net_fee, None::<&C>).await? } TransactionType::ConfidentialMPTConvert | TransactionType::ConfidentialMPTConvertBack | TransactionType::ConfidentialMPTSend | TransactionType::ConfidentialMPTClawback | TransactionType::ConfidentialMPTMergeInbox => { calculate_base_fee_for_confidential_mpt(net_fee.clone())? } _ => net_fee.clone(), }; } let mut base_fee_decimal: BigDecimal = base_fee.try_into()?; // A `LoanSet` also pays one reference base fee per counterparty signer // (rippled `LoanSet::calculateBaseFee`: `normalCost + signerCount * base`). // `Fee` is a signing field, so it cannot be raised after the first party // signs — it has to be right here, before the transaction is distributed // for counterparty signing. if transaction.get_transaction_type() == &TransactionType::LoanSet { // Without a client the counterparty's signer list is unknown, but // rippled always charges for at least one counterparty signature // outside a Batch, so one base fee is the floor — not zero, which would // underestimate and force a re-sign. let counterparty_signers = match client { Some(client) => get_counterparty_signers_count(transaction, client).await?, None => 1, }; let net_fee_decimal: BigDecimal = net_fee.clone().try_into()?; base_fee_decimal += &(net_fee_decimal * BigDecimal::from(counterparty_signers)); } if let Some(signers_count) = signers_count { // rippled charges one extra reference base fee per signer on top of the // transaction's own base cost (Transactor::calculateBaseFee: // `base + signerCount * base`). base_fee already includes the reference // "1", so add only `signers_count` more — NOT `1 + signers_count`, which // would double-count the reference fee and overcharge by one base fee. let net_fee_decimal: BigDecimal = net_fee.try_into()?; let signer_count_fee_decimal: BigDecimal = signers_count.into(); base_fee_decimal += &(net_fee_decimal * signer_count_fee_decimal); } Ok(base_fee_decimal .with_scale_round(0, RoundingMode::Down) .into()) } /// The number of counterparty signatures a `LoanSet` will carry, for fee /// purposes. /// /// The counterparty is the `Counterparty` account when the transaction names /// one; otherwise the borrower submitted it and the counterparty is the /// broker's owner, which is read from the `LoanBroker` ledger entry (rippled /// `LoanSet.cpp`: `counterparty = tx[~sfCounterparty].value_or(brokerOwner)`). An account /// with a signer list contributes one signature per signer entry; an account /// without one signs once. /// /// This is an upper bound, not the exact count. rippled charges on the /// signatures the transaction actually carries /// (`max(1, |CounterpartySignature.Signers|)`), but those do not exist yet at /// autofill time — the counterparty signs later, possibly on another machine — /// so the signer list is the only thing available to size the fee from. A /// counterparty that owns a signer list but single-signs therefore overpays by /// one base fee per unused signer entry; it never underpays, which would cost a /// `telINSUF_FEE_P` and a re-signing round trip, since `Fee` is a signing field. /// Callers who know the exact count can set `Fee` themselves before calling /// `autofill`, which skips this calculation entirely. /// /// Mirrors `fetchCounterPartySignersCount` in xrpl.js's `autofill`, which sizes /// the fee the same way. async fn get_counterparty_signers_count<'a, T, F, C>( transaction: &T, client: &C, ) -> XRPLHelperResult where T: Transaction<'a, F>, F: IntoEnumIterator + Serialize + Debug + PartialEq, C: XRPLAsyncClient, { fn unquote(value: String) -> String { value.trim_matches('"').to_string() } let counterparty = match transaction.get_field_value("Counterparty")? { Some(counterparty) => unquote(counterparty), None => { let loan_broker_id = transaction .get_field_value("LoanBrokerID")? .map(unquote) .ok_or_else(|| { XRPLModelException::MissingField( "LoanBrokerID (required to resolve the LoanSet counterparty)".to_string(), ) })?; let response = client .request( LedgerEntry { index: Some(loan_broker_id.into()), ..Default::default() } .into(), ) .await?; let result: LedgerEntryResult = response.try_into()?; let node = result.node.ok_or_else(|| { XRPLModelException::MissingField("LoanBroker ledger entry".to_string()) })?; node["Owner"] .as_str() .ok_or_else(|| XRPLModelException::MissingField("LoanBroker.Owner".to_string()))? .to_string() } }; let response = client .request( AccountInfo::new( None, counterparty.into(), None, None, None, None, Some(true), ) .into(), ) .await?; let result = response .raw_result .ok_or_else(|| XRPLModelException::MissingField("account_info result".to_string()))?; // `signer_lists` sits at the root of the response under api_version 2 but // nested inside `account_data` under api_version 1, which is what rippled // serves when the request does not ask for a version — so accept either. let signer_lists = result.get("signer_lists").or_else(|| { result .get("account_data") .and_then(|d| d.get("signer_lists")) }); // An account without a signer list signs once; otherwise it contributes one // signature per signer entry. Ok(signer_lists .and_then(|lists| lists.get(0)) .and_then(|list| list.get("SignerEntries")) .and_then(|entries| entries.as_array()) .map(|entries| entries.len() as u32) .unwrap_or(1)) } async fn get_owner_reserve_from_response( client: &impl XRPLAsyncClient, ) -> XRPLHelperResult> { let owner_reserve_response = client.request(ServerState::new(None).into()).await?; let result: ServerStateResult = owner_reserve_response.try_into()?; match result.state.validated_ledger { Some(validated_ledger) => Ok(validated_ledger.reserve_inc), None => Err(XRPLModelException::MissingField("validated_ledger".to_string()).into()), } } fn calculate_base_fee_for_escrow_finish<'a: 'b, 'b>( net_fee: XRPAmount<'a>, fulfillment: Option>, ) -> XRPLHelperResult> { if let Some(fulfillment) = fulfillment { calculate_based_on_fulfillment(fulfillment, net_fee) } else { Ok(net_fee) } } fn calculate_based_on_fulfillment<'a>( fulfillment: Cow, net_fee: XRPAmount<'_>, ) -> XRPLHelperResult> { let fulfillment_bytes: Vec = fulfillment.chars().map(|c| c as u8).collect(); let net_fee_f64: f64 = net_fee.try_into()?; let base_fee_string = (net_fee_f64 * (33.0 + (fulfillment_bytes.len() as f64 / 16.0))).to_string(); let base_fee: XRPAmount = base_fee_string.into(); let base_fee_decimal: BigDecimal = base_fee.try_into()?; Ok(base_fee_decimal .with_scale_round(0, RoundingMode::Down) .into()) } /// ConfidentialMPT transactions pay [`CONFIDENTIAL_MPT_FEE_MULTIPLIER`]× the /// reference base fee (rippled's `kCONFIDENTIAL_FEE_MULTIPLIER`), reflecting the /// cost of verifying the transaction's zero-knowledge proof. fn calculate_base_fee_for_confidential_mpt<'a: 'b, 'b>( net_fee: XRPAmount<'a>, ) -> XRPLHelperResult> { let net_fee_decimal: BigDecimal = net_fee.try_into()?; let base_fee_decimal = net_fee_decimal * BigDecimal::from(CONFIDENTIAL_MPT_FEE_MULTIPLIER); Ok(base_fee_decimal .with_scale_round(0, RoundingMode::Down) .into()) } /// XLS-56 §2.2: `(2 + n) × base + Σ inner base fees`, `n` = signatures in /// `BatchSigners` (a multi-signed entry counts each signer). Outer multisign /// signers are added by the caller through `signers_count`. async fn calculate_base_fee_for_batch<'a, T, F, C>( transaction: &T, net_fee: &XRPAmount<'_>, client: Option<&C>, ) -> XRPLHelperResult> where T: Transaction<'a, F>, F: IntoEnumIterator + Serialize + Debug + PartialEq, C: XRPLAsyncClient, { let raw_transactions: Vec = match transaction.get_field_value("RawTransactions")? { Some(json) => serde_json::from_str(&json).map_err(XRPLModelException::from)?, None => Vec::new(), }; let batch_signers: Vec = match transaction.get_field_value("BatchSigners")? { Some(json) => serde_json::from_str(&json).map_err(XRPLModelException::from)?, None => Vec::new(), }; let net: BigDecimal = net_fee.clone().try_into()?; // server_state exposes the open-ledger escalation and reference factors; // scale XRP reserve-based inner fees by their ratio, matching net_fee. let has_reserve_fee = raw_transactions.iter().any(|raw| { matches!( raw.transaction_type(), Ok(TransactionType::AMMCreate | TransactionType::AccountDelete) ) }); let load_scale = if has_reserve_fee { if let Some(client) = client { let response = client.request(ServerState::new(None).into()).await?; let result: ServerStateResult = response.try_into()?; match ( result.state.load_factor_fee_escalation, result.state.load_factor_fee_reference, ) { (Some(escalation), Some(reference)) if reference != 0 => { BigDecimal::from(escalation) / BigDecimal::from(reference) } _ => BigDecimal::from(1u8), } } else { BigDecimal::from(1u8) } } else { BigDecimal::from(1u8) }; let mut total = &net * BigDecimal::from(2u8); let signatures: usize = batch_signers .iter() .map(|s| s.signers.as_ref().map_or(1, Vec::len)) .sum(); total += &(&net * BigDecimal::from(signatures as u64)); let mut owner_reserve: Option = None; for raw in &raw_transactions { let inner: BigDecimal = match raw.transaction_type()? { TransactionType::AMMCreate | TransactionType::AccountDelete => { if owner_reserve.is_none() { let reserve = match client { Some(client) => get_owner_reserve_from_response(client).await?, None => XRPAmount::from(OWNER_RESERVE), }; owner_reserve = Some(reserve.try_into()?); } owner_reserve.clone().unwrap_or_default() * &load_scale } TransactionType::ConfidentialMPTConvert | TransactionType::ConfidentialMPTConvertBack | TransactionType::ConfidentialMPTSend | TransactionType::ConfidentialMPTClawback | TransactionType::ConfidentialMPTMergeInbox => { &net * BigDecimal::from(CONFIDENTIAL_MPT_FEE_MULTIPLIER) } TransactionType::EscrowFinish => calculate_base_fee_for_escrow_finish( net_fee.clone(), raw.as_json() .get("Fulfillment") .and_then(|v| v.as_str()) .map(Cow::Borrowed), )? .try_into()?, _ => net.clone(), }; total += &inner; } Ok(total.with_scale_round(0, RoundingMode::Down).into()) } fn txn_needs_network_id(common_fields: CommonFields<'_>) -> XRPLHelperResult { let is_higher_restricted_networks = if let Some(network_id) = common_fields.network_id { network_id > RESTRICTED_NETWORKS as u32 } else { false }; if let Some(build_version) = common_fields.build_version { match is_not_later_rippled_version(REQUIRED_NETWORKID_VERSION.into(), build_version.into()) { Ok(is_not_later_rippled_version) => { Ok(is_higher_restricted_networks && is_not_later_rippled_version) } Err(e) => Err(e), } } else { Ok(false) } } fn is_not_later_rippled_version(source: String, target: String) -> XRPLHelperResult { if source == target { Ok(true) } else { let source_decomp = source .split('.') .map(|i| i.to_string()) .collect::>(); let target_decomp = target .split('.') .map(|i| i.to_string()) .collect::>(); let (source_major, source_minor) = ( source_decomp[0] .parse::() .map_err(XRPLTransactionHelperException::ParseRippledVersionError)?, source_decomp[1] .parse::() .map_err(XRPLTransactionHelperException::ParseRippledVersionError)?, ); let (target_major, target_minor) = ( target_decomp[0] .parse::() .map_err(XRPLTransactionHelperException::ParseRippledVersionError)?, target_decomp[1] .parse::() .map_err(XRPLTransactionHelperException::ParseRippledVersionError)?, ); if source_major != target_major { Ok(source_major < target_major) } else if source_minor != target_minor { Ok(source_minor < target_minor) } else { let source_patch = source_decomp[2] .split('-') .map(|i| i.to_string()) .collect::>(); let target_patch = target_decomp[2] .split('-') .map(|i| i.to_string()) .collect::>(); let source_patch_version = source_patch[0] .parse::() .map_err(XRPLTransactionHelperException::ParseRippledVersionError)?; let target_patch_version = target_patch[0] .parse::() .map_err(XRPLTransactionHelperException::ParseRippledVersionError)?; if source_patch_version != target_patch_version { Ok(source_patch_version < target_patch_version) } else if source_patch.len() != target_patch.len() { Ok(source_patch.len() < target_patch.len()) } else if source_patch.len() == 2 { if source_patch[1].chars().next().ok_or( XRPLTransactionHelperException::InvalidRippledVersion( "source patch version".into(), ), )? != target_patch[1].chars().next().ok_or( XRPLTransactionHelperException::InvalidRippledVersion( "target patch version".into(), ), )? { Ok(source_patch[1] < target_patch[1]) } else if source_patch[1].starts_with('b') { Ok(source_patch[1][1..] < target_patch[1][1..]) } else { Ok(source_patch[1][2..] < target_patch[1][2..]) } } else { Ok(false) } } } } async fn check_txn_fee<'a, 'b, T, F, C>(transaction: &mut T, client: &'b C) -> XRPLHelperResult<()> where F: IntoEnumIterator + Serialize + Debug + PartialEq, T: Transaction<'a, F> + Model + Serialize + DeserializeOwned + Clone, C: XRPLAsyncClient, { // max of xrp_to_drops(0.1) and calculate_fee_per_transaction_type let expected_fee = XRPAmount::from("100000") .max(calculate_fee_per_transaction_type(transaction, Some(client), None).await?); let transaction_fee = transaction .get_common_fields() .fee .clone() .unwrap_or(XRPAmount::from("0")); if transaction_fee > expected_fee { Err(XRPLSignTransactionException::FeeTooHigh(transaction_fee.to_string()).into()) } else { Ok(()) } } #[cfg(all(feature = "websocket", feature = "std", feature = "integration"))] #[cfg(test)] mod test_autofill { use super::autofill; use crate::{ asynch::{ clients::{AsyncWebSocketClient, SingleExecutorMutex}, exceptions::XRPLHelperResult, }, models::{ transactions::{offer_create::OfferCreate, Transaction}, IssuedCurrencyAmount, XRPAmount, }, }; #[tokio::test] async fn test_autofill_txn() -> XRPLHelperResult<()> { let ws_url = std::env::var("XRPL_WS_URL") .unwrap_or_else(|_| "wss://s.altnet.rippletest.net:51233/".to_string()); let account = if ws_url.contains("localhost") || ws_url.contains("127.0.0.1") { "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" } else { "r9mhdWo1NXVZr2pDnCtC1xwxE85kFtSzYR" }; let mut txn = OfferCreate::new( account.into(), None, None, None, None, None, None, None, None, None, XRPAmount::from("1000000").into(), IssuedCurrencyAmount::new( "USD".into(), "rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq".into(), "0.3".into(), ) .into(), None, None, ); let open_result = AsyncWebSocketClient::::open(ws_url.parse().unwrap()).await; let client = match open_result { Ok(c) => c, Err(e) => { let msg = e.to_string(); if crate::utils::testing::is_known_network_error(&msg) { return Ok(()); } return Err(e.into()); } }; let fill_result = autofill(&mut txn, &client, None).await; if let Err(ref e) = fill_result { let msg = e.to_string(); if crate::utils::testing::is_known_network_error(&msg) { return Ok(()); } } fill_result?; assert!(txn.get_common_fields().network_id.is_none()); assert!(txn.get_common_fields().sequence.is_some()); assert!(txn.get_common_fields().fee.is_some()); assert!(txn.get_common_fields().last_ledger_sequence.is_some()); Ok(()) } } #[cfg(all(feature = "json-rpc", feature = "std"))] #[cfg(test)] mod test_sign { use alloc::borrow::Cow; use crate::{ asynch::{ clients::AsyncJsonRpcClient, transaction::{autofill_and_sign, sign}, wallet::generate_faucet_wallet, }, handle_test_result, models::transactions::{ account_set::AccountSet, CommonFields, Transaction, TransactionType, }, utils::testing::{ assertions, test_constants, test_network_operation, test_wallets, TestTimeouts, }, }; #[test] fn test_sign() { let wallet = test_wallets::create_test_wallet_unwrap(); let mut tx = AccountSet { common_fields: CommonFields::from_account(&wallet.classic_address) .with_transaction_type(TransactionType::AccountSet) .with_fee("10".into()) .with_sequence(227234), domain: Some(test_constants::EXAMPLE_COM_HEX.into()), ..Default::default() }; sign(&mut tx, &wallet, false).unwrap(); let expected_signature: Cow = "C3F435CFBFAE996FE297F3A71BEAB68FF5322CBF039E41A9615BC48A59FB4EC\ 5A55F8D4EC0225D47056E02ECCCDF7E8FF5F8B7FAA1EBBCBF7D0491FCB2D98807" .into(); let actual_signature = tx.get_common_fields().txn_signature.as_ref().unwrap(); assert_eq!(expected_signature, *actual_signature); assertions::assert_transaction_signed(&tx); } #[test] fn test_multisign() { let wallet = test_wallets::create_test_wallet_unwrap(); let mut tx = AccountSet { common_fields: CommonFields::from_account(&wallet.classic_address) .with_transaction_type(TransactionType::AccountSet) .with_fee("10".into()) .with_sequence(227234), domain: Some(test_constants::EXAMPLE_COM_HEX.into()), ..Default::default() }; sign(&mut tx, &wallet, true).unwrap(); assertions::assert_transaction_multisigned(&tx); } #[cfg(feature = "integration")] #[tokio::test] async fn test_autofill_and_sign() { let client = AsyncJsonRpcClient::connect(test_constants::TESTNET_URL.parse().unwrap()); let wallet_result = test_network_operation( generate_faucet_wallet(&client, None, None, None, None), TestTimeouts::FAUCET, "faucet wallet generation for autofill test", ) .await; let wallet = handle_test_result!(wallet_result, "test_autofill_and_sign - wallet generation"); let mut tx = AccountSet { common_fields: CommonFields::from_account(&wallet.classic_address) .with_transaction_type(TransactionType::AccountSet), domain: Some(test_constants::EXAMPLE_COM_HEX.into()), ..Default::default() }; // Try autofill_and_sign with timeout and error handling let autofill_result = test_network_operation( autofill_and_sign(&mut tx, &client, &wallet, true), TestTimeouts::NETWORK, "autofill and sign", ) .await; handle_test_result!( autofill_result, "test_autofill_and_sign - autofill operation" ); // Verify the transaction was properly filled and signed assertions::assert_transaction_autofilled(&tx); assertions::assert_transaction_signed(&tx); } #[test] fn test_transaction_creation() { // Test the transaction builder pattern without network calls let wallet = test_wallets::create_test_wallet_unwrap(); let tx = AccountSet { common_fields: CommonFields::from_account(&wallet.classic_address) .with_transaction_type(TransactionType::AccountSet) .with_fee("12".into()) .with_sequence(100), domain: Some(test_constants::EXAMPLE_COM_HEX.into()), ..Default::default() }; assert_eq!(tx.common_fields.account, wallet.classic_address); assert_eq!( tx.common_fields.transaction_type, TransactionType::AccountSet ); assert_eq!(tx.common_fields.fee, Some("12".into())); assert_eq!(tx.common_fields.sequence, Some(100)); assert_eq!(tx.domain, Some(test_constants::EXAMPLE_COM_HEX.into())); // Test that we can get common fields let common_fields = tx.get_common_fields(); assert_eq!(common_fields.account, wallet.classic_address); assert!(!common_fields.is_signed()); // Should not be signed yet } } #[cfg(all(feature = "json-rpc", feature = "std"))] #[cfg(test)] mod test_calculate_fee { use super::calculate_base_fee_for_confidential_mpt; use crate::models::XRPAmount; #[test] fn confidential_mpt_base_fee_is_ten_times_base() { let fee = calculate_base_fee_for_confidential_mpt(XRPAmount::from("200")).unwrap(); assert_eq!(fee, XRPAmount::from("2000")); } } // Autofill flow for every ConfidentialMPT transaction (akin to `test_autofill`'s // OfferCreate test). These tests use `AsyncJsonRpcClient` against `localhost:5005`. They // assert autofill populates the common fields and applies the 10× cMPT fee. #[cfg(all( feature = "json-rpc", feature = "std", feature = "integration", feature = "confidential-mpt" ))] #[cfg(test)] mod test_autofill_confidential_mpt { use super::autofill; use crate::asynch::clients::AsyncJsonRpcClient; use crate::models::transactions::{ confidential_mpt_clawback::ConfidentialMPTClawback, confidential_mpt_convert::ConfidentialMPTConvert, confidential_mpt_convert_back::ConfidentialMPTConvertBack, confidential_mpt_merge_inbox::ConfidentialMPTMergeInbox, confidential_mpt_send::ConfidentialMPTSend, CommonFields, Transaction, TransactionType, }; use crate::models::XRPAmount; // Genesis account on the standalone node — exists + funded, so autofill can // resolve its sequence. autofill never submits, so each transaction's // cMPT-specific fields are left at their defaults. const GENESIS: &str = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; const STANDALONE_URL: &str = "http://localhost:5005"; // Each ConfidentialMPT transaction autofills to 10× the reference base fee // (rippled's kCONFIDENTIAL_FEE_MULTIPLIER); the node's 200-drop base → 2000, // alongside an autofilled sequence + last_ledger_sequence. macro_rules! autofill_fee_test { ($name:ident, $ty:ident) => { #[tokio::test] async fn $name() { let mut tx = $ty { common_fields: CommonFields { account: GENESIS.into(), transaction_type: TransactionType::$ty, ..Default::default() }, ..Default::default() }; let client = AsyncJsonRpcClient::connect(STANDALONE_URL.parse().unwrap()); autofill(&mut tx, &client, None) .await .expect("autofill should populate the common fields"); let common = tx.get_common_fields(); assert!(common.sequence.is_some(), "autofill should set sequence"); assert!( common.last_ledger_sequence.is_some(), "autofill should set last_ledger_sequence" ); assert_eq!(common.fee, Some(XRPAmount::from("2000"))); } }; } autofill_fee_test!(merge_inbox_autofill, ConfidentialMPTMergeInbox); autofill_fee_test!(convert_autofill, ConfidentialMPTConvert); autofill_fee_test!(convert_back_autofill, ConfidentialMPTConvertBack); autofill_fee_test!(send_autofill, ConfidentialMPTSend); autofill_fee_test!(clawback_autofill, ConfidentialMPTClawback); }