diff --git a/main.go b/main.go index 17fb192..a0d9571 100644 --- a/main.go +++ b/main.go @@ -119,37 +119,22 @@ func tryRebalance(ctx context.Context, r *regolancer, attempt *int) (err error, return err, true } routeCtxCancel() - invoice, err := r.createInvoice(ctx, from, to, amt) - if err != nil { - log.Printf("Error creating invoice: %s", err) - return err, true - } - defer func() { - if ctx.Err() == context.DeadlineExceeded { - r.invalidateInvoice(amt) - } - }() for _, route := range routes { log.Printf("Attempt %s, amount: %s (max fee: %s)", hiWhiteColorF("#%d", *attempt), hiWhiteColor(amt), formatFee(fee)) r.printRoute(ctx, route) - err = r.pay(ctx, invoice, amt, params.MinAmount, route, params.ProbeSteps) + err = r.pay(ctx, amt, params.MinAmount, route, params.ProbeSteps) if err == nil { return nil, false } if retryErr, ok := err.(ErrRetry); ok { amt = retryErr.amount log.Printf("Trying to rebalance again with %s", hiWhiteColor(amt)) - probedInvoice, err := r.createInvoice(ctx, from, to, amt) - if err != nil { - log.Printf("Error creating invoice: %s", err) - return err, true - } probedRoute, err := r.rebuildRoute(ctx, route, amt) if err != nil { log.Printf("Error rebuilding the route for probed payment: %s", errColor(err)) } else { - err = r.pay(ctx, probedInvoice, amt, 0, probedRoute, 0) + err = r.pay(ctx, amt, 0, probedRoute, 0) if err == nil { return nil, false } else { diff --git a/payment.go b/payment.go index f15e113..02a4e7b 100644 --- a/payment.go +++ b/payment.go @@ -21,13 +21,13 @@ func (e ErrRetry) Error() string { var ErrProbeFailed = fmt.Errorf("probe failed") -func (r *regolancer) createInvoice(ctx context.Context, from, to uint64, amount int64) (result *lnrpc.AddInvoiceResponse, err error) { +func (r *regolancer) createInvoice(ctx context.Context, amount int64) (result *lnrpc.AddInvoiceResponse, err error) { var ok bool if result, ok = r.invoiceCache[amount]; ok { return } result, err = r.lnClient.AddInvoice(ctx, &lnrpc.Invoice{Value: amount, - Memo: fmt.Sprintf("Rebalance %d ⇒ %d", from, to), + Memo: "Rebalance attempt", Expiry: int64(time.Hour.Seconds() * 24)}) r.invoiceCache[amount] = result return @@ -37,10 +37,20 @@ func (r *regolancer) invalidateInvoice(amount int64) { delete(r.invoiceCache, amount) } -func (r *regolancer) pay(ctx context.Context, invoice *lnrpc.AddInvoiceResponse, - amount int64, minAmount int64, route *lnrpc.Route, probeSteps int) error { +func (r *regolancer) pay(ctx context.Context, amount int64, minAmount int64, + route *lnrpc.Route, probeSteps int) error { fmt.Println() defer fmt.Println() + invoice, err := r.createInvoice(ctx, amount) + if err != nil { + log.Printf("Error creating invoice: %s", err) + return err + } + defer func() { + if ctx.Err() == context.DeadlineExceeded { + r.invalidateInvoice(amount) + } + }() lastHop := route.Hops[len(route.Hops)-1] lastHop.MppRecord = &lnrpc.MPPRecord{ PaymentAddr: invoice.PaymentAddr,