11package loopin
22
33import (
4+ "bytes"
45 "context"
56 "errors"
67 "fmt"
@@ -93,6 +94,8 @@ type StaticAddressLoopIn struct {
9394 // swap.
9495 DepositOutpoints []string
9596
97+ SelectedAmount btcutil.Amount
98+
9699 // state is the current state of the swap.
97100 state fsm.StateType
98101
@@ -287,10 +290,20 @@ func (l *StaticAddressLoopIn) createHtlcTx(chainParams *chaincfg.Params,
287290 weight := l .htlcWeight ()
288291 fee := feeRate .FeeForWeight (weight )
289292
290- // Check if the server breaches our fee limits.
291- amt := float64 (l .TotalDepositAmount ())
292- feeLimit := btcutil .Amount (amt * maxFeePercentage )
293+ // Determine the swap amount. If the user selected a specific amount, we
294+ // use that and use the difference to the total deposit amount as the
295+ // change.
296+ var (
297+ swapAmt = float64 (l .TotalDepositAmount ())
298+ changeAmount btcutil.Amount
299+ )
300+ if l .SelectedAmount > 0 {
301+ swapAmt = float64 (l .SelectedAmount )
302+ changeAmount = l .TotalDepositAmount () - l .SelectedAmount
303+ }
293304
305+ // Check if the server breaches our fee limits.
306+ feeLimit := btcutil .Amount (swapAmt * maxFeePercentage )
294307 if fee > feeLimit {
295308 return nil , fmt .Errorf ("htlc tx fee %v exceeds max fee %v" ,
296309 fee , feeLimit )
@@ -314,6 +327,14 @@ func (l *StaticAddressLoopIn) createHtlcTx(chainParams *chaincfg.Params,
314327
315328 msgTx .AddTxOut (sweepOutput )
316329
330+ // We expect change to be sent back to our static address output script.
331+ if changeAmount > 0 {
332+ msgTx .AddTxOut (& wire.TxOut {
333+ Value : int64 (changeAmount ),
334+ PkScript : l .AddressParams .PkScript ,
335+ })
336+ }
337+
317338 return msgTx , nil
318339}
319340
@@ -373,11 +394,24 @@ func (l *StaticAddressLoopIn) createHtlcSweepTx(ctx context.Context,
373394 return nil , err
374395 }
375396
397+ // Check if the htlc tx has a change output. If so we need to select the
398+ // non-change output index to construct the sweep with.
399+ htlcInputIndex := uint32 (0 )
400+ if len (htlcTx .TxOut ) == 2 {
401+ // If the first htlc tx output matches our static address
402+ // script we need to select the second output to sweep from.
403+ if bytes .Equal (
404+ htlcTx .TxOut [0 ].PkScript , l .AddressParams .PkScript ,
405+ ) {
406+ htlcInputIndex = 1
407+ }
408+ }
409+
376410 // Add the htlc input.
377411 sweepTx .AddTxIn (& wire.TxIn {
378412 PreviousOutPoint : wire.OutPoint {
379413 Hash : htlcTx .TxHash (),
380- Index : 0 ,
414+ Index : htlcInputIndex ,
381415 },
382416 SignatureScript : htlc .SigScript ,
383417 Sequence : htlc .SuccessSequence (),
0 commit comments