From d47da7b0a09d15172617d0bf88fe60d4e9c4fdb0 Mon Sep 17 00:00:00 2001 From: lisicky Date: Tue, 12 Nov 2024 16:32:17 +0800 Subject: [PATCH] add useful error for collateral return --- rust/src/builders/tx_builder.rs | 7 +++++++ rust/src/tests/builders/tx_builder.rs | 29 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/rust/src/builders/tx_builder.rs b/rust/src/builders/tx_builder.rs index f885c195..8269886d 100644 --- a/rust/src/builders/tx_builder.rs +++ b/rust/src/builders/tx_builder.rs @@ -803,6 +803,13 @@ impl TransactionBuilder { )); } let col_input_value: Value = collateral.total_value()?; + let col_input_coin = col_input_value.coin; + if col_input_coin < *total_collateral { + return Err(JsError::from_str( + "Total collateral value cannot exceed the sum of collateral inputs", + )); + } + let col_return: Value = col_input_value.checked_sub(&Value::new(&total_collateral))?; if col_return.multiasset.is_some() || col_return.coin > BigNum::zero() { let return_output = TransactionOutput::new(return_address, &col_return); diff --git a/rust/src/tests/builders/tx_builder.rs b/rust/src/tests/builders/tx_builder.rs index 6035c607..52cb339c 100644 --- a/rust/src/tests/builders/tx_builder.rs +++ b/rust/src/tests/builders/tx_builder.rs @@ -4923,6 +4923,35 @@ fn test_add_collateral_return_fails_no_enough_ada() { assert!(tx_builder.collateral_return.is_none()); } +#[test] +fn test_add_collateral_return_fails_no_enough_ada_to_cover_return() { + let mut tx_builder = fake_reallistic_tx_builder(); + tx_builder.set_fee(&BigNum(123456)); + + let masset = fake_multiasset(123); + + let mut inp = TxInputsBuilder::new(); + let collateral_input_value = 2_000_000; + inp.add_regular_input( + &fake_base_address(0), + &fake_tx_input(0), + &Value::new_with_assets(&BigNum(collateral_input_value.clone()), &masset), + ).expect("Failed to add input"); + + tx_builder.set_collateral(&inp); + + let collateral_return_address = fake_base_address(1); + + let total_collateral = BigNum(collateral_input_value + 1); + + let coll_add_res = tx_builder + .set_total_collateral_and_return(&total_collateral, &collateral_return_address); + + assert!(coll_add_res.is_err()); + assert!(tx_builder.total_collateral.is_none()); + assert!(tx_builder.collateral_return.is_none()); +} + #[test] fn test_auto_calc_collateral_return_fails_on_no_collateral() { let mut tx_builder = fake_reallistic_tx_builder();