Skip to content

Commit 26c69f6

Browse files
committed
fix: update invoice amount calculations to handle fees correctly
1 parent e2fd50f commit 26c69f6

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

crates/fiber-lib/src/cch/actor.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -500,7 +500,10 @@ impl<S: CchOrderStore> CchState<S> {
500500
.as_ref(),
501501
)
502502
.into();
503-
let invoice_amount_sats = amount_msat.div_ceil(1_000u128) + fee_sats;
503+
let invoice_amount_sats = amount_msat
504+
.div_ceil(1_000u128)
505+
.checked_add(fee_sats)
506+
.ok_or(CchError::SendBTCOrderAmountTooLarge)?;
504507

505508
let invoice = InvoiceBuilder::new(send_btc.currency)
506509
.amount(Some(invoice_amount_sats))
@@ -602,12 +605,13 @@ impl<S: CchOrderStore> CchState<S> {
602605
let fee_sats = amount_sats * (self.config.fee_rate_per_million_sats as u128)
603606
/ 1_000_000u128
604607
+ (self.config.base_fee_sats as u128);
605-
if amount_sats <= fee_sats {
606-
return Err(CchError::ReceiveBTCOrderAmountTooSmall);
607-
}
608-
if amount_sats > (i64::MAX / 1_000i64) as u128 {
609-
return Err(CchError::ReceiveBTCOrderAmountTooLarge);
610-
}
608+
let total_msat = i64::try_from(
609+
amount_sats
610+
.checked_add(fee_sats)
611+
.and_then(|s| s.checked_mul(1_000u128))
612+
.unwrap_or(u128::MAX),
613+
)
614+
.map_err(|_| CchError::ReceiveBTCOrderAmountTooLarge)?;
611615

612616
// Verify wrapped_btc_type_script matches invoice UDT type script
613617
let wrapped_btc_type_script: ckb_jsonrpc_types::Script = get_script_by_contract(
@@ -646,7 +650,7 @@ impl<S: CchOrderStore> CchState<S> {
646650
let mut client = self.lnd_connection.create_invoices_client().await?;
647651
let req = invoicesrpc::AddHoldInvoiceRequest {
648652
hash: payment_hash.as_ref().to_vec(),
649-
value_msat: ((amount_sats + fee_sats) * 1_000u128) as i64,
653+
value_msat: total_msat,
650654
expiry: outgoing_invoice_expiry_delta_seconds as i64,
651655
cltv_expiry: self.config.btc_final_tlc_expiry_delta_blocks,
652656
..Default::default()

crates/fiber-lib/src/cch/error.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,8 @@ pub enum CchError {
4545
expected: Currency,
4646
actual: Currency,
4747
},
48-
#[error("ReceiveBTC order payment amount is too small")]
49-
ReceiveBTCOrderAmountTooSmall,
48+
#[error("SendBTC order payment amount is too large")]
49+
SendBTCOrderAmountTooLarge,
5050
#[error("ReceiveBTC order payment amount is too large")]
5151
ReceiveBTCOrderAmountTooLarge,
5252
#[error("Wrapped BTC type script mismatch")]

0 commit comments

Comments
 (0)