From 9b1499616d77d622f712a95d16183b32a7a5f8d1 Mon Sep 17 00:00:00 2001 From: Michael Bumann Date: Sat, 29 Aug 2020 19:40:45 +0200 Subject: [PATCH] Add PaymentResponse wrapper This is an experimental wrapper around the send_payment shortcut calls. The goal is to provide a simple interface to check if the payment was successful. --- lib/lnrpc.rb | 1 + lib/lnrpc/client.rb | 4 ++-- lib/lnrpc/payment_response.rb | 30 ++++++++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 lib/lnrpc/payment_response.rb diff --git a/lib/lnrpc.rb b/lib/lnrpc.rb index a411215..eecb839 100644 --- a/lib/lnrpc.rb +++ b/lib/lnrpc.rb @@ -11,6 +11,7 @@ module Lnrpc class Error < StandardError; end autoload :Client, 'lnrpc/client' autoload :GrpcWrapper, 'lnrpc/grpc_wrapper' + autoload :PaymentResponse, 'lnrpc/payment_response' autoload :MacaroonInterceptor, 'lnrpc/macaroon_interceptor' PREIMAGE_BYTE_LENGTH = 32 diff --git a/lib/lnrpc/client.rb b/lib/lnrpc/client.rb index 366ef21..1c67f6a 100644 --- a/lib/lnrpc/client.rb +++ b/lib/lnrpc/client.rb @@ -75,12 +75,12 @@ module Lnrpc args[:dest_custom_records][Lnrpc::KEY_SEND_PREIMAGE_TYPE] ||= Lnrpc.create_preimage args[:payment_hash] ||= Digest::SHA256.digest(args[:dest_custom_records][Lnrpc::KEY_SEND_PREIMAGE_TYPE]) args[:timeout_seconds] ||= 60 - router.send_payment_v2(args) + PaymentResponse.new(router.send_payment_v2(args)) end def pay(args) args[:timeout_seconds] ||= 60 - router.send_payment_v2(args) + PaymentResponse.new(router.send_payment_v2(args)) end def inspect diff --git a/lib/lnrpc/payment_response.rb b/lib/lnrpc/payment_response.rb new file mode 100644 index 0000000..3d531ee --- /dev/null +++ b/lib/lnrpc/payment_response.rb @@ -0,0 +1,30 @@ +module Lnrpc + class PaymentResponse + attr_reader :grpc_response, :exception + + def initialize(send_payment_response) + @grpc_response = send_payment_response + end + + def states + @states ||= response_array.map(&:status) + end + + def success? + return false if exception + + @success ||= states.include?(:SUCCEEDED) + end + + def fee + @fee ||= response_array.sum(&:fee) + end + + def response_array + @response_array ||= @grpc_response.to_a + rescue GRPC::BadStatus => e + @exception = e + [] + end + end +end