Skip to content

Commit

Permalink
add useful error for collateral return
Browse files Browse the repository at this point in the history
  • Loading branch information
lisicky committed Nov 12, 2024
1 parent c55738a commit d47da7b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
7 changes: 7 additions & 0 deletions rust/src/builders/tx_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
29 changes: 29 additions & 0 deletions rust/src/tests/builders/tx_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit d47da7b

Please sign in to comment.